From d456a2af7ecb3550389e7fd47fab44a0a2aeef6b Mon Sep 17 00:00:00 2001 From: tisachi Date: Sun, 11 Oct 2026 17:56:54 +0200 Subject: [PATCH] Aplikacja: trasy /trainees tylko dla trenerow, tykajacy licznik sesji na dashboardzie, blokady podwojnego wysylania formularzy/sesji --- app/src/App.tsx | 51 ++++++++++++++-- app/src/pages/Dashboard.tsx | 59 ++++++++++++++----- app/src/pages/DayExecution.tsx | 15 ++++- .../pages/profile/ProfileBodyParameters.tsx | 55 +++++++++++------ app/test/message-thread.test.tsx | 51 +++++++++++++--- 5 files changed, 182 insertions(+), 49 deletions(-) diff --git a/app/src/App.tsx b/app/src/App.tsx index add9f5f..76ed8a1 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -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 ; + return <>{children}; +} + export default function App() { const { user, ready, init } = useAuth(); @@ -49,10 +62,38 @@ export default function App() { } /> } /> } /> - } /> - } /> - } /> - } /> + + + + } + /> + + + + } + /> + + + + } + /> + + + + } + /> } /> } /> } /> diff --git a/app/src/pages/Dashboard.tsx b/app/src/pages/Dashboard.tsx index 5d84d6c..19408eb 100644 --- a/app/src/pages/Dashboard.tsx +++ b/app/src/pages/Dashboard.tsx @@ -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 ( -
{title}
+
+ {title} +
{subtitle}
-
{elapsed}
-
czas sesji
+
+ {elapsed} +
+
+ czas sesji +
+ ) : ( diff --git a/app/src/pages/DayExecution.tsx b/app/src/pages/DayExecution.tsx index a127b01..27649b9 100644 --- a/app/src/pages/DayExecution.tsx +++ b/app/src/pages/DayExecution.tsx @@ -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; } }; diff --git a/app/src/pages/profile/ProfileBodyParameters.tsx b/app/src/pages/profile/ProfileBodyParameters.tsx index ac5aa02..3460552 100644 --- a/app/src/pages/profile/ProfileBodyParameters.tsx +++ b/app/src/pages/profile/ProfileBodyParameters.tsx @@ -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 () => { diff --git a/app/test/message-thread.test.tsx b/app/test/message-thread.test.tsx index 4a9b23b..4987fff 100644 --- a/app/test/message-thread.test.tsx +++ b/app/test/message-thread.test.tsx @@ -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: [] });