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

296 lines
12 KiB
TypeScript

import { describe, it, expect, beforeAll } from 'vitest';
import { prisma } from '../../src/lib/prisma.js';
import {
buildApp,
createExercise,
createUserWithToken,
rand,
seedPlan,
seedSession,
} from '../helpers.js';
describe('presence — check-in, occupancy, telemetria', () => {
let realGymId: string;
let virtualGymId: string;
let member: { user: { id: string }; token: string };
beforeAll(async () => {
const real = await prisma.gym.create({
data: { name: `Presence Gym ${rand()}`, kind: 'REAL', capacity: 50 },
});
realGymId = real.id;
const virtual = await prisma.gym.create({
data: { name: `Presence Virtual ${rand()}`, kind: 'VIRTUAL' },
});
virtualGymId = virtual.id;
member = await createUserWithToken();
await prisma.gymMembership.create({
data: { userId: member.user.id, gymId: realGymId, roles: ['MEMBER'] },
});
await prisma.gymMembership.create({
data: { userId: member.user.id, gymId: virtualGymId, roles: ['MEMBER'] },
});
});
const auth = (token: string) => ({ Authorization: `Bearer ${token}` });
it('POST /gyms/:id/check-in creates an ACTIVE presence (source QR)', async () => {
const app = buildApp();
const { user, token } = await createUserWithToken();
const res = await app
.post(`/api/v1/gyms/${realGymId}/check-in`)
.set(auth(token))
.send({ source: 'QR' });
expect(res.status).toBe(200);
expect(res.body.presence).toMatchObject({ userId: user.id, gymId: realGymId, status: 'ACTIVE', source: 'QR' });
const row = await prisma.gymPresence.findFirst({ where: { userId: user.id } });
expect(row?.status).toBe('ACTIVE');
});
it('defaults source to MANUAL', async () => {
const app = buildApp();
const { token } = await createUserWithToken();
const res = await app
.post(`/api/v1/gyms/${realGymId}/check-in`)
.set(auth(token))
.send({});
expect(res.status).toBe(200);
expect(res.body.presence.source).toBe('MANUAL');
});
it('is idempotent — checking in to the same gym twice returns the same presence', async () => {
const app = buildApp();
const { token } = await createUserWithToken();
const first = await app.post(`/api/v1/gyms/${realGymId}/check-in`).set(auth(token)).send({});
const second = await app.post(`/api/v1/gyms/${realGymId}/check-in`).set(auth(token)).send({});
expect(second.status).toBe(200);
expect(second.body.presence.id).toBe(first.body.presence.id);
});
it('rejects check-in to a VIRTUAL gym with 400', async () => {
const app = buildApp();
const { token } = await createUserWithToken();
const res = await app
.post(`/api/v1/gyms/${virtualGymId}/check-in`)
.set(auth(token))
.send({});
expect(res.status).toBe(400);
expect(res.body.error.code).toBe('BAD_REQUEST');
});
it('rejects check-in to an unknown gym with 404 and without auth with 401', async () => {
const app = buildApp();
const { token } = await createUserWithToken();
const missing = await app.post('/api/v1/gyms/unknown/check-in').set(auth(token)).send({});
expect(missing.status).toBe(404);
const anon = await app.post(`/api/v1/gyms/${realGymId}/check-in`).send({});
expect(anon.status).toBe(401);
});
it('moving A->B closes the old presence and opens a new one', async () => {
const app = buildApp();
const gymA = await prisma.gym.create({ data: { name: `Gym A ${rand()}`, kind: 'REAL' } });
const gymB = await prisma.gym.create({ data: { name: `Gym B ${rand()}`, kind: 'REAL' } });
const { user, token } = await createUserWithToken();
await app.post(`/api/v1/gyms/${gymA.id}/check-in`).set(auth(token)).send({});
const moved = await app.post(`/api/v1/gyms/${gymB.id}/check-in`).set(auth(token)).send({});
expect(moved.status).toBe(200);
expect(moved.body.presence.gymId).toBe(gymB.id);
const state = await app.get('/api/v1/me/presence').set(auth(token));
expect(state.body.presence).toMatchObject({ gymId: gymB.id, status: 'ACTIVE', gymName: gymB.name });
const closedA = await prisma.gymPresence.findFirst({
where: { userId: user.id, gymId: gymA.id },
});
expect(closedA?.status).toBe('CLOSED');
expect(closedA?.closedAt).toBeInstanceOf(Date);
});
it('partial unique index blocks two ACTIVE presences per user at the DB level', async () => {
const { user } = await createUserWithToken();
const gymC = await prisma.gym.create({ data: { name: `Gym C ${rand()}`, kind: 'REAL' } });
const gymD = await prisma.gym.create({ data: { name: `Gym D ${rand()}`, kind: 'REAL' } });
await prisma.gymPresence.create({ data: { userId: user.id, gymId: gymC.id } });
await expect(
prisma.gymPresence.create({ data: { userId: user.id, gymId: gymD.id } }),
).rejects.toMatchObject({ code: 'P2002' });
});
it('GET /gyms exposes currentOccupancy for REAL and null for VIRTUAL', async () => {
const app = buildApp();
const { token: visitorToken } = await createUserWithToken();
await app.post(`/api/v1/gyms/${realGymId}/check-in`).set(auth(visitorToken)).send({});
const res = await app.get('/api/v1/gyms').set(auth(member.token));
expect(res.status).toBe(200);
const real = res.body.gyms.find((g: { id: string }) => g.id === realGymId);
const virtual = res.body.gyms.find((g: { id: string }) => g.id === virtualGymId);
expect(real.currentOccupancy).toBeGreaterThanOrEqual(1);
expect(virtual.currentOccupancy).toBeNull();
});
it('GET /gyms/:id exposes currentOccupancy', async () => {
const app = buildApp();
const res = await app.get(`/api/v1/gyms/${realGymId}`).set(auth(member.token));
expect(res.status).toBe(200);
expect(res.body.gym.currentOccupancy).toBeGreaterThanOrEqual(1);
// publiczna VIRTUAL jest widoczna dla każdego zalogowanego — currentOccupancy null (VIRTUAL nie przyjmuje meldunków)
const virtualRes = await app.get(`/api/v1/gyms/${virtualGymId}`).set(auth(member.token));
expect(virtualRes.status).toBe(200);
expect(virtualRes.body.gym.currentOccupancy).toBeNull();
});
it('heartbeat refreshes the slot; check-out closes the presence', async () => {
const app = buildApp();
const { user, token } = await createUserWithToken();
await app.post(`/api/v1/gyms/${realGymId}/check-in`).set(auth(token)).send({});
// cofnij aktywność o 10 min, żeby przesunięcie było mierzalne
await prisma.gymPresence.updateMany({
where: { userId: user.id },
data: { lastActivityAt: new Date(Date.now() - 10 * 60 * 1000) },
});
const beat = await app.post('/api/v1/me/presence/heartbeat').set(auth(token));
expect(beat.status).toBe(200);
expect(beat.body).toEqual({ touched: true });
const touched = await prisma.gymPresence.findFirst({ where: { userId: user.id } });
expect(touched!.lastActivityAt.getTime()).toBeGreaterThan(Date.now() - 9 * 60 * 1000);
const out = await app.post('/api/v1/me/presence/check-out').set(auth(token));
expect(out.body).toEqual({ checkedOut: true });
const state = await app.get('/api/v1/me/presence').set(auth(token));
expect(state.body.presence).toBeNull();
const again = await app.post('/api/v1/me/presence/check-out').set(auth(token));
expect(again.body).toEqual({ checkedOut: false });
});
it('heartbeat without an active presence is a no-op', async () => {
const app = buildApp();
const { token } = await createUserWithToken();
const beat = await app.post('/api/v1/me/presence/heartbeat').set(auth(token));
expect(beat.body).toEqual({ touched: false });
});
it('GET /me/presence/history lists visits with gym name and duration', async () => {
const app = buildApp();
const { token } = await createUserWithToken();
await app.post(`/api/v1/gyms/${realGymId}/check-in`).set(auth(token)).send({ source: 'QR' });
await app.post('/api/v1/me/presence/check-out').set(auth(token));
const res = await app.get('/api/v1/me/presence/history').set(auth(token));
expect(res.status).toBe(200);
expect(res.body.visits).toHaveLength(1);
expect(res.body.visits[0]).toMatchObject({
gymId: realGymId,
status: 'CLOSED',
source: 'QR',
});
expect(res.body.visits[0].durationMinutes).toBeGreaterThanOrEqual(0);
// filtr po gymId działa
const filtered = await app
.get(`/api/v1/me/presence/history?gymId=${virtualGymId}`)
.set(auth(token));
expect(filtered.body.visits).toHaveLength(0);
});
it('GET /me/presence/stats aggregates the caller visits', async () => {
const app = buildApp();
const { token } = await createUserWithToken();
await app.post(`/api/v1/gyms/${realGymId}/check-in`).set(auth(token)).send({});
const res = await app.get('/api/v1/me/presence/stats').set(auth(token));
expect(res.status).toBe(200);
expect(res.body.stats.visits).toBe(1);
expect(res.body.stats.topGyms[0]).toMatchObject({ gymId: realGymId });
});
it('zapis serii w sesji przesuwa lastActivityAt aktywnej bytności (hook)', async () => {
const app = buildApp();
const { user, token } = await createUserWithToken();
await app.post(`/api/v1/gyms/${realGymId}/check-in`).set(auth(token)).send({});
const exercise = await createExercise();
const plan = await seedPlan({
userId: user.id,
status: 'ACTIVE',
startDate: new Date(Date.UTC(2026, 9, 19)),
weeks: [
{
index: 0,
days: [
{
dayOfWeek: 1,
date: new Date(Date.UTC(2026, 9, 19)),
exercises: [{ exerciseId: exercise.id, order: 0, sets: [{ index: 0 }] }],
},
],
},
],
});
const day = plan.weeks[0].days[0];
const session = await seedSession(day.id, {
status: 'IN_PROGRESS',
exercises: [
{
exerciseId: exercise.id,
planExerciseId: day.exercises[0].id,
order: 0,
sets: [{ planSetId: day.exercises[0].sets[0].id, reps: null }],
},
],
});
// cofnij aktywność, żeby przesunięcie było mierzalne
await prisma.gymPresence.updateMany({
where: { userId: user.id },
data: { lastActivityAt: new Date(Date.now() - 10 * 60 * 1000) },
});
const setId = session.exercises[0].sets[0].id;
const patch = await app
.patch(`/api/v1/sessions/sets/${setId}`)
.set(auth(token))
.send({ reps: 10 });
expect(patch.status).toBe(200);
const row = await prisma.gymPresence.findFirst({ where: { userId: user.id } });
expect(row!.lastActivityAt.getTime()).toBeGreaterThan(Date.now() - 9 * 60 * 1000);
});
it('admin occupancy lists live gyms; forbidden for non-admins', async () => {
const app = buildApp();
const admin = await createUserWithToken({ isAdmin: true });
const gym = await prisma.gym.create({ data: { name: `Occupied ${rand()}`, kind: 'REAL' } });
const visitor = await createUserWithToken();
await app.post(`/api/v1/gyms/${gym.id}/check-in`).set(auth(visitor.token)).send({});
const res = await app.get('/api/v1/admin/gyms/occupancy').set(auth(admin.token));
expect(res.status).toBe(200);
const found = res.body.gyms.find((g: { gymId: string }) => g.gymId === gym.id);
expect(found).toMatchObject({ name: gym.name, count: 1 });
const denied = await app.get('/api/v1/admin/gyms/occupancy').set(auth(member.token));
expect(denied.status).toBe(403);
});
it('admin presence-stats exposes telemetry for a gym', async () => {
const app = buildApp();
const admin = await createUserWithToken({ isAdmin: true });
const res = await app
.get(`/api/v1/admin/gyms/${realGymId}/presence-stats`)
.set(auth(admin.token));
expect(res.status).toBe(200);
expect(res.body.gym.id).toBe(realGymId);
expect(res.body.stats.visits).toBeGreaterThanOrEqual(1);
expect(res.body.stats.live).toBeGreaterThanOrEqual(1);
expect(res.body.stats.visitsPerDay).toBeGreaterThanOrEqual(0);
expect(Array.isArray(res.body.stats.heatmap)).toBe(true);
const missing = await app
.get('/api/v1/admin/gyms/unknown/presence-stats')
.set(auth(admin.token));
expect(missing.status).toBe(404);
const denied = await app
.get(`/api/v1/admin/gyms/${realGymId}/presence-stats`)
.set(auth(member.token));
expect(denied.status).toBe(403);
});
});