Plany: wizard 3-etapowy tworzenia/edycji, silownia i alias tygodnia (UX + API + migracja)

This commit is contained in:
tisachi
2026-09-12 15:16:13 +02:00
parent a2d31ee46b
commit ef2fa726bb
26 changed files with 1340 additions and 361 deletions

View File

@@ -54,9 +54,7 @@ export function useBodyParameters() {
return useQuery({
queryKey: ['me', 'body-parameters'],
queryFn: () =>
api<{ weight: WeightPoint[]; circumferences: CircumferenceSeries[] }>(
'/me/body-parameters',
),
api<{ weight: WeightPoint[]; circumferences: CircumferenceSeries[] }>('/me/body-parameters'),
});
}
@@ -71,12 +69,18 @@ function toIsoDate(date: string | undefined): string | undefined {
export function addWeight(value: number, date?: string) {
const iso = toIsoDate(date);
return api('/me/body-parameters/weight', { method: 'POST', body: { value, ...(iso ? { date: iso } : {}) } });
return api('/me/body-parameters/weight', {
method: 'POST',
body: { value, ...(iso ? { date: iso } : {}) },
});
}
export function addCircumference(name: string, value: number, date?: string) {
const iso = toIsoDate(date);
return api('/me/body-parameters/circumference', { method: 'POST', body: { name, value, ...(iso ? { date: iso } : {}) } });
return api('/me/body-parameters/circumference', {
method: 'POST',
body: { name, value, ...(iso ? { date: iso } : {}) },
});
}
export function removeWeightPoint(id: string) {
@@ -126,10 +130,9 @@ export function useGymDetail(id: string | undefined) {
export function addGymPhotos(gymId: string, files: File[]) {
const form = new FormData();
for (const f of files) form.append('photos', f);
return api<{ gym: Gym & { photos: { id: string; url: string; order: number; createdAt: string }[] } }>(
`/gyms/${gymId}/photos`,
{ method: 'POST', body: form },
);
return api<{
gym: Gym & { photos: { id: string; url: string; order: number; createdAt: string }[] };
}>(`/gyms/${gymId}/photos`, { method: 'POST', body: form });
}
export function deleteGymPhoto(gymId: string, photoId: string) {
@@ -224,7 +227,10 @@ export function useGymExceptions(gymId: string) {
});
}
export function createGymException(gymId: string, body: { date: string; availability: { start: string; end: string } | null }) {
export function createGymException(
gymId: string,
body: { date: string; availability: { start: string; end: string } | null },
) {
return api<{ exception: GymException }>(`/gyms/${gymId}/exceptions`, {
method: 'POST',
body,
@@ -323,17 +329,26 @@ export function useGymInviteeSearch(gymId: string, firstName: string, lastName:
/** List the equipment (machine/device) catalog. */
export function useEquipment() {
return useQuery({ queryKey: ['equipment'], queryFn: () => api<{ equipment: Equipment[] }>('/equipment') });
return useQuery({
queryKey: ['equipment'],
queryFn: () => api<{ equipment: Equipment[] }>('/equipment'),
});
}
// ---------- exercises ----------
export function useExercises() {
return useQuery({ queryKey: ['exercises'], queryFn: () => api<{ exercises: Exercise[] }>('/exercises') });
return useQuery({
queryKey: ['exercises'],
queryFn: () => api<{ exercises: Exercise[] }>('/exercises'),
});
}
// ---------- focus areas (priorities/exclusions) ----------
export function useFocusAreas() {
return useQuery({ queryKey: ['focus-areas'], queryFn: () => api<{ focusAreas: FocusArea[] }>('/focus-areas') });
return useQuery({
queryKey: ['focus-areas'],
queryFn: () => api<{ focusAreas: FocusArea[] }>('/focus-areas'),
});
}
export function useFocusChain() {
@@ -378,20 +393,26 @@ export interface PlanDayInput {
export interface PlanWeekInput {
index: number;
/** Opcjonalny alias tygodnia (np. „Deload"); null = bez aliasu. */
customName?: string | null;
days: PlanDayInput[];
}
export function createPlan(body: {
export interface PlanBody {
title: string;
weeksCount: number;
/** Informacyjna — siłownia planu; null/brak = bez siłowni. */
gymId?: string | null;
weeks: PlanWeekInput[];
/** Opcjonalna data startu (poniedziałek) — plan tworzony i aktywowany w jednym kroku. */
startDate?: string;
}) {
}
export function createPlan(body: PlanBody) {
return api<{ plan: { id: string } }>('/plans', { method: 'POST', body });
}
export function updatePlan(id: string, body: { title: string; weeksCount: number; weeks: PlanWeekInput[] }) {
export function updatePlan(id: string, body: Omit<PlanBody, 'startDate'>) {
return api(`/plans/${id}`, { method: 'PATCH', body });
}
@@ -439,7 +460,10 @@ export function addSessionExercise(sessionId: string, exerciseId: string) {
});
}
export function setSessionExerciseState(exerciseId: string, data: { hidden?: boolean; removed?: boolean }) {
export function setSessionExerciseState(
exerciseId: string,
data: { hidden?: boolean; removed?: boolean },
) {
return api(`/sessions/exercises/${exerciseId}`, { method: 'PATCH', body: data });
}
@@ -447,7 +471,15 @@ export function addSessionSet(exerciseId: string) {
return api<{ setId: string }>(`/sessions/exercises/${exerciseId}/sets`, { method: 'POST' });
}
export function updateSessionSet(setId: string, data: { reps?: number | null; rir?: number | null; difficulty?: number | null; note?: string | null }) {
export function updateSessionSet(
setId: string,
data: {
reps?: number | null;
rir?: number | null;
difficulty?: number | null;
note?: string | null;
},
) {
return api(`/sessions/sets/${setId}`, { method: 'PATCH', body: data });
}
@@ -539,7 +571,10 @@ export function useTraineeSearch(firstName: string, lastName: string) {
}
export function sendInvitation(userId: string) {
return api<{ coaching: { id: string } }>('/trainer/invitations', { method: 'POST', body: { userId } });
return api<{ coaching: { id: string } }>('/trainer/invitations', {
method: 'POST',
body: { userId },
});
}
export function archiveTrainee(userId: string) {
@@ -569,9 +604,7 @@ export function useCalendar(month?: string) {
return useQuery({
queryKey: ['calendar', month],
queryFn: () =>
api<{ month: string; days: CalendarDay[] }>(
`/calendar${month ? `?month=${month}` : ''}`,
),
api<{ month: string; days: CalendarDay[] }>(`/calendar${month ? `?month=${month}` : ''}`),
});
}
@@ -617,13 +650,20 @@ export function addTraineeComment(
userId: string,
data: { body: string; sessionId?: string; sessionExerciseId?: string },
) {
return api<{ comment: ExerciseComment }>(`/trainer/trainees/${encodeURIComponent(userId)}/comments`, {
method: 'POST',
body: data,
});
return api<{ comment: ExerciseComment }>(
`/trainer/trainees/${encodeURIComponent(userId)}/comments`,
{
method: 'POST',
body: data,
},
);
}
export function addMyComment(data: { body: string; sessionId: string; sessionExerciseId?: string }) {
export function addMyComment(data: {
body: string;
sessionId: string;
sessionExerciseId?: string;
}) {
return api<{ comment: ExerciseComment }>('/me/comments', { method: 'POST', body: data });
}
@@ -647,7 +687,8 @@ export function useExerciseProgress() {
export function useTraineeExerciseProgress(userId: string) {
return useQuery({
queryKey: ['trainees', userId, 'exercise-progress'],
queryFn: () => api<{ exercises: ExerciseProgress[] }>(`/trainer/trainees/${userId}/exercise-progress`),
queryFn: () =>
api<{ exercises: ExerciseProgress[] }>(`/trainer/trainees/${userId}/exercise-progress`),
enabled: !!userId,
});
}
@@ -655,7 +696,8 @@ export function useTraineeExerciseProgress(userId: string) {
export function useTraineeLatestResults(userId: string) {
return useQuery({
queryKey: ['trainees', userId, 'exercise-latest'],
queryFn: () => api<{ results: LatestExerciseResult[] }>(`/trainer/trainees/${userId}/exercise-latest`),
queryFn: () =>
api<{ results: LatestExerciseResult[] }>(`/trainer/trainees/${userId}/exercise-latest`),
enabled: !!userId,
});
}
@@ -677,20 +719,18 @@ export function useTraineePlan(userId: string, planId: string) {
});
}
export function createTraineePlan(
userId: string,
body: {
title: string;
weeksCount: number;
weeks: PlanWeekInput[];
/** Opcjonalna data startu (poniedziałek) — plan tworzony i aktywowany w jednym kroku. */
startDate?: string;
},
) {
return api<{ plan: { id: string } }>(`/trainer/trainees/${userId}/plans`, { method: 'POST', body });
export function createTraineePlan(userId: string, body: PlanBody) {
return api<{ plan: { id: string } }>(`/trainer/trainees/${userId}/plans`, {
method: 'POST',
body,
});
}
export function updateTraineePlan(userId: string, planId: string, body: { title: string; weeksCount: number; weeks: PlanWeekInput[] }) {
export function updateTraineePlan(
userId: string,
planId: string,
body: Omit<PlanBody, 'startDate'>,
) {
return api(`/trainer/trainees/${userId}/plans/${planId}`, { method: 'PATCH', body });
}
@@ -699,7 +739,10 @@ export function deleteTraineePlan(userId: string, planId: string) {
}
export function activateTraineePlan(userId: string, planId: string, startDate: string) {
return api(`/trainer/trainees/${userId}/plans/${planId}/activate`, { method: 'POST', body: { startDate } });
return api(`/trainer/trainees/${userId}/plans/${planId}/activate`, {
method: 'POST',
body: { startDate },
});
}
export function abandonTraineePlan(userId: string, planId: string) {

View File

@@ -184,7 +184,12 @@ export interface GymInvitation {
/** Kto został zaproszony (tylko direction = 'sent'). */
user: { id: string; firstName: string | null; lastName: string | null; email: string } | null;
/** Kto zaprosił (tylko direction = 'received'). */
invitedBy: { id: string; firstName: string | null; lastName: string | null; email: string } | null;
invitedBy: {
id: string;
firstName: string | null;
lastName: string | null;
email: string;
} | null;
invitedAt: string;
expiresAt: string;
}
@@ -262,6 +267,8 @@ export interface PlanDay {
export interface PlanWeek {
id: string;
index: number;
/** Opcjonalny alias tygodnia (np. „Deload"). */
customName: string | null;
days: PlanDay[];
}
@@ -271,6 +278,8 @@ export interface Plan {
status: 'DRAFT' | 'ACTIVE' | 'COMPLETED' | 'ABANDONED';
weeksCount: number;
startDate: string | null;
/** Informacyjna — siłownia, w której realizowany jest plan; null = bez siłowni. */
gym: { id: string; name: string } | null;
/** Kto utworzył plan (trener, gdy plan należy do podopiecznego); null = podopieczny sam. */
creator: { id: string; firstName: string | null; lastName: string | null } | null;
/** Podsumowanie postępu (lista planów); brak = dane niedostępne. */
@@ -325,7 +334,11 @@ export interface ActiveSession {
export interface Dashboard {
killstreak: number;
nextTraining: { dayId: string; date: string; exercises: { name: string; muscle: string }[] } | null;
nextTraining: {
dayId: string;
date: string;
exercises: { name: string; muscle: string }[];
} | null;
progress: { completed: number; total: number; percent: number } | null;
/** Serie wykonane ponad plan (planSetId = null) w ukończonych sesjach aktywnego planu. */
extra: { sets: number } | null;
@@ -353,7 +366,12 @@ export interface HistorySet {
reps: number | null;
rir: number | null;
difficulty: number | null;
planned: { reps: number | null; loadKg: number | null; restSec: number | null; rir: number | null } | null;
planned: {
reps: number | null;
loadKg: number | null;
restSec: number | null;
rir: number | null;
} | null;
}
export interface ExerciseComment {
@@ -418,7 +436,12 @@ export interface MessageAttachment {
index: number;
reps: number | null;
rir: number | null;
planned: { reps: number | null; loadKg: number | null; restSec: number | null; rir: number | null } | null;
planned: {
reps: number | null;
loadKg: number | null;
restSec: number | null;
rir: number | null;
} | null;
}[];
} | null;
/** Tylko gdy exercise == null. */
@@ -483,7 +506,11 @@ export interface UserSearchResult {
export interface Trainee {
user: { id: string; firstName: string | null; lastName: string | null; nickname: string | null };
gyms: { id: string; name: string }[];
activePlan: { id: string; title: string; progress: { completed: number; total: number; percent: number } } | null;
activePlan: {
id: string;
title: string;
progress: { completed: number; total: number; percent: number };
} | null;
killstreak: number;
lastSessionAt: string | null;
flags: TraineeFlag[];
@@ -498,7 +525,11 @@ export interface TraineeDetail {
activePlan: { id: string; title: string; startDate: string } | null;
progress: { completed: number; total: number; percent: number } | null;
killstreak: number;
nextTraining: { dayId: string; date: string; exercises: { name: string; muscle: string }[] } | null;
nextTraining: {
dayId: string;
date: string;
exercises: { name: string; muscle: string }[];
} | null;
extra: { sets: number } | null;
missing: { sets: number } | null;
lastSessionAt: string | null;
@@ -535,7 +566,14 @@ export interface DayMoveEntry {
export interface Invitation {
id: string;
direction: 'sent' | 'received';
other: { id: string; firstName: string | null; lastName: string | null; nickname: string | null; email: string; phone: string | null } | null;
other: {
id: string;
firstName: string | null;
lastName: string | null;
nickname: string | null;
email: string;
phone: string | null;
} | null;
invitedAt: string;
expiresAt: string;
}

View File

@@ -31,10 +31,15 @@ export function PlanDayRow({
actions?: ReactNode;
}) {
return (
<div className={`rounded-[10px] px-3 py-3 transition-colors hover:bg-line/20 ${DAY_TINT[day.status]}`.trim()}>
<div
className={`rounded-[10px] px-3 py-3 transition-colors hover:bg-line/20 ${DAY_TINT[day.status]}`.trim()}
>
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div className="flex min-w-0 flex-wrap items-center gap-2">
<span aria-hidden="true" className={`h-2 w-2 flex-none rounded-full ${DAY_DOT[day.status]}`} />
<span
aria-hidden="true"
className={`h-2 w-2 flex-none rounded-full ${DAY_DOT[day.status]}`}
/>
<strong className="text-[0.95rem]">{DAY_NAMES[day.dayOfWeek]}</strong>
{showDate && day.date && (
<span className="text-dim text-[0.8125rem] tabular-nums">{fmtDate(day.date)}</span>
@@ -51,7 +56,9 @@ export function PlanDayRow({
<span className="min-w-0 truncate text-[0.875rem]">{ex.exercise.name}</span>
<span className="shrink-0 text-dim text-[0.8125rem] tabular-nums">
{ex.sets.length}×{' '}
{ex.sets.map((s) => `${s.reps ?? '?'} powt.${s.loadKg ? ` @ ${s.loadKg}kg` : ''}`).join(', ')}
{ex.sets
.map((s) => `${s.reps ?? '?'} powt.${s.loadKg ? ` @ ${s.loadKg}kg` : ''}`)
.join(', ')}
</span>
</li>
))}
@@ -78,6 +85,7 @@ export function PlanWeekCard({
<div className="mb-1 flex flex-wrap items-center justify-between gap-2">
<div className="flex items-center gap-2.5">
<H2 className="mb-0">Tydzień {week.index + 1}</H2>
{week.customName && <Badge color="blue">{week.customName}</Badge>}
{total > 0 && (
<Badge color={completed === total ? 'green' : 'gray'}>
{completed}/{total} dni
@@ -92,7 +100,9 @@ export function PlanWeekCard({
style={{ width: `${percent}%` }}
/>
</div>
<span className="font-display text-[0.75rem] font-bold tabular-nums text-dim">{percent}%</span>
<span className="font-display text-[0.75rem] font-bold tabular-nums text-dim">
{percent}%
</span>
</div>
)}
</div>

View File

@@ -1,7 +1,7 @@
import { useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
import { CalendarDays, Pencil, Play, Trash2 } from 'lucide-react';
import { CalendarDays, MapPin, Pencil, Play, Trash2 } from 'lucide-react';
import {
abandonPlan,
activatePlan,
@@ -73,10 +73,22 @@ export default function PlanDetail() {
label: 'Aktywuj',
icon: Play,
disabled: !startDate || busy || hasOtherActivePlan,
onClick: () => void act(() => activatePlan(planData.id, startDate), 'Plan aktywowany'),
onClick: () =>
void act(() => activatePlan(planData.id, startDate), 'Plan aktywowany'),
},
{
label: 'Edytuj',
to: `/plans/${planData.id}/edit`,
variant: 'secondary',
icon: Pencil,
},
{
label: 'Usuń',
icon: Trash2,
variant: 'danger',
disabled: busy,
onClick: () => setConfirm('delete'),
},
{ label: 'Edytuj', to: `/plans/${planData.id}/edit`, variant: 'secondary', icon: Pencil },
{ label: 'Usuń', icon: Trash2, variant: 'danger', disabled: busy, onClick: () => setConfirm('delete') },
]
: planData.status === 'ACTIVE'
? [
@@ -86,7 +98,12 @@ export default function PlanDetail() {
disabled: busy,
onClick: () => void act(() => completePlan(planData.id), 'Plan ukończony'),
},
{ label: 'Porzuć', variant: 'danger', disabled: busy, onClick: () => setConfirm('abandon') },
{
label: 'Porzuć',
variant: 'danger',
disabled: busy,
onClick: () => setConfirm('abandon'),
},
]
: undefined
: undefined,
@@ -131,7 +148,10 @@ export default function PlanDetail() {
<span className="text-dim text-[0.875rem]">
{doneDays}/{allDays.length} dni
</span>
{plan.startDate && <MetaItem icon={CalendarDays}>start: {fmtDate(plan.startDate)}</MetaItem>}
{plan.gym && <MetaItem icon={MapPin}>{plan.gym.name}</MetaItem>}
{plan.startDate && (
<MetaItem icon={CalendarDays}>start: {fmtDate(plan.startDate)}</MetaItem>
)}
{creatorName && <Muted className="text-[0.875rem]">utworzył: {creatorName}</Muted>}
</div>
{allDays.length > 0 && (
@@ -142,7 +162,9 @@ export default function PlanDetail() {
style={{ width: `${planPercent}%` }}
/>
</div>
<span className="font-display text-[0.8125rem] font-bold tabular-nums text-dim">{planPercent}%</span>
<span className="font-display text-[0.8125rem] font-bold tabular-nums text-dim">
{planPercent}%
</span>
</div>
)}
{plan.status === 'DRAFT' && (
@@ -156,8 +178,8 @@ export default function PlanDetail() {
</p>
) : (
<p className="mt-3 text-[0.875rem] text-dim">
Zaznacz tydzień startu — plan zacznie się w jego poniedziałek. Daty dni treningowych liczone
automatycznie.
Zaznacz tydzień startu — plan zacznie się w jego poniedziałek. Daty dni treningowych
liczone automatycznie.
</p>
)}
</div>

View File

@@ -1,24 +1,30 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Link, useNavigate, useParams } from 'react-router-dom';
import {
createPlan,
createTraineePlan,
updatePlan,
updateTraineePlan,
useGyms,
usePlan,
useTrainee,
useTraineePlan,
useTraineeExerciseProgress,
useTraineeLatestResults,
useExercises,
type PlanWeekInput,
type PlanBody,
} from '../../api/queries';
import { CalendarX, Check } from 'lucide-react';
import {
BackButton,
Button,
Card,
ConfirmDialog,
EmptyState,
ErrorText,
Field,
isPastWeek,
Select,
Skeleton,
Tabs,
type BadgeColor,
@@ -35,6 +41,7 @@ import { useTopbar } from '../../topbar';
import { displayedDaysOf, type EditorDay, type EditorWeek } from './plan-editor/types';
import { usePlanEditorState } from './plan-editor/usePlanEditorState';
import { PlanMetaForm } from './plan-editor/PlanMetaForm';
import { PlanSummary } from './plan-editor/PlanSummary';
import { WeekPanel } from './plan-editor/WeekPanel';
import { DayPicker } from './plan-editor/DayPicker';
import { DayEditor } from './plan-editor/DayEditor';
@@ -51,6 +58,60 @@ function EditorSkeleton() {
);
}
const WIZARD_STEPS = [
{ n: 1, label: 'Szczegóły' },
{ n: 2, label: 'Ćwiczenia' },
{ n: 3, label: 'Podsumowanie' },
];
/** Stepper 3 kroków — klikalny (zwrot do wcześniejszego kroku zawsze dozwolony). */
function WizardStepper({ step, onGo }: { step: number; onGo: (n: number) => void }) {
return (
<div
className="flex items-center gap-1.5 sm:gap-2"
role="list"
aria-label="Kroki tworzenia planu"
>
{WIZARD_STEPS.map((s, i) => {
const done = step > s.n;
const active = step === s.n;
return (
<div key={s.n} className="flex items-center gap-1.5 sm:gap-2" role="listitem">
{i > 0 && <span className="h-px w-4 sm:w-8 bg-line" aria-hidden="true" />}
<button
type="button"
onClick={() => onGo(s.n)}
aria-current={active ? 'step' : undefined}
className={cn(
'flex items-center gap-2 rounded-full border px-2.5 py-1.5 text-[0.8125rem] font-medium transition-colors',
active
? 'border-accent bg-accent/10 text-accent-text'
: done
? 'border-line text-ink hover:border-accent/50'
: 'border-line text-dim',
)}
>
<span
className={cn(
'flex h-5 w-5 items-center justify-center rounded-full text-[0.6875rem] font-bold',
active
? 'bg-accent text-white'
: done
? 'bg-accent/15 text-accent-text'
: 'bg-line text-dim',
)}
>
{done ? <Check className="h-3 w-3" /> : s.n}
</span>
<span className="hidden sm:inline">{s.label}</span>
</button>
</div>
);
})}
</div>
);
}
export default function PlanEditor() {
const { id, userId, planId } = useParams();
const traineeUserId = userId ?? '';
@@ -65,6 +126,9 @@ export default function PlanEditor() {
const { data: exData } = useExercises();
const { data: latestData } = useTraineeLatestResults(traineeUserId);
const { data: progressData } = useTraineeExerciseProgress(traineeUserId);
// Siłownie do wyboru: tryb własny = członkostwa zalogowanego, tryb trenera = członkostwa podopiecznego.
const { data: gymsData } = useGyms();
const { data: traineeData } = useTrainee(isTraineeMode ? traineeUserId : '');
const backPath = isTraineeMode
? `/trainees/${traineeUserId}?tab=plans`
@@ -73,6 +137,7 @@ export default function PlanEditor() {
: '/plans';
const [saving, setSaving] = useState(false);
const [step, setStep] = useState(1);
const requestExit = () => {
if (editor.dirty) setConfirmExit(true);
@@ -130,6 +195,17 @@ export default function PlanEditor() {
? 'Tydzień startu nie może być w przeszłości'
: '';
// Krok 1 blokuje przejście: pusty tytuł lub start w przeszłości. Krok 2 → 3 zawsze.
const step1Valid = editor.title.trim() !== '' && !startWeekError;
const goToStep = (n: number) => {
if (n <= step) {
setStep(n);
return;
}
if (n === 2 && step1Valid) setStep(2);
if (n === 3 && step1Valid) setStep(3);
};
// Podsumowanie stopki: dni/ćwiczenia/serie + tygodnie bez ćwiczeń (nie blokuje)
const totals = useMemo(() => {
let days = 0;
@@ -206,29 +282,30 @@ export default function PlanEditor() {
setError(`Plan ma ${editor.weeksCount} tygodni — zdefiniuj je wszystkie`);
return;
}
const body: { title: string; weeksCount: number; weeks: PlanWeekInput[]; startDate?: string } =
{
title: editor.title.trim(),
weeksCount: editor.weeksCount,
weeks: editor.weeks.map((_, i) => ({
index: i,
days: displayedDaysOf(editor.weeks, i).map((d) => ({
dayOfWeek: d.dayOfWeek,
exercises: d.exercises.map((e, oi) => ({
exerciseId: e.exerciseId,
order: oi,
sets: e.sets.map((s, si) => ({
index: si,
reps: s.reps ? parseInt(s.reps) : null,
loadKg: s.loadKg ? parseFloat(s.loadKg) : null,
restSec: s.restSec ? parseInt(s.restSec) : null,
rir: s.rir !== '' ? parseInt(s.rir) : null,
difficulty: s.difficulty ? parseInt(s.difficulty) : null,
})),
const body: PlanBody = {
title: editor.title.trim(),
weeksCount: editor.weeksCount,
gymId: editor.gymId,
weeks: editor.weeks.map((w, i) => ({
index: i,
customName: w.customName.trim() || null,
days: displayedDaysOf(editor.weeks, i).map((d) => ({
dayOfWeek: d.dayOfWeek,
exercises: d.exercises.map((e, oi) => ({
exerciseId: e.exerciseId,
order: oi,
sets: e.sets.map((s, si) => ({
index: si,
reps: s.reps ? parseInt(s.reps) : null,
loadKg: s.loadKg ? parseFloat(s.loadKg) : null,
restSec: s.restSec ? parseInt(s.restSec) : null,
rir: s.rir !== '' ? parseInt(s.rir) : null,
difficulty: s.difficulty ? parseInt(s.difficulty) : null,
})),
})),
})),
};
})),
};
// Data startu tylko przy tworzeniu — plan tworzony i aktywowany w jednym kroku.
// Tydzień startu: bieżący lub przyszły (WeekPicker blokuje minione; guard zapasowy).
if (!isEdit && editor.startDate) {
@@ -281,136 +358,211 @@ export default function PlanEditor() {
return <EditorSkeleton />;
}
// Opcje siłowni: tryb własny = useGyms (cłonkostwa zalogowanego),
// tryb trenera = gyms z detalu podopiecznego (cłonkostwa podopiecznego).
const gymOptions = isTraineeMode
? (traineeData?.gyms ?? [])
: (gymsData?.gyms ?? []).map((g) => ({ id: g.id, name: g.name }));
const gymName = gymOptions.find((g) => g.id === editor.gymId)?.name ?? null;
const week = editor.weeks[activeWi];
const weekDays = displayedDaysOf(editor.weeks, activeWi);
const weekSummaryActive = weekSummary(activeWi, week, weekDays);
return (
<>
<div className="flex justify-end mb-4">
<div className="flex items-center justify-between gap-2 mb-4">
<BackButton onClick={requestExit} />
<WizardStepper step={step} onGo={goToStep} />
</div>
<PlanMetaForm
title={editor.title}
onTitleChange={editor.setTitle}
onTitleBlur={() => setTitleTouched(true)}
titleError={titleError}
weeksCount={editor.weeksCount}
onWeeksCountChange={editor.setWeeksCount}
startDate={editor.startDate}
onStartDateChange={editor.setStartDate}
startWeekError={startWeekError}
showStartWeek={!isEdit}
/>
{/* Zakładki tygodni (sticky pod topbarem): każdy tydzień z osobna,
renderowany jest tylko panel aktywnej zakładki */}
<div className="sticky top-[55px] md:top-[59px] z-20 -mx-4 px-4 md:-mx-8 md:px-8 py-2 bg-bg/95 backdrop-blur">
<Tabs
tabs={editor.weeks.map((w, wi) => ({
id: String(wi),
label: (
<span className="inline-flex items-center gap-1.5">
<span className="sm:hidden">T.{wi + 1}</span>
<span className="hidden sm:inline">Tydzień {wi + 1}</span>
<span
aria-hidden="true"
className={cn(
'h-2 w-2 rounded-full',
DOT_COLORS[weekSummary(wi, w, displayedDaysOf(editor.weeks, wi)).color],
)}
/>
</span>
),
}))}
active={String(activeWi)}
onChange={(id) => setActiveWeek(parseInt(id, 10))}
{step === 1 && (
<PlanMetaForm
title={editor.title}
onTitleChange={editor.setTitle}
onTitleBlur={() => setTitleTouched(true)}
titleError={titleError}
weeksCount={editor.weeksCount}
onWeeksCountChange={editor.setWeeksCount}
startDate={editor.startDate}
onStartDateChange={editor.setStartDate}
startWeekError={startWeekError}
showStartWeek={!isEdit}
/>
</div>
)}
<div ref={panelRef} className="scroll-mt-28">
<WeekPanel
index={activeWi}
summary={weekSummaryActive}
canCopy={activeWi > 0}
onCopyPrev={() => editor.copyPrevWeek(activeWi)}
canClear={weekDays.length > 0 || !week.detached}
onClear={() => setClearWeekIdx(activeWi)}
>
<DayPicker
days={weekDays}
onAddDay={(dow) => editor.addDay(activeWi, dow)}
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);
}}
/>
{step === 2 && (
<>
{/* Wybór siłowni (informacyjny) — z członkostw właściciela planu */}
<Card className="mb-4">
<Field label="Siłownia">
{gymOptions.length > 0 ? (
<Select
value={editor.gymId ?? ''}
onChange={(e) => editor.setGymId(e.target.value || null)}
>
<option value="">Bez siłowni</option>
{gymOptions.map((g) => (
<option key={g.id} value={g.id}>
{g.name}
</option>
))}
</Select>
) : (
<p className="text-dim text-[0.875rem] py-1">
{isTraineeMode ? (
'Podopieczny nie należy do żadnej siłowni.'
) : (
<>
Nie należysz do żadnej siłowni.{' '}
<Link to="/gyms" className="text-accent-text underline">
Zarządzaj siłowniami
</Link>
</>
)}
</p>
)}
</Field>
</Card>
{weekDays.length === 0 && (
<EmptyState
icon={CalendarX}
title="Brak dni treningowych"
description={
activeWi === 0
? 'Wybierz dni treningowe powyżej — pozostałe tygodnie będą je odzwierciedlać.'
: week.detached
? 'Tydzień wolny (przerwa) — pozostanie pusty.'
: 'Odzwierciedla tydzień 1. Kliknij dzień, aby edytować niezależnie.'
}
{/* Zakładki tygodni (sticky pod topbarem): każdy tydzień z osobna,
renderowany jest tylko panel aktywnej zakładki */}
<div className="sticky top-[55px] md:top-[59px] z-20 -mx-4 px-4 md:-mx-8 md:px-8 py-2 bg-bg/95 backdrop-blur">
<Tabs
tabs={editor.weeks.map((w, wi) => ({
id: String(wi),
label: (
<span className="inline-flex items-center gap-1.5">
<span className="sm:hidden">T.{wi + 1}</span>
<span className="hidden sm:inline">Tydzień {wi + 1}</span>
<span
aria-hidden="true"
className={cn(
'h-2 w-2 rounded-full',
DOT_COLORS[weekSummary(wi, w, displayedDaysOf(editor.weeks, wi)).color],
)}
/>
</span>
),
}))}
active={String(activeWi)}
onChange={(id) => setActiveWeek(parseInt(id, 10))}
/>
)}
</div>
{weekDays.length > 0 && (
<div className="mt-3 divide-y divide-line">
{weekDays.map((d, di) => (
<DayEditor
key={d.dayOfWeek}
day={d}
weekIndex={activeWi}
dayIndex={di}
exerciseName={exerciseName}
isTraineeMode={isTraineeMode}
exercises={exercises}
exercisesLoading={exData === undefined}
resultsOpenKey={resultsOpenKey}
onToggleResults={(ei) => {
const key = `${activeWi}:${di}:${ei}`;
setResultsOpenKey(resultsOpenKey === key ? null : key);
}}
onAddExercise={(exerciseId) => editor.addExercise(activeWi, di, exerciseId)}
onRemoveExercise={(ei) => editor.removeExercise(activeWi, di, ei)}
onMoveExercise={(ei, dir) => editor.moveExercise(activeWi, di, ei, dir)}
onSetField={(ei, si, field, value) =>
editor.setSetField(activeWi, di, ei, si, field, value)
<div ref={panelRef} className="scroll-mt-28">
<WeekPanel
index={activeWi}
summary={weekSummaryActive}
canCopy={activeWi > 0}
onCopyPrev={() => editor.copyPrevWeek(activeWi)}
canClear={weekDays.length > 0 || !week.detached}
onClear={() => setClearWeekIdx(activeWi)}
alias={week.customName}
onAliasChange={(v) => editor.setWeekAlias(activeWi, v)}
>
<DayPicker
days={weekDays}
onAddDay={(dow) => editor.addDay(activeWi, dow)}
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);
}}
/>
{weekDays.length === 0 && (
<EmptyState
icon={CalendarX}
title="Brak dni treningowych"
description={
activeWi === 0
? 'Wybierz dni treningowe powyżej — pozostałe tygodnie będą je odzwierciedlać.'
: week.detached
? 'Tydzień wolny (przerwa) — pozostanie pusty.'
: 'Odzwierciedla tydzień 1. Kliknij dzień, aby edytować niezależnie.'
}
onAddSet={(ei) => editor.addSet(activeWi, di, ei)}
onRemoveSet={(ei, si) => editor.removeSet(activeWi, di, ei, si)}
onDuplicateSet={(ei, si) => editor.duplicateSet(activeWi, di, ei, si)}
latestByExercise={latestByExercise}
progressByExercise={progressByExercise}
onPrefill={(ei) => {
const latest = latestByExercise.get(d.exercises[ei].exerciseId);
if (latest) editor.prefillExercise(activeWi, di, ei, latest);
}}
/>
))}
</div>
)}
</WeekPanel>
</div>
)}
{weekDays.length > 0 && (
<div className="mt-3 divide-y divide-line">
{weekDays.map((d, di) => (
<DayEditor
key={d.dayOfWeek}
day={d}
weekIndex={activeWi}
dayIndex={di}
exerciseName={exerciseName}
isTraineeMode={isTraineeMode}
exercises={exercises}
exercisesLoading={exData === undefined}
resultsOpenKey={resultsOpenKey}
onToggleResults={(ei) => {
const key = `${activeWi}:${di}:${ei}`;
setResultsOpenKey(resultsOpenKey === key ? null : key);
}}
onAddExercise={(exerciseId) => editor.addExercise(activeWi, di, exerciseId)}
onRemoveExercise={(ei) => editor.removeExercise(activeWi, di, ei)}
onMoveExercise={(ei, dir) => editor.moveExercise(activeWi, di, ei, dir)}
onSetField={(ei, si, field, value) =>
editor.setSetField(activeWi, di, ei, si, field, value)
}
onAddSet={(ei) => editor.addSet(activeWi, di, ei)}
onRemoveSet={(ei, si) => editor.removeSet(activeWi, di, ei, si)}
onDuplicateSet={(ei, si) => editor.duplicateSet(activeWi, di, ei, si)}
latestByExercise={latestByExercise}
progressByExercise={progressByExercise}
onPrefill={(ei) => {
const latest = latestByExercise.get(d.exercises[ei].exerciseId);
if (latest) editor.prefillExercise(activeWi, di, ei, latest);
}}
/>
))}
</div>
)}
</WeekPanel>
</div>
</>
)}
{step === 3 && (
<PlanSummary
title={editor.title}
gymName={gymName}
startDate={isEdit ? '' : editor.startDate}
weeks={editor.weeks}
/>
)}
{/* sticky stopka; na mobile pod stałym dolnym paskiem topmenu (+ safe-area) */}
<div className="sticky bottom-0 -mx-4 px-4 py-3 bg-bg/95 backdrop-blur border-t border-line mt-2 md:-mx-8 md:px-8 max-md:bottom-[calc(43px+max(0.5rem,env(safe-area-inset-bottom)))]">
{error && <ErrorText>{error}</ErrorText>}
<div className="text-dim text-[0.8125rem]">
{dayCountLabel(totals.days)} · {exerciseCountLabel(totals.exercises)} ·{' '}
{setCountLabel(totals.sets)}
{totals.emptyWeeks > 0 && (
<span className="text-warn"> · {weekCountLabel(totals.emptyWeeks)} bez ćwiczeń</span>
)}
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
<div className="text-dim text-[0.8125rem]">
{dayCountLabel(totals.days)} · {exerciseCountLabel(totals.exercises)} ·{' '}
{setCountLabel(totals.sets)}
{totals.emptyWeeks > 0 && (
<span className="text-warn"> · {weekCountLabel(totals.emptyWeeks)} bez ćwiczeń</span>
)}
</div>
<div className="flex items-center gap-2 sm:ml-auto">
{step > 1 && (
<Button variant="secondary" onClick={() => setStep(step - 1)}>
Wstecz
</Button>
)}
{step < 3 ? (
<Button onClick={() => goToStep(step + 1)} disabled={step === 1 && !step1Valid}>
Dalej
</Button>
) : (
<Button onClick={() => save()} disabled={saving}>
{isEdit ? 'Zapisz zmiany' : 'Zapisz'}
</Button>
)}
</div>
</div>
</div>

View File

@@ -0,0 +1,89 @@
import { MapPin } from 'lucide-react';
import { Badge, Card, H2, H3 } from '../../../components/ui';
import {
DAY_NAMES,
dayCountLabel,
exerciseCountLabel,
setCountLabel,
weekCountLabel,
} from '../../../lib/labels';
import { fmtDate } from '../../../lib/format';
import { displayedDaysOf, type EditorWeek } from './types';
/**
* Krok 3 wizarda: przejrzysty przegląd całego planu przed zapisem.
* Puste tygodnie nie blokują zapisu — są oznaczone ostrzeżeniem.
*/
export function PlanSummary({
title,
gymName,
startDate,
weeks,
}: {
title: string;
gymName: string | null;
/** '' = szkic bez tygodnia startu. */
startDate: string;
weeks: EditorWeek[];
}) {
const rows = weeks.map((w, i) => {
const days = displayedDaysOf(weeks, i);
let exercises = 0;
let sets = 0;
days.forEach((d) => {
exercises += d.exercises.length;
d.exercises.forEach((e) => {
sets += e.sets.length;
});
});
return { i, alias: w.customName.trim(), days, exercises, sets };
});
const totals = rows.reduce(
(acc, r) => ({
days: acc.days + r.days.length,
exercises: acc.exercises + r.exercises,
sets: acc.sets + r.sets,
empty: acc.empty + (r.exercises === 0 ? 1 : 0),
}),
{ days: 0, exercises: 0, sets: 0, empty: 0 },
);
return (
<Card>
<H2>{title || 'Bez tytułu'}</H2>
<div className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-dim text-[0.875rem]">
<span className="inline-flex items-center gap-1.5">
<MapPin className="w-4 h-4" />
{gymName ?? 'bez siłowni'}
</span>
<span>{startDate ? `start: ${fmtDate(startDate)}` : 'szkic — bez startu'}</span>
</div>
<div className="mt-4 divide-y divide-line">
{rows.map((r) => (
<div key={r.i} className="py-2.5">
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
<H3 className="mb-0">{r.alias || `Tydzień ${r.i + 1}`}</H3>
{r.exercises === 0 && <Badge color="yellow">bez ćwiczeń</Badge>}
<span className="text-dim text-[0.8125rem] sm:ml-auto">
{r.days.length > 0
? `${r.days.map((d) => DAY_NAMES[d.dayOfWeek].slice(0, 3)).join(', ')} · `
: ''}
{dayCountLabel(r.days.length)} · {exerciseCountLabel(r.exercises)} ·{' '}
{setCountLabel(r.sets)}
</span>
</div>
</div>
))}
</div>
<div className="mt-3 border-t border-line pt-3 text-dim text-[0.875rem]">
Łącznie: {dayCountLabel(totals.days)} · {exerciseCountLabel(totals.exercises)} ·{' '}
{setCountLabel(totals.sets)}
{totals.empty > 0 && (
<span className="text-warn"> · {weekCountLabel(totals.empty)} bez ćwiczeń</span>
)}
</div>
</Card>
);
}

View File

@@ -1,9 +1,10 @@
import type { ReactNode } from 'react';
import { Copy, Trash2 } from 'lucide-react';
import { Badge, Button, Card, H2, type BadgeColor } from '../../../components/ui';
import { Badge, Button, Card, Field, H2, Input, type BadgeColor } from '../../../components/ui';
/* Panel tygodnia (zamiast akordeonu): nagłówek z badge podsumowania + akcje,
treść zawsze widoczna — przełączanie tygodni odbywa się przez zakładki. */
opcjonalny alias tygodnia, treść zawsze widoczna — przełączanie tygodni
odbywa się przez zakładki. */
export function WeekPanel({
index,
summary,
@@ -11,6 +12,8 @@ export function WeekPanel({
onCopyPrev,
canClear,
onClear,
alias,
onAliasChange,
children,
}: {
index: number;
@@ -19,6 +22,9 @@ export function WeekPanel({
onCopyPrev: () => void;
canClear: boolean;
onClear: () => void;
/** Opcjonalny alias tygodnia (np. „Deload"); undefined = pole ukryte. */
alias?: string;
onAliasChange?: (v: string) => void;
children: ReactNode;
}) {
return (
@@ -41,6 +47,18 @@ export function WeekPanel({
)}
</div>
</div>
{alias !== undefined && onAliasChange && (
<div className="mt-4 max-w-xs">
<Field label="Nazwa tygodnia (opcjonalnie)">
<Input
value={alias}
onChange={(e) => onAliasChange(e.target.value)}
placeholder="np. Deload"
maxLength={40}
/>
</Field>
</div>
)}
<div className="mt-4">{children}</div>
</Card>
);

View File

@@ -19,12 +19,20 @@ export interface EditorDay {
export interface EditorWeek {
days: EditorDay[];
detached: boolean;
/** Opcjonalny alias tygodnia (np. „Deload"); '' = bez aliasu. */
customName: string;
}
export const DEFAULT_SET: EditorSet = { reps: '10', loadKg: '20', restSec: '90', rir: '2', difficulty: '3' };
export const DEFAULT_SET: EditorSet = {
reps: '10',
loadKg: '20',
restSec: '90',
rir: '2',
difficulty: '3',
};
export function emptyWeek(): EditorWeek {
return { days: [], detached: false };
return { days: [], detached: false, customName: '' };
}
export function displayedDaysOf(ws: EditorWeek[], wi: number): EditorDay[] {
@@ -33,8 +41,25 @@ export function displayedDaysOf(ws: EditorWeek[], wi: number): EditorDay[] {
return ws[0].days;
}
export function weekFromApi(week: { index: number; days: { dayOfWeek: number; exercises: { exerciseId: string; sets: { reps: number | null; loadKg: number | null; restSec: number | null; rir: number | null; difficulty: number | null }[] }[] }[] }): EditorWeek {
export function weekFromApi(week: {
index: number;
customName?: string | null;
days: {
dayOfWeek: number;
exercises: {
exerciseId: string;
sets: {
reps: number | null;
loadKg: number | null;
restSec: number | null;
rir: number | null;
difficulty: number | null;
}[];
}[];
}[];
}): EditorWeek {
return {
customName: week.customName ?? '',
days: week.days.map((d) => ({
dayOfWeek: d.dayOfWeek,
exercises: d.exercises.map((e) => ({

View File

@@ -6,6 +6,8 @@ import { DEFAULT_SET, emptyWeek, weekFromApi, type EditorSet, type EditorWeek }
export interface PlanLike {
title: string;
weeksCount: number;
/** Informacyjna — siłownia planu; null = bez siłowni. */
gym?: { id: string; name: string } | null;
weeks: Parameters<typeof weekFromApi>[0][];
}
@@ -21,17 +23,19 @@ export function usePlanEditorState() {
const [weeks, setWeeks] = useState<EditorWeek[]>(() =>
Array.from({ length: 4 }, () => emptyWeek()),
);
// Siłownia planu (informacyjna): null = „bez siłowni”.
const [gymId, setGymIdState] = useState<string | null>(null);
const [initialized, setInitialized] = useState(false);
// snapshot startowy: tryb nowy = stan początkowy; tryb edycji = po initFromPlan
const snapshotRef = useRef<string | null>(null);
if (snapshotRef.current === null) {
snapshotRef.current = JSON.stringify({ title, startDate, weeksCount, weeks });
snapshotRef.current = JSON.stringify({ title, startDate, weeksCount, weeks, gymId });
}
const dirty = useMemo(
() => JSON.stringify({ title, startDate, weeksCount, weeks }) !== snapshotRef.current,
[title, startDate, weeksCount, weeks],
() => JSON.stringify({ title, startDate, weeksCount, weeks, gymId }) !== snapshotRef.current,
[title, startDate, weeksCount, weeks, gymId],
);
/** Inicjalizacja trybu edycji po załadowaniu danych (zamiast setState during render). */
@@ -40,17 +44,20 @@ export function usePlanEditorState() {
setTitleState(plan.title);
setWeeksCountState(plan.weeksCount);
setWeeks(loaded);
setGymIdState(plan.gym?.id ?? null);
snapshotRef.current = JSON.stringify({
title: plan.title,
startDate: '',
weeksCount: plan.weeksCount,
weeks: loaded,
gymId: plan.gym?.id ?? null,
});
setInitialized(true);
}, []);
const setTitle = useCallback((v: string) => setTitleState(v), []);
const setStartDate = useCallback((v: string) => setStartDateState(v), []);
const setGymId = useCallback((v: string | null) => setGymIdState(v), []);
const setWeeksCount = useCallback((n: number) => {
setWeeksCountState(n);
@@ -58,7 +65,7 @@ export function usePlanEditorState() {
const next = [...ws];
while (next.length < n) {
const prev = next[next.length - 1] ?? emptyWeek();
next.push({ days: structuredClone(prev.days), detached: true });
next.push({ days: structuredClone(prev.days), detached: true, customName: '' });
}
return next.slice(0, n);
});
@@ -242,7 +249,12 @@ export function usePlanEditorState() {
if (wi === 0) return;
setWeeks((ws) => {
const prevDays = ws[wi - 1].detached ? ws[wi - 1].days : ws[0].days;
return ws.map((w, i) => (i === wi ? { days: structuredClone(prevDays), detached: true } : w));
// Alias tygodnia jest specyficzny — nie jest kopiowany z poprzedniego tygodnia.
return ws.map((w, i) =>
i === wi
? { days: structuredClone(prevDays), detached: true, customName: w.customName }
: w,
);
});
}, []);
@@ -252,16 +264,24 @@ export function usePlanEditorState() {
[],
);
/** Alias tygodnia (np. „Deload”) — bez odłączania dni od lustrzanego tygodnia 1. */
const setWeekAlias = useCallback((wi: number, v: string) => {
setWeeks((ws) => ws.map((w, i) => (i === wi ? { ...w, customName: v.slice(0, 40) } : w)));
}, []);
return {
title,
startDate,
weeksCount,
weeks,
gymId,
initialized,
dirty,
setTitle,
setStartDate,
setGymId,
setWeeksCount,
setWeekAlias,
initFromPlan,
addDay,
removeDay,

View File

@@ -39,7 +39,11 @@ export function TraineePlansTab({ userId }: { userId: string }) {
const { data, isLoading, error } = useTraineePlans(userId);
const { data: meData } = useMe();
const [selectedId, setSelectedId] = useState<string | null>(null);
const { data: detail, isLoading: detailLoading, error: detailError } = useTraineePlan(userId, selectedId ?? '');
const {
data: detail,
isLoading: detailLoading,
error: detailError,
} = useTraineePlan(userId, selectedId ?? '');
const [startDate, setStartDate] = useState('');
const [actionError, setActionError] = useState('');
const [busy, setBusy] = useState(false);
@@ -96,7 +100,10 @@ export function TraineePlansTab({ userId }: { userId: string }) {
const st = PLAN_STATUS[p.status];
const isSel = p.id === selectedId;
return (
<div key={p.id} className={isSel ? 'rounded-xl bg-accent/10 px-2 py-3' : 'px-1 py-3'}>
<div
key={p.id}
className={isSel ? 'rounded-xl bg-accent/10 px-2 py-3' : 'px-1 py-3'}
>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
<button
type="button"
@@ -107,8 +114,12 @@ export function TraineePlansTab({ userId }: { userId: string }) {
</button>
<Badge color={st.color}>{st.label}</Badge>
<Muted className="text-[0.875rem]">{p.weeksCount} tyg.</Muted>
{p.startDate && <Muted className="text-[0.875rem]">start {fmtDate(p.startDate)}</Muted>}
{creatorLabel(p) && <Muted className="text-[0.875rem]">{creatorLabel(p)}</Muted>}
{p.startDate && (
<Muted className="text-[0.875rem]">start {fmtDate(p.startDate)}</Muted>
)}
{creatorLabel(p) && (
<Muted className="text-[0.875rem]">{creatorLabel(p)}</Muted>
)}
</div>
{isSel && (
@@ -125,10 +136,18 @@ export function TraineePlansTab({ userId }: { userId: string }) {
actionError={actionError}
startDate={startDate}
onStartDateChange={setStartDate}
onActivate={() => setConfirm({ type: 'activate', planId: selectedDetail.id })}
onDelete={() => setConfirm({ type: 'delete', planId: selectedDetail.id })}
onComplete={() => setConfirm({ type: 'complete', planId: selectedDetail.id })}
onAbandon={() => setConfirm({ type: 'abandon', planId: selectedDetail.id })}
onActivate={() =>
setConfirm({ type: 'activate', planId: selectedDetail.id })
}
onDelete={() =>
setConfirm({ type: 'delete', planId: selectedDetail.id })
}
onComplete={() =>
setConfirm({ type: 'complete', planId: selectedDetail.id })
}
onAbandon={() =>
setConfirm({ type: 'abandon', planId: selectedDetail.id })
}
activateDisabled={hasActivePlan}
hint={
hasActivePlan
@@ -139,8 +158,13 @@ export function TraineePlansTab({ userId }: { userId: string }) {
</div>
{selectedDetail.weeks.map((w) => (
<div key={w.id} className="mb-3">
<H3 className="mb-1.5">Tydzień {w.index + 1}</H3>
{w.days.length === 0 && <p className="text-dim">Brak dni treningowych.</p>}
<div className="mb-1.5 flex items-center gap-2">
<H3 className="mb-0">Tydzień {w.index + 1}</H3>
{w.customName && <Badge color="blue">{w.customName}</Badge>}
</div>
{w.days.length === 0 && (
<p className="text-dim">Brak dni treningowych.</p>
)}
<div className="divide-y divide-line">
{w.days.map((d) => (
<PlanDayRow key={d.id} day={d} showDate />