From 081188afbbbf0ef21bbc44c8165d447ce1c58c3a Mon Sep 17 00:00:00 2001 From: tisachi Date: Fri, 23 Oct 2026 20:11:38 +0200 Subject: [PATCH] API: mapa ciepla godzinowa korzystania z urzadzen - GET /gyms/:id/equipment-usage + /admin/gyms/:id/equipment-usage (sesje startowane w oknach bytnosci, filtr okresu 7/30/90 dni) --- api/src/routes/gyms.ts | 30 +- api/src/routes/presence.ts | 31 +- api/src/services/presence.ts | 117 ++++++- api/src/swagger.ts | 41 +++ .../integration/gym-equipment-usage.test.ts | 301 ++++++++++++++++++ 5 files changed, 509 insertions(+), 11 deletions(-) create mode 100644 api/test/integration/gym-equipment-usage.test.ts diff --git a/api/src/routes/gyms.ts b/api/src/routes/gyms.ts index 02dd88c..4be511c 100644 --- a/api/src/routes/gyms.ts +++ b/api/src/routes/gyms.ts @@ -16,7 +16,8 @@ import { } from '../services/gyms.js'; import { logActivity } from '../services/audit.js'; import { asyncHandler } from '../lib/asyncHandler.js'; -import { checkIn } from '../services/presence.js'; +import { checkIn, getEquipmentUsage } from '../services/presence.js'; +import { rangeQuerySchema, resolveRange } from './presence.js'; import { checkInSchema, createGymSchema, rateGymSchema, updateGymSchema } from './gyms/schemas.js'; import { createGymClaimRoutes } from './gyms/claims.js'; import { createGymInvitationRoutes } from './gyms/invitations.js'; @@ -141,6 +142,33 @@ export function createGymRoutes(deps: AppDeps) { }), ); + /** + * @openapi + * /gyms/{gymId}/equipment-usage: + * get: + * summary: Equipment usage heatmap (rows = equipment, 24 hourly cells; default range: last 30 days). REAL visible to all logged-in users, VIRTUAL to managers (empty — presence is REAL only) + * tags: [Gyms] + * parameters: + * - { in: query, name: from, schema: { type: string, format: date-time } } + * - { in: query, name: to, schema: { type: string, format: date-time } } + * responses: + * 200: { description: "OK, returns { equipment: [{ equipmentId, name, nameEn, cells: [{hour,count}], peak }] }" } + * 403: { description: VIRTUAL gym and the caller is not a manager } + * 404: { description: Gym not found } + */ + router.get( + '/:gymId/equipment-usage', + validate(rangeQuerySchema, 'query'), + asyncHandler(async (req, res) => { + const query = req.query as z.infer; + const result = await getEquipmentUsage(prisma, req.params.gymId, resolveRange(query), { + userId: req.user!.id, + isAdmin: req.user!.isAdmin, + }); + res.json(result); + }), + ); + // Per-gym sub-routes: gallery photos, equipment instance photos, then equipment/exceptions. router.use('/:gymId/photos', createGymPhotoRoutes(deps)); router.use('/:gymId/equipment/:equipmentInstanceId/photos', createEquipmentPhotoRoutes(deps)); diff --git a/api/src/routes/presence.ts b/api/src/routes/presence.ts index 5588bcc..c2a1cdb 100644 --- a/api/src/routes/presence.ts +++ b/api/src/routes/presence.ts @@ -7,6 +7,7 @@ import { asyncHandler } from '../lib/asyncHandler.js'; import { checkOut, getActive, + getEquipmentUsage, getGymStats, getHistory, getLiveOccupancy, @@ -14,7 +15,7 @@ import { touch, } from '../services/presence.js'; -const rangeQuerySchema = z.object({ +export const rangeQuerySchema = z.object({ from: z.coerce.date().optional(), to: z.coerce.date().optional(), }); @@ -24,7 +25,7 @@ const historyQuerySchema = rangeQuerySchema.extend({ }); /** Domyślny okres telemetrii: ostatnie 30 dni. */ -function resolveRange(query: { from?: Date; to?: Date }): { from: Date; to: Date } { +export function resolveRange(query: { from?: Date; to?: Date }): { from: Date; to: Date } { const to = query.to ?? new Date(); const from = query.from ?? new Date(to.getTime() - 30 * 24 * 60 * 60 * 1000); return { from, to }; @@ -185,5 +186,31 @@ export function createPresenceAdminRoutes({ prisma }: AppDeps) { }), ); + /** + * @openapi + * /admin/gyms/{gymId}/equipment-usage: + * get: + * summary: Equipment usage heatmap of a gym (admin) — rows = equipment, 24 hourly cells (default range: last 30 days) + * tags: [Admin] + * parameters: + * - { in: query, name: from, schema: { type: string, format: date-time } } + * - { in: query, name: to, schema: { type: string, format: date-time } } + * responses: + * 200: { description: "OK, returns { equipment: [{ equipmentId, name, nameEn, cells: [{hour,count}], peak }] }" } + * 404: { description: Gym not found } + */ + router.get( + '/gyms/:gymId/equipment-usage', + validate(rangeQuerySchema, 'query'), + asyncHandler(async (req, res) => { + const query = req.query as z.infer; + const result = await getEquipmentUsage(prisma, req.params.gymId, resolveRange(query), { + userId: req.user!.id, + isAdmin: true, + }); + res.json(result); + }), + ); + return router; } diff --git a/api/src/services/presence.ts b/api/src/services/presence.ts index 3c6ef21..a4e995e 100644 --- a/api/src/services/presence.ts +++ b/api/src/services/presence.ts @@ -1,5 +1,5 @@ import type { Prisma, PrismaClient } from '@prisma/client'; -import { badRequest, notFound } from '../lib/errors.js'; +import { badRequest, forbidden, notFound } from '../lib/errors.js'; export type PresenceSourceInput = 'QR' | 'MANUAL'; @@ -279,11 +279,26 @@ async function buildStats(prisma: PrismaClient, presences: PresenceRow[]): Promi return { visits: presences.length, avgStayMinutes, heatmap, topGyms, peak, topEquipment }; } -async function topEquipmentOf( +interface PresenceWindow { + start: number; + end: number; +} + +interface SessionInWindow { + startedAt: Date; + exercises: { exercise: { equipment: { id: string; name: string; nameEn: string | null }[] } }[]; +} + +/** + * Okna bytności per user (start=checkedInAt, end=closedAt/lastActivityAt), a w nich + * sesje treningowe z ćwiczeniami i ich urządzeniami (wzorzec top Equipment): + * startedAt musi wypaść w oknie bytności autora sesji. + */ +async function sessionsInPresenceWindows( prisma: PrismaClient, presences: PresenceRow[], -): Promise { - const windowsByUser = new Map(); +): Promise { + const windowsByUser = new Map(); let minStart = Infinity; let maxEnd = -Infinity; for (const p of presences) { @@ -312,12 +327,23 @@ async function topEquipmentOf( }, }, }); + return sessions + .filter((s) => { + const t = s.startedAt.getTime(); + return (windowsByUser.get(s.day.week.plan.userId) ?? []).some( + (w) => t >= w.start && t <= w.end, + ); + }) + .map((s) => ({ startedAt: s.startedAt, exercises: s.exercises })); +} + +async function topEquipmentOf( + prisma: PrismaClient, + presences: PresenceRow[], +): Promise { + const sessions = await sessionsInPresenceWindows(prisma, presences); const counts = new Map(); for (const s of sessions) { - const userId = s.day.week.plan.userId; - const t = s.startedAt.getTime(); - const inWindow = (windowsByUser.get(userId) ?? []).some((w) => t >= w.start && t <= w.end); - if (!inWindow) continue; for (const se of s.exercises) { for (const eq of se.exercise.equipment) { const cur = counts.get(eq.id); @@ -403,3 +429,78 @@ export async function getGymStats( stats: { ...stats, live, visitsPerDay: Math.round((stats.visits / days) * 10) / 10 }, }; } + +export interface EquipmentUsageCell { + hour: number; + count: number; +} + +export interface EquipmentUsageRow { + equipmentId: string; + name: string; + nameEn: string | null; + /** Kafle godzinowe (0–23) z niepustymi licznikami; godzina lokalna procesu (jak heatmapa bytności). */ + cells: EquipmentUsageCell[]; + /** Maksimum w jednym kaflu — podstawa natężenia koloru. */ + peak: number; +} + +/** + * Mapa ciepła urządzeń (24 kafle godzinowe): okna bytności siłowni → sesje w oknach → + * ćwiczenia → urządzenia katalogu (ta sama logika wywodząca co top urządzenia w getGymStats, bez cięcia top-10). + * Sort po sumie użyć malejąco. On-the-fly, bez rollupów. + * Dostęp jak szczegóły siłowni: REAL — każdy zalogowany; VIRTUAL — tylko menedżer (403) + * i pusta lista (bytność istnieje tylko dla REAL). 404 gdy brak siłowni. + */ +export async function getEquipmentUsage( + prisma: PrismaClient, + gymId: string, + range: Required, + caller: { userId: string; isAdmin: boolean }, +): Promise<{ equipment: EquipmentUsageRow[] }> { + const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { kind: true } }); + if (!gym) throw notFound('Gym not found'); + if (gym.kind !== 'REAL') { + if (!caller.isAdmin) { + const membership = await prisma.gymMembership.findUnique({ + where: { userId_gymId: { userId: caller.userId, gymId } }, + select: { roles: true }, + }); + if (!membership?.roles.includes('OWNER')) + throw forbidden('You do not have access to this gym'); + } + return { equipment: [] }; + } + const presences = await prisma.gymPresence.findMany({ + where: { gymId, ...rangeWhere(range) }, + orderBy: { checkedInAt: 'asc' }, + }); + const sessions = await sessionsInPresenceWindows(prisma, presences); + const byEquipment = new Map< + string, + { name: string; nameEn: string | null; cells: Map } + >(); + for (const s of sessions) { + const hour = s.startedAt.getHours(); + for (const se of s.exercises) { + for (const eq of se.exercise.equipment) { + let row = byEquipment.get(eq.id); + if (!row) { + row = { name: eq.name, nameEn: eq.nameEn, cells: new Map() }; + byEquipment.set(eq.id, row); + } + row.cells.set(hour, (row.cells.get(hour) ?? 0) + 1); + } + } + } + const rows = [...byEquipment.entries()].map(([equipmentId, row]) => { + const cells = [...row.cells.entries()] + .map(([hour, count]) => ({ hour, count })) + .sort((a, b) => a.hour - b.hour); + const peak = cells.reduce((m, c) => Math.max(m, c.count), 0); + const total = cells.reduce((sum, c) => sum + c.count, 0); + return { equipmentId, name: row.name, nameEn: row.nameEn, cells, peak, total }; + }); + rows.sort((a, b) => b.total - a.total || a.name.localeCompare(b.name, 'pl')); + return { equipment: rows.map(({ total: _total, ...row }) => row) }; +} diff --git a/api/src/swagger.ts b/api/src/swagger.ts index cdb1c37..930815e 100644 --- a/api/src/swagger.ts +++ b/api/src/swagger.ts @@ -555,6 +555,27 @@ export const openapi: Record = { }, }, }, + '/gyms/{gymId}/equipment-usage': { + get: { + tags: ['Gyms'], + summary: + 'Equipment usage heatmap of a gym: rows = equipment, 24 hourly cells aggregated from sessions started within presence windows (default range: last 30 days). REAL visible to all logged-in users; VIRTUAL to managers only (empty — presence is REAL only)', + security: [{ bearerAuth: [] }], + parameters: [ + { name: 'gymId', in: 'path', required: true, schema: { type: 'string' } }, + { name: 'from', in: 'query', schema: { type: 'string', format: 'date-time' } }, + { name: 'to', in: 'query', schema: { type: 'string', format: 'date-time' } }, + ], + responses: { + 200: { + description: + 'OK, returns { equipment: [{ equipmentId, name, nameEn, cells: [{ hour, count }], peak }] } (sorted by total uses desc)', + }, + 403: { description: 'VIRTUAL gym and the caller is not a manager' }, + 404: { description: 'Gym not found' }, + }, + }, + }, '/me/presence': { get: { tags: ['Presence'], @@ -1397,6 +1418,26 @@ export const openapi: Record = { }, }, }, + '/admin/gyms/{id}/equipment-usage': { + get: { + tags: ['Admin'], + summary: + 'Equipment usage heatmap of a gym (admin): rows = equipment, 24 hourly cells aggregated from sessions started within presence windows (default range: last 30 days)', + security: [{ bearerAuth: [] }], + parameters: [ + { name: 'id', in: 'path', required: true, schema: { type: 'string' } }, + { name: 'from', in: 'query', schema: { type: 'string', format: 'date-time' } }, + { name: 'to', in: 'query', schema: { type: 'string', format: 'date-time' } }, + ], + responses: { + 200: { + description: + 'OK, returns { equipment: [{ equipmentId, name, nameEn, cells: [{ hour, count }], peak }] } (sorted by total uses desc)', + }, + 404: { description: 'Gym not found' }, + }, + }, + }, '/admin/gyms': { get: { tags: ['Admin'], diff --git a/api/test/integration/gym-equipment-usage.test.ts b/api/test/integration/gym-equipment-usage.test.ts new file mode 100644 index 0000000..6be00b1 --- /dev/null +++ b/api/test/integration/gym-equipment-usage.test.ts @@ -0,0 +1,301 @@ +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); + }); +});