194 lines
7.5 KiB
TypeScript
194 lines
7.5 KiB
TypeScript
import { describe, it, expect } from 'vitest';
|
|
import { prisma } from '../../src/lib/prisma.js';
|
|
import {
|
|
buildApp,
|
|
createExercise,
|
|
createUser,
|
|
loginViaApi,
|
|
registerViaApi,
|
|
seedPlan,
|
|
} from '../helpers.js';
|
|
|
|
// Data startu musi być z bieżącego lub przyszłego tygodnia — dynamiczny poniedziałek.
|
|
function mondayIso(offsetWeeks: number): string {
|
|
const d = new Date();
|
|
d.setDate(d.getDate() - ((d.getDay() + 6) % 7) + offsetWeeks * 7);
|
|
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
|
}
|
|
const MONDAY = mondayIso(1);
|
|
|
|
describe('activity logs (audit trail)', () => {
|
|
it('rejects GET /admin/logs without auth with 401', async () => {
|
|
const res = await buildApp().get('/api/v1/admin/logs');
|
|
expect(res.status).toBe(401);
|
|
});
|
|
|
|
it('rejects GET /admin/logs for a non-admin user with 403', async () => {
|
|
const { token } = await registerViaApi();
|
|
const res = await buildApp().get('/api/v1/admin/logs').set('Authorization', `Bearer ${token}`);
|
|
expect(res.status).toBe(403);
|
|
});
|
|
|
|
it('records user registration', async () => {
|
|
const { user } = await registerViaApi();
|
|
const log = await prisma.activityLog.findFirst({
|
|
where: { actorId: user.id, action: 'user.registered' },
|
|
});
|
|
expect(log).toBeTruthy();
|
|
expect(log?.entityType).toBe('user');
|
|
expect(log?.entityId).toBe(user.id);
|
|
expect(log?.details).toMatchObject({ actorId: user.id, email: user.email });
|
|
});
|
|
|
|
it('records the plan lifecycle (created, activated, abandoned)', async () => {
|
|
const { token, user } = await registerViaApi();
|
|
const exercise = await createExercise();
|
|
const app = buildApp();
|
|
const created = await app
|
|
.post('/api/v1/plans')
|
|
.set('Authorization', `Bearer ${token}`)
|
|
.send({
|
|
title: 'Audit plan',
|
|
weeksCount: 1,
|
|
weeks: [{ index: 0, days: [{ dayOfWeek: 1, exercises: [] }] }],
|
|
});
|
|
expect(created.status).toBe(201);
|
|
const planId = created.body.plan.id;
|
|
|
|
const activated = await app
|
|
.post(`/api/v1/plans/${planId}/activate`)
|
|
.set('Authorization', `Bearer ${token}`)
|
|
.send({ startDate: MONDAY });
|
|
expect(activated.status).toBe(200);
|
|
|
|
const abandoned = await app
|
|
.post(`/api/v1/plans/${planId}/abandon`)
|
|
.set('Authorization', `Bearer ${token}`);
|
|
expect(abandoned.status).toBe(200);
|
|
|
|
const logs = await prisma.activityLog.findMany({
|
|
where: { actorId: user.id, entityType: 'plan' },
|
|
orderBy: { createdAt: 'asc' },
|
|
});
|
|
expect(logs.map((l) => l.action)).toEqual(['plan.created', 'plan.activated', 'plan.abandoned']);
|
|
expect(logs[0].details).toMatchObject({ actorId: user.id, title: 'Audit plan' });
|
|
expect(logs[1].details).toMatchObject({ actorId: user.id, title: 'Audit plan', startDate: MONDAY });
|
|
expect(logs[2].entityId).toBe(planId);
|
|
});
|
|
|
|
it('records session start and completion', async () => {
|
|
const { token, user } = await registerViaApi();
|
|
const plan = await seedPlan({
|
|
userId: user.id,
|
|
status: 'ACTIVE',
|
|
startDate: new Date(MONDAY),
|
|
weeks: [{ index: 0, days: [{ dayOfWeek: 1, date: new Date(MONDAY) }] }],
|
|
});
|
|
const dayId = plan.weeks[0].days[0].id;
|
|
const app = buildApp();
|
|
|
|
const started = await app
|
|
.post(`/api/v1/days/${dayId}/sessions`)
|
|
.set('Authorization', `Bearer ${token}`);
|
|
expect(started.status).toBe(201);
|
|
const sessionId = started.body.sessionId;
|
|
|
|
const completed = await app
|
|
.post(`/api/v1/sessions/${sessionId}/complete`)
|
|
.set('Authorization', `Bearer ${token}`);
|
|
expect(completed.status).toBe(200);
|
|
|
|
const logs = await prisma.activityLog.findMany({
|
|
where: { actorId: user.id, entityType: 'session' },
|
|
orderBy: { createdAt: 'asc' },
|
|
});
|
|
expect(logs.map((l) => l.action)).toEqual(['session.started', 'session.completed']);
|
|
expect(logs[0].entityId).toBe(sessionId);
|
|
expect(logs[1].entityId).toBe(sessionId);
|
|
// details zawsze zawiera ID aktora
|
|
expect(logs[0].details).toMatchObject({ actorId: user.id });
|
|
expect(logs[1].details).toMatchObject({ actorId: user.id });
|
|
});
|
|
|
|
it('records body parameter removal', async () => {
|
|
const { token, user } = await registerViaApi();
|
|
const app = buildApp();
|
|
const auth = { Authorization: `Bearer ${token}` };
|
|
|
|
const weight = await app.post('/api/v1/me/body-parameters/weight').set(auth).send({ value: 82.5 });
|
|
const circ = await app
|
|
.post('/api/v1/me/body-parameters/circumference')
|
|
.set(auth)
|
|
.send({ name: 'biceps', value: 40 });
|
|
expect((await app.delete(`/api/v1/me/body-parameters/weight/${weight.body.id}`).set(auth)).status).toBe(204);
|
|
expect(
|
|
(await app.delete(`/api/v1/me/body-parameters/circumference/${circ.body.id}`).set(auth)).status,
|
|
).toBe(204);
|
|
|
|
const logs = await prisma.activityLog.findMany({
|
|
where: { actorId: user.id, action: { in: ['weight.removed', 'circumference.removed'] } },
|
|
});
|
|
expect(logs).toHaveLength(2);
|
|
expect(logs.find((l) => l.action === 'weight.removed')?.details).toMatchObject({
|
|
actorId: user.id,
|
|
value: 82.5,
|
|
});
|
|
expect(logs.find((l) => l.action === 'circumference.removed')?.details).toMatchObject({
|
|
actorId: user.id,
|
|
name: 'biceps',
|
|
value: 40,
|
|
});
|
|
});
|
|
|
|
it('lists logs for admin with actor data, newest first', async () => {
|
|
const { token, user } = await registerViaApi();
|
|
const admin = await createUser({ isAdmin: true });
|
|
const adminLogin = await loginViaApi(admin.user.email, admin.password);
|
|
|
|
const res = await buildApp()
|
|
.get('/api/v1/admin/logs')
|
|
.set('Authorization', `Bearer ${adminLogin.token}`);
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.total).toBeGreaterThanOrEqual(1);
|
|
expect(Array.isArray(res.body.logs)).toBe(true);
|
|
|
|
const mine = res.body.logs.find((l: { actor: { id: string } }) => l.actor.id === user.id);
|
|
expect(mine).toBeTruthy();
|
|
expect(mine.actor).toMatchObject({ email: user.email });
|
|
expect(mine.action).toBe('user.registered');
|
|
|
|
const dates = res.body.logs.map((l: { createdAt: string }) => new Date(l.createdAt).getTime());
|
|
for (let i = 1; i < dates.length; i++) {
|
|
expect(dates[i - 1]).toBeGreaterThanOrEqual(dates[i]);
|
|
}
|
|
});
|
|
|
|
it('filters logs by action and limits the page size', async () => {
|
|
const admin = await createUser({ isAdmin: true });
|
|
const adminLogin = await loginViaApi(admin.user.email, admin.password);
|
|
const app = buildApp();
|
|
const auth = { Authorization: `Bearer ${adminLogin.token}` };
|
|
|
|
const filtered = await app.get('/api/v1/admin/logs?action=user.registered').set(auth);
|
|
expect(filtered.status).toBe(200);
|
|
expect(filtered.body.logs.length).toBeGreaterThan(0);
|
|
for (const l of filtered.body.logs) expect(l.action).toBe('user.registered');
|
|
|
|
const limited = await app.get('/api/v1/admin/logs?limit=1&offset=0').set(auth);
|
|
expect(limited.status).toBe(200);
|
|
expect(limited.body.logs).toHaveLength(1);
|
|
expect(limited.body.total).toBeGreaterThanOrEqual(1);
|
|
});
|
|
|
|
it('rejects invalid query parameters with 400', async () => {
|
|
const admin = await createUser({ isAdmin: true });
|
|
const adminLogin = await loginViaApi(admin.user.email, admin.password);
|
|
const app = buildApp();
|
|
const auth = { Authorization: `Bearer ${adminLogin.token}` };
|
|
|
|
expect((await app.get('/api/v1/admin/logs?limit=0').set(auth)).status).toBe(400);
|
|
expect((await app.get('/api/v1/admin/logs?limit=501').set(auth)).status).toBe(400);
|
|
expect((await app.get('/api/v1/admin/logs?from=2026-1-01').set(auth)).status).toBe(400);
|
|
});
|
|
});
|