302 lines
11 KiB
TypeScript
302 lines
11 KiB
TypeScript
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
|
import { prisma } from '../../src/lib/prisma.js';
|
|
import {
|
|
buildApp,
|
|
createEquipment,
|
|
createUserWithToken,
|
|
rand,
|
|
seedPlan,
|
|
seedSession,
|
|
} from '../helpers.js';
|
|
|
|
interface UsageCell {
|
|
hour: number;
|
|
count: number;
|
|
}
|
|
interface UsageRow {
|
|
equipmentId: string;
|
|
name: string;
|
|
nameEn: string | null;
|
|
cells: UsageCell[];
|
|
peak: number;
|
|
}
|
|
|
|
describe('gym equipment-usage — mapa ciepła urządzeń (24h)', () => {
|
|
let ownerToken: string;
|
|
let ownerId: string;
|
|
let strangerToken: string;
|
|
let adminToken: string;
|
|
|
|
const gymIds: string[] = [];
|
|
const presenceIds: string[] = [];
|
|
|
|
beforeAll(async () => {
|
|
const owner = await createUserWithToken();
|
|
ownerId = owner.user.id;
|
|
ownerToken = owner.token;
|
|
const stranger = await createUserWithToken();
|
|
strangerToken = stranger.token;
|
|
const admin = await createUserWithToken({ isAdmin: true });
|
|
adminToken = admin.token;
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await prisma.gymPresence
|
|
.deleteMany({ where: { gymId: { in: gymIds } } })
|
|
.catch(() => undefined);
|
|
await prisma.gymMembership
|
|
.deleteMany({ where: { gymId: { in: gymIds } } })
|
|
.catch(() => undefined);
|
|
await prisma.gym.deleteMany({ where: { id: { in: gymIds } } }).catch(() => undefined);
|
|
});
|
|
|
|
async function createRealGym() {
|
|
const gym = await prisma.gym.create({
|
|
data: { name: `Usage Gym ${rand()}`, kind: 'REAL', location: 'Warszawa' },
|
|
});
|
|
gymIds.push(gym.id);
|
|
await prisma.gymMembership.create({
|
|
data: { userId: ownerId, gymId: gym.id, roles: ['OWNER'] },
|
|
});
|
|
return gym;
|
|
}
|
|
|
|
async function createVirtualGym() {
|
|
const gym = await prisma.gym.create({
|
|
data: { name: `Usage Virtual ${rand()}`, kind: 'VIRTUAL' },
|
|
});
|
|
gymIds.push(gym.id);
|
|
await prisma.gymMembership.create({
|
|
data: { userId: ownerId, gymId: gym.id, roles: ['OWNER'] },
|
|
});
|
|
return gym;
|
|
}
|
|
|
|
/** Bytność CLOSED: okno [checkedInAt, +2h] — sesje muszą startnąć w środku. */
|
|
async function seedPresence(userId: string, gymId: string, checkedInAt: Date) {
|
|
const closedAt = new Date(checkedInAt.getTime() + 2 * 60 * 60 * 1000);
|
|
const row = await prisma.gymPresence.create({
|
|
data: {
|
|
userId,
|
|
gymId,
|
|
status: 'CLOSED',
|
|
checkedInAt,
|
|
lastActivityAt: closedAt,
|
|
closedAt,
|
|
},
|
|
});
|
|
presenceIds.push(row.id);
|
|
return { start: checkedInAt, end: closedAt };
|
|
}
|
|
|
|
/** Start bytności o stałej godzinie (13:05 lokalnie) — deterministyczne kafle godzinowe. */
|
|
function baseAt(daysAgo: number): Date {
|
|
const base = new Date(Date.now() - daysAgo * 86_400_000);
|
|
base.setHours(13, 5, 0, 0);
|
|
return base;
|
|
}
|
|
|
|
/** Ćwiczenie podpięte do urządzenia katalogowego. */
|
|
async function createExerciseWithEquipment(equipmentIds: string[]) {
|
|
const slug = `usage-ex-${rand()}`;
|
|
return prisma.exercise.create({
|
|
data: {
|
|
slug,
|
|
name: `Exercise ${slug}`,
|
|
primaryMuscle: 'chest',
|
|
secondaryMuscles: [],
|
|
source: 'BUILTIN',
|
|
equipment: { connect: equipmentIds.map((id) => ({ id })) },
|
|
},
|
|
});
|
|
}
|
|
|
|
/** Plan (DRAFT — brak limitu aktywnego planu) + sesja startująca o wskazanej chwili. */
|
|
async function seedSessionAt(userId: string, startedAt: Date, exerciseIds: string[]) {
|
|
const plan = await seedPlan({
|
|
userId,
|
|
status: 'DRAFT',
|
|
startDate: startedAt,
|
|
weeks: [
|
|
{
|
|
index: 0,
|
|
days: [
|
|
{
|
|
dayOfWeek: (startedAt.getDay() + 6) % 7,
|
|
date: startedAt,
|
|
status: 'COMPLETED',
|
|
},
|
|
],
|
|
},
|
|
],
|
|
});
|
|
const day = plan.weeks[0].days[0];
|
|
return seedSession(day.id, {
|
|
status: 'COMPLETED',
|
|
startedAt,
|
|
exercises: exerciseIds.map((exerciseId, order) => ({ exerciseId, order })),
|
|
});
|
|
}
|
|
|
|
it('agreguje użycia urządzeń w kaflach godzinowych (sesje w oknach bytności)', async () => {
|
|
const app = buildApp();
|
|
const gym = await createRealGym();
|
|
const visitor = await createUserWithToken();
|
|
|
|
const eqA = await createEquipment(`Ławka ${rand()}`);
|
|
const eqB = await createEquipment(`Sztanga ${rand()}`);
|
|
const exA1 = await createExerciseWithEquipment([eqA.id]);
|
|
const exA2 = await createExerciseWithEquipment([eqA.id]);
|
|
const exB = await createExerciseWithEquipment([eqB.id]);
|
|
|
|
// okno bytności 5 dni temu (start 13:05): dwie sesje w oknie + jedna POZA oknem
|
|
const base = baseAt(5);
|
|
const win = await seedPresence(visitor.user.id, gym.id, base);
|
|
const inWindowA = new Date(win.start.getTime() + 30 * 60 * 1000); // 13:35
|
|
const inWindowB = new Date(win.start.getTime() + 60 * 60 * 1000); // 14:05
|
|
const outsideWindow = new Date(win.end.getTime() + 3 * 60 * 60 * 1000);
|
|
|
|
await seedSessionAt(visitor.user.id, inWindowA, [exA1.id, exA2.id]);
|
|
await seedSessionAt(visitor.user.id, inWindowB, [exA1.id]);
|
|
// ta sesja (poza oknem) nie wolno się liczyć nawet z tym samym sprzętem
|
|
await seedSessionAt(visitor.user.id, outsideWindow, [exB.id]);
|
|
|
|
const res = await app
|
|
.get(`/api/v1/gyms/${gym.id}/equipment-usage`)
|
|
.set('Authorization', `Bearer ${strangerToken}`);
|
|
expect(res.status).toBe(200);
|
|
const rows = res.body.equipment as UsageRow[];
|
|
// eqB liczony tylko przez sesję poza oknem → niewidoczny
|
|
expect(rows).toHaveLength(1);
|
|
const [rowA] = rows;
|
|
expect(rowA).toMatchObject({ equipmentId: eqA.id, name: eqA.name, nameEn: null });
|
|
// 13:35 → 2 użycia, 14:05 → 1 użycie; kafle posortowane po godzinie
|
|
expect(rowA.cells).toEqual([
|
|
{ hour: 13, count: 2 },
|
|
{ hour: 14, count: 1 },
|
|
]);
|
|
expect(rowA.peak).toBe(2);
|
|
});
|
|
|
|
it('sortuje wiersze po sumie użyć malejąco i pomija urządzenia bez użyć', async () => {
|
|
const app = buildApp();
|
|
const gym = await createRealGym();
|
|
const visitor = await createUserWithToken();
|
|
|
|
const hot = await createEquipment(`Hot ${rand()}`);
|
|
const cold = await createEquipment(`Cold ${rand()}`);
|
|
const unused = await createEquipment(`Unused ${rand()}`);
|
|
const exHot = await createExerciseWithEquipment([hot.id]);
|
|
const exCold = await createExerciseWithEquipment([cold.id]);
|
|
const exUnused = await createExerciseWithEquipment([unused.id]);
|
|
|
|
const base = baseAt(3);
|
|
const win = await seedPresence(visitor.user.id, gym.id, base);
|
|
await seedSessionAt(visitor.user.id, new Date(win.start.getTime() + 10 * 60 * 1000), [
|
|
exHot.id,
|
|
exHot.id,
|
|
exHot.id,
|
|
exCold.id,
|
|
]);
|
|
// ćwiczenie z nieużywanym urządzeniem nigdy nie startuje w oknie bytności tej siłowni
|
|
await seedSessionAt(visitor.user.id, new Date(win.end.getTime() + 4 * 60 * 60 * 1000), [
|
|
exUnused.id,
|
|
]);
|
|
|
|
const res = await app
|
|
.get(`/api/v1/gyms/${gym.id}/equipment-usage`)
|
|
.set('Authorization', `Bearer ${strangerToken}`);
|
|
expect(res.status).toBe(200);
|
|
const rows = res.body.equipment as UsageRow[];
|
|
expect(rows.map((r) => r.equipmentId)).toEqual([hot.id, cold.id]);
|
|
expect(rows[0].cells).toEqual([{ hour: 13, count: 3 }]);
|
|
expect(rows[0].peak).toBe(3);
|
|
expect(rows[1].cells).toEqual([{ hour: 13, count: 1 }]);
|
|
expect(rows[1].peak).toBe(1);
|
|
});
|
|
|
|
it('filtr from zawęża okno: poza zakresem → pusta lista', async () => {
|
|
const app = buildApp();
|
|
const gym = await createRealGym();
|
|
const visitor = await createUserWithToken();
|
|
const eq = await createEquipment(`Range ${rand()}`);
|
|
const ex = await createExerciseWithEquipment([eq.id]);
|
|
const base = baseAt(10);
|
|
const win = await seedPresence(visitor.user.id, gym.id, base);
|
|
await seedSessionAt(visitor.user.id, new Date(win.start.getTime() + 30 * 60 * 1000), [ex.id]);
|
|
|
|
const all = await app
|
|
.get(`/api/v1/gyms/${gym.id}/equipment-usage`)
|
|
.set('Authorization', `Bearer ${strangerToken}`);
|
|
expect(all.status).toBe(200);
|
|
expect((all.body.equipment as UsageRow[]).map((r) => r.equipmentId)).toContain(eq.id);
|
|
|
|
const from = new Date(Date.now() - 2 * 86_400_000).toISOString();
|
|
const narrowed = await app
|
|
.get(`/api/v1/gyms/${gym.id}/equipment-usage?from=${encodeURIComponent(from)}`)
|
|
.set('Authorization', `Bearer ${strangerToken}`);
|
|
expect(narrowed.status).toBe(200);
|
|
expect(narrowed.body.equipment).toEqual([]);
|
|
});
|
|
|
|
it('404 dla nieistniejącej siłowni; REAL dostępny dla strangerów', async () => {
|
|
const app = buildApp();
|
|
const missing = await app
|
|
.get('/api/v1/gyms/does-not-exist/equipment-usage')
|
|
.set('Authorization', `Bearer ${strangerToken}`);
|
|
expect(missing.status).toBe(404);
|
|
});
|
|
|
|
it('VIRTUAL: stranger 403, właściciel i admin dostają pustą listę', async () => {
|
|
const app = buildApp();
|
|
const virtual = await createVirtualGym();
|
|
|
|
const denied = await app
|
|
.get(`/api/v1/gyms/${virtual.id}/equipment-usage`)
|
|
.set('Authorization', `Bearer ${strangerToken}`);
|
|
expect(denied.status).toBe(403);
|
|
|
|
const byOwner = await app
|
|
.get(`/api/v1/gyms/${virtual.id}/equipment-usage`)
|
|
.set('Authorization', `Bearer ${ownerToken}`);
|
|
expect(byOwner.status).toBe(200);
|
|
expect(byOwner.body).toEqual({ equipment: [] });
|
|
|
|
const byAdmin = await app
|
|
.get(`/api/v1/gyms/${virtual.id}/equipment-usage`)
|
|
.set('Authorization', `Bearer ${adminToken}`);
|
|
expect(byAdmin.status).toBe(200);
|
|
expect(byAdmin.body).toEqual({ equipment: [] });
|
|
});
|
|
|
|
it('admin route: 200 z danymi, 403 dla nie-admina, 404 dla braku siłowni', async () => {
|
|
const app = buildApp();
|
|
const gym = await createRealGym();
|
|
const visitor = await createUserWithToken();
|
|
const eq = await createEquipment(`Admin ${rand()}`);
|
|
const ex = await createExerciseWithEquipment([eq.id]);
|
|
const base = baseAt(4);
|
|
const win = await seedPresence(visitor.user.id, gym.id, base);
|
|
await seedSessionAt(visitor.user.id, new Date(win.start.getTime() + 20 * 60 * 1000), [ex.id]);
|
|
|
|
const res = await app
|
|
.get(`/api/v1/admin/gyms/${gym.id}/equipment-usage`)
|
|
.set('Authorization', `Bearer ${adminToken}`);
|
|
expect(res.status).toBe(200);
|
|
const rows = res.body.equipment as UsageRow[];
|
|
expect(rows).toHaveLength(1);
|
|
expect(rows[0]).toMatchObject({ equipmentId: eq.id, peak: 1 });
|
|
expect(rows[0].cells).toEqual([{ hour: 13, count: 1 }]);
|
|
|
|
const denied = await app
|
|
.get(`/api/v1/admin/gyms/${gym.id}/equipment-usage`)
|
|
.set('Authorization', `Bearer ${ownerToken}`);
|
|
expect(denied.status).toBe(403);
|
|
|
|
const missing = await app
|
|
.get('/api/v1/admin/gyms/does-not-exist/equipment-usage')
|
|
.set('Authorization', `Bearer ${adminToken}`);
|
|
expect(missing.status).toBe(404);
|
|
});
|
|
});
|