Silownie: Wciaz tu jestem jako globalny modal keep-alive (20 min bez aktywnosci = pytanie, heartbeat albo wymeldowanie) zamiast przycisku w topbarze sirowni
This commit is contained in:
@@ -143,10 +143,11 @@ export function useGymDetail(id: string | undefined) {
|
||||
|
||||
// ---------- bytność (check-in, live occupancy) ----------
|
||||
/** Aktywna bytność zalogowanego — podstawa przycisków „Idę ćwiczyć / Wychodzę / Wciąż tu jestem". */
|
||||
export function useActivePresence() {
|
||||
export function useActivePresence(refetchIntervalMs?: number) {
|
||||
return useQuery({
|
||||
queryKey: ['me', 'presence'],
|
||||
queryFn: () => api<{ presence: ActivePresence | null }>('/me/presence'),
|
||||
refetchInterval: refetchIntervalMs,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
} from '../api/queries';
|
||||
import { ThemeToggle, LanguageToggle, Button } from './ui';
|
||||
import { ToastProvider } from './toast';
|
||||
import { PresenceKeepAliveModal } from './presence/PresenceKeepAliveModal';
|
||||
import { Topbar } from '../topbar';
|
||||
import { Brandmark } from './Brandmark';
|
||||
import { Avatar } from './Avatar';
|
||||
@@ -382,6 +383,8 @@ export default function Layout() {
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
{/* globalne przypomnienie o bytności — niezależne od aktywnej strony */}
|
||||
<PresenceKeepAliveModal />
|
||||
</ToastProvider>
|
||||
);
|
||||
}
|
||||
|
||||
99
app/src/components/presence/PresenceKeepAliveModal.tsx
Normal file
99
app/src/components/presence/PresenceKeepAliveModal.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { Button, Modal } from '../ui';
|
||||
import { checkOutPresence, presenceHeartbeat, useActivePresence } from '../../api/queries';
|
||||
import { fmtTime } from '../../lib/format';
|
||||
|
||||
// Przypomnienie o bytności: brak jakiejkolwiek aktywności (zapisy w sesji,
|
||||
// heartbeat z ekranu treningu) od 20 min — czyli 10 min przed wygaśnięciem slotu (30 min).
|
||||
const PROMPT_AFTER_MS = 20 * 60_000;
|
||||
// Zamknięcie okna bez odpowiedzi = kolejne pytanie po 5 min (nie blokujemy aplikacji).
|
||||
const SNOOZE_MS = 5 * 60_000;
|
||||
// Co minutę odświeżamy aktywną bytność i zegar (tańsze niż osobny timer na godzinę).
|
||||
const POLL_MS = 60_000;
|
||||
|
||||
/**
|
||||
* Globalny modal „Nadal jesteś na siłowni?” (montowany w Layout).
|
||||
* Wyskakuje sam, gdy aktywny meldunek długo nie ma aktywności — user potwierdza
|
||||
* pobyt („Wciąż tu jestem” = heartbeat) albo wymeldowuje się („Wychodzę”).
|
||||
* Zastępuje ręczny przycisk odświeżania slotu: kontrolka istnieje w jednym miejscu.
|
||||
*/
|
||||
export function PresenceKeepAliveModal() {
|
||||
const { t } = useTranslation('presence');
|
||||
const queryClient = useQueryClient();
|
||||
const { data } = useActivePresence(POLL_MS);
|
||||
const presence = data?.presence ?? null;
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
const [snoozedUntil, setSnoozedUntil] = useState(0);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!presence) return;
|
||||
const id = window.setInterval(() => setNow(Date.now()), POLL_MS);
|
||||
return () => window.clearInterval(id);
|
||||
// nowy meldunek (id) = nowy cykl pomiaru beztczynności
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [presence?.id, presence == null]);
|
||||
|
||||
if (!presence || presence.status !== 'ACTIVE') return null;
|
||||
|
||||
const idleMs = now - new Date(presence.lastActivityAt).getTime();
|
||||
const open = idleMs >= PROMPT_AFTER_MS && now >= snoozedUntil;
|
||||
|
||||
const invalidatePresence = async () => {
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: ['me', 'presence'] }),
|
||||
queryClient.invalidateQueries({ queryKey: ['gyms'] }),
|
||||
]);
|
||||
};
|
||||
|
||||
const stay = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await presenceHeartbeat();
|
||||
await invalidatePresence();
|
||||
} catch {
|
||||
// awaria sieciowa: modal zostaje otwarty, polling spróbuje ponownie
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const leave = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await checkOutPresence();
|
||||
await invalidatePresence();
|
||||
} catch {
|
||||
// jw. — wymeldowanie można ponowić przy następnym pokazie
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={() => setSnoozedUntil(Date.now() + SNOOZE_MS)}
|
||||
title={t('keepAlive.title')}
|
||||
>
|
||||
<p className="mb-4 text-[0.9rem] text-dim">
|
||||
{t('keepAlive.body', { gym: presence.gymName, from: fmtTime(presence.checkedInAt) })}
|
||||
</p>
|
||||
<div className="flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => void leave()}
|
||||
disabled={busy}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
{t('keepAlive.leave')}
|
||||
</Button>
|
||||
<Button onClick={() => void stay()} disabled={busy} className="w-full sm:w-auto">
|
||||
{t('keepAlive.stay')}
|
||||
</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -5,8 +5,12 @@
|
||||
"checkingIn": "Checking in…",
|
||||
"checkedInHere": "You're in since {{time}}",
|
||||
"checkOut": "Check out",
|
||||
"stillHere": "I'm still here",
|
||||
"stillHereDone": "Slot refreshed",
|
||||
"keepAlive": {
|
||||
"title": "Still at the gym?",
|
||||
"body": "Your check-in at \"{{gym}}\" (since {{from}}) has had no activity for a while. Confirm you're still working out, or check out.",
|
||||
"stay": "I'm still here",
|
||||
"leave": "I'm leaving"
|
||||
},
|
||||
"activeElsewhere": "You are checked in at {{gym}}.",
|
||||
"switchHere": "Switch to this gym",
|
||||
"virtualNotice": "This is a virtual gym — check-in only works for real gyms.",
|
||||
|
||||
@@ -5,8 +5,12 @@
|
||||
"checkingIn": "Melduję…",
|
||||
"checkedInHere": "Jesteś od {{time}}",
|
||||
"checkOut": "Wychodzę",
|
||||
"stillHere": "Wciąż tu jestem",
|
||||
"stillHereDone": "Slot odświeżony",
|
||||
"keepAlive": {
|
||||
"title": "Nadal jesteś na siłowni?",
|
||||
"body": "Meldunek w „{{gym}}” (od {{from}}) nie ma już dawno żadnej aktywności. Potwierdź, że wciąż ćwiczysz, albo się wymelduj.",
|
||||
"stay": "Wciąż tu jestem",
|
||||
"leave": "Wychodzę"
|
||||
},
|
||||
"activeElsewhere": "Jesteś zameldowany w siłowni {{gym}}.",
|
||||
"switchHere": "Przepnij na tę siłownię",
|
||||
"virtualNotice": "To wirtualna siłownia — meldunek działa tylko na realnych siłowniach.",
|
||||
|
||||
@@ -22,7 +22,6 @@ import {
|
||||
deleteGym,
|
||||
deleteGymAnnouncement,
|
||||
deleteGymException,
|
||||
presenceHeartbeat,
|
||||
useActivePresence,
|
||||
useGymAnnouncements,
|
||||
useGymDetail,
|
||||
@@ -445,18 +444,6 @@ export default function GymDetail() {
|
||||
}
|
||||
};
|
||||
|
||||
const doStillHere = async () => {
|
||||
setPresenceBusy(true);
|
||||
try {
|
||||
await presenceHeartbeat();
|
||||
push(tp('stillHereDone'), 'info');
|
||||
} catch (e) {
|
||||
push((e as Error).message, 'error');
|
||||
} finally {
|
||||
setPresenceBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async () => {
|
||||
if (!gym) return;
|
||||
setBusy(true);
|
||||
@@ -580,16 +567,12 @@ export default function GymDetail() {
|
||||
: undefined;
|
||||
|
||||
// Meldunek bytności (REAL) — akcje dla każdego użytkownika siłowni.
|
||||
// „Wciąż tu jestem” celowo NIE ma tu przycisku: odświeżanie slotu obsługuje
|
||||
// globalny PresenceKeepAliveModal (1 kontrolka = 1 miejsce).
|
||||
const presenceActions: TopbarAction[] | undefined =
|
||||
gym && gym.kind === 'REAL'
|
||||
? presence && presence.gymId === gym.id
|
||||
? [
|
||||
{
|
||||
label: tp('stillHere'),
|
||||
variant: 'secondary',
|
||||
disabled: presenceBusy,
|
||||
onClick: () => void doStillHere(),
|
||||
},
|
||||
{
|
||||
label: tp('checkOut'),
|
||||
variant: 'secondary',
|
||||
|
||||
@@ -1812,9 +1812,11 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ checkedOut: true }) });
|
||||
});
|
||||
|
||||
page.route('**/api/v1/me/presence/heartbeat', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ touched: activePresence != null }) }),
|
||||
);
|
||||
page.route('**/api/v1/me/presence/heartbeat', (route) => {
|
||||
// heartbeat odświeża slot — globalny modal keep-alive zamyka się po potwierdzeniu
|
||||
if (activePresence) activePresence.lastActivityAt = new Date().toISOString();
|
||||
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ touched: activePresence != null }) });
|
||||
});
|
||||
|
||||
page.route('**/api/v1/me/presence/history*', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ visits: presenceVisits }) }),
|
||||
|
||||
@@ -82,9 +82,10 @@ test('meldunek i wymeldowanie z menu kontekstowego siłowni + licznik „teraz
|
||||
await page.getByRole('button', { name: 'Idę ćwiczyć' }).click();
|
||||
await expect(page.getByText('Zameldowany — udanego treningu')).toBeVisible();
|
||||
|
||||
// po meldunku: akcje „Wciąż tu jestem” + „Wychodzę”, licznik rośnie
|
||||
// po meldunku: akcja „Wychodzę”, licznik rośnie (brak przycisku „Wciąż tu jestem” —
|
||||
// odświeżanie slotu to globalny modal keep-alive, nie kontrolka w topbarze)
|
||||
await expect(page.getByRole('button', { name: 'Wychodzę' })).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: 'Wciąż tu jestem' })).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: 'Wciąż tu jestem' })).not.toBeVisible();
|
||||
await expect(page.getByText('teraz: 1 osoba')).toBeVisible();
|
||||
|
||||
await page.getByRole('button', { name: 'Wychodzę' }).click();
|
||||
@@ -248,3 +249,38 @@ test('profil → historia treningów: sekcja „Moje wizyty” z listą wizyt',
|
||||
await expect(page.getByText('75 min', { exact: true })).toBeVisible();
|
||||
await expect(page.getByText('QR', { exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
function stalePresence(): Record<string, unknown> {
|
||||
// meldunek bez żadnej aktywności od 25 min — próg globalnego modala keep-alive (20 min)
|
||||
return {
|
||||
id: 'presence-1',
|
||||
gymId: 'gym-1',
|
||||
gymName: 'Żelazna Świątynia',
|
||||
status: 'ACTIVE',
|
||||
source: 'QR',
|
||||
checkedInAt: new Date(Date.now() - 40 * 60_000).toISOString(),
|
||||
lastActivityAt: new Date(Date.now() - 25 * 60_000).toISOString(),
|
||||
closedAt: null,
|
||||
durationMinutes: 0,
|
||||
};
|
||||
}
|
||||
|
||||
test('globalny modal keep-alive: po 20+ min bez aktywności wyskakuje sam, „Wciąż tu jestem” zamyka', async ({ page }) => {
|
||||
mockApi(page, { presence: stalePresence() });
|
||||
await login(page);
|
||||
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog.getByText('Nadal jesteś na siłowni?')).toBeVisible();
|
||||
await dialog.getByRole('button', { name: 'Wciąż tu jestem' }).click();
|
||||
await expect(dialog).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('globalny modal keep-alive: „Wychodzę” wymeldowuje i zamyka modal', async ({ page }) => {
|
||||
mockApi(page, { presence: stalePresence() });
|
||||
await login(page);
|
||||
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog.getByText('Nadal jesteś na siłowni?')).toBeVisible();
|
||||
await dialog.getByRole('button', { name: 'Wychodzę' }).click();
|
||||
await expect(dialog).toHaveCount(0);
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
@@ -9,6 +9,7 @@ import { setAccessToken } from '../src/api/client';
|
||||
import type { ActivePresence, User } from '../src/api/types';
|
||||
import GymQrModal from '../src/components/gyms/GymQrModal';
|
||||
import StartTrainingPresenceModal from '../src/components/presence/StartTrainingPresenceModal';
|
||||
import { PresenceKeepAliveModal } from '../src/components/presence/PresenceKeepAliveModal';
|
||||
|
||||
// QR generowany przez stub — w jsdom canvas może być niedostępny
|
||||
vi.mock('qrcode', () => ({
|
||||
@@ -41,7 +42,11 @@ function jsonResponse(status: number, body: unknown) {
|
||||
});
|
||||
}
|
||||
|
||||
function presence(gymId: string, gymName: string): ActivePresence {
|
||||
function presence(gymId: string, gymName: string, idleMinutes = 0): ActivePresence {
|
||||
// świeże znaczniki czasu — inaczej globalny modal keep-alive (Layout)
|
||||
// wyskakiwałby w testach razem z upływem czasu rzeczywistego
|
||||
const checkedInAt = new Date(Date.now() - (idleMinutes + 15) * 60_000).toISOString();
|
||||
const lastActivityAt = new Date(Date.now() - idleMinutes * 60_000).toISOString();
|
||||
return {
|
||||
id: 'p1',
|
||||
gymId,
|
||||
@@ -49,8 +54,8 @@ function presence(gymId: string, gymName: string): ActivePresence {
|
||||
gymCapacity: 50,
|
||||
status: 'ACTIVE',
|
||||
source: 'MANUAL',
|
||||
checkedInAt: '2026-10-23T16:00:00.000Z',
|
||||
lastActivityAt: '2026-10-23T16:00:00.000Z',
|
||||
checkedInAt,
|
||||
lastActivityAt,
|
||||
closedAt: null,
|
||||
};
|
||||
}
|
||||
@@ -283,3 +288,69 @@ describe('Modal rozpoczęcia treningu', () => {
|
||||
expect(onContinue).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Globalny modal keep-alive bytności', () => {
|
||||
function stubPresenceFetch(initial: ActivePresence | null) {
|
||||
let current = initial;
|
||||
const calls: { url: string; method: string }[] = [];
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = String(input);
|
||||
const method = init?.method || 'GET';
|
||||
calls.push({ url, method });
|
||||
if (url.includes('/me/presence/heartbeat') && method === 'POST') {
|
||||
if (current) current = { ...current, lastActivityAt: new Date().toISOString() };
|
||||
return jsonResponse(200, { touched: current != null });
|
||||
}
|
||||
if (url.includes('/me/presence/check-out') && method === 'POST') {
|
||||
current = null;
|
||||
return jsonResponse(200, { checkedOut: true });
|
||||
}
|
||||
if (url.includes('/me/presence')) return jsonResponse(200, { presence: current });
|
||||
throw new Error(`Unexpected fetch: ${url}`);
|
||||
}),
|
||||
);
|
||||
return calls;
|
||||
}
|
||||
|
||||
it('po 20+ min bez aktywności modal wyskakuje sam, „Wciąż tu jestem” odświeża i zamyka', async () => {
|
||||
setAccessToken('tok-1');
|
||||
const calls = stubPresenceFetch(presence('gym-1', 'Żelazna Świątynia', 25));
|
||||
renderIsolated(<PresenceKeepAliveModal />);
|
||||
|
||||
expect(await screen.findByText('Nadal jesteś na siłowni?')).toBeInTheDocument();
|
||||
expect(screen.getByText(/Żelazna Świątynia/)).toBeInTheDocument();
|
||||
|
||||
const tester = userEvent.setup();
|
||||
await tester.click(screen.getByRole('button', { name: 'Wciąż tu jestem' }));
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByText('Nadal jesteś na siłowni?')).not.toBeInTheDocument(),
|
||||
);
|
||||
expect(calls.some((c) => c.method === 'POST' && c.url.includes('heartbeat'))).toBe(true);
|
||||
});
|
||||
|
||||
it('„Wychodzę” wymeldowuje i zamyka modal', async () => {
|
||||
setAccessToken('tok-1');
|
||||
const calls = stubPresenceFetch(presence('gym-1', 'Żelazna Świątynia', 25));
|
||||
renderIsolated(<PresenceKeepAliveModal />);
|
||||
|
||||
expect(await screen.findByText('Nadal jesteś na siłowni?')).toBeInTheDocument();
|
||||
const tester = userEvent.setup();
|
||||
await tester.click(screen.getByRole('button', { name: 'Wychodzę' }));
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByText('Nadal jesteś na siłowni?')).not.toBeInTheDocument(),
|
||||
);
|
||||
expect(calls.some((c) => c.method === 'POST' && c.url.includes('check-out'))).toBe(true);
|
||||
});
|
||||
|
||||
it('świeży meldunek (<20 min aktywności): modal się nie pokazuje', async () => {
|
||||
setAccessToken('tok-1');
|
||||
const calls = stubPresenceFetch(presence('gym-1', 'Żelazna Świątynia', 5));
|
||||
renderIsolated(<PresenceKeepAliveModal />);
|
||||
|
||||
// czekamy aż zapytanie o bytność realnie się wykona, potem brak modala
|
||||
await waitFor(() => expect(calls.some((c) => c.url.includes('/me/presence'))).toBe(true));
|
||||
expect(screen.queryByText('Nadal jesteś na siłowni?')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user