App+API: ogloszenia — strona szczegolow z autorem (GET /me/feed/announcements/:id oznacza przeczytane), skracanie list do 3 lini i menu kontekstowe Aktualnosci w topbarze (wyszukiwarka, filtr typu, filtr okresu z kalendarzowym selektorem miesiaca, akcja Oznacz wszystkie; wspoldzielony FilterDropdown; swagger + testy unit/integracyjne/e2e)
This commit is contained in:
@@ -2,6 +2,7 @@ import { Router } from 'express';
|
||||
import type { AppDeps } from '../deps.js';
|
||||
import { authenticate } from '../middleware/auth.js';
|
||||
import {
|
||||
getAnnouncementDetail,
|
||||
getFeed,
|
||||
getFeedUnreadCount,
|
||||
markAnnouncementRead,
|
||||
@@ -89,6 +90,24 @@ export function createFeedRoutes({ prisma }: AppDeps) {
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /me/feed/announcements/{id}:
|
||||
* get:
|
||||
* summary: Single announcement with author info (visible to the user only); GET marks it as read
|
||||
* tags: [Feed]
|
||||
* responses:
|
||||
* 200: { description: 'OK, returns { announcement: {...authorId, authorName, authorRole}, read: true }' }
|
||||
* 404: { description: Not found or not visible }
|
||||
*/
|
||||
router.get(
|
||||
'/announcements/:id',
|
||||
asyncHandler(async (req, res) => {
|
||||
const result = await getAnnouncementDetail(prisma, req.user!.id, req.params.id);
|
||||
res.json(result);
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /me/feed/announcements/{id}/read:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { PrismaClient } from '@prisma/client';
|
||||
import { badRequest, forbidden, notFound } from '../lib/errors.js';
|
||||
import { authorInfos } from './feed.js';
|
||||
import type { DayAvailability } from './me.js';
|
||||
|
||||
export interface AnnouncementInput {
|
||||
@@ -35,8 +36,14 @@ export async function listGymAnnouncements(prisma: PrismaClient, gymId: string,
|
||||
where: { gymId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
const infos = await authorInfos(prisma, announcements);
|
||||
return {
|
||||
announcements,
|
||||
announcements: announcements.map((a) => ({
|
||||
...a,
|
||||
...(a.authorId
|
||||
? infos.get(a.authorId)
|
||||
: { authorId: null, authorName: null, authorRole: null }),
|
||||
})),
|
||||
canManage: membership.roles.includes('OWNER'),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -52,7 +52,16 @@ export interface FeedNotificationItem {
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface FeedAnnouncementItem {
|
||||
/** Rola autora ogłoszenia w sensie odbiorcy: admin platformy albo OWNER/TRENER siłowni. */
|
||||
export type AnnouncementAuthorRole = 'ADMIN' | 'OWNER' | 'TRAINER';
|
||||
|
||||
export interface AnnouncementAuthorInfo {
|
||||
authorId: string | null;
|
||||
authorName: string | null;
|
||||
authorRole: AnnouncementAuthorRole | null;
|
||||
}
|
||||
|
||||
export interface FeedAnnouncementItem extends AnnouncementAuthorInfo {
|
||||
source: 'announcement';
|
||||
id: string;
|
||||
kind: 'MANUAL' | 'HOURS_CHANGE' | 'EXCEPTION';
|
||||
@@ -75,6 +84,103 @@ async function memberGymIds(prisma: PrismaClient, userId: string): Promise<strin
|
||||
return memberships.map((m) => m.gymId);
|
||||
}
|
||||
|
||||
type AnnouncementAuthorSelect = {
|
||||
id: string;
|
||||
firstName: string | null;
|
||||
lastName: string | null;
|
||||
isAdmin: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Pola „od kogo" dla listy ogłoszeń: zbiorcze membershipy autorów w siłowni
|
||||
* (bez N+1 per wiersz) + fallback OWNER dla ręcznych ogłoszeń po utracie
|
||||
* członkostwa.
|
||||
*/
|
||||
export async function authorInfos(
|
||||
prisma: PrismaClient,
|
||||
announcements: { authorId: string | null; gymId: string | null; kind: string }[],
|
||||
): Promise<Map<string, AnnouncementAuthorInfo>> {
|
||||
const authorIds = [
|
||||
...new Set(announcements.map((a) => a.authorId).filter((v): v is string => !!v)),
|
||||
];
|
||||
const memberships =
|
||||
authorIds.length === 0
|
||||
? []
|
||||
: await prisma.gymMembership.findMany({
|
||||
where: {
|
||||
userId: { in: authorIds },
|
||||
gymId: {
|
||||
in: [...new Set(announcements.map((a) => a.gymId).filter((v): v is string => !!v))],
|
||||
},
|
||||
},
|
||||
select: { userId: true, gymId: true, roles: true },
|
||||
});
|
||||
const authors =
|
||||
authorIds.length === 0
|
||||
? []
|
||||
: await prisma.user.findMany({
|
||||
where: { id: { in: authorIds } },
|
||||
select: { id: true, firstName: true, lastName: true, isAdmin: true },
|
||||
});
|
||||
const byAuthor = new Map(authors.map((u) => [u.id, u]));
|
||||
const result = new Map<string, AnnouncementAuthorInfo>();
|
||||
for (const a of announcements) {
|
||||
if (!a.authorId) continue;
|
||||
const author = byAuthor.get(a.authorId);
|
||||
if (!author) continue;
|
||||
const membership = memberships.find((m) => m.userId === a.authorId && m.gymId === a.gymId);
|
||||
const role: AnnouncementAuthorRole | null = author.isAdmin
|
||||
? 'ADMIN'
|
||||
: membership
|
||||
? membership.roles.includes('OWNER')
|
||||
? 'OWNER'
|
||||
: membership.roles.includes('TRAINER')
|
||||
? 'TRAINER'
|
||||
: 'OWNER'
|
||||
: a.kind === 'MANUAL'
|
||||
? 'OWNER'
|
||||
: null;
|
||||
result.set(a.authorId, {
|
||||
authorId: a.authorId,
|
||||
authorName: [author.firstName, author.lastName].join(' ').trim() || null,
|
||||
authorRole: role,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Pola „od kogo" dla pojedynczego ogłoszenia (jeden membership). */
|
||||
async function authorInfo(
|
||||
prisma: PrismaClient,
|
||||
author: AnnouncementAuthorSelect | null,
|
||||
gymId: string | null,
|
||||
kind: string,
|
||||
): Promise<AnnouncementAuthorInfo> {
|
||||
if (!author) return { authorId: null, authorName: null, authorRole: null };
|
||||
const membership = gymId
|
||||
? await prisma.gymMembership.findFirst({
|
||||
where: { userId: author.id, gymId },
|
||||
select: { roles: true },
|
||||
})
|
||||
: null;
|
||||
const role: AnnouncementAuthorRole | null = author.isAdmin
|
||||
? 'ADMIN'
|
||||
: membership
|
||||
? membership.roles.includes('OWNER')
|
||||
? 'OWNER'
|
||||
: membership.roles.includes('TRAINER')
|
||||
? 'TRAINER'
|
||||
: 'OWNER'
|
||||
: kind === 'MANUAL'
|
||||
? 'OWNER'
|
||||
: null;
|
||||
return {
|
||||
authorId: author.id,
|
||||
authorName: [author.firstName, author.lastName].join(' ').trim() || null,
|
||||
authorRole: role,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -104,10 +210,15 @@ export async function getFeed(
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: limit,
|
||||
include: { gym: { select: { id: true, name: true } } },
|
||||
include: {
|
||||
gym: { select: { id: true, name: true } },
|
||||
author: { select: { id: true, firstName: true, lastName: true, isAdmin: true } },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
const infos = await authorInfos(prisma, announcements);
|
||||
|
||||
const readSet = new Set(
|
||||
(
|
||||
await prisma.announcementRead.findMany({
|
||||
@@ -127,17 +238,25 @@ export async function getFeed(
|
||||
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),
|
||||
})),
|
||||
...announcements.map((a): FeedAnnouncementItem => {
|
||||
const info = a.authorId
|
||||
? (infos.get(a.authorId) ?? { authorId: null, authorName: null, authorRole: null })
|
||||
: { authorId: null, authorName: null, authorRole: null };
|
||||
return {
|
||||
source: 'announcement',
|
||||
id: a.id,
|
||||
kind: a.kind,
|
||||
title: a.title,
|
||||
body: a.body,
|
||||
gymId: a.gymId,
|
||||
gymName: a.gym?.name ?? null,
|
||||
authorId: info.authorId,
|
||||
authorName: info.authorName,
|
||||
authorRole: info.authorRole,
|
||||
createdAt: a.createdAt.toISOString(),
|
||||
read: readSet.has(a.id),
|
||||
};
|
||||
}),
|
||||
].sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
||||
|
||||
const page = items.slice(0, limit);
|
||||
@@ -194,6 +313,48 @@ export async function markAnnouncementRead(prisma: PrismaClient, userId: string,
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Szczegóły pojedynczego ogłoszenia (strona „Aktualności -> ogłoszenie").
|
||||
* Widoczność jak w feedzie: globalne albo z siłowni usera; GET oznacza
|
||||
* przeczytane (bez osobnej mutacji po stronie UI).
|
||||
*/
|
||||
export async function getAnnouncementDetail(prisma: PrismaClient, userId: string, id: string) {
|
||||
const announcement = await prisma.announcement.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
gym: { select: { id: true, name: true } },
|
||||
author: { select: { id: true, firstName: true, lastName: true, isAdmin: true } },
|
||||
},
|
||||
});
|
||||
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 },
|
||||
});
|
||||
const info = await authorInfo(prisma, announcement.author, announcement.gymId, announcement.kind);
|
||||
return {
|
||||
announcement: {
|
||||
id: announcement.id,
|
||||
kind: announcement.kind,
|
||||
title: announcement.title,
|
||||
body: announcement.body,
|
||||
gymId: announcement.gymId,
|
||||
gymName: announcement.gym?.name ?? null,
|
||||
...info,
|
||||
createdAt: announcement.createdAt.toISOString(),
|
||||
},
|
||||
read: 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);
|
||||
|
||||
@@ -477,6 +477,8 @@ export const openapi: Record<string, unknown> = {
|
||||
get: {
|
||||
tags: ['Gyms'],
|
||||
summary: "List the gym's announcements (any member; canManage = OWNER)",
|
||||
description:
|
||||
'Announcements carry author attribution: authorId, authorName, authorRole (ADMIN | OWNER | TRAINER; null for system-generated).',
|
||||
security: [{ bearerAuth: [] }],
|
||||
parameters: [{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } }],
|
||||
},
|
||||
@@ -801,6 +803,8 @@ export const openapi: Record<string, unknown> = {
|
||||
tags: ['Feed'],
|
||||
summary:
|
||||
'Merged feed of personal notifications and gym/global announcements (cursor = createdAt)',
|
||||
description:
|
||||
'Announcement items carry author attribution: authorId, authorName, authorRole (ADMIN | OWNER | TRAINER; null for system-generated).',
|
||||
security: [{ bearerAuth: [] }],
|
||||
parameters: [
|
||||
{ name: 'limit', in: 'query', schema: { type: 'integer', default: 20 } },
|
||||
@@ -835,6 +839,16 @@ export const openapi: Record<string, unknown> = {
|
||||
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
|
||||
},
|
||||
},
|
||||
'/me/feed/announcements/{id}': {
|
||||
get: {
|
||||
tags: ['Feed'],
|
||||
summary:
|
||||
'Single announcement with author info (visible to the user only); GET marks it as read',
|
||||
description: 'Returns { announcement: {...authorId, authorName, authorRole}, read: true }.',
|
||||
security: [{ bearerAuth: [] }],
|
||||
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
|
||||
},
|
||||
},
|
||||
'/me/feed/announcements/{id}/read': {
|
||||
post: {
|
||||
tags: ['Feed'],
|
||||
|
||||
@@ -120,7 +120,10 @@ describe('feed — aktualności (powiadomienia + ogłoszenia)', () => {
|
||||
|
||||
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: owner, token: ownerToken } = await createUserWithToken({
|
||||
firstName: 'Anna',
|
||||
lastName: 'Kowalska',
|
||||
});
|
||||
const { user: member, token: memberToken } = await createUserWithToken();
|
||||
const { user: stranger, token: strangerToken } = await createUserWithToken();
|
||||
const created = await app
|
||||
@@ -143,6 +146,11 @@ describe('feed — aktualności (powiadomienia + ogłoszenia)', () => {
|
||||
expect(list.status).toBe(200);
|
||||
expect(list.body.canManage).toBe(false);
|
||||
expect(list.body.announcements).toHaveLength(1);
|
||||
expect(list.body.announcements[0]).toMatchObject({
|
||||
authorId: owner.id,
|
||||
authorName: 'Anna Kowalska',
|
||||
authorRole: 'OWNER',
|
||||
});
|
||||
|
||||
const memberPost = await app
|
||||
.post(`/api/v1/gyms/${gymId}/announcements`)
|
||||
@@ -333,6 +341,119 @@ describe('feed — aktualności (powiadomienia + ogłoszenia)', () => {
|
||||
expect(again.status).toBe(200);
|
||||
});
|
||||
|
||||
it('szczegóły ogłoszenia: atrybucja autora, GET oznacza przeczytane, postronny = 404', async () => {
|
||||
const app = buildApp();
|
||||
const { user: admin, token: adminToken } = await createUserWithToken({
|
||||
isAdmin: true,
|
||||
firstName: 'Adam',
|
||||
lastName: 'Admin',
|
||||
});
|
||||
const { user: owner, token: ownerToken } = await createUserWithToken({
|
||||
firstName: 'Olgierd',
|
||||
lastName: 'Właściciel',
|
||||
});
|
||||
const { token: memberToken } = await createUserWithToken();
|
||||
const { token: strangerToken } = await createUserWithToken();
|
||||
const created = await app
|
||||
.post('/api/v1/gyms')
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.send({ name: `Szczeg. Gym ${rand()}`, location: 'Zielona Góra' });
|
||||
const gymId = created.body.gym.id as string;
|
||||
await app.post(`/api/v1/gyms/${gymId}/join`).set('Authorization', `Bearer ${memberToken}`);
|
||||
|
||||
const gymPost = await app
|
||||
.post(`/api/v1/gyms/${gymId}/announcements`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.send({ title: 'Dlugie ogloszenie', body: 'X'.repeat(2000) });
|
||||
expect(gymPost.status).toBe(201);
|
||||
|
||||
const globalPost = await app
|
||||
.post('/api/v1/admin/announcements')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.send({ title: 'Przerwa platformy', body: 'W nocy nie będzie działalo.' });
|
||||
expect(globalPost.status).toBe(201);
|
||||
|
||||
// feed: pola autora przy każdym ogłoszeniu widocznym członkowi
|
||||
const feed = await app
|
||||
.get('/api/v1/me/feed')
|
||||
.set('Authorization', `Bearer ${memberToken}`);
|
||||
const gymItem = feed.body.items.find(
|
||||
(i: { id?: string }) => i.id === gymPost.body.announcement.id,
|
||||
);
|
||||
expect(gymItem).toMatchObject({
|
||||
authorName: 'Olgierd Właściciel',
|
||||
authorRole: 'OWNER',
|
||||
read: false,
|
||||
});
|
||||
const globalItem = feed.body.items.find(
|
||||
(i: { id?: string }) => i.id === globalPost.body.announcement.id,
|
||||
);
|
||||
expect(globalItem).toMatchObject({ authorName: 'Adam Admin', authorRole: 'ADMIN' });
|
||||
|
||||
// szczegóły: pełna treść + autor + automatyczne oznaczenie przeczytanego
|
||||
const detail = await app
|
||||
.get(`/api/v1/me/feed/announcements/${gymPost.body.announcement.id}`)
|
||||
.set('Authorization', `Bearer ${memberToken}`);
|
||||
expect(detail.status).toBe(200);
|
||||
expect(detail.body.read).toBe(true);
|
||||
expect(detail.body.announcement).toMatchObject({
|
||||
id: gymPost.body.announcement.id,
|
||||
kind: 'MANUAL',
|
||||
title: 'Dlugie ogloszenie',
|
||||
gymName: created.body.gym.name,
|
||||
authorId: owner.id,
|
||||
authorName: 'Olgierd Właściciel',
|
||||
authorRole: 'OWNER',
|
||||
});
|
||||
expect(detail.body.announcement.body).toHaveLength(2000);
|
||||
|
||||
const unread = await app
|
||||
.get('/api/v1/me/feed/unread-count')
|
||||
.set('Authorization', `Bearer ${memberToken}`);
|
||||
expect(unread.body.unreadCount).toBe(1);
|
||||
const feedAfter = await app
|
||||
.get('/api/v1/me/feed')
|
||||
.set('Authorization', `Bearer ${memberToken}`);
|
||||
const readItem = feedAfter.body.items.find(
|
||||
(i: { id?: string }) => i.id === gymPost.body.announcement.id,
|
||||
);
|
||||
expect(readItem.read).toBe(true);
|
||||
|
||||
// ogłoszenie systemowe: bez autora
|
||||
const exc = await app
|
||||
.post(`/api/v1/gyms/${gymId}/exceptions`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.send({ date: '2027-01-01', availability: null });
|
||||
expect(exc.status).toBe(201);
|
||||
const sys = await prisma.announcement.findFirst({ where: { gymId, kind: 'EXCEPTION' } });
|
||||
const sysDetail = await app
|
||||
.get(`/api/v1/me/feed/announcements/${sys!.id}`)
|
||||
.set('Authorization', `Bearer ${memberToken}`);
|
||||
expect(sysDetail.status).toBe(200);
|
||||
expect(sysDetail.body.announcement).toMatchObject({
|
||||
authorId: null,
|
||||
authorName: null,
|
||||
authorRole: null,
|
||||
});
|
||||
|
||||
// postronny: brak widoczności = 404 (także dla globalnego nie istnieje problem — tylko per-gym)
|
||||
const strangerDetail = await app
|
||||
.get(`/api/v1/me/feed/announcements/${gymPost.body.announcement.id}`)
|
||||
.set('Authorization', `Bearer ${strangerToken}`);
|
||||
expect(strangerDetail.status).toBe(404);
|
||||
|
||||
// globalne widoczne dla postronnego, autor = ADMIN
|
||||
const strangerGlobal = await app
|
||||
.get(`/api/v1/me/feed/announcements/${globalPost.body.announcement.id}`)
|
||||
.set('Authorization', `Bearer ${strangerToken}`);
|
||||
expect(strangerGlobal.status).toBe(200);
|
||||
expect(strangerGlobal.body.announcement).toMatchObject({
|
||||
gymId: null,
|
||||
authorName: 'Adam Admin',
|
||||
authorRole: 'ADMIN',
|
||||
});
|
||||
});
|
||||
|
||||
it('ogłoszenia admina: globalne widoczne dla wszystkich; typ systemowy nietykalny', async () => {
|
||||
const app = buildApp();
|
||||
const { user: admin, token: adminToken } = await createUserWithToken({ isAdmin: true });
|
||||
|
||||
@@ -32,6 +32,7 @@ import Invitations from './pages/Invitations';
|
||||
import Messages from './pages/messages/Messages';
|
||||
import MessageThread from './pages/messages/MessageThread';
|
||||
import Announcements from './pages/announcements/Announcements';
|
||||
import AnnouncementDetail from './pages/announcements/AnnouncementDetail';
|
||||
|
||||
/**
|
||||
* Trasa tylko dla trenerów — API i tak odda 403, ale nie pokazujemy pustej
|
||||
@@ -115,6 +116,7 @@ export default function App() {
|
||||
<Route path="/messages" element={<Messages />} />
|
||||
<Route path="/messages/:coachingId" element={<MessageThread />} />
|
||||
<Route path="/announcements" element={<Announcements />} />
|
||||
<Route path="/announcements/:id" element={<AnnouncementDetail />} />
|
||||
<Route path="/profile" element={<Profile />} />
|
||||
<Route path="/profile/info" element={<ProfileInfo />} />
|
||||
<Route path="/profile/body-parameters" element={<ProfileBodyParameters />} />
|
||||
|
||||
@@ -3,6 +3,7 @@ import { api } from './client';
|
||||
import type {
|
||||
ActiveSession,
|
||||
ActivePresence,
|
||||
AnnouncementDetail,
|
||||
Availability,
|
||||
CalendarDay,
|
||||
Conversation,
|
||||
@@ -1055,6 +1056,18 @@ export function markFeedAllRead() {
|
||||
return api('/me/feed/read-all', { method: 'POST' });
|
||||
}
|
||||
|
||||
/**
|
||||
* Szczegóły ogłoszenia (strona /announcements/:id). GET oznacza przeczytane
|
||||
* po stronie API — strona unieważnia feed po wczytaniu, żeby zgasł badge.
|
||||
*/
|
||||
export function useAnnouncementDetail(id: string | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['announcement', id],
|
||||
queryFn: () => api<{ announcement: AnnouncementDetail }>(`/me/feed/announcements/${id}`),
|
||||
enabled: !!id,
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- ogłoszenia siłowni (właściciel) ----------
|
||||
export function useGymAnnouncements(gymId: string | undefined, enabled = true) {
|
||||
return useQuery({
|
||||
|
||||
@@ -695,7 +695,17 @@ export interface FeedNotificationItem {
|
||||
|
||||
export type AnnouncementKind = 'MANUAL' | 'HOURS_CHANGE' | 'EXCEPTION';
|
||||
|
||||
export interface FeedAnnouncementItem {
|
||||
/** Rola autora ogłoszenia: admin platformy albo OWNER/TRENER siłowni; null = systemowe. */
|
||||
export type AnnouncementAuthorRole = 'ADMIN' | 'OWNER' | 'TRAINER';
|
||||
|
||||
/** Atrybucja „od kogo" w kontraktach list i szczegółów ogłoszeń. */
|
||||
export interface AnnouncementAuthorInfo {
|
||||
authorId: string | null;
|
||||
authorName: string | null;
|
||||
authorRole: AnnouncementAuthorRole | null;
|
||||
}
|
||||
|
||||
export interface FeedAnnouncementItem extends AnnouncementAuthorInfo {
|
||||
source: 'announcement';
|
||||
id: string;
|
||||
kind: AnnouncementKind;
|
||||
@@ -709,11 +719,20 @@ export interface FeedAnnouncementItem {
|
||||
|
||||
export type FeedItem = FeedNotificationItem | FeedAnnouncementItem;
|
||||
|
||||
/** Ogłoszenie siłowni w widoku zarządzania (właściciel) i listy członków. */
|
||||
export interface GymAnnouncement {
|
||||
/** Szczegóły pojedynczego ogłoszenia (GET /me/feed/announcements/:id, oznacza przeczytane). */
|
||||
export interface AnnouncementDetail extends AnnouncementAuthorInfo {
|
||||
id: string;
|
||||
kind: AnnouncementKind;
|
||||
title: string;
|
||||
body: string;
|
||||
gymId: string | null;
|
||||
authorId: string | null;
|
||||
gymName: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
/** Ogłoszenie siłowni w widoku zarządzania (właściciel) i listy członków. */
|
||||
export interface GymAnnouncement extends AnnouncementAuthorInfo {
|
||||
id: string;
|
||||
kind: AnnouncementKind;
|
||||
title: string;
|
||||
body: string;
|
||||
|
||||
@@ -24,7 +24,7 @@ export function feedDeeplink(item: FeedItem): string | null {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return item.gymId ? `/gyms/${item.gymId}` : null;
|
||||
return `/announcements/${item.id}`;
|
||||
}
|
||||
|
||||
/** Ikona + podpis źródła wpisu (wspólna dla karty dashboardu i strony aktualności). */
|
||||
@@ -59,6 +59,10 @@ export function FeedItemRow({ item, compact = false }: { item: FeedItem; compact
|
||||
const { push } = useToast();
|
||||
const { Icon, label } = feedItemIcon(item);
|
||||
const to = feedDeeplink(item);
|
||||
const attribution =
|
||||
item.source === 'announcement' && item.authorName && item.authorRole
|
||||
? `${item.gymName ?? i18n.t('feed:platform')} · ${item.authorName} (${i18n.t('feed:authorRole.' + item.authorRole)})`
|
||||
: label;
|
||||
|
||||
const open = async () => {
|
||||
if (!item.read) {
|
||||
@@ -98,7 +102,7 @@ export function FeedItemRow({ item, compact = false }: { item: FeedItem; compact
|
||||
{item.title}
|
||||
</span>
|
||||
<span className="mt-0.5 block truncate text-dim text-[0.78rem]">
|
||||
{label} · {timeAgo(item.createdAt)}
|
||||
{attribution} · {timeAgo(item.createdAt)}
|
||||
</span>
|
||||
{!compact && item.source === 'announcement' && (
|
||||
<span className="mt-1 block line-clamp-3 text-dim text-[0.8125rem]">{item.body}</span>
|
||||
|
||||
70
app/src/components/FilterDropdown.tsx
Normal file
70
app/src/components/FilterDropdown.tsx
Normal file
@@ -0,0 +1,70 @@
|
||||
import { useState } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { Check, ChevronDown } from 'lucide-react';
|
||||
import { Button } from './ui';
|
||||
import { cn } from '../lib/utils';
|
||||
|
||||
/**
|
||||
* Otwierany panel (filtr/sort) z listą opcji; zamknięcie kliknięciem tła lub wyborem.
|
||||
* Współdzielony przez strony list (Plany, Aktualności...) — kontrolka w menu
|
||||
* kontekstowym topbaru.
|
||||
*/
|
||||
export function FilterDropdown({
|
||||
icon,
|
||||
label,
|
||||
active,
|
||||
options,
|
||||
selected,
|
||||
onSelect,
|
||||
}: {
|
||||
icon: ReactNode;
|
||||
label: string;
|
||||
active: boolean;
|
||||
options: { id: string; label: string }[];
|
||||
selected: string;
|
||||
onSelect: (id: string) => void;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<div className="relative">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
aria-haspopup="true"
|
||||
aria-expanded={open}
|
||||
/* accent tylko gdy wybrano nie-domyślną opcję; telefon: pełna szerokość */
|
||||
className={cn('max-md:w-full', active && 'border-accent/55 bg-accent/11 text-accent-text')}
|
||||
>
|
||||
{icon}
|
||||
{label}
|
||||
<ChevronDown className={`w-4 h-4 transition-transform ${open ? 'rotate-180' : ''}`} />
|
||||
</Button>
|
||||
{open && (
|
||||
<>
|
||||
<div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
|
||||
{/* telefon: panel filtrów otwiera się w górę od dolnego paska — dropdown też w górę */}
|
||||
<div className="absolute right-0 top-full z-50 mt-2 min-w-full rounded-xl border border-line bg-card p-1.5 shadow-lg max-md:top-auto max-md:bottom-full max-md:mb-2 max-md:mt-0">
|
||||
{options.map((o) => (
|
||||
<button
|
||||
key={o.id}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onSelect(o.id);
|
||||
setOpen(false);
|
||||
}}
|
||||
className={cn(
|
||||
'flex w-full cursor-pointer items-center justify-between gap-3 rounded-lg px-2.5 py-2 text-left text-[0.9rem] font-semibold transition-colors',
|
||||
selected === o.id ? 'bg-accent/12 text-accent-text' : 'text-ink hover:bg-line/30',
|
||||
)}
|
||||
>
|
||||
{o.label}
|
||||
{selected === o.id && <Check className="w-4 h-4" />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -43,6 +43,7 @@
|
||||
"searchTrainees": "Search trainee",
|
||||
"searchInvitations": "Search invitation",
|
||||
"searchMessages": "Search conversation",
|
||||
"searchAnnouncements": "Search announcements",
|
||||
"prevMonth": "Previous month",
|
||||
"nextMonth": "Next month",
|
||||
"prevMonthWithData": "Previous month with data",
|
||||
|
||||
@@ -12,5 +12,27 @@
|
||||
"announcement": "Announcement",
|
||||
"hoursChange": "Hours change",
|
||||
"exception": "Schedule exception"
|
||||
}
|
||||
},
|
||||
"platform": "Platform",
|
||||
"systemBadge": "System",
|
||||
"authorRole": {
|
||||
"ADMIN": "Admin",
|
||||
"OWNER": "Owner",
|
||||
"TRAINER": "Trainer"
|
||||
},
|
||||
"detail": {
|
||||
"title": "Announcement",
|
||||
"notFound": "The announcement does not exist or you no longer have access to it.",
|
||||
"openGym": "Open gym"
|
||||
},
|
||||
"filters": {
|
||||
"typeLabel": "Type: {{label}}",
|
||||
"ALL": "All",
|
||||
"UNREAD": "Unread",
|
||||
"ANNOUNCEMENTS": "Announcements",
|
||||
"NOTIFICATIONS": "Notifications"
|
||||
},
|
||||
"noResultsTitle": "No results",
|
||||
"noResultsDesc": "No item matches the search or filter.",
|
||||
"filterPaginationHint": "Search and filter apply to the items loaded so far."
|
||||
}
|
||||
|
||||
@@ -125,7 +125,8 @@
|
||||
"publish": "Publish",
|
||||
"publishing": "Publishing…",
|
||||
"empty": "No announcements.",
|
||||
"systemBadge": "System"
|
||||
"systemBadge": "System",
|
||||
"authorLine": "by {{name}} ({{role}})"
|
||||
},
|
||||
"invites": {
|
||||
"desc": "A private gym is hidden — invite specific users.",
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
"searchTrainees": "Szukaj podopiecznego",
|
||||
"searchInvitations": "Szukaj zaproszenia",
|
||||
"searchMessages": "Szukaj rozmowy",
|
||||
"searchAnnouncements": "Szukaj w aktualnościach",
|
||||
"prevMonth": "Poprzedni miesiąc",
|
||||
"nextMonth": "Następny miesiąc",
|
||||
"prevMonthWithData": "Poprzedni miesiąc z danymi",
|
||||
|
||||
@@ -12,5 +12,27 @@
|
||||
"announcement": "Ogłoszenie",
|
||||
"hoursChange": "Zmiana godzin",
|
||||
"exception": "Wyjątek w godzinach"
|
||||
}
|
||||
},
|
||||
"platform": "Platforma",
|
||||
"systemBadge": "Systemowe",
|
||||
"authorRole": {
|
||||
"ADMIN": "Administrator",
|
||||
"OWNER": "Właściciel",
|
||||
"TRAINER": "Trener"
|
||||
},
|
||||
"detail": {
|
||||
"title": "Ogłoszenie",
|
||||
"notFound": "Ogłoszenie nie istnieje lub nie masz do niego dostępu.",
|
||||
"openGym": "Otwórz siłownię"
|
||||
},
|
||||
"filters": {
|
||||
"typeLabel": "Typ: {{label}}",
|
||||
"ALL": "Wszystkie",
|
||||
"UNREAD": "Nieprzeczytane",
|
||||
"ANNOUNCEMENTS": "Ogłoszenia",
|
||||
"NOTIFICATIONS": "Powiadomienia"
|
||||
},
|
||||
"noResultsTitle": "Brak wyników",
|
||||
"noResultsDesc": "Żaden wpis nie pasuje do wyszukiwania lub filtra.",
|
||||
"filterPaginationHint": "Wyszukiwanie i filtr działają na wczytanych wpisach."
|
||||
}
|
||||
|
||||
@@ -129,7 +129,8 @@
|
||||
"publish": "Opublikuj",
|
||||
"publishing": "Publikowanie…",
|
||||
"empty": "Brak ogłoszeń.",
|
||||
"systemBadge": "Systemowe"
|
||||
"systemBadge": "Systemowe",
|
||||
"authorLine": "od {{name}} ({{role}})"
|
||||
},
|
||||
"invites": {
|
||||
"desc": "Prywatna siłownia jest ukryta — zapraszaj określonych userów.",
|
||||
|
||||
78
app/src/pages/announcements/AnnouncementDetail.tsx
Normal file
78
app/src/pages/announcements/AnnouncementDetail.tsx
Normal file
@@ -0,0 +1,78 @@
|
||||
import { useEffect } from 'react';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { Building2 } from 'lucide-react';
|
||||
import { useAnnouncementDetail } from '../../api/queries';
|
||||
import { BackButton, Card, ErrorText, Loading } from '../../components/ui';
|
||||
import { useTopbar } from '../../topbar';
|
||||
import { fmtDateTime } from '../../lib/format';
|
||||
|
||||
/**
|
||||
* Pełna treść pojedynczego ogłoszenia (deeplink z Aktualności i list siłowni).
|
||||
* GET /me/feed/announcements/:id oznacza przeczytane po stronie API —
|
||||
* unieważniamy feed, żeby badge nieprzeczytanych zgasł od razu.
|
||||
*/
|
||||
export default function AnnouncementDetail() {
|
||||
const { id } = useParams();
|
||||
const { t } = useTranslation('feed');
|
||||
useTopbar({ title: t('detail.title'), back: '/announcements' });
|
||||
const queryClient = useQueryClient();
|
||||
const { data, isLoading, error } = useAnnouncementDetail(id);
|
||||
|
||||
useEffect(() => {
|
||||
if (data) void queryClient.invalidateQueries({ queryKey: ['feed'] });
|
||||
}, [data, queryClient]);
|
||||
|
||||
if (isLoading) return <Loading />;
|
||||
if (error || !data) {
|
||||
return (
|
||||
<>
|
||||
<BackButton to="/announcements" className="mb-4" />
|
||||
<ErrorText>{t('detail.notFound')}</ErrorText>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const a = data.announcement;
|
||||
const source = a.gymName ?? t('platform');
|
||||
const author =
|
||||
a.authorName && a.authorRole ? ` · ${a.authorName} (${t(`authorRole.${a.authorRole}`)})` : '';
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mb-5 flex flex-wrap items-end justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<span className="font-display block text-[1.35rem] font-bold leading-snug tracking-[-0.02em]">
|
||||
{a.title}
|
||||
</span>
|
||||
<span className="mt-0.5 block text-[0.85rem] text-dim">
|
||||
{source}
|
||||
{author} · {fmtDateTime(a.createdAt)}
|
||||
{a.kind !== 'MANUAL' && (
|
||||
<span className="ml-2 rounded-full bg-dim/13 px-2 py-0.5 text-[0.65rem] font-extrabold uppercase tracking-wide">
|
||||
{t('systemBadge')}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<BackButton to="/announcements" />
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<p className="whitespace-pre-wrap text-[0.9rem] leading-relaxed">{a.body}</p>
|
||||
{a.gymId && (
|
||||
<div className="mt-4">
|
||||
<Link
|
||||
to={`/gyms/${a.gymId}`}
|
||||
className="inline-flex items-center gap-1.5 text-[0.85rem] font-semibold text-accent-text hover:underline"
|
||||
>
|
||||
<Building2 className="h-4 w-4" aria-hidden="true" />
|
||||
{t('detail.openGym')}
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,19 +1,59 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { Megaphone } from 'lucide-react';
|
||||
import { Filter, Megaphone } from 'lucide-react';
|
||||
import { markFeedAllRead, useFeed } from '../../api/queries';
|
||||
import type { FeedItem } from '../../api/types';
|
||||
import { FeedItemRow } from '../../components/FeedItemRow';
|
||||
import { FilterDropdown } from '../../components/FilterDropdown';
|
||||
import { Button, Card, EmptyState, ErrorText, Loading } from '../../components/ui';
|
||||
import { useToast } from '../../components/toast';
|
||||
import { useTopbar } from '../../topbar';
|
||||
import { useListSearch } from '../../store/list-search';
|
||||
import { MonthPickerCore, useTopbar } from '../../topbar';
|
||||
import { monthStr } from '../../lib/format';
|
||||
|
||||
/** Filtry typu wpisu w menu kontekstowym (domyślnie: wszystko naraz). */
|
||||
const TYPE_FILTERS: {
|
||||
id: 'ALL' | 'UNREAD' | 'ANNOUNCEMENTS' | 'NOTIFICATIONS';
|
||||
labelKey: string;
|
||||
}[] = [
|
||||
{ id: 'ALL', labelKey: 'filters.ALL' },
|
||||
{ id: 'UNREAD', labelKey: 'filters.UNREAD' },
|
||||
{ id: 'ANNOUNCEMENTS', labelKey: 'filters.ANNOUNCEMENTS' },
|
||||
{ id: 'NOTIFICATIONS', labelKey: 'filters.NOTIFICATIONS' },
|
||||
];
|
||||
|
||||
/** Pola tekstu przeszukiwane w aktualnościach (ogłoszenia i powiadomienia). */
|
||||
function matchesQuery(item: FeedItem, q: string): boolean {
|
||||
if (item.source === 'announcement') {
|
||||
return [item.title, item.body, item.gymName, item.authorName].some(
|
||||
(v) => v && v.toLowerCase().includes(q),
|
||||
);
|
||||
}
|
||||
return [item.title, JSON.stringify(item.payload)].some((v) => v.toLowerCase().includes(q));
|
||||
}
|
||||
|
||||
export default function Announcements() {
|
||||
const { t } = useTranslation('feed');
|
||||
useTopbar({ title: t('nav:announcements') });
|
||||
const [typeFilter, setTypeFilter] = useState<
|
||||
'ALL' | 'UNREAD' | 'ANNOUNCEMENTS' | 'NOTIFICATIONS'
|
||||
>('ALL');
|
||||
// okres: '' = wszystkie; inaczej miesiąc 'RRRR-MM' (selektor jak w historii)
|
||||
const [period, setPeriod] = useState('');
|
||||
const queryClient = useQueryClient();
|
||||
const { push } = useToast();
|
||||
const { data, isLoading, error, hasNextPage, isFetchingNextPage, fetchNextPage } = useFeed(20);
|
||||
const items = data?.pages.flatMap((p) => p.items ?? []) ?? [];
|
||||
// miesiące dostępne w załadowanym feedzie (malejąco) — opcje filtra okresu
|
||||
const months = useMemo(
|
||||
() => [...new Set(items.map((i) => monthStr(new Date(i.createdAt))))].sort().reverse(),
|
||||
[items],
|
||||
);
|
||||
const query = useListSearch((s) => s.queries.announcements);
|
||||
const setQuery = useListSearch((s) => s.setQuery);
|
||||
|
||||
// wyszukiwarka jest w menu kontekstowym (topbar) — czyścimy ją przy opuszczeniu strony
|
||||
useEffect(() => () => setQuery('announcements', ''), [setQuery]);
|
||||
|
||||
const markAll = async () => {
|
||||
try {
|
||||
@@ -25,6 +65,40 @@ export default function Announcements() {
|
||||
}
|
||||
};
|
||||
|
||||
useTopbar({
|
||||
title: t('nav:announcements'),
|
||||
search: 'announcements',
|
||||
dateFilter: (
|
||||
<MonthPickerCore month={period} setMonth={setPeriod} availableMonths={months} allowAll />
|
||||
),
|
||||
filters: [
|
||||
<FilterDropdown
|
||||
key="type"
|
||||
icon={<Filter className="w-4 h-4" />}
|
||||
label={t('filters.typeLabel', {
|
||||
label: t(TYPE_FILTERS.find((f) => f.id === typeFilter)?.labelKey ?? 'filters.ALL'),
|
||||
})}
|
||||
active={typeFilter !== 'ALL'}
|
||||
options={TYPE_FILTERS.map((f) => ({ id: f.id, label: t(f.labelKey) }))}
|
||||
selected={typeFilter}
|
||||
onSelect={(id) => setTypeFilter(id as typeof typeFilter)}
|
||||
/>,
|
||||
],
|
||||
filterActive: typeFilter !== 'ALL' || period !== '',
|
||||
actions: items.some((i) => !i.read) ? [{ label: t('markAll'), onClick: markAll }] : [],
|
||||
});
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
let list = items;
|
||||
if (typeFilter === 'UNREAD') list = list.filter((i) => !i.read);
|
||||
else if (typeFilter === 'ANNOUNCEMENTS') list = list.filter((i) => i.source === 'announcement');
|
||||
else if (typeFilter === 'NOTIFICATIONS') list = list.filter((i) => i.source === 'notification');
|
||||
if (period !== '') list = list.filter((i) => monthStr(new Date(i.createdAt)) === period);
|
||||
const q = query.trim().toLowerCase();
|
||||
if (q) list = list.filter((i) => matchesQuery(i, q));
|
||||
return list;
|
||||
}, [items, typeFilter, period, query]);
|
||||
|
||||
if (isLoading) return <Loading />;
|
||||
if (error)
|
||||
return (
|
||||
@@ -34,26 +108,23 @@ export default function Announcements() {
|
||||
</ErrorText>
|
||||
);
|
||||
|
||||
const filtering = typeFilter !== 'ALL' || period !== '' || query.trim() !== '';
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card>
|
||||
{items.some((i) => !i.read) && (
|
||||
<div className="mb-3 flex justify-end">
|
||||
<Button variant="secondary" size="sm" type="button" onClick={() => void markAll()}>
|
||||
{t('markAll')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{items.length === 0 ? (
|
||||
<EmptyState icon={Megaphone} title={t('emptyTitle')} description={t('emptyDesc')} />
|
||||
) : filtered.length === 0 ? (
|
||||
<EmptyState icon={Filter} title={t('noResultsTitle')} description={t('noResultsDesc')} />
|
||||
) : (
|
||||
<div className="-mx-2">
|
||||
{items.map((item) => (
|
||||
{filtered.map((item) => (
|
||||
<FeedItemRow key={`${item.source}-${item.id}`} item={item} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{hasNextPage && (
|
||||
{hasNextPage && !filtering && (
|
||||
<div className="mt-3">
|
||||
<Button
|
||||
variant="secondary"
|
||||
@@ -65,6 +136,9 @@ export default function Announcements() {
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{hasNextPage && filtering && (
|
||||
<p className="mt-3 text-[0.78rem] text-dim">{t('filterPaginationHint')}</p>
|
||||
)}
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { Megaphone } from 'lucide-react';
|
||||
@@ -80,7 +80,7 @@ export default function GymAnnouncementsPage() {
|
||||
);
|
||||
}
|
||||
|
||||
/* Lista tylko do odczytu (treść podstrony). */
|
||||
/* Lista tylko do odczytu (treść podstrony): klik = strona ogłoszenia z pełną treścią. */
|
||||
function AnnouncementsList({ gymId }: { gymId: string }) {
|
||||
const { t } = useTranslation('gyms');
|
||||
const { data, isLoading } = useGymAnnouncements(gymId);
|
||||
@@ -98,7 +98,11 @@ function AnnouncementsList({ gymId }: { gymId: string }) {
|
||||
return (
|
||||
<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">
|
||||
<Link
|
||||
key={a.id}
|
||||
to={`/announcements/${a.id}`}
|
||||
className="block rounded-[10px] border border-line bg-card/50 px-3 py-2.5 transition-colors hover:bg-line/20"
|
||||
>
|
||||
<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' && (
|
||||
@@ -110,8 +114,18 @@ function AnnouncementsList({ gymId }: { gymId: string }) {
|
||||
{fmtDateTime(a.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-1 whitespace-pre-wrap text-dim text-[0.8125rem]">{a.body}</p>
|
||||
</div>
|
||||
{a.authorName && a.authorRole && (
|
||||
<span className="mt-0.5 block truncate text-[0.75rem] text-dim">
|
||||
{t('announcements.authorLine', {
|
||||
name: a.authorName,
|
||||
role: t(`feed:authorRole.${a.authorRole}`),
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
<p className="mt-1 line-clamp-3 whitespace-pre-wrap text-dim text-[0.8125rem]">
|
||||
{a.body}
|
||||
</p>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
@@ -211,7 +225,17 @@ function AnnouncementsManageSection({ gymId }: { gymId: string }) {
|
||||
{fmtDateTime(a.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-1 whitespace-pre-wrap text-dim text-[0.8125rem]">{a.body}</p>
|
||||
{a.authorName && a.authorRole && (
|
||||
<span className="mt-0.5 block truncate text-[0.75rem] text-dim">
|
||||
{t('announcements.authorLine', {
|
||||
name: a.authorName,
|
||||
role: t(`feed:authorRole.${a.authorRole}`),
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
<p className="mt-1 line-clamp-3 whitespace-pre-wrap text-dim text-[0.8125rem]">
|
||||
{a.body}
|
||||
</p>
|
||||
{a.kind === 'MANUAL' && (
|
||||
<div className="mt-2">
|
||||
<Button
|
||||
|
||||
@@ -1,22 +1,13 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
ArrowUpDown,
|
||||
CalendarPlus,
|
||||
Check,
|
||||
ChevronDown,
|
||||
Dumbbell,
|
||||
Filter,
|
||||
Plus,
|
||||
} from 'lucide-react';
|
||||
import { ArrowUpDown, CalendarPlus, Dumbbell, Filter, Plus } from 'lucide-react';
|
||||
import { useMe, usePlans, useSharedWithMe } from '../../api/queries';
|
||||
import { PLAN_STATUS } from '../../lib/labels';
|
||||
import { FilterDropdown } from '../../components/FilterDropdown';
|
||||
import { PlanCard } from '../../components/plans/PlanCard';
|
||||
import { Badge, Button, Card, EmptyState, ErrorText, H3, Skeleton } from '../../components/ui';
|
||||
import type { Plan } from '../../api/types';
|
||||
import { cn } from '../../lib/utils';
|
||||
import { useListSearch } from '../../store/list-search';
|
||||
import { useTopbar } from '../../topbar';
|
||||
|
||||
@@ -42,67 +33,6 @@ const SORT_OPTIONS: { id: SortKey; labelKey: string }[] = [
|
||||
{ id: 'progress', labelKey: 'sorts.progress' },
|
||||
];
|
||||
|
||||
/** Otwierany panel (filter/sort) z listą opcji; zamknięcie kliknięciem tła lub wyborem. */
|
||||
function FilterDropdown({
|
||||
icon,
|
||||
label,
|
||||
active,
|
||||
options,
|
||||
selected,
|
||||
onSelect,
|
||||
}: {
|
||||
icon: ReactNode;
|
||||
label: string;
|
||||
active: boolean;
|
||||
options: { id: string; label: string }[];
|
||||
selected: string;
|
||||
onSelect: (id: string) => void;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<div className="relative">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
aria-haspopup="true"
|
||||
aria-expanded={open}
|
||||
/* accent tylko gdy wybrano nie-domyślną opcję; telefon: pełna szerokość */
|
||||
className={cn('max-md:w-full', active && 'border-accent/55 bg-accent/11 text-accent-text')}
|
||||
>
|
||||
{icon}
|
||||
{label}
|
||||
<ChevronDown className={`w-4 h-4 transition-transform ${open ? 'rotate-180' : ''}`} />
|
||||
</Button>
|
||||
{open && (
|
||||
<>
|
||||
<div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
|
||||
{/* telefon: panel filtrów otwiera się w górę od dolnego paska — dropdown też w górę */}
|
||||
<div className="absolute right-0 top-full z-50 mt-2 min-w-full rounded-xl border border-line bg-card p-1.5 shadow-lg max-md:top-auto max-md:bottom-full max-md:mb-2 max-md:mt-0">
|
||||
{options.map((o) => (
|
||||
<button
|
||||
key={o.id}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onSelect(o.id);
|
||||
setOpen(false);
|
||||
}}
|
||||
className={cn(
|
||||
'flex w-full cursor-pointer items-center justify-between gap-3 rounded-lg px-2.5 py-2 text-left text-[0.9rem] font-semibold transition-colors',
|
||||
selected === o.id ? 'bg-accent/12 text-accent-text' : 'text-ink hover:bg-line/30',
|
||||
)}
|
||||
>
|
||||
{o.label}
|
||||
{selected === o.id && <Check className="w-4 h-4" />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Sortowanie listy planów wg klucza („default” = kolejność z API). */
|
||||
function sortPlans(list: Plan[], sortKey: SortKey): Plan[] {
|
||||
if (sortKey === 'default') return list;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { create } from 'zustand';
|
||||
|
||||
export type SearchableSection = 'plans' | 'gyms' | 'trainees' | 'invitations' | 'messages';
|
||||
export type SearchableSection =
|
||||
'plans' | 'gyms' | 'trainees' | 'invitations' | 'messages' | 'announcements';
|
||||
|
||||
const EMPTY_QUERIES: Record<SearchableSection, string> = {
|
||||
plans: '',
|
||||
@@ -8,6 +9,7 @@ const EMPTY_QUERIES: Record<SearchableSection, string> = {
|
||||
trainees: '',
|
||||
invitations: '',
|
||||
messages: '',
|
||||
announcements: '',
|
||||
};
|
||||
|
||||
interface ListSearchState {
|
||||
|
||||
@@ -15,6 +15,7 @@ const SEARCH_KEYS: Record<SearchableSection, string> = {
|
||||
trainees: 'topbar.searchTrainees',
|
||||
invitations: 'topbar.searchInvitations',
|
||||
messages: 'topbar.searchMessages',
|
||||
announcements: 'topbar.searchAnnouncements',
|
||||
};
|
||||
|
||||
function SectionSearchInput({ section }: { section: SearchableSection }) {
|
||||
|
||||
110
app/test/announcement-detail.test.tsx
Normal file
110
app/test/announcement-detail.test.tsx
Normal file
@@ -0,0 +1,110 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import AnnouncementDetail from '../src/pages/announcements/AnnouncementDetail';
|
||||
import { Topbar } from '../src/topbar';
|
||||
import { setAccessToken } from '../src/api/client';
|
||||
import type { AnnouncementDetail as AnnouncementDetailType } from '../src/api/types';
|
||||
|
||||
const GYM_ANNOUNCEMENT: AnnouncementDetailType = {
|
||||
id: 'a1',
|
||||
kind: 'MANUAL',
|
||||
title: 'Awarida klimatyzacji',
|
||||
body: 'Klimatyzacja nie działa do odwołania.',
|
||||
gymId: 'g1',
|
||||
gymName: 'Gym A',
|
||||
authorId: 'u-owner',
|
||||
authorName: 'Anna Kowalska',
|
||||
authorRole: 'OWNER',
|
||||
createdAt: '2026-01-05T00:00:00.000Z',
|
||||
};
|
||||
|
||||
const GLOBAL_ANNOUNCEMENT: AnnouncementDetailType = {
|
||||
...GYM_ANNOUNCEMENT,
|
||||
id: 'a2',
|
||||
title: 'Przerwa techniczna',
|
||||
gymId: null,
|
||||
gymName: null,
|
||||
authorName: 'Adam Admin',
|
||||
authorRole: 'ADMIN',
|
||||
};
|
||||
|
||||
function jsonResponse(status: number, body: unknown) {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
function stubFetch(announcement: AnnouncementDetailType | null) {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url.includes('/me/feed/announcements/')) {
|
||||
if (!announcement)
|
||||
return jsonResponse(404, {
|
||||
error: { code: 'NOT_FOUND', message: 'Announcement not found' },
|
||||
});
|
||||
return jsonResponse(200, { announcement, read: true });
|
||||
}
|
||||
throw new Error(`Unexpected fetch: ${url}`);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function renderDetail(path: string) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<Topbar />
|
||||
<Routes>
|
||||
<Route path="/announcements/:id" element={<AnnouncementDetail />} />
|
||||
</Routes>
|
||||
</QueryClientProvider>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
setAccessToken('tok');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('app strona szczegółów ogłoszenia', () => {
|
||||
it('ogłoszenie siłowni: pełna treść, atrybucja autora i link do siłowni', async () => {
|
||||
stubFetch(GYM_ANNOUNCEMENT);
|
||||
renderDetail('/announcements/a1');
|
||||
|
||||
expect(await screen.findByText('Awarida klimatyzacji')).toBeInTheDocument();
|
||||
expect(screen.getByRole('heading', { name: 'Ogłoszenie' })).toBeInTheDocument();
|
||||
expect(screen.getByText('Klimatyzacja nie działa do odwołania.')).toBeInTheDocument();
|
||||
expect(screen.getByText(/Gym A · Anna Kowalska \(Właściciel\)/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: 'Otwórz siłownię' })).toHaveAttribute(
|
||||
'href',
|
||||
'/gyms/g1',
|
||||
);
|
||||
});
|
||||
|
||||
it('ogłoszenie globalne: źródło Platforma, autor Admin, bez linku do siłowni', async () => {
|
||||
stubFetch(GLOBAL_ANNOUNCEMENT);
|
||||
renderDetail('/announcements/a2');
|
||||
|
||||
expect(await screen.findByText(/Platforma · Adam Admin \(Administrator\)/)).toBeInTheDocument();
|
||||
expect(screen.queryByRole('link', { name: 'Otwórz siłownię' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('brak ogłoszenia: komunikat błędu zamiast treści', async () => {
|
||||
stubFetch(null);
|
||||
renderDetail('/announcements/nope');
|
||||
|
||||
expect(
|
||||
await screen.findByText('Ogłoszenie nie istnieje lub nie masz do niego dostępu.'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -24,6 +24,9 @@ function feedState() {
|
||||
body: 'Sauna niedostępna do piątku.',
|
||||
gymId: TEST_GYM_OWNED.id,
|
||||
gymName: TEST_GYM_OWNED.name,
|
||||
authorId: 'u-owner',
|
||||
authorName: 'Anna Kowalska',
|
||||
authorRole: 'OWNER',
|
||||
read: false,
|
||||
createdAt: iso(60),
|
||||
},
|
||||
@@ -35,8 +38,11 @@ function feedState() {
|
||||
body: 'Tego dnia siłownia będzie nieczynna.',
|
||||
gymId: TEST_GYM_OWNED.id,
|
||||
gymName: TEST_GYM_OWNED.name,
|
||||
authorId: null,
|
||||
authorName: null,
|
||||
authorRole: null,
|
||||
read: true,
|
||||
createdAt: iso(1440),
|
||||
createdAt: iso(46000),
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -64,7 +70,9 @@ test('Aktualności: karta na dashboardzie i badge nieprzeczytanych w nawigacji',
|
||||
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 }) => {
|
||||
test('Aktualności: strona pełna z treścią ogłoszeń, autorem i „Oznacz wszystkie”', async ({
|
||||
page,
|
||||
}) => {
|
||||
mockApi(page, { feed: feedState() });
|
||||
await login(page);
|
||||
|
||||
@@ -72,18 +80,79 @@ test('Aktualności: strona pełna z treścią ogłoszeń i „Oznacz wszystkie
|
||||
await expect(page.getByRole('heading', { name: 'Aktualności', exact: true })).toBeVisible();
|
||||
await expect(page.getByText('Sauna niedostępna do piątku.')).toBeVisible();
|
||||
await expect(page.getByText('Tego dnia siłownia będzie nieczynna.')).toBeVisible();
|
||||
// atrybucja autora: siłownia · imię nazwisko (rola)
|
||||
await expect(page.getByText('Żelazna Świątynia · Anna Kowalska (Właściciel)')).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 }) => {
|
||||
test('Aktualności: menu kontekstowe — filtr typu i wyszukiwarka', async ({ page }) => {
|
||||
mockApi(page, { feed: feedState() });
|
||||
await login(page);
|
||||
|
||||
await page.getByRole('link', { name: 'Zobacz wszystkie' }).click();
|
||||
await expect(page.getByText('Awarida sauny')).toBeVisible();
|
||||
await expect(page.getByText('Plan startowy')).toBeVisible();
|
||||
|
||||
// filtr typu: tylko powiadomienia
|
||||
await page.getByRole('button', { name: 'Typ: Wszystkie' }).click();
|
||||
await page.getByRole('button', { name: 'Powiadomienia', exact: true }).click();
|
||||
await expect(page.getByText('Plan startowy')).toBeVisible();
|
||||
await expect(page.getByText('Awarida sauny')).toBeHidden();
|
||||
|
||||
// filtr typu: tylko ogłoszenia
|
||||
await page.getByRole('button', { name: 'Typ: Powiadomienia' }).click();
|
||||
await page.getByRole('button', { name: 'Ogłoszenia', exact: true }).click();
|
||||
await expect(page.getByText('Awarida sauny')).toBeVisible();
|
||||
await expect(page.getByText('Plan startowy')).toBeHidden();
|
||||
|
||||
// wyszukiwarka w menu kontekstowym zawęża ogłoszenia
|
||||
await page.locator('input[type="search"]').fill('sauny');
|
||||
await expect(page.getByText('Awarida sauny')).toBeVisible();
|
||||
await expect(page.getByText('Zamknięcie 24.12.2026')).toBeHidden();
|
||||
await page.locator('input[type="search"]').fill('');
|
||||
|
||||
// filtr okresu (selektor miesiąca jak w historii): miesiąc najstarszego wpisu
|
||||
const shortMonth = (d: Date) => {
|
||||
const s = new Intl.DateTimeFormat('pl-PL', { month: 'short' }).format(d).replace(/\.$/, '');
|
||||
return s.charAt(0).toUpperCase() + s.slice(1);
|
||||
};
|
||||
const monthLabel = (d: Date) => {
|
||||
const name = new Intl.DateTimeFormat('pl-PL', { month: 'long' }).format(d);
|
||||
return `${name.charAt(0).toUpperCase()}${name.slice(1)} ${d.getFullYear()}`;
|
||||
};
|
||||
const prevDate = new Date(NOW - 46000 * 60_000);
|
||||
await page.getByRole('button', { name: 'Wszystkie', exact: true }).click();
|
||||
if (prevDate.getFullYear() !== new Date(NOW).getFullYear()) {
|
||||
await page.getByRole('button', { name: String(prevDate.getFullYear()), exact: true }).click();
|
||||
}
|
||||
await page.getByRole('button', { name: shortMonth(prevDate), exact: true }).click();
|
||||
await expect(page.getByText('Zamknięcie 24.12.2026')).toBeVisible();
|
||||
await expect(page.getByText('Awarida sauny')).toBeHidden();
|
||||
|
||||
// powrót do pełnego zakresu
|
||||
await page.getByRole('button', { name: monthLabel(prevDate) }).click();
|
||||
await page.getByRole('button', { name: 'Wszystkie', exact: true }).click();
|
||||
await expect(page.getByText('Awarida sauny')).toBeVisible();
|
||||
await expect(page.getByText('Zamknięcie 24.12.2026')).toBeVisible();
|
||||
});
|
||||
|
||||
test('Aktualności: klik w ogłoszenie prowadzi na stronę ogłoszenia z powrotem do listy', 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(`/announcements/a-1`));
|
||||
await expect(page.getByRole('heading', { name: 'Ogłoszenie' })).toBeVisible();
|
||||
await expect(page.getByText('Sauna niedostępna do piątku.')).toBeVisible();
|
||||
await expect(page.getByText('Anna Kowalska (Właściciel)')).toBeVisible();
|
||||
// powrót do Aktualności + link do siłowni
|
||||
await page.getByRole('link', { name: 'Otwórz siłownię' }).click();
|
||||
await expect(page).toHaveURL(new RegExp(`/gyms/${TEST_GYM_OWNED.id}`));
|
||||
await expect(page.getByRole('heading', { name: TEST_GYM_OWNED.name })).toBeVisible();
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -56,6 +56,9 @@ const ANNOUNCEMENT: GymAnnouncement = {
|
||||
kind: 'MANUAL',
|
||||
title: 'Awarida klimatyzacji',
|
||||
body: 'Klimatyzacja nie działa.',
|
||||
authorId: 'u-owner',
|
||||
authorName: 'Anna Kowalska',
|
||||
authorRole: 'OWNER',
|
||||
createdAt: '2026-01-05T00:00:00.000Z',
|
||||
};
|
||||
|
||||
@@ -316,11 +319,16 @@ describe('app podstrony sekcji siłowni', () => {
|
||||
expect(() => actionButton('Edytuj urządzenia')).toThrow();
|
||||
});
|
||||
|
||||
it('podstrona ogłoszeń: lista read-only; właściciel otwiera modal tworzenia', async () => {
|
||||
it('podstrona ogłoszeń: lista read-only z autorem i linkiem do szczegółów; właściciel otwiera modal tworzenia', async () => {
|
||||
stubGymFetch();
|
||||
renderGym('/gyms/g1/announcements');
|
||||
|
||||
expect(await screen.findByText('Awarida klimatyzacji')).toBeInTheDocument();
|
||||
expect(await screen.findByText('od Anna Kowalska (Właściciel)')).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: /Awarida klimatyzacji/ })).toHaveAttribute(
|
||||
'href',
|
||||
'/announcements/a1',
|
||||
);
|
||||
fireEvent.click(actionButton('Nowe ogłoszenie'));
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
expect(within(dialog).getByRole('button', { name: 'Opublikuj' })).toBeInTheDocument();
|
||||
|
||||
Reference in New Issue
Block a user