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:
tisachi
2026-10-27 06:22:17 +01:00
parent a7e1ac8223
commit a230dee285
26 changed files with 1504 additions and 268 deletions

View File

@@ -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:

View File

@@ -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'),
};
}

View File

@@ -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);

View File

@@ -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'],