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

584 lines
21 KiB
TypeScript

import { describe, it, expect } from 'vitest';
import { prisma } from '../../src/lib/prisma.js';
import {
buildApp,
registerViaApi,
rand,
createExercise,
seedPlan,
seedSession,
} from '../helpers.js';
describe('me routes', () => {
it('rejects /me without a token with 401', async () => {
const app = buildApp();
const res = await app.get('/api/v1/me');
expect(res.status).toBe(401);
expect(res.body.error.code).toBe('UNAUTHORIZED');
});
it('rejects an invalid token with 401', async () => {
const app = buildApp();
const res = await app.get('/api/v1/me').set('Authorization', 'Bearer invalid');
expect(res.status).toBe(401);
});
it('returns the profile with empty memberships', async () => {
const app = buildApp();
const { token, user } = await registerViaApi(`me-${rand()}@test.local`);
const res = await app.get('/api/v1/me').set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.user).toMatchObject({ id: user.id, email: user.email, isAdmin: false });
expect(res.body.user).not.toHaveProperty('passwordHash');
expect(res.body.memberships).toEqual([]);
});
it('updates the profile via PATCH', async () => {
const app = buildApp();
const { token } = await registerViaApi(`patch-${rand()}@test.local`);
const res = await app
.patch('/api/v1/me')
.set('Authorization', `Bearer ${token}`)
.send({
firstName: 'Anna',
birthDate: '2001-01-01',
heightCm: 170,
priorities: 'siła',
availability: [{ start: '18:00', end: '20:00' }, null, null, null, null, null, null],
});
expect(res.status).toBe(200);
expect(res.body.user).toMatchObject({
firstName: 'Anna',
birthDate: '2001-01-01T00:00:00.000Z',
heightCm: 170,
});
const me = await app.get('/api/v1/me').set('Authorization', `Bearer ${token}`);
expect(me.body.user).toMatchObject({
firstName: 'Anna',
priorities: 'siła',
availability: [{ start: '18:00', end: '20:00' }, null, null, null, null, null, null],
});
});
it('updates nickname and socialMedia via PATCH', async () => {
const app = buildApp();
const { token } = await registerViaApi(`nick-${rand()}@test.local`);
const res = await app
.patch('/api/v1/me')
.set('Authorization', `Bearer ${token}`)
.send({
nickname: 'fitfan',
socialMedia: [
{ platform: 'INSTAGRAM', url: 'https://instagram.com/fitfan' },
{ platform: 'OTHER', url: 'https://example.com/blog', label: 'Blog' },
],
});
expect(res.status).toBe(200);
expect(res.body.user).toMatchObject({
nickname: 'fitfan',
socialMedia: [
{ platform: 'INSTAGRAM', url: 'https://instagram.com/fitfan' },
{ platform: 'OTHER', url: 'https://example.com/blog', label: 'Blog' },
],
});
const me = await app.get('/api/v1/me').set('Authorization', `Bearer ${token}`);
expect(me.body.user.nickname).toBe('fitfan');
expect(me.body.user.socialMedia).toHaveLength(2);
});
it('PATCH clears nickname and socialMedia with null', async () => {
const app = buildApp();
const { token } = await registerViaApi(`nicknull-${rand()}@test.local`);
const auth = { Authorization: `Bearer ${token}` };
await app
.patch('/api/v1/me')
.set(auth)
.send({ nickname: 'fitfan', socialMedia: [{ platform: 'X', url: 'https://x.com/fitfan' }] });
const res = await app.patch('/api/v1/me').set(auth).send({ nickname: null, socialMedia: null });
expect(res.status).toBe(200);
expect(res.body.user.nickname).toBeNull();
expect(res.body.user.socialMedia).toBeNull();
});
it('PATCH rejects an invalid socialMedia url with 400', async () => {
const app = buildApp();
const { token } = await registerViaApi(`smurl-${rand()}@test.local`);
const res = await app
.patch('/api/v1/me')
.set('Authorization', `Bearer ${token}`)
.send({ socialMedia: [{ platform: 'INSTAGRAM', url: 'instagram.com/fitfan' }] });
expect(res.status).toBe(400);
});
it('PATCH rejects an unknown socialMedia platform with 400', async () => {
const app = buildApp();
const { token } = await registerViaApi(`smplat-${rand()}@test.local`);
const res = await app
.patch('/api/v1/me')
.set('Authorization', `Bearer ${token}`)
.send({ socialMedia: [{ platform: 'SNAPCHAT', url: 'https://snapchat.com/fitfan' }] });
expect(res.status).toBe(400);
});
it('PATCH rejects a nickname longer than 50 chars with 400', async () => {
const app = buildApp();
const { token } = await registerViaApi(`nicklen-${rand()}@test.local`);
const res = await app
.patch('/api/v1/me')
.set('Authorization', `Bearer ${token}`)
.send({ nickname: 'a'.repeat(51) });
expect(res.status).toBe(400);
});
it('PATCH rejects a future birthDate with 400', async () => {
const app = buildApp();
const { token } = await registerViaApi(`bdfuture-${rand()}@test.local`);
const future = new Date(Date.now() + 24 * 3600 * 1000).toISOString().slice(0, 10);
const res = await app
.patch('/api/v1/me')
.set('Authorization', `Bearer ${token}`)
.send({ birthDate: future });
expect(res.status).toBe(400);
expect(res.body.error.details.fieldErrors.birthDate).toBeDefined();
});
it('PATCH rejects a malformed birthDate with 400', async () => {
const app = buildApp();
const { token } = await registerViaApi(`bdformat-${rand()}@test.local`);
const res = await app
.patch('/api/v1/me')
.set('Authorization', `Bearer ${token}`)
.send({ birthDate: '01.1990' });
expect(res.status).toBe(400);
expect(res.body.error.details.fieldErrors.birthDate).toBeDefined();
});
it('PATCH clears birthDate with null', async () => {
const app = buildApp();
const { token } = await registerViaApi(`bdnull-${rand()}@test.local`);
const auth = { Authorization: `Bearer ${token}` };
await app.patch('/api/v1/me').set(auth).send({ birthDate: '1990-06-01' });
const res = await app.patch('/api/v1/me').set(auth).send({ birthDate: null });
expect(res.status).toBe(200);
expect(res.body.user.birthDate).toBeNull();
});
it('PATCH rejects an empty firstName with 400', async () => {
const app = buildApp();
const { token } = await registerViaApi(`name-${rand()}@test.local`);
const res = await app
.patch('/api/v1/me')
.set('Authorization', `Bearer ${token}`)
.send({ firstName: '' });
expect(res.status).toBe(400);
});
it('changes own password and the new one works on login', async () => {
const app = buildApp();
const email = `pwd-${rand()}@test.local`;
const { token } = await registerViaApi(email);
const res = await app
.post('/api/v1/me/password')
.set('Authorization', `Bearer ${token}`)
.send({ currentPassword: 'Password123!', newPassword: 'NowaSekret123!' });
expect(res.status).toBe(204);
const oldLogin = await app.post('/api/v1/auth/login').send({ email, password: 'Password123!' });
expect(oldLogin.status).toBe(401);
const newLogin = await app
.post('/api/v1/auth/login')
.send({ email, password: 'NowaSekret123!' });
expect(newLogin.status).toBe(200);
});
it('rejects a password change with a wrong current password (403 INVALID_CREDENTIALS)', async () => {
const app = buildApp();
const { token } = await registerViaApi(`pwdwrong-${rand()}@test.local`);
const res = await app
.post('/api/v1/me/password')
.set('Authorization', `Bearer ${token}`)
.send({ currentPassword: 'WrongPass123!', newPassword: 'NowaSekret123!' });
expect(res.status).toBe(403);
expect(res.body.error.code).toBe('INVALID_CREDENTIALS');
});
it('rejects a too short new password with 400', async () => {
const app = buildApp();
const { token } = await registerViaApi(`pwdshort-${rand()}@test.local`);
const res = await app
.post('/api/v1/me/password')
.set('Authorization', `Bearer ${token}`)
.send({ currentPassword: 'Password123!', newPassword: 'abc' });
expect(res.status).toBe(400);
});
it('adds weight and circumference measurements and lists them', async () => {
const app = buildApp();
const { token } = await registerViaApi(`body-${rand()}@test.local`);
const auth = { Authorization: `Bearer ${token}` };
const weight = await app
.post('/api/v1/me/body-parameters/weight')
.set(auth)
.send({ value: 82.5, date: '2026-08-01T08:00:00.000Z' });
expect(weight.status).toBe(201);
expect(weight.body.value).toBe(82.5);
const circ = await app
.post('/api/v1/me/body-parameters/circumference')
.set(auth)
.send({ typeId: 'biceps', side: 'left', value: 40, date: '2026-08-01T08:00:00.000Z' });
expect(circ.status).toBe(201);
expect(circ.body).toMatchObject({ typeId: 'biceps', side: 'left' });
const list = await app.get('/api/v1/me/body-parameters').set(auth);
expect(list.status).toBe(200);
expect(list.body.weight).toHaveLength(1);
expect(list.body.weight[0]).toMatchObject({ value: 82.5 });
expect(list.body.weight[0].id).toBeTruthy();
expect(list.body.circumferences).toHaveLength(1);
expect(list.body.circumferences[0]).toMatchObject({
typeId: 'biceps',
side: 'left',
name: null,
points: [{ value: 40, date: '2026-08-01T08:00:00.000Z' }],
});
expect(list.body.circumferences[0].points[0].id).toBeTruthy();
});
it('rejects an unknown circumference type with 400', async () => {
const app = buildApp();
const { token } = await registerViaApi(`badtype-${rand()}@test.local`);
const res = await app
.post('/api/v1/me/body-parameters/circumference')
.set('Authorization', `Bearer ${token}`)
.send({ typeId: 'ogon', value: 40 });
expect(res.status).toBe(400);
});
it('deletes weight and circumference measurements (own only)', async () => {
const app = buildApp();
const { token } = await registerViaApi(`del-${rand()}@test.local`);
const other = await registerViaApi(`del-other-${rand()}@test.local`);
const auth = { Authorization: `Bearer ${token}` };
const weight = await app
.post('/api/v1/me/body-parameters/weight')
.set(auth)
.send({ value: 80 });
const circ = await app
.post('/api/v1/me/body-parameters/circumference')
.set(auth)
.send({ typeId: 'biceps', side: 'left', value: 40 });
const weightId = weight.body.id;
const circId = circ.body.id;
// usunięcie własnych pomiarów
expect(
(await app.delete(`/api/v1/me/body-parameters/weight/${weightId}`).set(auth)).status,
).toBe(204);
expect(
(await app.delete(`/api/v1/me/body-parameters/circumference/${circId}`).set(auth)).status,
).toBe(204);
const list = await app.get('/api/v1/me/body-parameters').set(auth);
expect(list.body.weight).toHaveLength(0);
expect(list.body.circumferences).toHaveLength(0);
// cudzy pomiar -> 404, nieistniejący -> 404
const otherWeight = await app
.post('/api/v1/me/body-parameters/weight')
.set(auth)
.send({ value: 81 });
expect(
(
await app
.delete(`/api/v1/me/body-parameters/weight/${otherWeight.body.id}`)
.set('Authorization', `Bearer ${other.token}`)
).status,
).toBe(404);
expect((await app.delete('/api/v1/me/body-parameters/weight/none').set(auth)).status).toBe(404);
});
it('groups circumference series by type and side', async () => {
const app = buildApp();
const { token } = await registerViaApi(`circ-${rand()}@test.local`);
const auth = { Authorization: `Bearer ${token}` };
await app
.post('/api/v1/me/body-parameters/circumference')
.set(auth)
.send({ typeId: 'biceps', side: 'left', value: 40 });
await app
.post('/api/v1/me/body-parameters/circumference')
.set(auth)
.send({ typeId: 'biceps', side: 'left', value: 41 });
await app
.post('/api/v1/me/body-parameters/circumference')
.set(auth)
.send({ typeId: 'biceps', side: 'right', value: 38 });
await app
.post('/api/v1/me/body-parameters/circumference')
.set(auth)
.send({ typeId: 'waist', value: 85 });
const list = await app.get('/api/v1/me/body-parameters').set(auth);
const bySeries = Object.fromEntries(
list.body.circumferences.map(
(c: { typeId: string; side: string | null; points: unknown[] }) => [
`${c.typeId}/${c.side ?? '-'}`,
c.points.length,
],
),
);
expect(bySeries).toEqual({ 'biceps/left': 2, 'biceps/right': 1, 'waist/-': 1 });
});
it('exposes legacy free-text series as-is (typeId/side null, name preserved)', async () => {
const app = buildApp();
const { token, user } = await registerViaApi(`legacy-${rand()}@test.local`);
const auth = { Authorization: `Bearer ${token}` };
// historyczny wiersz sprzed migracji — swobodna nazwa bez typeId (backfill jej nie rozpoznał)
await prisma.circumferenceMeasurement.create({
data: { userId: user.id, name: 'Stary biceps', value: 33 },
});
const list = await app.get('/api/v1/me/body-parameters').set(auth);
expect(list.body.circumferences).toHaveLength(1);
expect(list.body.circumferences[0]).toMatchObject({
typeId: null,
side: null,
name: 'Stary biceps',
points: [{ value: 33 }],
});
});
it('weight measurement rejects a non-positive value with 400', async () => {
const app = buildApp();
const { token } = await registerViaApi(`wval-${rand()}@test.local`);
const res = await app
.post('/api/v1/me/body-parameters/weight')
.set('Authorization', `Bearer ${token}`)
.send({ value: -1 });
expect(res.status).toBe(400);
});
it('weight measurement rejects an invalid date with 400', async () => {
const app = buildApp();
const { token } = await registerViaApi(`wdate-${rand()}@test.local`);
const res = await app
.post('/api/v1/me/body-parameters/weight')
.set('Authorization', `Bearer ${token}`)
.send({ value: 80, date: 'not-a-date' });
expect(res.status).toBe(400);
});
it('marks extra (non-planned) exercises in /me/history', async () => {
const app = buildApp();
const { token, user } = await registerViaApi(`hist-${rand()}@test.local`);
const exercise = await createExercise();
const plan = await seedPlan({
userId: user.id,
title: 'History plan',
status: 'ACTIVE',
weeks: [
{
index: 0,
days: [
{
dayOfWeek: 1,
date: new Date(),
status: 'COMPLETED',
exercises: [{ exerciseId: exercise.id, order: 0, sets: [{ index: 0, reps: 10 }] }],
},
],
},
],
});
const day = plan.weeks[0].days[0];
const planExercise = day.exercises[0];
await seedSession(day.id, {
status: 'COMPLETED',
exercises: [
{
exerciseId: exercise.id,
planExerciseId: planExercise.id,
order: 0,
sets: [{ planSetId: planExercise.sets[0].id, reps: 10 }],
},
{
exerciseId: exercise.id,
planExerciseId: null,
order: 1,
sets: [{ reps: 8 }],
},
],
});
const res = await app.get('/api/v1/me/history').set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.sessions).toHaveLength(1);
const session = res.body.sessions[0];
expect(session.exercises).toHaveLength(2);
const [planned, added] = session.exercises;
expect(planned.isExtra).toBe(false);
expect(added.isExtra).toBe(true);
expect(planned.sets[0].planned).toMatchObject({ reps: 10 });
expect(added.sets[0].planned).toBeNull();
});
it('returns the trainee set note in /me/history (visible to the trainer too)', async () => {
const app = buildApp();
const { token, user } = await registerViaApi(`histnote-${rand()}@test.local`);
const exercise = await createExercise();
const plan = await seedPlan({
userId: user.id,
title: 'History note plan',
status: 'ACTIVE',
weeks: [
{
index: 0,
days: [
{
dayOfWeek: 1,
date: new Date(),
status: 'COMPLETED',
exercises: [{ exerciseId: exercise.id, order: 0, sets: [{ index: 0, reps: 10 }] }],
},
],
},
],
});
const day = plan.weeks[0].days[0];
const planExercise = day.exercises[0];
await seedSession(day.id, {
status: 'COMPLETED',
exercises: [
{
exerciseId: exercise.id,
planExerciseId: planExercise.id,
order: 0,
sets: [
{ planSetId: planExercise.sets[0].id, reps: 10, note: 'plecy bolały przy tej serii' },
],
},
],
});
const res = await app.get('/api/v1/me/history').set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
const set = res.body.sessions[0].exercises[0].sets[0];
expect(set.note).toBe('plecy bolały przy tej serii');
});
it('returns the full history without a session limit', async () => {
const app = buildApp();
const { token, user } = await registerViaApi(`histall-${rand()}@test.local`);
const exercise = await createExercise();
const weeks = Array.from({ length: 5 }, (_, w) => ({
index: w,
days: Array.from({ length: 7 }, (_, d) => ({
dayOfWeek: d + 1,
date: new Date(2026, 7, 1 + w * 7 + d),
status: 'COMPLETED' as const,
exercises: [{ exerciseId: exercise.id, order: 0, sets: [{ index: 0, reps: 10 }] }],
})),
}));
const plan = await seedPlan({ userId: user.id, title: 'Limit plan', status: 'ACTIVE', weeks });
for (const week of plan.weeks) {
for (const day of week.days) {
const pe = day.exercises[0];
await seedSession(day.id, {
status: 'COMPLETED',
exercises: [
{
exerciseId: exercise.id,
planExerciseId: pe.id,
order: 0,
sets: [{ planSetId: pe.sets[0].id, reps: 10 }],
},
],
});
}
}
const res = await app.get('/api/v1/me/history').set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.sessions).toHaveLength(35);
});
it('filters /me/history by month', async () => {
const app = buildApp();
const { token, user } = await registerViaApi(`histmon-${rand()}@test.local`);
const exercise = await createExercise();
const plan = await seedPlan({
userId: user.id,
title: 'Month plan',
status: 'ACTIVE',
weeks: [
{
index: 0,
days: [
{
dayOfWeek: 1,
date: new Date(2026, 7, 10),
status: 'COMPLETED',
exercises: [{ exerciseId: exercise.id, order: 0, sets: [{ index: 0, reps: 10 }] }],
},
{
dayOfWeek: 2,
date: new Date(2026, 8, 10),
status: 'COMPLETED',
exercises: [{ exerciseId: exercise.id, order: 0, sets: [{ index: 0, reps: 10 }] }],
},
],
},
],
});
for (const day of plan.weeks[0].days) {
const pe = day.exercises[0];
await seedSession(day.id, {
status: 'COMPLETED',
exercises: [
{
exerciseId: exercise.id,
planExerciseId: pe.id,
order: 0,
sets: [{ planSetId: pe.sets[0].id, reps: 10 }],
},
],
});
}
const auth = { Authorization: `Bearer ${token}` };
const all = await app.get('/api/v1/me/history').set(auth);
expect(all.status).toBe(200);
expect(all.body.sessions).toHaveLength(2);
const aug = await app.get('/api/v1/me/history?month=2026-08').set(auth);
expect(aug.status).toBe(200);
expect(aug.body.sessions).toHaveLength(1);
expect(aug.body.sessions[0].date.slice(0, 7)).toBe('2026-08');
const sep = await app.get('/api/v1/me/history?month=2026-09').set(auth);
expect(sep.status).toBe(200);
expect(sep.body.sessions).toHaveLength(1);
expect(sep.body.sessions[0].date.slice(0, 7)).toBe('2026-09');
const empty = await app.get('/api/v1/me/history?month=2025-01').set(auth);
expect(empty.status).toBe(200);
expect(empty.body.sessions).toHaveLength(0);
});
it('rejects an invalid month format in /me/history with 400', async () => {
const app = buildApp();
const { token } = await registerViaApi(`histbad-${rand()}@test.local`);
const res = await app
.get('/api/v1/me/history?month=2026-1')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(400);
});
});