Files
FitOS/api/test/integration/feed.test.ts

554 lines
22 KiB
TypeScript

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({
firstName: 'Anna',
lastName: 'Kowalska',
});
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);
expect(list.body.announcements[0]).toMatchObject({
authorId: owner.id,
authorName: 'Anna Kowalska',
authorRole: 'OWNER',
});
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('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 });
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);
});
});