Feed: aktualnosci — powiadomienia + ogloszenia silni i platformy (karta na dashboardzie, strona /announcements, badge, CRUD ownera i admina)

This commit is contained in:
Tilumca
2026-10-15 02:12:22 +02:00
parent ac4ea4ae07
commit 0fe259a866
35 changed files with 2830 additions and 97 deletions

View File

@@ -18,6 +18,7 @@ import UserClaims from './pages/users/UserClaims';
import FocusAreas from './pages/catalog/FocusAreas';
import Exercises from './pages/catalog/Exercises';
import EquipmentCatalog from './pages/catalog/Equipment';
import Announcements from './pages/announcements/Announcements';
import Logs from './pages/Logs';
import VerificationsList, { VerificationDetail } from './pages/Verifications';
@@ -54,6 +55,7 @@ export default function App() {
<Route path="/equipment" element={<EquipmentCatalog />} />
<Route path="/verifications" element={<VerificationsList />} />
<Route path="/verifications/:id" element={<VerificationDetail />} />
<Route path="/announcements" element={<Announcements />} />
<Route path="/logs" element={<Logs />} />
</Route>
<Route path="*" element={<Navigate to="/" replace />} />

View File

@@ -316,3 +316,17 @@ export interface ExerciseProgress {
muscle: string;
points: ExerciseProgressPoint[];
}
export type AnnouncementKind = 'MANUAL' | 'HOURS_CHANGE' | 'EXCEPTION';
/** Ogłoszenie w widoku panelu admina (globalne lub per-siłownia). */
export interface AdminAnnouncement {
id: string;
gymId: string | null;
authorId: string | null;
kind: AnnouncementKind;
title: string;
body: string;
createdAt: string;
gymName: string | null;
}

View File

@@ -4,6 +4,7 @@ import {
Building2,
Dumbbell,
LogOut,
Megaphone,
Menu,
ScrollText,
ShieldCheck,
@@ -39,6 +40,7 @@ const SECTIONS: NavSection[] = [
{ to: '/gyms', label: 'Siłownie', icon: Building2, end: false },
{ to: '/verifications', label: 'Weryfikacje', icon: ShieldCheck, end: false },
{ to: '/users', label: 'Użytkownicy', icon: Users, end: false },
{ to: '/announcements', label: 'Ogłoszenia', icon: Megaphone, end: false },
],
},
{

View File

@@ -0,0 +1,262 @@
import { useEffect, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Megaphone, Pencil, Plus, Trash2 } from 'lucide-react';
import { api } from '../../api/client';
import type { AdminAnnouncement, Gym } from '../../api/types';
import { useTopbar } from '../../topbar';
import { useListSearch } from '../../store/list-search';
import { fmtDateTime } from '../../lib/format';
import {
Badge,
Button,
Card,
ConfirmDialog,
EmptyState,
ErrorText,
Field,
Input,
Loading,
Modal,
Muted,
Select,
Textarea,
} from '../../components/ui';
const KIND_LABELS: Record<
AdminAnnouncement['kind'],
{ label: string; color: 'blue' | 'yellow' | 'gray' }
> = {
MANUAL: { label: 'Ręczne', color: 'blue' },
HOURS_CHANGE: { label: 'Zmiana godzin', color: 'yellow' },
EXCEPTION: { label: 'Wyjątek', color: 'yellow' },
};
interface FormState {
title: string;
body: string;
/** '' = globalne (wszyscy userzy); inaczej id siłowni. */
gymId: string;
}
const EMPTY: FormState = { title: '', body: '', gymId: '' };
export default function Announcements() {
const qc = useQueryClient();
const { data, isLoading, error } = useQuery({
queryKey: ['admin-announcements'],
queryFn: () => api<{ announcements: AdminAnnouncement[] }>('/admin/announcements'),
});
const announcements = data?.announcements ?? [];
const { data: gymsData } = useQuery({
queryKey: ['gyms'],
queryFn: () => api<{ gyms: Gym[] }>('/admin/gyms'),
});
const gyms = gymsData?.gyms ?? [];
const query = useListSearch((s) => s.queries['announcements']);
const setQuery = useListSearch((s) => s.setQuery);
const filtered = query
? announcements.filter((a) =>
[a.title, a.body, a.gymName ?? 'Platforma'].some((s) =>
s.toLowerCase().includes(query.toLowerCase()),
),
)
: announcements;
useEffect(() => () => setQuery('announcements', ''), [setQuery]);
const [formOpen, setFormOpen] = useState(false);
const [editing, setEditing] = useState<AdminAnnouncement | null>(null);
const [form, setForm] = useState<FormState>(EMPTY);
const [formError, setFormError] = useState<string | null>(null);
const [deleting, setDeleting] = useState<AdminAnnouncement | null>(null);
const invalidate = () => qc.invalidateQueries({ queryKey: ['admin-announcements'] });
const save = useMutation({
mutationFn: async () => {
const body = {
title: form.title.trim(),
body: form.body.trim(),
...(editing ? {} : { gymId: form.gymId || null }),
};
if (editing) {
await api(`/admin/announcements/${editing.id}`, { method: 'PATCH', body });
} else {
await api('/admin/announcements', { method: 'POST', body });
}
},
onSuccess: () => {
invalidate();
setFormOpen(false);
setEditing(null);
setForm(EMPTY);
setFormError(null);
},
onError: (e) => setFormError((e as Error).message),
});
const remove = useMutation({
mutationFn: (id: string) => api(`/admin/announcements/${id}`, { method: 'DELETE' }),
onSuccess: () => {
invalidate();
setDeleting(null);
},
});
function openCreate() {
setEditing(null);
setForm(EMPTY);
setFormError(null);
setFormOpen(true);
}
function openEdit(a: AdminAnnouncement) {
setEditing(a);
setForm({ title: a.title, body: a.body, gymId: a.gymId ?? '' });
setFormError(null);
setFormOpen(true);
}
useTopbar({
title: 'Ogłoszenia',
search: 'announcements',
actions: [{ label: 'Nowe ogłoszenie', onClick: openCreate, icon: Plus }],
});
return (
<>
<Muted className="mb-4 block">
Ogłoszenia platformy (trafiają do wszystkich użytkowników) oraz awaryjne ogłoszenia
publikowane w imieniu siłowni — gdy właściciel nie może tego zrobić sam.
</Muted>
{isLoading && <Loading />}
{error && <ErrorText>Błąd: {(error as Error).message}</ErrorText>}
<div className="flex flex-col gap-3">
{filtered.map((a) => (
<Card key={a.id} className="mb-0">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="text-[1.05rem] font-semibold">{a.title}</div>
<div className="mt-1 flex flex-wrap items-center gap-1.5">
<Badge color={a.gymId ? 'gray' : 'green'}>{a.gymName ?? 'Platforma'}</Badge>
<Badge color={KIND_LABELS[a.kind].color}>{KIND_LABELS[a.kind].label}</Badge>
<span className="text-[0.75rem] tabular-nums text-dim">
{fmtDateTime(a.createdAt)}
</span>
</div>
<p className="mt-2 whitespace-pre-wrap text-dim text-[0.875rem]">{a.body}</p>
</div>
{a.kind === 'MANUAL' && (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => openEdit(a)}
aria-label={`Edytuj ${a.title}`}
>
<Pencil className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
className="text-danger hover:text-danger"
onClick={() => setDeleting(a)}
aria-label={`Usuń ${a.title}`}
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
)}
</div>
</Card>
))}
</div>
{!isLoading && !error && filtered.length === 0 && (
<Card>
<EmptyState
icon={Megaphone}
title="Brak ogłoszeń"
description={
query
? 'Brak wyników dla podanego zapytania.'
: 'Brak ogłoszeń. Dodaj pierwsze przyciskiem „Nowe ogłoszenie” w menu kontekstowym.'
}
/>
</Card>
)}
<Modal
open={formOpen}
onClose={() => setFormOpen(false)}
title={editing ? 'Edytuj ogłoszenie' : 'Nowe ogłoszenie'}
>
<div className="flex flex-col gap-3.5">
{!editing && (
<Field label="Adresaci">
<Select
value={form.gymId}
onChange={(e) => setForm((f) => ({ ...f, gymId: e.target.value }))}
>
<option value="">Wszyscy użytkownicy (platforma)</option>
{gyms.map((g) => (
<option key={g.id} value={g.id}>
Siłownia: {g.name}
</option>
))}
</Select>
</Field>
)}
{editing && (
<Muted className="block">
Adresaci: {editing.gymName ?? 'wszyscy użytkownicy (platforma)'}
</Muted>
)}
<Field label="Tytuł">
<Input
value={form.title}
onChange={(e) => setForm((f) => ({ ...f, title: e.target.value }))}
maxLength={120}
placeholder="np. Przerwa techniczna platformy"
/>
</Field>
<Field label="Treść">
<Textarea
value={form.body}
onChange={(e) => setForm((f) => ({ ...f, body: e.target.value }))}
maxLength={2000}
rows={4}
placeholder="Treść ogłoszenia…"
/>
</Field>
{formError && <ErrorText>{formError}</ErrorText>}
<div className="flex justify-end gap-2">
<Button variant="secondary" onClick={() => setFormOpen(false)}>
Anuluj
</Button>
<Button
onClick={() => save.mutate()}
disabled={save.isPending || !form.title.trim() || !form.body.trim()}
>
{editing ? 'Zapisz' : 'Opublikuj'}
</Button>
</div>
</div>
</Modal>
<ConfirmDialog
open={deleting != null}
onClose={() => setDeleting(null)}
onConfirm={() => deleting && remove.mutate(deleting.id)}
title="Usuń ogłoszenie"
description={`Na pewno usunąć „${deleting?.title}”?`}
confirmLabel="Usuń"
danger
busy={remove.isPending}
/>
</>
);
}

View File

@@ -6,6 +6,7 @@ import {
Dumbbell,
Image as ImageIcon,
MapPin,
Megaphone,
Pencil,
ShieldCheck,
Star,
@@ -19,13 +20,16 @@ import { useTopbar, type TopbarCustomGroup } from '../../topbar';
import { api } from '../../api/client';
import { AuthImage } from '../../components/AuthImage';
import { UserPicker } from '../../components/UserPicker';
import {
AddressFields,
addressPayload,
isAddressComplete,
} from '../../components/AddressFields';
import { AddressFields, addressPayload, isAddressComplete } from '../../components/AddressFields';
import { useAdminUsers } from '../users/user-queries';
import type { Equipment, Gym, GymException, GymOwner, GymPhoto } from '../../api/types';
import type {
AdminAnnouncement,
Equipment,
Gym,
GymException,
GymOwner,
GymPhoto,
} from '../../api/types';
import { formatEquipmentSpec, formatGymEquipment } from '../../lib/equipment';
import {
BackButton,
@@ -42,6 +46,7 @@ import {
SectionHeader,
Select,
SuccessText,
Textarea,
} from '../../components/ui';
import { AvailabilityEditor } from '../../components/AvailabilityEditor';
import { normalizeAvailability, TIME_SLOTS } from '../../lib/availability';
@@ -333,8 +338,7 @@ function GymEditForm({ gym, onSaved }: { gym: Gym; onSaved: () => void }) {
setBusy(true);
try {
// Bez adresu w bazie i pustych pól → nie rusamy adresu (stara, swobodna lokalizacja zostaje).
const sendAddress =
anyAddress || !!(gym.addressLine1 ?? gym.postalCode ?? gym.city);
const sendAddress = anyAddress || !!(gym.addressLine1 ?? gym.postalCode ?? gym.city);
await api(`/admin/gyms/${gym.id}`, {
method: 'PATCH',
body: {
@@ -436,7 +440,8 @@ function OwnersSection({ gym, onChanged }: { gym: Gym; onChanged: () => void })
};
const initials = (o: GymOwner) =>
`${o.firstName?.[0] ?? ''}${o.lastName?.[0] ?? ''}`.toUpperCase() || o.email.slice(0, 2).toUpperCase();
`${o.firstName?.[0] ?? ''}${o.lastName?.[0] ?? ''}`.toUpperCase() ||
o.email.slice(0, 2).toUpperCase();
return (
<div className="space-y-4">
@@ -530,6 +535,7 @@ export default function GymDetail() {
const [galleryOpen, setGalleryOpen] = useState(false);
const [equipmentOpen, setEquipmentOpen] = useState(false);
const [ownersOpen, setOwnersOpen] = useState(false);
const [announcementsOpen, setAnnouncementsOpen] = useState(false);
const [confirmOpen, setConfirmOpen] = useState(false);
const [busy, setBusy] = useState(false);
@@ -585,6 +591,14 @@ export default function GymDetail() {
icon: ShieldCheck,
actions: [{ label: 'Właściciele', onClick: () => setOwnersOpen(true) }],
},
{
id: 'announcements',
label: 'Ogłoszenia',
icon: Megaphone,
actions: [
{ label: 'Ogłoś w imieniu siłowni', onClick: () => setAnnouncementsOpen(true) },
],
},
]
: undefined;
@@ -773,13 +787,16 @@ export default function GymDetail() {
>
<EquipmentSection key={gym.id} gym={gym} onChanged={() => void invalidate()} />
</Modal>
<Modal
open={ownersOpen}
onClose={() => setOwnersOpen(false)}
title="Zarządzaj właścicielami"
>
<Modal open={ownersOpen} onClose={() => setOwnersOpen(false)} title="Zarządzaj właścicielami">
<OwnersSection key={gym.id} gym={gym} onChanged={() => void invalidate()} />
</Modal>
<Modal
open={announcementsOpen}
onClose={() => setAnnouncementsOpen(false)}
title="Ogłoszenia w imieniu siłowni"
>
<GymAnnouncementsSection key={gym.id} gym={gym} />
</Modal>
<ConfirmDialog
open={confirmOpen}
@@ -795,6 +812,112 @@ export default function GymDetail() {
);
}
/* Awaryjne ogłoszenia w imieniu siłowni (gdy właściciel nie może sam). */
function GymAnnouncementsSection({ gym }: { gym: Gym }) {
const queryClient = useQueryClient();
const { data, isLoading } = useQuery({
queryKey: ['admin-announcements', gym.id],
queryFn: () =>
api<{ announcements: AdminAnnouncement[] }>(
`/admin/announcements?gymId=${encodeURIComponent(gym.id)}`,
),
});
const announcements = data?.announcements ?? [];
const [title, setTitle] = useState('');
const [body, setBody] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const add = async () => {
setBusy(true);
setError(null);
try {
await api('/admin/announcements', {
method: 'POST',
body: { title: title.trim(), body: body.trim(), gymId: gym.id },
});
setTitle('');
setBody('');
await queryClient.invalidateQueries({ queryKey: ['admin-announcements', gym.id] });
} catch (err) {
setError(err instanceof Error ? err.message : 'Błąd');
} finally {
setBusy(false);
}
};
const remove = async (id: string) => {
setError(null);
try {
await api(`/admin/announcements/${id}`, { method: 'DELETE' });
await queryClient.invalidateQueries({ queryKey: ['admin-announcements', gym.id] });
} catch (err) {
setError(err instanceof Error ? err.message : 'Błąd');
}
};
return (
<div>
<div className="flex flex-col gap-2.5 rounded-xl border border-line bg-input/40 p-3.5">
<Muted className="block">
Ogłoszenie trafi do wszystkich członków siłowni „{gym.name}”.
</Muted>
<Field label="Tytuł">
<Input
value={title}
onChange={(e) => setTitle(e.target.value)}
maxLength={120}
placeholder="np. Awarida prądu — siłownia nieczynna"
/>
</Field>
<Field label="Treść">
<Textarea
value={body}
onChange={(e) => setBody(e.target.value)}
maxLength={2000}
rows={3}
placeholder="Treść ogłoszenia…"
/>
</Field>
{error && <ErrorText>{error}</ErrorText>}
<div>
<Button onClick={() => void add()} disabled={busy || !title.trim() || !body.trim()}>
{busy ? 'Publikowanie…' : 'Opublikuj'}
</Button>
</div>
</div>
<div className="mt-4">
{isLoading ? (
<Loading />
) : announcements.length === 0 ? (
<Muted className="block">Brak ogłoszeń tej siłowni.</Muted>
) : (
<div className="flex flex-col gap-2">
{announcements.map((a) => (
<div key={a.id} className="rounded-[10px] border border-line bg-card/50 px-3 py-2.5">
<div className="flex items-center justify-between gap-3">
<span className="min-w-0 truncate text-[0.9rem] font-bold">{a.title}</span>
{a.kind === 'MANUAL' && (
<Button
variant="danger"
size="sm"
onClick={() => void remove(a.id)}
aria-label={`Usuń ${a.title}`}
>
Usuń
</Button>
)}
</div>
<p className="mt-1 whitespace-pre-wrap text-dim text-[0.8125rem]">{a.body}</p>
</div>
))}
</div>
)}
</div>
</div>
);
}
function EquipmentSection({ gym, onChanged }: { gym: Gym; onChanged: () => void }) {
const { data: eqData, isLoading } = useQuery({
queryKey: ['equipment'],

View File

@@ -140,9 +140,15 @@ describe('admin GymDetail page', () => {
expect(screen.getByText('12 członków')).toBeInTheDocument();
expect(screen.getByText('Anna Kowalska')).toBeInTheDocument();
// menu kontekstowe: grupy Edycja/Galeria/Urządzenia + admin-only Właściciele
// menu kontekstowe: grupy Edycja/Galeria/Urządzenia + admin-only Właściciele + Ogłoszenia
const config = useTopbarStore.getState().config;
expect(config?.groups?.map((g) => g.id)).toEqual(['edit', 'gallery', 'equipment', 'owners']);
expect(config?.groups?.map((g) => g.id)).toEqual([
'edit',
'gallery',
'equipment',
'owners',
'announcements',
]);
expect(config?.actions?.some((a) => a.label === 'Usuń siłownię')).toBe(true);
});

View File

@@ -0,0 +1,92 @@
import type { Page } from '@playwright/test';
import { test, expect } from './fixtures';
import { mockApi } from './mock-api';
import type { AdminAnnouncement } from '../../src/api/types';
function manualGlobal(over: Partial<AdminAnnouncement> = {}): AdminAnnouncement {
return {
id: 'ann-manual',
gymId: null,
authorId: 'admin-test',
kind: 'MANUAL',
title: 'Przerwa techniczna',
body: 'Platforma niedostępna w nocy z piątku na sobotę.',
createdAt: '2026-10-13T20:00:00.000Z',
gymName: null,
...over,
};
}
function systemException(): AdminAnnouncement {
return {
id: 'ann-sys',
gymId: 'gym-1',
authorId: null,
kind: 'EXCEPTION',
title: 'Zamknięcie 24.12.2026',
body: 'Tego dnia siłownia będzie nieczynna.',
createdAt: '2026-10-12T08:00:00.000Z',
gymName: 'Wrocław Power Gym',
};
}
async function loginAsAdmin(page: Page) {
await page.goto('/login');
await page.locator('input[type="email"]').fill('admin@fitos.pl');
await page.locator('input[type="password"]').fill('haslo123');
await page.getByRole('button', { name: 'Zaloguj' }).click();
await expect(page).toHaveURL(/\/gyms$/);
}
async function openAnnouncements(page: Page) {
await page.getByRole('link', { name: 'Ogłoszenia' }).click();
await expect(page).toHaveURL(/\/announcements$/);
}
test('ogłoszenia: lista globalna i per-siłownia; typ systemowy bez akcji', async ({ page }) => {
mockApi(page, { announcements: [manualGlobal(), systemException()] });
await loginAsAdmin(page);
await openAnnouncements(page);
await expect(page.getByText('Przerwa techniczna')).toBeVisible();
await expect(page.getByText('Platforma', { exact: true })).toBeVisible();
await expect(page.getByText('Zamknięcie 24.12.2026')).toBeVisible();
await expect(page.getByText('Wyjątek', { exact: true })).toBeVisible();
// MANUAL ma akcje, EXCEPTION (systemowy) — nie
await expect(page.getByRole('button', { name: 'Edytuj Przerwa techniczna' })).toBeVisible();
await expect(page.getByRole('button', { name: /Zamknięcie 24/ })).toHaveCount(0);
});
test('ogłoszenia: utworzenie nowego ogłoszenia platformy', async ({ page }) => {
mockApi(page);
await loginAsAdmin(page);
await openAnnouncements(page);
await expect(page.getByRole('heading', { name: 'Brak ogłoszeń' })).toBeVisible();
await page.getByRole('button', { name: 'Nowe ogłoszenie' }).click();
await page
.getByPlaceholder('np. Przerwa techniczna platformy')
.fill('Konserwacja aplikacji');
await page.getByPlaceholder('Treść ogłoszenia…').fill('W niedzielę aplikacja może wolniej działać.');
await page.getByRole('button', { name: 'Opublikuj' }).click();
await expect(page.getByText('Konserwacja aplikacji')).toBeVisible();
await expect(page.getByText('Platforma', { exact: true })).toBeVisible();
});
test('ogłoszenia: edycja i usunięcie ogłoszenia ręcznego', async ({ page }) => {
mockApi(page, { announcements: [manualGlobal()] });
await loginAsAdmin(page);
await openAnnouncements(page);
await page.getByRole('button', { name: 'Edytuj Przerwa techniczna' }).click();
const titleInput = page.locator('input[maxlength="120"]');
await titleInput.fill('Przerwa techniczna (nowy termin)');
await page.getByRole('button', { name: 'Zapisz' }).click();
await expect(page.getByText('Przerwa techniczna (nowy termin)')).toBeVisible();
await page.getByRole('button', { name: 'Usuń Przerwa techniczna (nowy termin)' }).click();
await page.getByRole('button', { name: 'Usuń', exact: true }).click();
await expect(page.getByRole('heading', { name: 'Brak ogłoszeń' })).toBeVisible();
});

View File

@@ -1,5 +1,12 @@
import type { Page } from '@playwright/test';
import type { ActivityLog, Equipment, Gym, GymClaim, User } from '../../src/api/types';
import type {
ActivityLog,
AdminAnnouncement,
Equipment,
Gym,
GymClaim,
User,
} from '../../src/api/types';
export const TEST_ADMIN = {
id: 'admin-test',
@@ -243,6 +250,8 @@ export interface MockApiOptions {
logs?: unknown;
/** Ciało odpowiedzi GET /admin/gyms/claims. */
claims?: unknown;
/** Startowy stan GET /admin/announcements (stateful CRUD w teście). */
announcements?: unknown;
}
/**
@@ -258,6 +267,7 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
users = { users: [] },
logs = { logs: TEST_LOGS, total: TEST_LOGS.length },
claims = { claims: [] as GymClaim[] },
announcements = [] as AdminAnnouncement[],
} = opts;
// Stateful: claims persist across list/detail/approve/reject.
@@ -267,6 +277,75 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({}) }),
);
// Stateful: ogłoszenia (globalne + per-siłownia) — CRUD w ramach testu.
let announcementsState = JSON.parse(JSON.stringify(announcements)) as AdminAnnouncement[];
let announcementSeq = announcementsState.length;
page.route('**/api/v1/admin/announcements**', (route) => {
const req = route.request();
const url = new URL(req.url());
const method = req.method();
const id = url.pathname.split('/').at(-1);
const isCollection = id === 'announcements';
if (method === 'GET') {
const gymId = url.searchParams.get('gymId');
const items = gymId
? announcementsState.filter((a) => a.gymId === gymId)
: announcementsState;
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ announcements: items }),
});
}
if (method === 'POST' && isCollection) {
const body = (req.postDataJSON() ?? {}) as {
title?: string;
body?: string;
gymId?: string | null;
};
const created: AdminAnnouncement = {
id: `ann-${++announcementSeq}`,
kind: 'MANUAL',
authorId: TEST_ADMIN.id,
gymId: body.gymId ?? null,
gymName:
body.gymId === TEST_GYM.id ? TEST_GYM.name : body.gymId === TEST_GYM_2.id ? TEST_GYM_2.name : null,
title: body.title ?? '',
body: body.body ?? '',
createdAt: new Date().toISOString(),
};
announcementsState = [...announcementsState, created];
return route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({ announcement: created }),
});
}
const found = !isCollection ? announcementsState.find((a) => a.id === id) : undefined;
if (!found) {
return route.fulfill({
status: 404,
contentType: 'application/json',
body: JSON.stringify({ error: { message: 'Not found' } }),
});
}
if (method === 'PATCH') {
const patch = (req.postDataJSON() ?? {}) as { title?: string; body?: string };
const updated = { ...found, ...patch };
announcementsState = announcementsState.map((a) => (a.id === found.id ? updated : a));
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ announcement: updated }),
});
}
if (method === 'DELETE') {
announcementsState = announcementsState.filter((a) => a.id !== found.id);
return route.fulfill({ status: 204 });
}
return route.fulfill({ status: 405 });
});
page.route('**/api/v1/auth/refresh', (route) =>
route.fulfill({
status: 401,

View File

@@ -0,0 +1,71 @@
-- CreateEnum
CREATE TYPE "NotificationType" AS ENUM ('PLAN_READY', 'PLAN_SHARED', 'GYM_DELETED');
-- CreateEnum
CREATE TYPE "AnnouncementKind" AS ENUM ('MANUAL', 'HOURS_CHANGE', 'EXCEPTION');
-- CreateTable
CREATE TABLE "Notification" (
"id" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"type" "NotificationType" NOT NULL,
"title" TEXT NOT NULL,
"payload" JSONB NOT NULL,
"readAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Notification_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Announcement" (
"id" TEXT NOT NULL,
"gymId" TEXT,
"authorId" TEXT,
"kind" "AnnouncementKind" NOT NULL DEFAULT 'MANUAL',
"title" TEXT NOT NULL,
"body" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Announcement_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "AnnouncementRead" (
"announcementId" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"readAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- CreateIndex
CREATE INDEX "Notification_userId_readAt_idx" ON "Notification"("userId", "readAt");
-- CreateIndex
CREATE INDEX "Notification_userId_createdAt_idx" ON "Notification"("userId", "createdAt");
-- CreateIndex
CREATE INDEX "Announcement_gymId_createdAt_idx" ON "Announcement"("gymId", "createdAt");
-- CreateIndex
CREATE INDEX "Announcement_createdAt_idx" ON "Announcement"("createdAt");
-- CreateIndex
CREATE INDEX "AnnouncementRead_userId_idx" ON "AnnouncementRead"("userId");
-- CreateIndex
CREATE UNIQUE INDEX "AnnouncementRead_announcementId_userId_key" ON "AnnouncementRead"("announcementId", "userId");
-- AddForeignKey
ALTER TABLE "Notification" ADD CONSTRAINT "Notification_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Announcement" ADD CONSTRAINT "Announcement_gymId_fkey" FOREIGN KEY ("gymId") REFERENCES "Gym"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Announcement" ADD CONSTRAINT "Announcement_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "AnnouncementRead" ADD CONSTRAINT "AnnouncementRead_announcementId_fkey" FOREIGN KEY ("announcementId") REFERENCES "Announcement"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "AnnouncementRead" ADD CONSTRAINT "AnnouncementRead_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View File

@@ -107,25 +107,28 @@ model User {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
memberships GymMembership[]
plans TrainingPlan[]
createdPlans TrainingPlan[] @relation("PlanCreator")
planSharesBy PlanShare[] @relation("PlanShareBy")
planSharesWith PlanShare[] @relation("PlanShareWith")
weightEntries BodyMeasurement[]
circumferenceEntries CircumferenceMeasurement[]
coachingsAsTrainer Coaching[] @relation("CoachingTrainer")
coachingsAsUser Coaching[] @relation("CoachingUser")
commentsAsAuthor Comment[] @relation("CommentAuthor")
commentsAsTarget Comment[] @relation("CommentTarget")
messagesAsSender Message[] @relation("MessageSender")
conversationReads ConversationRead[]
activityLogs ActivityLog[] @relation("ActivityLogActor")
gymRatings GymRating[]
gymClaims GymClaim[]
claimsDecided GymClaim[] @relation("ClaimDecider")
gymInvitations GymInvitation[]
gymInvitationsSent GymInvitation[] @relation("GymInviteSender")
memberships GymMembership[]
plans TrainingPlan[]
createdPlans TrainingPlan[] @relation("PlanCreator")
planSharesBy PlanShare[] @relation("PlanShareBy")
planSharesWith PlanShare[] @relation("PlanShareWith")
weightEntries BodyMeasurement[]
circumferenceEntries CircumferenceMeasurement[]
coachingsAsTrainer Coaching[] @relation("CoachingTrainer")
coachingsAsUser Coaching[] @relation("CoachingUser")
commentsAsAuthor Comment[] @relation("CommentAuthor")
commentsAsTarget Comment[] @relation("CommentTarget")
messagesAsSender Message[] @relation("MessageSender")
conversationReads ConversationRead[]
activityLogs ActivityLog[] @relation("ActivityLogActor")
gymRatings GymRating[]
gymClaims GymClaim[]
claimsDecided GymClaim[] @relation("ClaimDecider")
gymInvitations GymInvitation[]
gymInvitationsSent GymInvitation[] @relation("GymInviteSender")
notifications Notification[]
announcementsAuthored Announcement[] @relation("AnnouncementAuthor")
announcementReads AnnouncementRead[]
}
/// Audit trail of user actions (app + trainer level). Best-effort writes,
@@ -217,6 +220,73 @@ model ConversationRead {
@@unique([coachingId, userId])
}
/// Rodzaj osobistego powiadomienia (warstwa systemowa feedu „Aktualności").
enum NotificationType {
PLAN_READY
PLAN_SHARED
GYM_DELETED
}
/// Osobiste powiadomienie generowane przez system. `payload` jest self-contained
/// (np. nazwa siłowni przy GYM_DELETED) — przeżywa usunięcie encji źródłowej.
model Notification {
id String @id @default(cuid())
userId String
type NotificationType
/// Gotowy tekst PL wygenerowany przy tworzeniu (renderowany 1:1 w UI).
title String
/// Dane do deeplinków: { planId?, planTitle?, gymName?, sharedBy?, ... }.
payload Json
readAt DateTime?
createdAt DateTime @default(now())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId, readAt])
@@index([userId, createdAt])
}
/// Rodzaj ogłoszenia — MANUAL pisane przez osobę, pozostałe generowane systemowo.
enum AnnouncementKind {
MANUAL
HOURS_CHANGE
EXCEPTION
}
/// Ogłoszenie broadcastowe: do członków siłowni (gymId) albo globalne (gymId = null).
/// NIE mnożone per odbiorca — stan przeczytania w AnnouncementRead.
model Announcement {
id String @id @default(cuid())
/// null = ogłoszenie globalne platformy (autor = admin).
gymId String?
/// Autor (OWNER siłowni / admin); null = wygenerowane systemowo.
authorId String?
kind AnnouncementKind @default(MANUAL)
title String
body String
createdAt DateTime @default(now())
gym Gym? @relation(fields: [gymId], references: [id], onDelete: Cascade)
author User? @relation("AnnouncementAuthor", fields: [authorId], references: [id], onDelete: SetNull)
reads AnnouncementRead[]
@@index([gymId, createdAt])
@@index([createdAt])
}
/// Oznaczenie przeczytania ogłoszenia per user (do licznika nieprzeczytanych).
model AnnouncementRead {
announcementId String
userId String
readAt DateTime @default(now())
announcement Announcement @relation(fields: [announcementId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([announcementId, userId])
@@index([userId])
}
model Gym {
id String @id @default(cuid())
name String
@@ -247,6 +317,7 @@ model Gym {
invitations GymInvitation[]
photos GymPhoto[]
plans TrainingPlan[]
announcements Announcement[]
}
/// Zdjęcie w galerii siłowni REAL. `order` = kolejność; okładka = najmniejsze `order` (tie → najstarsze `createdAt`).

View File

@@ -23,6 +23,7 @@ import { createDashboardRoutes } from './routes/dashboard.js';
import { createCalendarRoutes } from './routes/calendar.js';
import { createTrainerRoutes } from './routes/trainer.js';
import { createMessageRoutes } from './routes/messages.js';
import { createFeedRoutes } from './routes/feed.js';
import { createAdminRoutes } from './routes/admin.js';
import { createEquipmentRoutes } from './routes/equipment.js';
import { createEquipmentPublicRoutes } from './routes/equipmentPublic.js';
@@ -73,6 +74,8 @@ export function createApp(deps: AppDeps): express.Express {
app.use('/api/v1', deps.apiLimiter ?? apiLimiter);
app.use('/api/v1/auth', createAuthRoutes(deps));
// /me/feed przed /me — inaczej zapytania o feed wpadałyby najpierw do routera /me.
app.use('/api/v1/me/feed', createFeedRoutes(deps));
app.use('/api/v1/me', createMeRoutes(deps));
app.use('/api/v1/exercises', createExercisePoolRoutes(deps));
app.use('/api/v1/focus-areas', createFocusAreaRoutes(deps));

View File

@@ -56,6 +56,12 @@ import {
} from '../services/focusAreas.js';
import { getFocusChain } from '../services/focusChain.js';
import { createGymException, deleteGymException, listGymExceptions } from '../services/gyms.js';
import {
createAnnouncementAsAdmin,
deleteAnnouncementAsAdmin,
listAnnouncementsForAdmin,
updateAnnouncementAsAdmin,
} from '../services/announcements.js';
import { listActivityLogs, logActivity } from '../services/audit.js';
import { asyncHandler } from '../lib/asyncHandler.js';
@@ -1024,5 +1030,92 @@ export function createAdminRoutes({ prisma }: AppDeps) {
}),
);
const announcementTextSchema = z.object({
title: z.string().trim().min(1).max(120),
body: z.string().trim().min(1).max(2000),
});
const adminAnnouncementSchema = announcementTextSchema.extend({
/** null/brak = globalne; ustawione = per-siłownia (awaryjnie w imieniu właściciela). */
gymId: z.string().min(1).nullable().optional(),
});
/**
* @openapi
* /admin/announcements:
* get:
* summary: List all announcements or those of one gym (?gymId=) (admin)
* tags: [Admin]
* responses:
* 200: { description: OK }
*/
router.get(
'/announcements',
asyncHandler(async (req, res) => {
const gymId = typeof req.query.gymId === 'string' ? req.query.gymId : null;
const result = await listAnnouncementsForAdmin(prisma, { gymId });
res.json(result);
}),
);
/**
* @openapi
* /admin/announcements:
* post:
* summary: Create an announcement — global (gymId null) or for a gym (admin)
* tags: [Admin]
* responses:
* 201: { description: Created }
* 404: { description: Gym not found }
*/
router.post(
'/announcements',
validate(adminAnnouncementSchema),
asyncHandler(async (req, res) => {
const data = req.body as z.infer<typeof adminAnnouncementSchema>;
const result = await createAnnouncementAsAdmin(prisma, req.user!.id, data);
res.status(201).json(result);
}),
);
/**
* @openapi
* /admin/announcements/{id}:
* patch:
* summary: Edit a manual announcement (admin)
* tags: [Admin]
* responses:
* 200: { description: OK }
* 400: { description: System announcements cannot be edited }
* 404: { description: Not found }
*/
router.patch(
'/announcements/:id',
validate(announcementTextSchema),
asyncHandler(async (req, res) => {
const data = req.body as z.infer<typeof announcementTextSchema>;
const result = await updateAnnouncementAsAdmin(prisma, req.params.id, data);
res.json(result);
}),
);
/**
* @openapi
* /admin/announcements/{id}:
* delete:
* summary: Delete a manual announcement (admin)
* tags: [Admin]
* responses:
* 204: { description: Deleted }
* 400: { description: System announcements cannot be deleted }
* 404: { description: Not found }
*/
router.delete(
'/announcements/:id',
asyncHandler(async (req, res) => {
await deleteAnnouncementAsAdmin(prisma, req.params.id);
res.status(204).end();
}),
);
return router;
}

111
api/src/routes/feed.ts Normal file
View File

@@ -0,0 +1,111 @@
import { Router } from 'express';
import type { AppDeps } from '../deps.js';
import { authenticate } from '../middleware/auth.js';
import {
getFeed,
getFeedUnreadCount,
markAnnouncementRead,
markFeedAllRead,
markNotificationRead,
} from '../services/feed.js';
import { asyncHandler } from '../lib/asyncHandler.js';
/** Mounted at /api/v1/me/feed — „Aktualności" (osobiste powiadomienia + ogłoszenia). */
export function createFeedRoutes({ prisma }: AppDeps) {
const router = Router();
router.use(authenticate(prisma));
/**
* @openapi
* /me/feed:
* get:
* summary: Merged feed of personal notifications and gym/global announcements (cursor = createdAt)
* tags: [Feed]
* responses:
* 200: { description: OK }
*/
router.get(
'/',
asyncHandler(async (req, res) => {
const limit = req.query.limit ? Number(req.query.limit) : undefined;
const cursor = typeof req.query.cursor === 'string' ? req.query.cursor : null;
const result = await getFeed(prisma, req.user!.id, {
limit: Number.isFinite(limit) ? limit : undefined,
cursor,
});
res.json(result);
}),
);
/**
* @openapi
* /me/feed/unread-count:
* get:
* summary: Unread counter (notifications + visible announcements)
* tags: [Feed]
* responses:
* 200: { description: OK }
*/
router.get(
'/unread-count',
asyncHandler(async (req, res) => {
const result = await getFeedUnreadCount(prisma, req.user!.id);
res.json(result);
}),
);
/**
* @openapi
* /me/feed/read-all:
* post:
* summary: Mark all feed items as read (both sources)
* tags: [Feed]
* responses:
* 200: { description: OK }
*/
router.post(
'/read-all',
asyncHandler(async (req, res) => {
const result = await markFeedAllRead(prisma, req.user!.id);
res.json(result);
}),
);
/**
* @openapi
* /me/feed/notifications/{id}/read:
* post:
* summary: Mark a personal notification as read
* tags: [Feed]
* responses:
* 200: { description: OK }
* 404: { description: Not found or not yours }
*/
router.post(
'/notifications/:id/read',
asyncHandler(async (req, res) => {
const result = await markNotificationRead(prisma, req.user!.id, req.params.id);
res.json(result);
}),
);
/**
* @openapi
* /me/feed/announcements/{id}/read:
* post:
* summary: Mark an announcement as read (visible to the user only)
* tags: [Feed]
* responses:
* 200: { description: OK }
* 404: { description: Not found or not visible }
*/
router.post(
'/announcements/:id/read',
asyncHandler(async (req, res) => {
const result = await markAnnouncementRead(prisma, req.user!.id, req.params.id);
res.json(result);
}),
);
return router;
}

View File

@@ -10,7 +10,18 @@ import {
removeEquipment,
updateEquipmentQuantity,
} from '../../services/gyms.js';
import { equipmentQuantitySchema, equipmentSchema, gymExceptionSchema } from './schemas.js';
import {
createGymAnnouncement,
deleteGymAnnouncement,
listGymAnnouncements,
updateGymAnnouncement,
} from '../../services/announcements.js';
import {
announcementSchema,
equipmentQuantitySchema,
equipmentSchema,
gymExceptionSchema,
} from './schemas.js';
import { asyncHandler } from '../../lib/asyncHandler.js';
type GymParams = { gymId: string };
@@ -30,20 +41,14 @@ export function createGymManagementRoutes({ prisma }: AppDeps) {
* 403: { description: Not the gym owner }
* 404: { description: Equipment not found }
* 409: { description: Equipment already exists (update its quantity instead) }
*/
*/
router.post(
'/equipment',
validate(equipmentSchema),
asyncHandler(async (req, res) => {
const { equipmentId, quantity } = req.body as z.infer<typeof equipmentSchema>;
const { gymId } = req.params as GymParams;
const result = await addEquipment(
prisma,
gymId,
req.user!.id,
equipmentId,
quantity ?? 1,
);
const result = await addEquipment(prisma, gymId, req.user!.id, equipmentId, quantity ?? 1);
res.json(result);
}),
);
@@ -58,7 +63,7 @@ export function createGymManagementRoutes({ prisma }: AppDeps) {
* 200: { description: OK }
* 403: { description: Not the gym owner }
* 400: { description: Equipment not in the gym }
*/
*/
router.patch(
'/equipment/:equipmentId',
validate(equipmentQuantitySchema),
@@ -85,7 +90,7 @@ export function createGymManagementRoutes({ prisma }: AppDeps) {
* responses:
* 204: { description: Removed }
* 403: { description: Not the gym owner }
*/
*/
router.delete(
'/equipment/:equipmentId',
asyncHandler(async (req, res) => {
@@ -104,7 +109,7 @@ export function createGymManagementRoutes({ prisma }: AppDeps) {
* responses:
* 200: { description: OK }
* 403: { description: Not the gym owner }
*/
*/
router.get(
'/exceptions',
asyncHandler(async (req, res) => {
@@ -124,7 +129,7 @@ export function createGymManagementRoutes({ prisma }: AppDeps) {
* 201: { description: Created }
* 403: { description: Not the gym owner }
* 409: { description: Exception already exists for this date }
*/
*/
router.post(
'/exceptions',
validate(gymExceptionSchema),
@@ -149,17 +154,96 @@ export function createGymManagementRoutes({ prisma }: AppDeps) {
* 204: { description: Removed }
* 403: { description: Not the gym owner }
* 404: { description: Exception not found }
*/
*/
router.delete(
'/exceptions/:exceptionId',
asyncHandler(async (req, res) => {
const { gymId, exceptionId } = req.params as GymParams & { exceptionId: string };
await deleteOwnedGymException(
prisma,
gymId,
req.user!.id,
exceptionId,
);
await deleteOwnedGymException(prisma, gymId, req.user!.id, exceptionId);
res.status(204).end();
}),
);
/**
* @openapi
* /gyms/{gymId}/announcements:
* get:
* summary: List the gym's announcements (any member; canManage = OWNER)
* tags: [Gyms]
* responses:
* 200: { description: OK }
* 404: { description: Gym not found or not a member }
*/
router.get(
'/announcements',
asyncHandler(async (req, res) => {
const { gymId } = req.params as GymParams;
const result = await listGymAnnouncements(prisma, gymId, req.user!.id);
res.json(result);
}),
);
/**
* @openapi
* /gyms/{gymId}/announcements:
* post:
* summary: Publish an announcement to the gym's members (owner only)
* tags: [Gyms]
* responses:
* 201: { description: Created }
* 403: { description: Not the gym owner }
*/
router.post(
'/announcements',
validate(announcementSchema),
asyncHandler(async (req, res) => {
const data = req.body as z.infer<typeof announcementSchema>;
const { gymId } = req.params as GymParams;
const result = await createGymAnnouncement(prisma, gymId, req.user!.id, data);
res.status(201).json(result);
}),
);
/**
* @openapi
* /gyms/{gymId}/announcements/{announcementId}:
* patch:
* summary: Edit a manual announcement (owner only)
* tags: [Gyms]
* responses:
* 200: { description: OK }
* 400: { description: System announcements cannot be edited }
* 403: { description: Not the gym owner }
* 404: { description: Announcement not found }
*/
router.patch(
'/announcements/:announcementId',
validate(announcementSchema),
asyncHandler(async (req, res) => {
const data = req.body as z.infer<typeof announcementSchema>;
const { gymId, announcementId } = req.params as GymParams & { announcementId: string };
const result = await updateGymAnnouncement(prisma, gymId, req.user!.id, announcementId, data);
res.json(result);
}),
);
/**
* @openapi
* /gyms/{gymId}/announcements/{announcementId}:
* delete:
* summary: Delete a manual announcement (owner only)
* tags: [Gyms]
* responses:
* 204: { description: Deleted }
* 400: { description: System announcements cannot be deleted }
* 403: { description: Not the gym owner }
* 404: { description: Announcement not found }
*/
router.delete(
'/announcements/:announcementId',
asyncHandler(async (req, res) => {
const { gymId, announcementId } = req.params as GymParams & { announcementId: string };
await deleteGymAnnouncement(prisma, gymId, req.user!.id, announcementId);
res.status(204).end();
}),
);

View File

@@ -12,7 +12,12 @@ export const gymAddressFields = {
.nullable()
.optional(),
city: z.string().trim().min(1).max(100).nullable().optional(),
countryCode: z.string().trim().regex(/^[a-zA-Z]{2}$/).nullable().optional(),
countryCode: z
.string()
.trim()
.regex(/^[a-zA-Z]{2}$/)
.nullable()
.optional(),
};
export const createGymSchema = z.object({
@@ -36,7 +41,10 @@ export const gymClaimSchema = z.object({
gymId: z.string().min(1).optional(),
description: z.string().min(1).max(5000),
companyName: z.string().max(200).optional(),
nip: z.string().regex(/^\d{10}$/).optional(),
nip: z
.string()
.regex(/^\d{10}$/)
.optional(),
phone: z.string().max(20).optional(),
email: z.string().email().max(200).optional(),
address: z.string().max(500).optional(),
@@ -76,3 +84,8 @@ export const equipmentSchema = z.object({
export const equipmentQuantitySchema = z.object({
quantity: z.number().int().min(1).max(10000),
});
export const announcementSchema = z.object({
title: z.string().trim().min(1).max(120),
body: z.string().trim().min(1).max(2000),
});

View File

@@ -4,7 +4,9 @@ import { isPrismaNotFound, isPrismaUnique } from '../lib/prisma.js';
import { publicUser } from '../lib/publicUser.js';
import { badRequest, conflict, forbidden, notFound } from '../lib/errors.js';
import { removeGymClaimFiles, removeGymPhotoFiles } from '../lib/uploads.js';
import { gymPhotoUrl, listGymClaimIds } from './gyms.js';
import { availabilityChanged, gymPhotoUrl, listGymClaimIds } from './gyms.js';
import { announceHoursChange } from './announcements.js';
import { notifyGymDeleted } from './feed.js';
import { formatAddress, type AddressParts } from '../lib/address.js';
import {
resolveMuscleConflicts,
@@ -182,21 +184,14 @@ export async function createGym(prisma: PrismaClient, data: CreateGymInput) {
*/
export async function updateGym(prisma: PrismaClient, id: string, data: UpdateGymInput) {
try {
const {
availability,
addressLine1,
addressLine2,
postalCode,
city,
countryCode,
...rest
} = data;
const { availability, addressLine1, addressLine2, postalCode, city, countryCode, ...rest } =
data;
const existing = await prisma.gym.findUniqueOrThrow({ where: { id } });
let addressData: Prisma.GymUpdateInput = {};
const hasAddress = [addressLine1, addressLine2, postalCode, city, countryCode].some(
(v) => v !== undefined,
);
if (hasAddress) {
const existing = await prisma.gym.findUniqueOrThrow({ where: { id } });
const merged: AddressParts = {
addressLine1: addressLine1 !== undefined ? addressLine1 : existing.addressLine1,
addressLine2: addressLine2 !== undefined ? addressLine2 : existing.addressLine2,
@@ -204,7 +199,9 @@ export async function updateGym(prisma: PrismaClient, id: string, data: UpdateGy
city: city !== undefined ? city : existing.city,
countryCode:
countryCode !== undefined
? countryCode ? countryCode.trim().toUpperCase() : null
? countryCode
? countryCode.trim().toUpperCase()
: null
: existing.countryCode,
};
addressData = { ...merged, location: formatAddress(merged) };
@@ -213,6 +210,9 @@ export async function updateGym(prisma: PrismaClient, id: string, data: UpdateGy
where: { id },
data: { ...rest, ...addressData, availability: toPrismaAvailability(availability) },
});
if (availabilityChanged(existing.availability, availability)) {
await announceHoursChange(prisma, id, gym.name);
}
return { gym };
} catch (e) {
if (isPrismaNotFound(e)) throw notFound('Gym not found');
@@ -221,13 +221,12 @@ export async function updateGym(prisma: PrismaClient, id: string, data: UpdateGy
}
export async function deleteGym(prisma: PrismaClient, id: string) {
const gym = await prisma.gym.findUnique({ where: { id } });
if (!gym) throw notFound('Gym not found');
const claimIds = await listGymClaimIds(prisma, id);
try {
await prisma.gym.delete({ where: { id } });
} catch (e) {
if (isPrismaNotFound(e)) throw notFound('Gym not found');
throw e;
}
// Najpierw fan-out powiadomień (jak przy usuwaniu przez właściciela).
await notifyGymDeleted(prisma, id, gym.name);
await prisma.gym.delete({ where: { id } });
await removeGymClaimFiles(claimIds);
removeGymPhotoFiles(id);
}

View File

@@ -0,0 +1,198 @@
import type { PrismaClient } from '@prisma/client';
import { badRequest, forbidden, notFound } from '../lib/errors.js';
import type { DayAvailability } from './me.js';
export interface AnnouncementInput {
title: string;
body: string;
}
/**
* Lokalny zamiast importu `assertGymOwner` z `gyms/core.js` — ten moduł jest
* importowany przez core (ogłoszenia automatyczne), więc import zwrotny
* stworzyłby cykl.
*/
async function assertGymOwner(prisma: PrismaClient, gymId: string, userId: string) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
include: { memberships: { where: { userId } } },
});
if (!gym) throw notFound('Gym not found');
if (!gym.memberships.some((m) => m.roles.includes('OWNER')))
throw forbidden('Only the gym owner can manage this gym');
}
/** Wymaga członkostwa w siłowni (dowolna rola); `canManage` = OWNER. */
export async function listGymAnnouncements(prisma: PrismaClient, gymId: string, userId: string) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
include: { memberships: { where: { userId } } },
});
if (!gym) throw notFound('Gym not found');
const membership = gym.memberships[0];
if (!membership) throw notFound('Gym not found');
const announcements = await prisma.announcement.findMany({
where: { gymId },
orderBy: { createdAt: 'desc' },
});
return {
announcements,
canManage: membership.roles.includes('OWNER'),
};
}
/** Publikuje ogłoszenie do członków siłowni (tylko OWNER). */
export async function createGymAnnouncement(
prisma: PrismaClient,
gymId: string,
userId: string,
data: AnnouncementInput,
) {
await assertGymOwner(prisma, gymId, userId);
const announcement = await prisma.announcement.create({
data: { gymId, authorId: userId, kind: 'MANUAL', title: data.title, body: data.body },
});
return { announcement };
}
/** Edycja ręcznego ogłoszenia siłowni (tylko OWNER; ogłoszenia systemowe stałe). */
export async function updateGymAnnouncement(
prisma: PrismaClient,
gymId: string,
userId: string,
announcementId: string,
data: AnnouncementInput,
) {
await assertGymOwner(prisma, gymId, userId);
const announcement = await prisma.announcement.findUnique({ where: { id: announcementId } });
if (!announcement || announcement.gymId !== gymId) throw notFound('Announcement not found');
if (announcement.kind !== 'MANUAL') throw badRequest('System announcements cannot be edited');
const updated = await prisma.announcement.update({
where: { id: announcementId },
data: { title: data.title, body: data.body },
});
return { announcement: updated };
}
/** Usunięcie ręcznego ogłoszenia siłowni (tylko OWNER). */
export async function deleteGymAnnouncement(
prisma: PrismaClient,
gymId: string,
userId: string,
announcementId: string,
) {
await assertGymOwner(prisma, gymId, userId);
const announcement = await prisma.announcement.findUnique({ where: { id: announcementId } });
if (!announcement || announcement.gymId !== gymId) throw notFound('Announcement not found');
if (announcement.kind !== 'MANUAL') throw badRequest('System announcements cannot be deleted');
await prisma.announcement.delete({ where: { id: announcementId } });
}
/**
* Lista ogłoszeń dla panelu admina: wszystkie albo dla jednej siłowni;
* z nazwą siłowni przy ogłoszeniach per-gym.
*/
export async function listAnnouncementsForAdmin(
prisma: PrismaClient,
opts: { gymId?: string | null } = {},
) {
const announcements = await prisma.announcement.findMany({
where: opts.gymId ? { gymId: opts.gymId } : undefined,
orderBy: { createdAt: 'desc' },
include: { gym: { select: { id: true, name: true } } },
});
return {
announcements: announcements.map(({ gym, ...a }) => ({
...a,
gymName: gym?.name ?? null,
})),
};
}
/** Tworzenie ogłoszenia przez admina: `gymId` = per-siłownia (awaryjnie), null = globalne. */
export async function createAnnouncementAsAdmin(
prisma: PrismaClient,
authorId: string,
data: AnnouncementInput & { gymId?: string | null },
) {
if (data.gymId) {
const gym = await prisma.gym.findUnique({ where: { id: data.gymId }, select: { id: true } });
if (!gym) throw notFound('Gym not found');
}
const announcement = await prisma.announcement.create({
data: {
gymId: data.gymId ?? null,
authorId,
kind: 'MANUAL',
title: data.title,
body: data.body,
},
});
return { announcement };
}
export async function updateAnnouncementAsAdmin(
prisma: PrismaClient,
announcementId: string,
data: AnnouncementInput,
) {
const announcement = await prisma.announcement.findUnique({ where: { id: announcementId } });
if (!announcement) throw notFound('Announcement not found');
if (announcement.kind !== 'MANUAL') throw badRequest('System announcements cannot be edited');
const updated = await prisma.announcement.update({
where: { id: announcementId },
data: { title: data.title, body: data.body },
});
return { announcement: updated };
}
export async function deleteAnnouncementAsAdmin(prisma: PrismaClient, announcementId: string) {
const announcement = await prisma.announcement.findUnique({ where: { id: announcementId } });
if (!announcement) throw notFound('Announcement not found');
if (announcement.kind !== 'MANUAL') throw badRequest('System announcements cannot be deleted');
await prisma.announcement.delete({ where: { id: announcementId } });
}
/* --- Ogłoszenia generowane systemowo ------------------------------------- */
/** Data 'YYYY-MM-DD' → 'DD.MM.YYYY' (bez przesunięć stref czasowych). */
function plDate(isoDate: string): string {
const [y, m, d] = isoDate.split('-');
return `${d}.${m}.${y}`;
}
function exceptionBody(availability: DayAvailability | null): string {
return availability
? `Tego dnia siłownia będzie otwarta w godzinach ${availability.start}–${availability.end}.`
: 'Tego dnia siłownia będzie nieczynna.';
}
/** Automatyczne ogłoszenie o jednorazowym wyjątku w godzinach (dodanie GymException). */
export async function announceException(
prisma: PrismaClient,
gymId: string,
gymName: string,
isoDate: string,
availability: DayAvailability | null,
) {
return prisma.announcement.create({
data: {
gymId,
kind: 'EXCEPTION',
title: `Zmiana godzin ${plDate(isoDate)} — ${gymName}`,
body: exceptionBody(availability),
},
});
}
/** Automatyczne ogłoszenie o zmianie stałych godzin otwarcia siłowni. */
export async function announceHoursChange(prisma: PrismaClient, gymId: string, gymName: string) {
return prisma.announcement.create({
data: {
gymId,
kind: 'HOURS_CHANGE',
title: `Zmiana godzin otwarcia — ${gymName}`,
body: 'Godziny otwarcia siłowni zostały zaktualizowane. Sprawdź aktualny harmonogram na stronie siłowni.',
},
});
}

222
api/src/services/feed.ts Normal file
View File

@@ -0,0 +1,222 @@
import type { NotificationType, Prisma, PrismaClient } from '@prisma/client';
import { notFound } from '../lib/errors.js';
export interface CreateNotificationInput {
userId: string;
type: NotificationType;
title: string;
payload: Prisma.InputJsonObject;
}
/** Tworzy pojedyncze osobiste powiadomienie (warstwa systemowa feedu). */
export async function createNotification(prisma: PrismaClient, input: CreateNotificationInput) {
return prisma.notification.create({
data: {
userId: input.userId,
type: input.type,
title: input.title,
payload: input.payload,
},
});
}
/**
* Fan-out powiadomienia GYM_DELETED: wszyscy członkowie siłowni ∪ właściciele
* planów wskazujących na tę siłownię. Nazwa siłowni ląduje w payload, więc
* powiadomienie przeżywa twarde usunięcie encji.
*/
export async function notifyGymDeleted(prisma: PrismaClient, gymId: string, gymName: string) {
const [members, planOwners] = await Promise.all([
prisma.gymMembership.findMany({ where: { gymId }, select: { userId: true } }),
prisma.trainingPlan.findMany({ where: { gymId }, select: { userId: true } }),
]);
const userIds = [...new Set([...members, ...planOwners].map((r) => r.userId))];
if (userIds.length === 0) return;
await prisma.notification.createMany({
data: userIds.map((userId) => ({
userId,
type: 'GYM_DELETED' as const,
title: `Siłownia „${gymName}” została usunięta`,
payload: { gymName },
})),
});
}
export interface FeedNotificationItem {
source: 'notification';
id: string;
type: NotificationType;
title: string;
payload: Record<string, unknown>;
read: boolean;
createdAt: string;
}
export interface FeedAnnouncementItem {
source: 'announcement';
id: string;
kind: 'MANUAL' | 'HOURS_CHANGE' | 'EXCEPTION';
title: string;
body: string;
gymId: string | null;
gymName: string | null;
createdAt: string;
read: boolean;
}
export type FeedItem = FeedNotificationItem | FeedAnnouncementItem;
/** gymId, których user jest członkiem (widoczność ogłoszeń siłowni). */
async function memberGymIds(prisma: PrismaClient, userId: string): Promise<string[]> {
const memberships = await prisma.gymMembership.findMany({
where: { userId },
select: { gymId: true },
});
return memberships.map((m) => m.gymId);
}
/**
* Umerged feed „Aktualności”: osobiste powiadomienia + ogłoszenia siłowni usera
* i globalne. Po `limit` z każdego źródła (kursor = `createdAt`), merge po
* `createdAt desc`, slice do `limit`.
*/
export async function getFeed(
prisma: PrismaClient,
userId: string,
opts: { limit?: number; cursor?: string | null } = {},
) {
const limit = Math.min(Math.max(opts.limit ?? 20, 1), 100);
// Nieprawidłowy kursor traktujemy jak brak kursora (pierwsza strona).
const parsed = opts.cursor ? new Date(opts.cursor) : null;
const createdBefore = parsed && !Number.isNaN(parsed.getTime()) ? { lt: parsed } : undefined;
const gymIds = await memberGymIds(prisma, userId);
const [notifications, announcements] = await Promise.all([
prisma.notification.findMany({
where: { userId, ...(createdBefore ? { createdAt: createdBefore } : {}) },
orderBy: { createdAt: 'desc' },
take: limit,
}),
prisma.announcement.findMany({
where: {
OR: [{ gymId: { in: gymIds } }, { gymId: null }],
...(createdBefore ? { createdAt: createdBefore } : {}),
},
orderBy: { createdAt: 'desc' },
take: limit,
include: { gym: { select: { id: true, name: true } } },
}),
]);
const readSet = new Set(
(
await prisma.announcementRead.findMany({
where: { userId, announcementId: { in: announcements.map((a) => a.id) } },
select: { announcementId: true },
})
).map((r) => r.announcementId),
);
const items: FeedItem[] = [
...notifications.map((n): FeedNotificationItem => ({
source: 'notification',
id: n.id,
type: n.type,
title: n.title,
payload: n.payload as Record<string, unknown>,
read: n.readAt !== null,
createdAt: n.createdAt.toISOString(),
})),
...announcements.map((a): FeedAnnouncementItem => ({
source: 'announcement',
id: a.id,
kind: a.kind,
title: a.title,
body: a.body,
gymId: a.gymId,
gymName: a.gym?.name ?? null,
createdAt: a.createdAt.toISOString(),
read: readSet.has(a.id),
})),
].sort((a, b) => b.createdAt.localeCompare(a.createdAt));
const page = items.slice(0, limit);
const nextCursor = page.length === limit ? page[page.length - 1].createdAt : null;
return { items: page, nextCursor };
}
/** Licznik nieprzeczytanych: powiadomienia + widoczne ogłoszenia bez wiersza reads. */
export async function getFeedUnreadCount(prisma: PrismaClient, userId: string) {
const gymIds = await memberGymIds(prisma, userId);
const [notifications, announcements] = await Promise.all([
prisma.notification.count({ where: { userId, readAt: null } }),
prisma.announcement.count({
where: {
AND: [
{ OR: [{ gymId: { in: gymIds } }, { gymId: null }] },
{ reads: { none: { userId } } },
],
},
}),
]);
return { unreadCount: notifications + announcements };
}
/** Zaznacza powiadomienie jako przeczytane (właściciel). */
export async function markNotificationRead(prisma: PrismaClient, userId: string, id: string) {
const result = await prisma.notification.updateMany({
where: { id, userId, readAt: null },
data: { readAt: new Date() },
});
if (result.count === 0) {
const existing = await prisma.notification.findFirst({ where: { id, userId } });
if (!existing) throw notFound('Notification not found');
}
return { ok: true };
}
/** Zaznacza ogłoszenie jako przeczytane (tylko globalne albo z siłowni usera). */
export async function markAnnouncementRead(prisma: PrismaClient, userId: string, id: string) {
const announcement = await prisma.announcement.findUnique({ where: { id } });
if (!announcement) throw notFound('Announcement not found');
if (announcement.gymId !== null) {
const membership = await prisma.gymMembership.findFirst({
where: { userId, gymId: announcement.gymId },
select: { id: true },
});
if (!membership) throw notFound('Announcement not found');
}
await prisma.announcementRead.upsert({
where: { announcementId_userId: { announcementId: id, userId } },
update: {},
create: { announcementId: id, userId },
});
return { ok: true };
}
/** Oznacza wszystkie widoczne wpisy jako przeczytane (oba źródła naraz). */
export async function markFeedAllRead(prisma: PrismaClient, userId: string) {
const gymIds = await memberGymIds(prisma, userId);
const [_updated, announcements] = await Promise.all([
prisma.notification.updateMany({
where: { userId, readAt: null },
data: { readAt: new Date() },
}),
prisma.announcement.findMany({
where: {
AND: [
{ OR: [{ gymId: { in: gymIds } }, { gymId: null }] },
{ reads: { none: { userId } } },
],
},
select: { id: true },
}),
]);
if (announcements.length > 0) {
await prisma.announcementRead.createMany({
data: announcements.map((a) => ({ announcementId: a.id, userId })),
skipDuplicates: true,
});
}
return { ok: true };
}

View File

@@ -6,6 +6,8 @@ import { removeGymClaimFiles, removeGymPhotoFiles } from '../../lib/uploads.js';
import { toPrismaAvailability, type Availability } from '../me.js';
import { gymCoverInclude, gymEquipmentInclude } from './includes.js';
import { coverUrlOf } from './photos.js';
import { announceHoursChange } from '../announcements.js';
import { notifyGymDeleted } from '../feed.js';
export type GymKind = 'VIRTUAL' | 'REAL';
@@ -119,12 +121,10 @@ export async function listVirtualGyms(prisma: PrismaClient, userId: string) {
down,
myVote: myVoteByGym.get(g.id) ?? null,
claimStatus: claim?.status ?? null,
rejectReason: claim?.status === 'REJECTED' ? claim.rejectReason ?? null : null,
rejectReason: claim?.status === 'REJECTED' ? (claim.rejectReason ?? null) : null,
};
});
publicList.sort(
(a, b) => b.up - b.down - (a.up - a.down) || a.name.localeCompare(b.name, 'pl'),
);
publicList.sort((a, b) => b.up - b.down - (a.up - a.down) || a.name.localeCompare(b.name, 'pl'));
const privateList = privateGyms
.map((g) => ({ ...g, isPrivate: true, memberCount: g._count.memberships }))
@@ -209,7 +209,7 @@ export async function createGym(
const hasAddress = !!(data.addressLine1?.trim() && data.postalCode?.trim() && data.city?.trim());
if (kind === 'REAL' && !hasAddress)
throw badRequest('Address (street, postal code, city) is required for real gyms');
const location = kind === 'REAL' ? formatAddress(data) : data.location ?? null;
const location = kind === 'REAL' ? formatAddress(data) : (data.location ?? null);
const address =
kind === 'REAL'
? {
@@ -274,7 +274,9 @@ export async function updateOwnedGym(
city: city !== undefined ? city : gym.city,
countryCode:
countryCode !== undefined
? countryCode ? countryCode.trim().toUpperCase() : null
? countryCode
? countryCode.trim().toUpperCase()
: null
: gym.countryCode,
};
addressData = { ...merged, location: formatAddress(merged) };
@@ -283,6 +285,9 @@ export async function updateOwnedGym(
where: { id: gymId },
data: { ...rest, ...addressData, availability: toPrismaAvailability(availability) },
});
if (availabilityChanged(gym.availability, availability)) {
await announceHoursChange(prisma, gymId, gym.name);
}
return { gym: updated };
} catch (e) {
if (isPrismaNotFound(e)) throw notFound('Gym not found');
@@ -290,10 +295,44 @@ export async function updateOwnedGym(
}
}
/**
* Czy doszło do faktycznej zmiany stałych godzin? `undefined` = brak zmiany.
* Porównanie znormalizowane (null/undefined → null), bez spamu ogłoszeniami
* przy edycji innych pól.
*/
export function availabilityChanged(
previous: unknown,
next: Availability | null | undefined,
): boolean {
if (next === undefined) return false;
return canonical(previous) !== canonical(next);
}
/**
* Kanoniczna serializacja wartości ustrukturyzowanych. jsonb w PostgreSQL
* zwraca obiekty z posortowanymi kluczami, więc plain JSON.stringify nie jest
* stabilny przy porównywaniu wartości z bazy z wartością z requestu.
*/
function canonical(v: unknown): string {
if (v === null || v === undefined) return 'null';
if (Array.isArray(v)) return `[${v.map(canonical).join(',')}]`;
if (typeof v === 'object') {
const o = v as Record<string, unknown>;
return `{${Object.keys(o)
.sort()
.map((k) => `${JSON.stringify(k)}:${canonical(o[k])}`)
.join(',')}}`;
}
return JSON.stringify(v);
}
/** Delete a gym (owner only). Memberships are removed; user plans are kept. */
export async function deleteOwnedGym(prisma: PrismaClient, gymId: string, userId: string) {
const gym = await assertGymOwner(prisma, gymId, userId);
const claimIds = await listGymClaimIds(prisma, gymId);
// Najpierw fan-out powiadomień — twarde usunięcie zabiłoby źródło, a nazwa
// siłowni jest duplikowana w payload.
await notifyGymDeleted(prisma, gymId, gym.name);
try {
await prisma.gym.delete({ where: { id: gymId } });
} catch (e) {

View File

@@ -4,6 +4,7 @@ import { isPrismaUnique } from '../../lib/prisma.js';
import { toPrismaJson, type DayAvailability } from '../me.js';
import { assertGymOwner } from './core.js';
import { gymEquipmentInclude } from './includes.js';
import { announceException } from '../announcements.js';
export interface CreateGymExceptionInput {
/** ISO date (YYYY-MM-DD) the exception applies to. */
@@ -13,11 +14,7 @@ export interface CreateGymExceptionInput {
}
/** List a gym's upcoming schedule exceptions (owner only). */
export async function listOwnedGymExceptions(
prisma: PrismaClient,
gymId: string,
userId: string,
) {
export async function listOwnedGymExceptions(prisma: PrismaClient, gymId: string, userId: string) {
await assertGymOwner(prisma, gymId, userId);
const exceptions = await prisma.gymException.findMany({
where: { gymId },
@@ -33,7 +30,7 @@ export async function createOwnedGymException(
userId: string,
data: CreateGymExceptionInput,
) {
await assertGymOwner(prisma, gymId, userId);
const gym = await assertGymOwner(prisma, gymId, userId);
const date = new Date(data.date);
if (Number.isNaN(date.getTime())) throw badRequest('Invalid date');
try {
@@ -44,6 +41,7 @@ export async function createOwnedGymException(
availability: toPrismaJson(data.availability),
},
});
await announceException(prisma, gymId, gym.name, data.date, data.availability ?? null);
return { exception };
} catch (e) {
if (isPrismaUnique(e)) throw conflict('An exception already exists for this date');
@@ -80,7 +78,8 @@ export async function addEquipment(
try {
await prisma.gymEquipment.create({ data: { gymId, equipmentId, quantity } });
} catch (e) {
if (isPrismaUnique(e)) throw conflict('Equipment already exists in this gym — update its quantity instead');
if (isPrismaUnique(e))
throw conflict('Equipment already exists in this gym — update its quantity instead');
throw e;
}
const updated = await prisma.gym.findUnique({
@@ -156,6 +155,7 @@ export async function createGymException(
availability: toPrismaJson(data.availability),
},
});
await announceException(prisma, gymId, gym.name, data.date, data.availability ?? null);
return { exception };
} catch (e) {
if (isPrismaUnique(e)) throw conflict('An exception already exists for this date');
@@ -164,11 +164,7 @@ export async function createGymException(
}
/** Remove a schedule exception. */
export async function deleteGymException(
prisma: PrismaClient,
gymId: string,
exceptionId: string,
) {
export async function deleteGymException(prisma: PrismaClient, gymId: string, exceptionId: string) {
const exception = await prisma.gymException.findUnique({ where: { id: exceptionId } });
if (!exception || exception.gymId !== gymId) throw notFound('Exception not found');
await prisma.gymException.delete({ where: { id: exceptionId } });

View File

@@ -1,6 +1,7 @@
import type { PrismaClient } from '@prisma/client';
import { AppError, badRequest, conflict, forbidden, notFound } from '../lib/errors.js';
import { isPrismaUnique } from '../lib/prisma.js';
import { createNotification } from './feed.js';
export interface PlanSetInput {
index: number;
@@ -174,6 +175,15 @@ export async function createPlan(
// Tworzenie planu jest zawsze możliwe, niezależnie od aktywnego planu — gdy
// właściciel już ma plan aktywny, aktywacja zostaje pominięta (plan = DRAFT).
const activationSkipped = await tryActivate(prisma, plan.id, userId, startOfStart);
// Plan tworzony przez trenera dla podopiecznego → powiadomienie „trener zrobił plan".
if (creatorId && creatorId !== userId) {
await createNotification(prisma, {
userId,
type: 'PLAN_READY',
title: `Trener utworzył dla Ciebie plan: ${data.title}`,
payload: { planId: plan.id, planTitle: data.title },
});
}
const updated = await prisma.trainingPlan.findUnique({
where: { id: plan.id },
include: { gym: { select: { id: true, name: true } } },
@@ -470,6 +480,12 @@ export async function sharePlan(
const share = await prisma.planShare.create({
data: { planId, sharedById: plan.userId, sharedWithId: userId },
});
await createNotification(prisma, {
userId,
type: 'PLAN_SHARED',
title: `Plan „${plan.title}” został Ci udostępniony`,
payload: { planId, planTitle: plan.title, sharedById: plan.userId },
});
return { share };
} catch (e) {
if (isPrismaUnique(e)) throw conflict('Plan is already shared with this user');

View File

@@ -365,6 +365,117 @@ export const openapi: Record<string, unknown> = {
],
},
},
'/gyms/{gymId}/announcements': {
get: {
tags: ['Gyms'],
summary: "List the gym's announcements (any member; canManage = OWNER)",
security: [{ bearerAuth: [] }],
parameters: [{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } }],
},
post: {
tags: ['Gyms'],
summary: "Publish an announcement to the gym's members (owner only)",
security: [{ bearerAuth: [] }],
parameters: [{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } }],
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
required: ['title', 'body'],
properties: {
title: { type: 'string', maxLength: 120 },
body: { type: 'string', maxLength: 2000 },
},
},
},
},
},
},
},
'/gyms/{gymId}/announcements/{announcementId}': {
patch: {
tags: ['Gyms'],
summary: 'Edit a manual announcement (owner only)',
security: [{ bearerAuth: [] }],
parameters: [
{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } },
{ name: 'announcementId', in: 'path', required: true, schema: { type: 'string' } },
],
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
required: ['title', 'body'],
properties: {
title: { type: 'string', maxLength: 120 },
body: { type: 'string', maxLength: 2000 },
},
},
},
},
},
},
delete: {
tags: ['Gyms'],
summary: 'Delete a manual announcement (owner only)',
security: [{ bearerAuth: [] }],
parameters: [
{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } },
{ name: 'announcementId', in: 'path', required: true, schema: { type: 'string' } },
],
},
},
'/me/feed': {
get: {
tags: ['Feed'],
summary:
'Merged feed of personal notifications and gym/global announcements (cursor = createdAt)',
security: [{ bearerAuth: [] }],
parameters: [
{ name: 'limit', in: 'query', schema: { type: 'integer', default: 20 } },
{
name: 'cursor',
in: 'query',
schema: { type: 'string' },
description: 'ISO createdAt of the last item on the page',
},
],
},
},
'/me/feed/unread-count': {
get: {
tags: ['Feed'],
summary: 'Unread counter (notifications + visible announcements)',
security: [{ bearerAuth: [] }],
},
},
'/me/feed/read-all': {
post: {
tags: ['Feed'],
summary: 'Mark all feed items as read (both sources)',
security: [{ bearerAuth: [] }],
},
},
'/me/feed/notifications/{id}/read': {
post: {
tags: ['Feed'],
summary: 'Mark a personal notification as read',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
},
'/me/feed/announcements/{id}/read': {
post: {
tags: ['Feed'],
summary: 'Mark an announcement as read (visible to the user only)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
},
'/admin/equipment': {
get: {
tags: ['Equipment'],
@@ -470,6 +581,64 @@ export const openapi: Record<string, unknown> = {
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
},
'/admin/announcements': {
get: {
tags: ['Admin'],
summary: 'List all announcements or those of one gym (?gymId=) (admin)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'gymId', in: 'query', schema: { type: 'string' } }],
},
post: {
tags: ['Admin'],
summary: 'Create an announcement — global (gymId null) or for a gym (admin)',
security: [{ bearerAuth: [] }],
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
required: ['title', 'body'],
properties: {
title: { type: 'string', maxLength: 120 },
body: { type: 'string', maxLength: 2000 },
gymId: { type: 'string', nullable: true },
},
},
},
},
},
},
},
'/admin/announcements/{id}': {
patch: {
tags: ['Admin'],
summary: 'Edit a manual announcement (admin)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
required: ['title', 'body'],
properties: {
title: { type: 'string', maxLength: 120 },
body: { type: 'string', maxLength: 2000 },
},
},
},
},
},
},
delete: {
tags: ['Admin'],
summary: 'Delete a manual announcement (admin)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
},
'/focus-areas': {
get: {
tags: ['FocusAreas'],

View File

@@ -0,0 +1,432 @@
import { describe, it, expect } from 'vitest';
import { prisma } from '../../src/lib/prisma.js';
import {
buildApp,
createUser,
createUserWithToken,
createExercise,
rand,
} from '../helpers.js';
/* Ciało planu jednowyeku z jednym ćwiczeniem (wystarczające do testów powiadomień). */
function planBody(exerciseId: string, title = 'Plan testowy', gymId?: string) {
return {
title,
weeksCount: 1,
...(gymId ? { gymId } : {}),
weeks: [
{
index: 0,
days: [
{
dayOfWeek: 1,
exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 10, restSec: 60 }] }],
},
],
},
],
};
}
const AV = [{ start: '06:00', end: '22:00' }, null, null, null, null, null, null];
const AV_CHANGED = [{ start: '07:00', end: '21:00' }, null, null, null, null, null, null];
async function activeCoaching(trainerId: string, userId: string) {
await prisma.coaching.create({
data: {
trainerId,
userId,
invitedBy: trainerId,
status: 'ACTIVE',
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
},
});
}
describe('feed — aktualności (powiadomienia + ogłoszenia)', () => {
it('PLAN_READY: plan utworzony przez trenera trafia do feedu podopiecznego', async () => {
const app = buildApp();
const { user: trainee, token: traineeToken } = await createUserWithToken();
const { user: trainer, token: trainerToken } = await createUserWithToken();
const gym = await prisma.gym.create({ data: { name: `T Gym ${rand()}` } });
await prisma.gymMembership.create({
data: { userId: trainer.id, gymId: gym.id, roles: ['TRAINER'] as never },
});
await activeCoaching(trainer.id, trainee.id);
const ex = await createExercise();
const res = await app
.post(`/api/v1/trainer/trainees/${trainee.id}/plans`)
.set('Authorization', `Bearer ${trainerToken}`)
.send(planBody(ex.id, 'Plan dla Darka'));
expect(res.status).toBe(201);
const feed = await app
.get('/api/v1/me/feed')
.set('Authorization', `Bearer ${traineeToken}`);
expect(feed.status).toBe(200);
const item = feed.body.items.find((i: { type?: string }) => i.type === 'PLAN_READY');
expect(item).toMatchObject({
source: 'notification',
title: 'Trener utworzył dla Ciebie plan: Plan dla Darka',
read: false,
});
expect(item.payload.planId).toBe(res.body.plan.id);
const unread = await app
.get('/api/v1/me/feed/unread-count')
.set('Authorization', `Bearer ${traineeToken}`);
expect(unread.body.unreadCount).toBe(1);
});
it('brak powiadomienia, gdy user tworzy plan sam sobie', async () => {
const app = buildApp();
const { user, token } = await createUserWithToken();
const ex = await createExercise();
const res = await app
.post('/api/v1/plans')
.set('Authorization', `Bearer ${token}`)
.send(planBody(ex.id, 'Własny plan'));
expect(res.status).toBe(201);
const count = await prisma.notification.count({ where: { userId: user.id } });
expect(count).toBe(0);
});
it('PLAN_SHARED: udostępnienie planu generuje powiadomienie odbiorcy', async () => {
const app = buildApp();
const { user: owner, token: ownerToken } = await createUserWithToken();
const { user: partner, token: partnerToken } = await createUserWithToken();
await activeCoaching(owner.id, partner.id);
const ex = await createExercise();
const created = await app
.post('/api/v1/plans')
.set('Authorization', `Bearer ${ownerToken}`)
.send(planBody(ex.id, 'Wspólny plan'));
expect(created.status).toBe(201);
const shared = await app
.post(`/api/v1/plans/${created.body.plan.id}/share`)
.set('Authorization', `Bearer ${ownerToken}`)
.send({ userId: partner.id });
expect(shared.status).toBe(201);
const feed = await app
.get('/api/v1/me/feed')
.set('Authorization', `Bearer ${partnerToken}`);
const item = feed.body.items.find((i: { type?: string }) => i.type === 'PLAN_SHARED');
expect(item).toMatchObject({ title: 'Plan „Wspólny plan” został Ci udostępniony' });
expect(item.payload.planId).toBe(created.body.plan.id);
});
it('ogłoszenia siłowni: OWNER tworzy, MEMBER czyta bez prawa edycji, brak członkostwa = 404', async () => {
const app = buildApp();
const { user: owner, token: ownerToken } = await createUserWithToken();
const { user: member, token: memberToken } = await createUserWithToken();
const { user: stranger, token: strangerToken } = await createUserWithToken();
const created = await app
.post('/api/v1/gyms')
.set('Authorization', `Bearer ${ownerToken}`)
.send({ name: `Ann Gym ${rand()}`, location: 'Warszawa' });
const gymId = created.body.gym.id as string;
await app.post(`/api/v1/gyms/${gymId}/join`).set('Authorization', `Bearer ${memberToken}`);
const post = await app
.post(`/api/v1/gyms/${gymId}/announcements`)
.set('Authorization', `Bearer ${ownerToken}`)
.send({ title: 'Awarida sauny', body: 'Sauna niedostępna do odwołania.' });
expect(post.status).toBe(201);
expect(post.body.announcement).toMatchObject({ kind: 'MANUAL', authorId: owner.id });
const list = await app
.get(`/api/v1/gyms/${gymId}/announcements`)
.set('Authorization', `Bearer ${memberToken}`);
expect(list.status).toBe(200);
expect(list.body.canManage).toBe(false);
expect(list.body.announcements).toHaveLength(1);
const memberPost = await app
.post(`/api/v1/gyms/${gymId}/announcements`)
.set('Authorization', `Bearer ${memberToken}`)
.send({ title: 'X', body: 'Y' });
expect(memberPost.status).toBe(403);
const strangerList = await app
.get(`/api/v1/gyms/${gymId}/announcements`)
.set('Authorization', `Bearer ${strangerToken}`);
expect(strangerList.status).toBe(404);
// feed członka zawiera ogłoszenie, feed postronnego — nie
const memberFeed = await app
.get('/api/v1/me/feed')
.set('Authorization', `Bearer ${memberToken}`);
expect(
memberFeed.body.items.some(
(i: { source: string; title?: string }) =>
i.source === 'announcement' && i.title === 'Awarida sauny',
),
).toBe(true);
const strangerFeed = await app
.get('/api/v1/me/feed')
.set('Authorization', `Bearer ${strangerToken}`);
expect(
strangerFeed.body.items.some((i: { source: string }) => i.source === 'announcement'),
).toBe(false);
const patched = await app
.patch(`/api/v1/gyms/${gymId}/announcements/${post.body.announcement.id}`)
.set('Authorization', `Bearer ${ownerToken}`)
.send({ title: 'Awarida sauny (akt.)', body: 'Naprawa w piątek.' });
expect(patched.status).toBe(200);
const removed = await app
.delete(`/api/v1/gyms/${gymId}/announcements/${post.body.announcement.id}`)
.set('Authorization', `Bearer ${ownerToken}`);
expect(removed.status).toBe(204);
});
it('dodanie wyjątku generuje automatyczne ogłoszenie EXCEPTION', async () => {
const app = buildApp();
const { user: owner, token: ownerToken } = await createUserWithToken();
const { token: memberToken } = await createUserWithToken();
const created = await app
.post('/api/v1/gyms')
.set('Authorization', `Bearer ${ownerToken}`)
.send({ name: `Wyj. Gym ${rand()}`, location: 'Kraków' });
const gymId = created.body.gym.id as string;
await app.post(`/api/v1/gyms/${gymId}/join`).set('Authorization', `Bearer ${memberToken}`);
const ex = await app
.post(`/api/v1/gyms/${gymId}/exceptions`)
.set('Authorization', `Bearer ${ownerToken}`)
.send({ date: '2026-12-24', availability: null });
expect(ex.status).toBe(201);
const feed = await app
.get('/api/v1/me/feed')
.set('Authorization', `Bearer ${memberToken}`);
const item = feed.body.items.find(
(i: { kind?: string }) => i.kind === 'EXCEPTION',
);
expect(item).toBeTruthy();
expect(item.title).toContain('24.12.2026');
expect(item.body).toBe('Tego dnia siłownia będzie nieczynna.');
});
it('zmiana godzin ogłaszana raz; edycja innych pól nie generuje ogłoszenia', async () => {
const app = buildApp();
const { user: owner, token: ownerToken } = await createUserWithToken();
const created = await app
.post('/api/v1/gyms')
.set('Authorization', `Bearer ${ownerToken}`)
.send({ name: `Godz. Gym ${rand()}`, location: 'Gdańsk', availability: AV });
const gymId = created.body.gym.id as string;
const countHours = () =>
prisma.announcement.count({ where: { gymId, kind: 'HOURS_CHANGE' } });
await app
.patch(`/api/v1/gyms/${gymId}`)
.set('Authorization', `Bearer ${ownerToken}`)
.send({ name: `Godz. Gym renamed ${rand()}` });
await app
.patch(`/api/v1/gyms/${gymId}`)
.set('Authorization', `Bearer ${ownerToken}`)
.send({ availability: AV });
expect(await countHours()).toBe(0);
const changed = await app
.patch(`/api/v1/gyms/${gymId}`)
.set('Authorization', `Bearer ${ownerToken}`)
.send({ availability: AV_CHANGED });
expect(changed.status).toBe(200);
expect(await countHours()).toBe(1);
});
it('GYM_DELETED: fanaout do członków z nazwą w payloadzie; postronni bez powiadomienia', async () => {
const app = buildApp();
const { user: owner, token: ownerToken } = await createUserWithToken();
const { user: member, token: memberToken } = await createUserWithToken();
const { user: stranger } = await createUser();
const gymName = `Znikomy Club ${rand()}`;
const created = await app
.post('/api/v1/gyms')
.set('Authorization', `Bearer ${ownerToken}`)
.send({ name: gymName, location: 'Poznań' });
const gymId = created.body.gym.id as string;
await app.post(`/api/v1/gyms/${gymId}/join`).set('Authorization', `Bearer ${memberToken}`);
const del = await app
.delete(`/api/v1/gyms/${gymId}`)
.set('Authorization', `Bearer ${ownerToken}`);
expect(del.status).toBe(204);
const memberNotif = await prisma.notification.findFirst({
where: { userId: member.id, type: 'GYM_DELETED' },
});
expect(memberNotif?.title).toBe(`Siłownia „${gymName}” została usunięta`);
expect(memberNotif?.payload).toMatchObject({ gymName });
const strangerCount = await prisma.notification.count({
where: { userId: stranger.id, type: 'GYM_DELETED' },
});
expect(strangerCount).toBe(0);
// powiadomienie przeżywa usunięcie siłowni (payload self-contained)
const feed = await app
.get('/api/v1/me/feed')
.set('Authorization', `Bearer ${memberToken}`);
const item = feed.body.items.find((i: { type?: string }) => i.type === 'GYM_DELETED');
expect(item).toBeTruthy();
});
it('oznaczanie przeczytania: per wpis i „oznacz wszystkie”', async () => {
const app = buildApp();
const { user: owner, token: ownerToken } = await createUserWithToken();
const { token: memberToken } = await createUserWithToken();
const created = await app
.post('/api/v1/gyms')
.set('Authorization', `Bearer ${ownerToken}`)
.send({ name: `Read Gym ${rand()}`, location: 'Wrocław' });
const gymId = created.body.gym.id as string;
await app.post(`/api/v1/gyms/${gymId}/join`).set('Authorization', `Bearer ${memberToken}`);
const a1 = await app
.post(`/api/v1/gyms/${gymId}/announcements`)
.set('Authorization', `Bearer ${ownerToken}`)
.send({ title: 'Ogłoszenie 1', body: 'Treść 1' });
const a2 = await app
.post(`/api/v1/gyms/${gymId}/announcements`)
.set('Authorization', `Bearer ${ownerToken}`)
.send({ title: 'Ogłoszenie 2', body: 'Treść 2' });
let unread = await app
.get('/api/v1/me/feed/unread-count')
.set('Authorization', `Bearer ${memberToken}`);
expect(unread.body.unreadCount).toBe(2);
const mark = await app
.post(`/api/v1/me/feed/announcements/${a1.body.announcement.id}/read`)
.set('Authorization', `Bearer ${memberToken}`);
expect(mark.status).toBe(200);
unread = await app
.get('/api/v1/me/feed/unread-count')
.set('Authorization', `Bearer ${memberToken}`);
expect(unread.body.unreadCount).toBe(1);
const feed = await app
.get('/api/v1/me/feed')
.set('Authorization', `Bearer ${memberToken}`);
const readItem = feed.body.items.find(
(i: { id?: string }) => i.id === a1.body.announcement.id,
);
expect(readItem.read).toBe(true);
const all = await app
.post('/api/v1/me/feed/read-all')
.set('Authorization', `Bearer ${memberToken}`);
expect(all.status).toBe(200);
unread = await app
.get('/api/v1/me/feed/unread-count')
.set('Authorization', `Bearer ${memberToken}`);
expect(unread.body.unreadCount).toBe(0);
// idempotentność powtórnego oznaczenia
const again = await app
.post(`/api/v1/me/feed/announcements/${a2.body.announcement.id}/read`)
.set('Authorization', `Bearer ${memberToken}`);
expect(again.status).toBe(200);
});
it('ogłoszenia admina: globalne widoczne dla wszystkich; typ systemowy nietykalny', async () => {
const app = buildApp();
const { user: admin, token: adminToken } = await createUserWithToken({ isAdmin: true });
const { token: plainToken } = await createUserWithToken();
const forbidden = await app
.post('/api/v1/admin/announcements')
.set('Authorization', `Bearer ${plainToken}`)
.send({ title: 'Nie moje', body: 'Bez roli admina' });
expect(forbidden.status).toBe(403);
const global = await app
.post('/api/v1/admin/announcements')
.set('Authorization', `Bearer ${adminToken}`)
.send({ title: 'Przerwa techniczna', body: 'Platforma niedostępna w nocy.' });
expect(global.status).toBe(201);
expect(global.body.announcement).toMatchObject({ gymId: null, authorId: admin.id });
const feed = await app
.get('/api/v1/me/feed')
.set('Authorization', `Bearer ${plainToken}`);
const item = feed.body.items.find(
(i: { id?: string }) => i.id === global.body.announcement.id,
);
expect(item).toMatchObject({ source: 'announcement', gymId: null });
const patched = await app
.patch(`/api/v1/admin/announcements/${global.body.announcement.id}`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ title: 'Przerwa techniczna (akt.)', body: 'Nowa godzina.' });
expect(patched.status).toBe(200);
// typ systemowy: edycja/usunięcie zablokowane (400)
const { user: owner, token: ownerToken } = await createUserWithToken();
const created = await app
.post('/api/v1/gyms')
.set('Authorization', `Bearer ${ownerToken}`)
.send({ name: `Sys Gym ${rand()}`, location: 'Łódź' });
const gymId = created.body.gym.id as string;
await app
.post(`/api/v1/gyms/${gymId}/exceptions`)
.set('Authorization', `Bearer ${ownerToken}`)
.send({ date: '2026-12-31', availability: { start: '10:00', end: '14:00' } });
const sys = await prisma.announcement.findFirst({
where: { gymId, kind: 'EXCEPTION' },
});
expect(sys).toBeTruthy();
const sysPatch = await app
.patch(`/api/v1/admin/announcements/${sys!.id}`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ title: 'X', body: 'Y' });
expect(sysPatch.status).toBe(400);
const sysDelete = await app
.delete(`/api/v1/admin/announcements/${sys!.id}`)
.set('Authorization', `Bearer ${adminToken}`);
expect(sysDelete.status).toBe(400);
const del = await app
.delete(`/api/v1/admin/announcements/${global.body.announcement.id}`)
.set('Authorization', `Bearer ${adminToken}`);
expect(del.status).toBe(204);
});
it('paginacja kursorowa: limit + cursor zwracają kolejne, rozłączne strony', async () => {
const app = buildApp();
const { token } = await createUserWithToken();
const base = Date.now() - 1000 * 60;
for (let i = 0; i < 12; i++) {
await prisma.announcement.create({
data: {
gymId: null,
kind: 'MANUAL',
title: `Ogłoszenie ${i}`,
body: 'Treść',
createdAt: new Date(base + i * 1000),
},
});
}
const p1 = await app
.get('/api/v1/me/feed?limit=5')
.set('Authorization', `Bearer ${token}`);
expect(p1.status).toBe(200);
expect(p1.body.items).toHaveLength(5);
expect(p1.body.nextCursor).toBeTruthy();
const p2 = await app
.get(`/api/v1/me/feed?limit=5&cursor=${encodeURIComponent(p1.body.nextCursor)}`)
.set('Authorization', `Bearer ${token}`);
expect(p2.body.items).toHaveLength(5);
const ids1 = new Set(p1.body.items.map((i: { id: string }) => i.id));
expect(p2.body.items.every((i: { id: string }) => !ids1.has(i.id))).toBe(true);
// strona 1 = najnowsze, malejąco
const times = p1.body.items.map((i: { createdAt: string }) => i.createdAt);
expect([...times].sort().reverse()).toEqual(times);
});
});

View File

@@ -0,0 +1,38 @@
import { describe, it, expect } from 'vitest';
import { availabilityChanged } from '../../src/services/gyms/core.js';
describe('availabilityChanged — wykrywanie zmiany godzin', () => {
const AV = [{ start: '06:00', end: '22:00' }, null, null, null, null, null, null];
it('wraca false, gdy next jest undefined (brak pola w PATCH)', () => {
expect(availabilityChanged(AV, undefined)).toBe(false);
expect(availabilityChanged(null, undefined)).toBe(false);
});
it('identyczna struktura = brak zmiany', () => {
expect(availabilityChanged(AV, [...AV])).toBe(false);
});
it('kolejność kluczy nie ma znaczenia (jsonb sortuje klucze)', () => {
const fromDb = [{ end: '22:00', start: '06:00' }, null, null, null, null, null, null];
expect(availabilityChanged(fromDb, AV)).toBe(false);
});
it('null i undefined traktowane są jako ten sam brak wartości', () => {
expect(availabilityChanged(null, null)).toBe(false);
expect(availabilityChanged(undefined, null)).toBe(false);
expect(availabilityChanged(null, undefined === undefined ? null : undefined)).toBe(false);
});
it('zmiana godzin = true', () => {
expect(availabilityChanged(AV, [{ start: '07:00', end: '21:00' }, null, null, null, null, null, null])).toBe(true);
});
it('ustawienie godzin tam, gdzie ich nie było = true', () => {
expect(availabilityChanged(null, AV)).toBe(true);
});
it('wyczyszczenie godzin = true', () => {
expect(availabilityChanged(AV, null)).toBe(true);
});
});

View File

@@ -41,6 +41,7 @@ function mockPrisma() {
deleteMany: vi.fn(),
findMany: vi.fn(),
},
notification: { create: vi.fn(async (args: { data: unknown }) => ({ id: 'n1', ...args.data })) },
$transaction: vi.fn(async (cb: (tx: typeof tx) => Promise<void>) => cb(tx)),
};
return { prisma, tx };
@@ -445,6 +446,11 @@ describe('createPlan creatorId', () => {
startDate: null,
});
await createPlan(prisma, 'trainee-1', { title: 't', weeksCount: 1, weeks: [] }, 'trainer-1');
expect(prisma.notification.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({ userId: 'trainee-1', type: 'PLAN_READY' }),
}),
);
expect(prisma.trainingPlan.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({ userId: 'trainee-1', creatorId: 'trainer-1' }),
@@ -612,6 +618,11 @@ describe('sharePlan', () => {
data: { planId: 'p1', sharedById: 'u1', sharedWithId: 'trainee-1' },
});
expect(result).toEqual({ share: { id: 'share-1' } });
expect(prisma.notification.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({ userId: 'trainee-1', type: 'PLAN_SHARED' }),
}),
);
});
it('właściciel udostępnia plan swojemu trenerowi (odwrotny kierunek coachingu)', async () => {

View File

@@ -24,6 +24,7 @@ import TraineeDetail from './pages/trainees/TraineeDetail';
import Invitations from './pages/Invitations';
import Messages from './pages/messages/Messages';
import MessageThread from './pages/messages/MessageThread';
import Announcements from './pages/announcements/Announcements';
/**
* Trasa tylko dla trenerów — API i tak odda 403, ale nie pokazujemy pustej
@@ -97,6 +98,7 @@ export default function App() {
<Route path="/invitations" element={<Invitations />} />
<Route path="/messages" element={<Messages />} />
<Route path="/messages/:coachingId" element={<MessageThread />} />
<Route path="/announcements" element={<Announcements />} />
<Route path="/profile" element={<Profile />} />
<Route path="/profile/info" element={<ProfileInfo />} />
<Route path="/profile/body-parameters" element={<ProfileBodyParameters />} />

View File

@@ -1,4 +1,4 @@
import { useQuery } from '@tanstack/react-query';
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
import { api } from './client';
import type {
ActiveSession,
@@ -8,6 +8,8 @@ import type {
ConversationThread,
Dashboard,
Equipment,
FeedItem,
GymAnnouncement,
ExerciseComment,
ExerciseProgress,
FocusArea,
@@ -813,3 +815,61 @@ export function completeTraineePlan(userId: string, planId: string) {
export function reopenTraineePlan(userId: string, planId: string) {
return api(`/trainer/trainees/${userId}/plans/${planId}/reopen`, { method: 'POST' });
}
// ---------- aktualności (feed) ----------
export function useFeed(limit = 20) {
return useInfiniteQuery({
queryKey: ['feed', limit],
queryFn: ({ pageParam }) =>
api<{ items: FeedItem[]; nextCursor: string | null }>(
`/me/feed?limit=${limit}${pageParam ? `&cursor=${encodeURIComponent(pageParam)}` : ''}`,
),
initialPageParam: null as string | null,
getNextPageParam: (last) => last.nextCursor,
refetchInterval: 60_000,
});
}
export function useFeedUnreadCount() {
return useQuery({
queryKey: ['feed', 'unread-count'],
queryFn: () => api<{ unreadCount: number }>('/me/feed/unread-count'),
refetchInterval: 60_000,
});
}
/** Oznaczenie przeczytania wpisu feedu (wg źródła). */
export function markFeedItemRead(item: FeedItem) {
const path =
item.source === 'notification'
? `/me/feed/notifications/${encodeURIComponent(item.id)}/read`
: `/me/feed/announcements/${encodeURIComponent(item.id)}/read`;
return api(path, { method: 'POST' });
}
export function markFeedAllRead() {
return api('/me/feed/read-all', { method: 'POST' });
}
// ---------- ogłoszenia siłowni (właściciel) ----------
export function useGymAnnouncements(gymId: string | undefined, enabled = true) {
return useQuery({
queryKey: ['gym-announcements', gymId],
queryFn: () =>
api<{ announcements: GymAnnouncement[]; canManage: boolean }>(
`/gyms/${gymId}/announcements`,
),
enabled: !!gymId && enabled,
});
}
export function createGymAnnouncement(gymId: string, data: { title: string; body: string }) {
return api<{ announcement: GymAnnouncement }>(`/gyms/${gymId}/announcements`, {
method: 'POST',
body: data,
});
}
export function deleteGymAnnouncement(gymId: string, announcementId: string) {
return api(`/gyms/${gymId}/announcements/${announcementId}`, { method: 'DELETE' });
}

View File

@@ -482,6 +482,46 @@ export interface ConversationThread {
messages: Message[];
}
// ---------- aktualności (feed) ----------
export type NotificationType = 'PLAN_READY' | 'PLAN_SHARED' | 'GYM_DELETED';
export interface FeedNotificationItem {
source: 'notification';
id: string;
type: NotificationType;
title: string;
payload: Record<string, unknown>;
read: boolean;
createdAt: string;
}
export type AnnouncementKind = 'MANUAL' | 'HOURS_CHANGE' | 'EXCEPTION';
export interface FeedAnnouncementItem {
source: 'announcement';
id: string;
kind: AnnouncementKind;
title: string;
body: string;
gymId: string | null;
gymName: string | null;
createdAt: string;
read: boolean;
}
export type FeedItem = FeedNotificationItem | FeedAnnouncementItem;
/** Ogłoszenie siłowni w widoku zarządzania (właściciel) i listy członków. */
export interface GymAnnouncement {
id: string;
gymId: string | null;
authorId: string | null;
kind: AnnouncementKind;
title: string;
body: string;
createdAt: string;
}
// ---------- postępy per ćwiczenie ----------
export interface ExerciseProgressPoint {
date: string;

View File

@@ -0,0 +1,103 @@
import { CalendarX, Clock, Building2, Dumbbell, Megaphone, Share2, type LucideIcon } from 'lucide-react';
import { useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { markFeedItemRead } from '../api/queries';
import type { FeedItem } from '../api/types';
import { timeAgo } from '../lib/format';
import { useToast } from './toast';
/** Deeplink wpisu feedu; null = wpis bez przejścia. */
export function feedDeeplink(item: FeedItem): string | null {
if (item.source === 'notification') {
if (item.type === 'PLAN_READY' || item.type === 'PLAN_SHARED') {
const planId = item.payload.planId;
return typeof planId === 'string' ? `/plans/${planId}` : null;
}
return null;
}
return item.gymId ? `/gyms/${item.gymId}` : null;
}
/** Ikona + podpis źródła wpisu (wspólna dla karty dashboardu i strony aktualności). */
export function feedItemIcon(item: FeedItem): { Icon: LucideIcon; label: string } {
if (item.source === 'notification') {
switch (item.type) {
case 'PLAN_READY':
return { Icon: Dumbbell, label: 'Plan od trenera' };
case 'PLAN_SHARED':
return { Icon: Share2, label: 'Udostępniony plan' };
case 'GYM_DELETED':
return { Icon: Building2, label: 'Usunięta siłownia' };
}
}
switch (item.kind) {
case 'MANUAL':
return { Icon: Megaphone, label: item.gymName ?? 'Ogłoszenie' };
case 'HOURS_CHANGE':
return { Icon: Clock, label: item.gymName ?? 'Zmiana godzin' };
case 'EXCEPTION':
return { Icon: CalendarX, label: item.gymName ?? 'Wyjątek w godzinach' };
}
}
/**
* Wiersz wpisu „Aktualności": klik = oznaczenie przeczytania + deeplink.
* `compact` (karta dashboardu) pomija treść ogłoszenia.
*/
export function FeedItemRow({ item, compact = false }: { item: FeedItem; compact?: boolean }) {
const navigate = useNavigate();
const queryClient = useQueryClient();
const { push } = useToast();
const { Icon, label } = feedItemIcon(item);
const to = feedDeeplink(item);
const open = async () => {
if (!item.read) {
try {
await markFeedItemRead(item);
await queryClient.invalidateQueries({ queryKey: ['feed'] });
} catch (err) {
push((err as Error).message, 'error');
return;
}
}
if (to) navigate(to);
};
return (
<button
type="button"
onClick={() => void open()}
className={`flex w-full items-start gap-3 rounded-[10px] px-2 py-2.5 text-left transition-colors hover:bg-line/20 ${
to ? 'cursor-pointer' : 'cursor-default'
}`}
>
<span
aria-hidden="true"
className={`mt-0.5 grid h-8 w-8 shrink-0 place-items-center rounded-[10px] ${
item.source === 'notification' && item.type === 'GYM_DELETED'
? 'bg-danger/10 text-danger'
: 'bg-accent/12 text-accent-text'
}`}
>
<Icon className="h-4 w-4" />
</span>
<span className="min-w-0 flex-1">
<span
className={`block truncate text-[0.9rem] ${item.read ? 'font-semibold' : 'font-extrabold text-ink'}`}
>
{item.title}
</span>
<span className="mt-0.5 block truncate text-dim text-[0.78rem]">
{label} · {timeAgo(item.createdAt)}
</span>
{!compact && item.source === 'announcement' && (
<span className="mt-1 block line-clamp-3 text-dim text-[0.8125rem]">{item.body}</span>
)}
</span>
{!item.read && (
<span aria-hidden="true" className="mt-2.5 h-2 w-2 shrink-0 rounded-full bg-accent" />
)}
</button>
);
}

View File

@@ -7,6 +7,7 @@ import {
LayoutDashboard,
LogOut,
Mail,
Megaphone,
Menu,
MessageSquare,
Play,
@@ -19,6 +20,7 @@ import { useAuth } from '../store/auth';
import {
useActiveSession,
useConversations,
useFeedUnreadCount,
useGymInvitations,
useInvitations,
useIsTrainer,
@@ -49,6 +51,7 @@ const GYM_NAV: NavItem = { to: '/gyms', label: 'Siłownie', icon: Building2, end
const TRAINEES_NAV: NavItem = { to: '/trainees', label: 'Podopieczni', icon: Users, end: false };
const INVITATIONS_NAV: NavItem = { to: '/invitations', label: 'Zaproszenia', icon: Mail, end: false };
const MESSAGES_NAV: NavItem = { to: '/messages', label: 'Komunikator', icon: MessageSquare, end: false };
const ANNOUNCEMENTS_NAV: NavItem = { to: '/announcements', label: 'Aktualności', icon: Megaphone, end: false };
const SIDEBAR_KEY = 'fitos-sidebar-collapsed';
@@ -142,6 +145,9 @@ export default function Layout() {
(invitations?.invitations ?? []).length + (gymInvitations?.invitations ?? []).length;
// Nieprzeczytane wiadomości w komunikatorze (suma per rozmowa).
const unreadMessages = (conversations?.conversations ?? []).reduce((n, c) => n + c.unreadCount, 0);
// Nieprzeczytane aktualności (powiadomienia osobiste + ogłoszenia siłowni).
const { data: feedUnread } = useFeedUnreadCount();
const unreadFeed = feedUnread?.unreadCount ?? 0;
const { data: activeSessionData } = useActiveSession();
const activeSession = activeSessionData?.session ?? null;
// Aktywna sesja => stały skrót „Trening” w menu (po Kalendarzu), prowadzący do dnia sesji.
@@ -157,6 +163,12 @@ export default function Layout() {
{ ...MESSAGES_NAV, badge: unreadMessages },
navItems[navItems.length - 1],
];
// „Aktualności” zaraz za komunikatorem, badge = nieprzeczytany feed.
navItems = [
...navItems.slice(0, -1),
{ ...ANNOUNCEMENTS_NAV, badge: unreadFeed },
navItems[navItems.length - 1],
];
if (isTrainer) navItems = [...navItems.slice(0, -1), TRAINEES_NAV, navItems[navItems.length - 1]];
if (pendingInvitations > 0) navItems = [...navItems.slice(0, -1), INVITATIONS_NAV, navItems[navItems.length - 1]];

View File

@@ -1,8 +1,9 @@
import { useEffect, useState, type ReactNode } from 'react';
import { Link } from 'react-router-dom';
import { CalendarPlus, Dumbbell, Flame, Play } from 'lucide-react';
import { CalendarPlus, Dumbbell, Flame, Megaphone, Play } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { useActiveSession, useDashboard } from '../api/queries';
import { useActiveSession, useDashboard, useFeed } from '../api/queries';
import { FeedItemRow } from '../components/FeedItemRow';
import { useAuth } from '../store/auth';
import { fmtDate, todayStr } from '../lib/format';
import { DAY_NAMES, MUSCLE_NAMES } from '../lib/labels';
@@ -234,6 +235,36 @@ function SessionBanner({
);
}
/* Karta „Aktualności": ostatnie wpisy feedu (powiadomienia + ogłoszenia siłowni). */
function FeedCard() {
const { data } = useFeed(5);
const items = data?.pages.flatMap((p) => p.items ?? []) ?? [];
return (
<Card>
<SectionHeader
title="Aktualności"
actions={
<Link to="/announcements" className="text-[0.8125rem] font-bold text-accent-text hover:underline">
Zobacz wszystkie
</Link>
}
/>
{items.length === 0 ? (
<p className="flex items-center gap-2 text-[0.875rem] text-dim">
<Megaphone className="h-4 w-4" />
Brak aktualności — tu pojawią się plany od trenera i ogłoszenia siłowni.
</p>
) : (
<div className="-mx-2">
{items.map((item) => (
<FeedItemRow key={`${item.source}-${item.id}`} item={item} compact />
))}
</div>
)}
</Card>
);
}
export default function Dashboard() {
useTopbar({ title: 'Dashboard' });
const { user } = useAuth();
@@ -411,6 +442,10 @@ export default function Dashboard() {
/>
)}
</Card>
<div className="mt-4">
<FeedCard />
</div>
</>
);
}

View File

@@ -0,0 +1,72 @@
import { useQueryClient } from '@tanstack/react-query';
import { Megaphone } from 'lucide-react';
import { markFeedAllRead, useFeed } from '../../api/queries';
import { FeedItemRow } from '../../components/FeedItemRow';
import { Button, Card, ErrorText, Loading, Muted } from '../../components/ui';
import { useToast } from '../../components/toast';
import { useTopbar } from '../../topbar';
export default function Announcements() {
useTopbar({ title: 'Aktualności' });
const queryClient = useQueryClient();
const { push } = useToast();
const { data, isLoading, error, hasNextPage, isFetchingNextPage, fetchNextPage } = useFeed(20);
const items = data?.pages.flatMap((p) => p.items ?? []) ?? [];
const markAll = async () => {
try {
await markFeedAllRead();
await queryClient.invalidateQueries({ queryKey: ['feed'] });
push('Wszystko oznaczone jako przeczytane', 'success');
} catch (err) {
push((err as Error).message, 'error');
}
};
if (isLoading) return <Loading />;
if (error) return <ErrorText>Błąd: {(error as Error).message}</ErrorText>;
return (
<>
<Card>
{/* Tytuł strony jest w topbarze — tu tylko opis i akcje (bez duplikacji nagłówka). */}
<div className="mb-3 flex flex-wrap items-start justify-between gap-3">
<Muted className="text-[0.875rem]">
Plany od trenera, ogłoszenia Twoich siłowni i komunikaty platformy.
</Muted>
{items.some((i) => !i.read) && (
<div className="flex shrink-0 items-center gap-2">
<Button variant="secondary" size="sm" type="button" onClick={() => void markAll()}>
Oznacz wszystkie
</Button>
</div>
)}
</div>
{items.length === 0 ? (
<p className="flex items-center gap-2 text-[0.875rem] text-dim">
<Megaphone className="h-4 w-4" />
Brak aktualności — tu pojawią się plany od trenera i ogłoszenia siłowni.
</p>
) : (
<div className="-mx-2">
{items.map((item) => (
<FeedItemRow key={`${item.source}-${item.id}`} item={item} />
))}
</div>
)}
{hasNextPage && (
<div className="mt-3">
<Button
variant="secondary"
type="button"
disabled={isFetchingNextPage}
onClick={() => void fetchNextPage()}
>
{isFetchingNextPage ? 'Wczytywanie…' : 'Wczytaj starsze'}
</Button>
</div>
)}
</Card>
</>
);
}

View File

@@ -5,6 +5,7 @@ import {
ArrowLeft,
Dumbbell,
Image as ImageIcon,
Megaphone,
MapPin,
Pencil,
UserPlus,
@@ -12,9 +13,12 @@ import {
Wrench,
} from 'lucide-react';
import {
createGymAnnouncement,
createGymException,
deleteGym,
deleteGymAnnouncement,
deleteGymException,
useGymAnnouncements,
useGymDetail,
useGymExceptions,
useGymInvitations,
@@ -23,6 +27,7 @@ import {
withdrawGymInvitation,
} from '../../api/queries';
import type { Gym, GymException } from '../../api/types';
import { fmtDateTime } from '../../lib/format';
import { formatGymEquipment } from '../../lib/equipment';
import {
BackButton,
@@ -36,6 +41,7 @@ import {
Modal,
SectionHeader,
Select,
Textarea,
} from '../../components/ui';
import { useToast } from '../../components/toast';
import { Avatar } from '../../components/Avatar';
@@ -327,6 +333,7 @@ export default function GymDetail() {
const [editOpen, setEditOpen] = useState(false);
const [galleryOpen, setGalleryOpen] = useState(false);
const [equipmentOpen, setEquipmentOpen] = useState(false);
const [announcementsOpen, setAnnouncementsOpen] = useState(false);
const remove = async () => {
if (!gym) return;
@@ -385,6 +392,12 @@ export default function GymDetail() {
icon: Wrench,
actions: [{ label: 'Urządzenia', onClick: () => setEquipmentOpen(true) }],
},
{
id: 'announcements',
label: 'Ogłoszenia',
icon: Megaphone,
actions: [{ label: 'Ogłoszenia do członków', onClick: () => setAnnouncementsOpen(true) }],
},
...(gym.kind === 'VIRTUAL' && gym.isPrivate
? [
{
@@ -610,6 +623,13 @@ export default function GymDetail() {
>
<EquipmentSection key={gym.id} gym={gym} />
</Modal>
<Modal
open={announcementsOpen}
onClose={() => setAnnouncementsOpen(false)}
title="Ogłoszenia do członków"
>
<AnnouncementsSection gymId={gym.id} />
</Modal>
{gym.kind === 'VIRTUAL' && (
<ClaimModal
open={claimOpen}
@@ -641,6 +661,124 @@ export default function GymDetail() {
);
}
/* Ogłoszenia do członków (lista + tworzenie + usuwanie ręcznych). */
function AnnouncementsSection({ gymId }: { gymId: string }) {
const queryClient = useQueryClient();
const { push } = useToast();
const { data, isLoading } = useGymAnnouncements(gymId);
const announcements = data?.announcements ?? [];
const [title, setTitle] = useState('');
const [body, setBody] = useState('');
const [busy, setBusy] = useState(false);
const invalidate = async () => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['gym-announcements', gymId] }),
queryClient.invalidateQueries({ queryKey: ['feed'] }),
]);
};
const add = async () => {
setBusy(true);
try {
await createGymAnnouncement(gymId, { title, body });
await invalidate();
push('Ogłoszenie opublikowane', 'success');
setTitle('');
setBody('');
} catch (err) {
push((err as Error).message, 'error');
} finally {
setBusy(false);
}
};
const remove = async (id: string) => {
try {
await deleteGymAnnouncement(gymId, id);
await invalidate();
push('Ogłoszenie usunięte', 'success');
} catch (err) {
push((err as Error).message, 'error');
}
};
return (
<div>
<div className="rounded-xl border border-line bg-input/40 p-3.5">
<div className="mb-2.5 text-[11px] font-bold uppercase tracking-[0.1em] text-dim">
Nowe ogłoszenie — trafi do wszystkich członków siłowni
</div>
<Input
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Tytuł (np. Awarida klimatyzacji)"
aria-label="Tytuł ogłoszenia"
maxLength={120}
/>
<Textarea
value={body}
onChange={(e) => setBody(e.target.value)}
placeholder="Treść ogłoszenia…"
aria-label="Treść ogłoszenia"
maxLength={2000}
rows={3}
className="mt-2.5"
/>
<Button
type="button"
className="mt-2.5"
onClick={() => void add()}
disabled={busy || !title.trim() || !body.trim()}
>
{busy ? 'Publikowanie…' : 'Opublikuj'}
</Button>
</div>
<div className="mt-4">
{isLoading ? (
<Loading />
) : announcements.length === 0 ? (
<p className="text-[0.875rem] text-dim">Brak ogłoszeń.</p>
) : (
<div className="flex flex-col gap-2">
{announcements.map((a) => (
<div
key={a.id}
className="rounded-[10px] border border-line bg-card/50 px-3 py-2.5"
>
<div className="flex items-center gap-2">
<span className="min-w-0 flex-1 truncate text-[0.9rem] font-bold">{a.title}</span>
{a.kind !== 'MANUAL' && (
<span className="shrink-0 rounded-full bg-dim/13 px-2 py-0.5 text-[0.65rem] font-extrabold uppercase tracking-wide text-dim">
Systemowe
</span>
)}
<span className="shrink-0 text-[0.72rem] tabular-nums text-dim">
{fmtDateTime(a.createdAt)}
</span>
</div>
<p className="mt-1 whitespace-pre-wrap text-dim text-[0.8125rem]">{a.body}</p>
{a.kind === 'MANUAL' && (
<div className="mt-2">
<Button
variant="danger"
size="sm"
type="button"
onClick={() => void remove(a.id)}
>
Usuń
</Button>
</div>
)}
</div>
))}
</div>
)}
</div>
</div>
);
}
/* Zaproszenia do prywatnej siłowni (lista + wycofywanie). */
function GymInvitationsSection({ gym }: { gym: Gym }) {
const queryClient = useQueryClient();

89
app/test/e2e/feed.spec.ts Normal file
View File

@@ -0,0 +1,89 @@
import { test, expect } from './fixtures';
import { mockApi, TEST_GYM_OWNED } from './mock-api';
const NOW = Date.now();
const iso = (minsAgo: number) => new Date(NOW - minsAgo * 60_000).toISOString();
function feedState() {
return {
items: [
{
source: 'notification',
id: 'n-1',
type: 'PLAN_READY',
title: 'Trener utworzył dla Ciebie plan: Plan startowy',
payload: { planId: 'plan-1' },
read: false,
createdAt: iso(10),
},
{
source: 'announcement',
id: 'a-1',
kind: 'MANUAL',
title: 'Awarida sauny',
body: 'Sauna niedostępna do piątku.',
gymId: TEST_GYM_OWNED.id,
gymName: TEST_GYM_OWNED.name,
read: false,
createdAt: iso(60),
},
{
source: 'announcement',
id: 'a-2',
kind: 'EXCEPTION',
title: 'Zamknięcie 24.12.2026',
body: 'Tego dnia siłownia będzie nieczynna.',
gymId: TEST_GYM_OWNED.id,
gymName: TEST_GYM_OWNED.name,
read: true,
createdAt: iso(1440),
},
],
};
}
async function login(page: import('@playwright/test').Page) {
await page.goto('/login');
await page.locator('input[type="email"]').fill('test@fitos.pl');
await page.locator('input[type="password"]').fill('haslo123');
await page.getByRole('button', { name: 'Zaloguj' }).click();
await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
}
test('Aktualności: karta na dashboardzie i badge nieprzeczytanych w nawigacji', async ({
page,
}) => {
mockApi(page, { feed: feedState() });
await login(page);
await expect(page.getByRole('heading', { name: 'Aktualności' })).toBeVisible();
await expect(page.getByText('Trener utworzył dla Ciebie plan: Plan startowy')).toBeVisible();
await expect(page.getByText('Awarida sauny')).toBeVisible();
// badge = nieprzeczytane wpisy feedu (2)
await expect(page.getByRole('link', { name: /Aktualności/ })).toContainText('2');
});
test('Aktualności: strona pełna z treścią ogłoszeń i „Oznacz wszystkie”', async ({ page }) => {
mockApi(page, { feed: feedState() });
await login(page);
await page.getByRole('link', { name: 'Zobacz wszystkie' }).click();
await expect(page.getByRole('heading', { name: 'Aktualności' })).toBeVisible();
await expect(page.getByText('Sauna niedostępna do piątku.')).toBeVisible();
await expect(page.getByText('Tego dnia siłownia będzie nieczynna.')).toBeVisible();
await page.getByRole('button', { name: 'Oznacz wszystkie' }).click();
// badge znika po oznaczeniu wszystkich
await expect(page.getByRole('link', { name: /Aktualności/ })).not.toContainText('2');
});
test('Aktualności: klik w ogłoszenie prowadzi do siłowni', async ({ page }) => {
mockApi(page, { feed: feedState() });
await login(page);
await page.getByRole('link', { name: 'Zobacz wszystkie' }).click();
await page.getByRole('button', { name: /Awarida sauny/ }).click();
await expect(page).toHaveURL(new RegExp(`/gyms/${TEST_GYM_OWNED.id}`));
await expect(page.getByRole('heading', { name: TEST_GYM_OWNED.name })).toBeVisible();
});

View File

@@ -865,6 +865,8 @@ export interface MockApiOptions {
history?: unknown;
/** Ciało odpowiedzi GET /me/body-parameters (domyślnie: brak pomiarów; stateful POST /weight). */
bodyParameters?: unknown;
/** Wpisy feedu GET /me/feed (domyślnie: pusty; stateful: oznaczanie przeczytania). */
feed?: { items: { source: string; id: string; read?: boolean }[] };
}
/**
@@ -891,6 +893,7 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
myTrainers,
history,
bodyParameters,
feed,
} = opts;
// Stateful: equipment added via POST /gyms/:id/equipment persists on refetch.
@@ -1002,6 +1005,39 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(activeSession) }),
);
// ---------- feed / aktualności (powiadomienia + ogłoszenia), stateful ----------
const feedItems = JSON.parse(JSON.stringify(feed ?? { items: [] })).items as {
source: string;
id: string;
read?: boolean;
}[];
const feedJson = (status: number, body: unknown) =>
({ status, contentType: 'application/json', body: JSON.stringify(body) }) as const;
// Najpierw ogólna trasa, potem szczegółyne (Playwright: późniejsze rejestracje mają priorytet).
page.route('**/api/v1/me/feed*', (route) => {
const limit = Number(new URL(route.request().url()).searchParams.get('limit') ?? '20');
return route.fulfill(
feedJson(200, { items: feedItems.slice(0, limit), nextCursor: null }),
);
});
page.route('**/api/v1/me/feed/*/read', (route) => {
const id = new URL(route.request().url()).pathname.split('/').at(-2);
const item = feedItems.find((i) => i.id === id);
if (item) item.read = true;
return route.fulfill(feedJson(200, { ok: true }));
});
page.route('**/api/v1/me/feed/read-all', (route) => {
feedItems.forEach((i) => {
i.read = true;
});
return route.fulfill(feedJson(200, { ok: true }));
});
page.route('**/api/v1/me/feed/unread-count', (route) =>
route.fulfill(
feedJson(200, { unreadCount: feedItems.filter((i) => !i.read).length }),
),
);
// ---------- udostępnianie planów (PlanShare) ----------
page.route('**/api/v1/plans/shared-with-me', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(sharedWithMe ?? { plans: [] }) }),