Aplikacja: trasy /trainees tylko dla trenerow, tykajacy licznik sesji na dashboardzie, blokady podwojnego wysylania formularzy/sesji
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useEffect, type ReactNode } from 'react';
|
||||
import { Routes, Route, Navigate } from 'react-router-dom';
|
||||
import { useAuth } from './store/auth';
|
||||
import { useMe } from './api/queries';
|
||||
import Layout from './components/Layout';
|
||||
import Login from './pages/Login';
|
||||
import Register from './pages/Register';
|
||||
@@ -24,6 +25,18 @@ import Invitations from './pages/Invitations';
|
||||
import Messages from './pages/messages/Messages';
|
||||
import MessageThread from './pages/messages/MessageThread';
|
||||
|
||||
/**
|
||||
* Trasa tylko dla trenerów — API i tak odda 403, ale nie pokazujemy pustej
|
||||
* karty. Do czasu wczytania /me children zostają zamontowane (strony same
|
||||
* pokazują szkielety), więc redirect nie powoduje przeładowania komponentów.
|
||||
*/
|
||||
function TrainerOnly({ children }: { children: ReactNode }) {
|
||||
const { data, isLoading } = useMe();
|
||||
const isTrainer = (data?.memberships ?? []).some((m) => m.roles.includes('TRAINER'));
|
||||
if (!isLoading && data && !isTrainer) return <Navigate to="/" replace />;
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const { user, ready, init } = useAuth();
|
||||
|
||||
@@ -49,10 +62,38 @@ export default function App() {
|
||||
<Route path="/day/:dayId" element={<DayExecution />} />
|
||||
<Route path="/gyms" element={<Gyms />} />
|
||||
<Route path="/gyms/:id" element={<GymDetail />} />
|
||||
<Route path="/trainees" element={<Trainees />} />
|
||||
<Route path="/trainees/:userId" element={<TraineeDetail />} />
|
||||
<Route path="/trainees/:userId/plans/new" element={<PlanEditor />} />
|
||||
<Route path="/trainees/:userId/plans/:planId/edit" element={<PlanEditor />} />
|
||||
<Route
|
||||
path="/trainees"
|
||||
element={
|
||||
<TrainerOnly>
|
||||
<Trainees />
|
||||
</TrainerOnly>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/trainees/:userId"
|
||||
element={
|
||||
<TrainerOnly>
|
||||
<TraineeDetail />
|
||||
</TrainerOnly>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/trainees/:userId/plans/new"
|
||||
element={
|
||||
<TrainerOnly>
|
||||
<PlanEditor />
|
||||
</TrainerOnly>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/trainees/:userId/plans/:planId/edit"
|
||||
element={
|
||||
<TrainerOnly>
|
||||
<PlanEditor />
|
||||
</TrainerOnly>
|
||||
}
|
||||
/>
|
||||
<Route path="/invitations" element={<Invitations />} />
|
||||
<Route path="/messages" element={<Messages />} />
|
||||
<Route path="/messages/:coachingId" element={<MessageThread />} />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { useEffect, useState, type ReactNode } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { CalendarPlus, Dumbbell, Flame, Play } from 'lucide-react';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
@@ -20,6 +20,16 @@ function fmtElapsed(fromIso: string): string {
|
||||
return h > 0 ? `${h}:${mm}:${ss}` : `${m}:${ss}`;
|
||||
}
|
||||
|
||||
/* Prze-renderowanie co sekundę, dopóki trwa sesja (bez tego licznik stygnie). */
|
||||
function useTick(active: boolean) {
|
||||
const [, setN] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
const id = setInterval(() => setN((n) => n + 1), 1000);
|
||||
return () => clearInterval(id);
|
||||
}, [active]);
|
||||
}
|
||||
|
||||
/* Numer tygodnia planu od startDate (1-based). */
|
||||
function planWeekNo(startDate: string | null): number | null {
|
||||
if (!startDate) return null;
|
||||
@@ -42,7 +52,14 @@ function Sparkline({ value }: { value: number }) {
|
||||
}
|
||||
const last = pts[pts.length - 1].split(',');
|
||||
return (
|
||||
<svg aria-hidden="true" className="mt-1.5" width={w} height={h} viewBox={`0 0 ${w} ${h}`} fill="none">
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
className="mt-1.5"
|
||||
width={w}
|
||||
height={h}
|
||||
viewBox={`0 0 ${w} ${h}`}
|
||||
fill="none"
|
||||
>
|
||||
<polyline
|
||||
points={pts.join(' ')}
|
||||
stroke="var(--accent)"
|
||||
@@ -156,12 +173,18 @@ function SessionHero({
|
||||
<span className="live-dot" aria-hidden="true" />
|
||||
Trwa trening
|
||||
</div>
|
||||
<div className="mt-0.5 truncate font-display text-[1.3rem] font-bold tracking-[-0.01em]">{title}</div>
|
||||
<div className="mt-0.5 truncate font-display text-[1.3rem] font-bold tracking-[-0.01em]">
|
||||
{title}
|
||||
</div>
|
||||
<div className="mt-0.5 text-dim text-[0.8125rem]">{subtitle}</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div className="font-display text-[1.6rem] font-bold leading-none tabular-nums">{elapsed}</div>
|
||||
<div className="mt-1 text-[11px] font-bold uppercase tracking-[0.1em] text-dim">czas sesji</div>
|
||||
<div className="font-display text-[1.6rem] font-bold leading-none tabular-nums">
|
||||
{elapsed}
|
||||
</div>
|
||||
<div className="mt-1 text-[11px] font-bold uppercase tracking-[0.1em] text-dim">
|
||||
czas sesji
|
||||
</div>
|
||||
</div>
|
||||
<Link to={to} className="shrink-0">
|
||||
<Button>
|
||||
@@ -217,6 +240,7 @@ export default function Dashboard() {
|
||||
const { data, isLoading, error } = useDashboard();
|
||||
const { data: activeData } = useActiveSession();
|
||||
const active = activeData?.session ?? null;
|
||||
useTick(!!active);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
@@ -238,11 +262,16 @@ export default function Dashboard() {
|
||||
|
||||
const now = new Date();
|
||||
const greeting = now.getHours() >= 18 ? 'Dobry wieczór' : 'Dzień dobry';
|
||||
const dateLine = now.toLocaleDateString('pl-PL', { weekday: 'long', day: 'numeric', month: 'long' });
|
||||
const dateLine = now.toLocaleDateString('pl-PL', {
|
||||
weekday: 'long',
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
});
|
||||
const weekNo = planWeekNo(data.activePlan?.startDate ?? null);
|
||||
const subParts = [dateLine, weekNo != null && data.activePlan ? `tydzień ${weekNo} planu` : null].filter(
|
||||
Boolean,
|
||||
);
|
||||
const subParts = [
|
||||
dateLine,
|
||||
weekNo != null && data.activePlan ? `tydzień ${weekNo} planu` : null,
|
||||
].filter(Boolean);
|
||||
|
||||
const nextDate = data.nextTraining?.date ?? null;
|
||||
const nextIsToday = nextDate != null && nextDate.slice(0, 10) === todayStr();
|
||||
@@ -300,7 +329,9 @@ export default function Dashboard() {
|
||||
<Card className="mb-0 flex min-w-0 items-center gap-4 p-5">
|
||||
<ProgressRing percent={progress?.percent ?? 0} />
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] font-bold uppercase tracking-[0.1em] text-dim">Postęp planu</div>
|
||||
<div className="text-[11px] font-bold uppercase tracking-[0.1em] text-dim">
|
||||
Postęp planu
|
||||
</div>
|
||||
<div className="mt-1 text-dim text-[0.8125rem]">
|
||||
{progress ? `${progress.completed} z ${progress.total} dni` : 'brak aktywnego planu'}
|
||||
{daysLeft != null && daysLeft > 0 ? ` · ${daysLeft} dni do końca` : ''}
|
||||
@@ -352,10 +383,10 @@ export default function Dashboard() {
|
||||
))}
|
||||
</ul>
|
||||
<Link to={`/day/${data.nextTraining.dayId}`} className="mt-4 block">
|
||||
<Button className="w-full sm:w-auto">
|
||||
<Play className="h-4 w-4" />
|
||||
{active?.dayId === data.nextTraining.dayId ? 'Wróć do treningu' : 'Wykonaj trening'}
|
||||
</Button>
|
||||
<Button className="w-full sm:w-auto">
|
||||
<Play className="h-4 w-4" />
|
||||
{active?.dayId === data.nextTraining.dayId ? 'Wróć do treningu' : 'Wykonaj trening'}
|
||||
</Button>
|
||||
</Link>
|
||||
</>
|
||||
) : (
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState, type ReactNode } from 'react';
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { Check, ChevronDown, Plus, Trash2 } from 'lucide-react';
|
||||
@@ -579,13 +579,19 @@ export default function DayExecution() {
|
||||
: undefined,
|
||||
});
|
||||
|
||||
// podwójny klik nie może wysłać dwóch żądań (serwer zbiłby drugie 400)
|
||||
const addingRef = useRef(false);
|
||||
|
||||
const addExercise = async (exerciseId: string) => {
|
||||
if (!session) return;
|
||||
if (!session || addingRef.current) return;
|
||||
addingRef.current = true;
|
||||
try {
|
||||
await addSessionExercise(session.id, exerciseId);
|
||||
await queryClient.invalidateQueries({ queryKey: ['sessions', session.id] });
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Błąd');
|
||||
} finally {
|
||||
addingRef.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -600,12 +606,15 @@ export default function DayExecution() {
|
||||
};
|
||||
|
||||
const addSet = async (exerciseId: string) => {
|
||||
if (!session) return;
|
||||
if (!session || addingRef.current) return;
|
||||
addingRef.current = true;
|
||||
try {
|
||||
await addSessionSet(exerciseId);
|
||||
await queryClient.invalidateQueries({ queryKey: ['sessions', session.id] });
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Błąd');
|
||||
} finally {
|
||||
addingRef.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState, type ReactNode } from 'react';
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { ChevronDown, Plus, Ruler, Scale, Trash2, type LucideIcon } from 'lucide-react';
|
||||
import {
|
||||
@@ -381,30 +381,47 @@ export default function ProfileBodyParameters() {
|
||||
if (available.length > 0 && !available.includes(month)) setMonth(available[0]);
|
||||
}, [monthsKey, month, setMonth]);
|
||||
|
||||
// ref (nie stan): drugi klik w tym samym ticku musi zobaczyć flagę natychmiast
|
||||
const savingRef = useRef(false);
|
||||
|
||||
const saveWeight = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!weight) return;
|
||||
await addWeight(parseFloat(weight), weightDate || undefined);
|
||||
setWeight('');
|
||||
setWeightDate(today());
|
||||
setAddOpen(false);
|
||||
await refetchBp();
|
||||
push('Waga dodana', 'success');
|
||||
if (!weight || savingRef.current) return;
|
||||
savingRef.current = true;
|
||||
try {
|
||||
await addWeight(parseFloat(weight), weightDate || undefined);
|
||||
setWeight('');
|
||||
setWeightDate(today());
|
||||
setAddOpen(false);
|
||||
await refetchBp();
|
||||
push('Waga dodana', 'success');
|
||||
} catch (err) {
|
||||
push(err instanceof Error ? err.message : 'Błąd zapisu', 'error');
|
||||
} finally {
|
||||
savingRef.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
const saveCirc = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!circValue) return;
|
||||
await addCircumference(
|
||||
measurementName(circType, circSide),
|
||||
parseFloat(circValue),
|
||||
circDate || undefined,
|
||||
);
|
||||
setCircValue('');
|
||||
setCircDate(today());
|
||||
setAddOpen(false);
|
||||
await refetchBp();
|
||||
push('Obwód dodany', 'success');
|
||||
if (!circValue || savingRef.current) return;
|
||||
savingRef.current = true;
|
||||
try {
|
||||
await addCircumference(
|
||||
measurementName(circType, circSide),
|
||||
parseFloat(circValue),
|
||||
circDate || undefined,
|
||||
);
|
||||
setCircValue('');
|
||||
setCircDate(today());
|
||||
setAddOpen(false);
|
||||
await refetchBp();
|
||||
push('Obwód dodany', 'success');
|
||||
} catch (err) {
|
||||
push(err instanceof Error ? err.message : 'Błąd zapisu', 'error');
|
||||
} finally {
|
||||
savingRef.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
const confirmRemove = async () => {
|
||||
|
||||
@@ -57,7 +57,15 @@ const TRAINEE_HISTORY = {
|
||||
muscle: 'legs',
|
||||
isExtra: false,
|
||||
comments: [],
|
||||
sets: [{ index: 0, reps: 10, rir: 2, difficulty: 3, planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 } }],
|
||||
sets: [
|
||||
{
|
||||
index: 0,
|
||||
reps: 10,
|
||||
rir: 2,
|
||||
difficulty: 3,
|
||||
planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'se-2',
|
||||
@@ -87,7 +95,8 @@ function mockApi() {
|
||||
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = String(input);
|
||||
const method = init?.method || 'GET';
|
||||
if (url.includes('/auth/login')) return jsonResponse(200, { user: TRAINER, accessToken: 'tok-1' });
|
||||
if (url.includes('/auth/login'))
|
||||
return jsonResponse(200, { user: TRAINER, accessToken: 'tok-1' });
|
||||
if (url.includes('/auth/refresh'))
|
||||
return jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'no cookie' } });
|
||||
if (url.includes('/messages/conversations/coaching-1')) {
|
||||
@@ -105,7 +114,14 @@ function mockApi() {
|
||||
plan: 'Plan testowy',
|
||||
exercise: {
|
||||
name: 'Przysiady',
|
||||
sets: [{ index: 0, reps: 10, rir: 2, planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 } }],
|
||||
sets: [
|
||||
{
|
||||
index: 0,
|
||||
reps: 10,
|
||||
rir: 2,
|
||||
planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 },
|
||||
},
|
||||
],
|
||||
},
|
||||
exercises: [],
|
||||
}
|
||||
@@ -143,12 +159,17 @@ function mockApi() {
|
||||
coachingId: 'coaching-1',
|
||||
role: 'trainer',
|
||||
other: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak' },
|
||||
lastMessage: { body: 'Dobrze się czuję', createdAt: '2026-08-24T10:00:00.000Z', senderId: 'trainee-1' },
|
||||
lastMessage: {
|
||||
body: 'Dobrze się czuję',
|
||||
createdAt: '2026-08-24T10:00:00.000Z',
|
||||
senderId: 'trainee-1',
|
||||
},
|
||||
unreadCount: 0,
|
||||
},
|
||||
],
|
||||
});
|
||||
if (url.includes('/trainer/trainees/trainee-1/history')) return jsonResponse(200, TRAINEE_HISTORY);
|
||||
if (url.includes('/trainer/trainees/trainee-1/history'))
|
||||
return jsonResponse(200, TRAINEE_HISTORY);
|
||||
if (url.includes('/trainer/trainees/trainee-1'))
|
||||
return jsonResponse(200, {
|
||||
coachingId: 'coaching-1',
|
||||
@@ -158,16 +179,30 @@ function mockApi() {
|
||||
activePlan: { id: 'plan-1', title: 'Plan testowy', startDate: '2026-08-01' },
|
||||
progress: { completed: 5, total: 14, percent: 36 },
|
||||
killstreak: 3,
|
||||
nextTraining: { dayId: 'day-1', date: '2026-08-26', exercises: [{ name: 'Przysiady', muscle: 'legs' }] },
|
||||
nextTraining: {
|
||||
dayId: 'day-1',
|
||||
date: '2026-08-26',
|
||||
exercises: [{ name: 'Przysiady', muscle: 'legs' }],
|
||||
},
|
||||
extra: null,
|
||||
missing: null,
|
||||
lastSessionAt: '2026-08-24T08:30:00.000Z',
|
||||
flags: ['no_session_7d'],
|
||||
});
|
||||
if (url.includes('/me/history')) return jsonResponse(200, { sessions: [] });
|
||||
if (url.includes('/me')) return jsonResponse(200, { user: TRAINER, memberships: [] });
|
||||
if (url.includes('/me'))
|
||||
return jsonResponse(200, {
|
||||
user: TRAINER,
|
||||
// wątek treningowy wymaga roli trenera (guard trasy /trainees/*)
|
||||
memberships: [{ gymId: 'gym-1', roles: ['TRAINER'] }],
|
||||
});
|
||||
if (url.includes('/dashboard'))
|
||||
return jsonResponse(200, { killstreak: 0, activePlan: null, nextTraining: null, progress: null });
|
||||
return jsonResponse(200, {
|
||||
killstreak: 0,
|
||||
activePlan: null,
|
||||
nextTraining: null,
|
||||
progress: null,
|
||||
});
|
||||
if (url.includes('/trainer/trainees')) return jsonResponse(200, { trainees: [] });
|
||||
if (url.includes('/trainer/invitations')) return jsonResponse(200, { invitations: [] });
|
||||
if (url.includes('/gyms/invitations')) return jsonResponse(200, { invitations: [] });
|
||||
|
||||
Reference in New Issue
Block a user