API+App+Admin: telemetria bytnosci w ogolnym widoku sirowni - GET /gyms/:id/presence-stats (heatmapa dzien×godzina, sredni pobyt, wizyty/dzien, szczyt, teraz w srodku, top urzadzenia; stale 30 dni), wspoldzielony komponent PresenceHeatmap, telemetria wyciagnieta z podstrony statystyk; pasek godzin w forma zegarowa z minutami, usuniete karta Dane i filtr okresu; swagger + testy integracyjne, unit i e2e

This commit is contained in:
tisachi
2026-10-27 05:32:55 +01:00
parent 104748b3e8
commit 1629068bf0
30 changed files with 965 additions and 507 deletions

View File

@@ -16,7 +16,12 @@ import {
} from '../services/gyms.js';
import { logActivity } from '../services/audit.js';
import { asyncHandler } from '../lib/asyncHandler.js';
import { checkIn, getEquipmentUsage, getGymStatsOverview } from '../services/presence.js';
import {
checkIn,
getEquipmentUsage,
getGymPresenceTelemetry,
getGymStatsOverview,
} 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';
@@ -170,6 +175,33 @@ export function createGymRoutes(deps: AppDeps) {
}),
);
/**
* @openapi
* /gyms/{gymId}/presence-stats:
* get:
* summary: Presence telemetry of a gym (general view) — day×hour heatmap, avg stay, visits/day, peak, live, top equipment (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 { gym, stats: { visits, avgStayMinutes, heatmap, topGyms, peak, topEquipment, live, visitsPerDay } }" }
* 403: { description: VIRTUAL gym and the caller is not a manager }
* 404: { description: Gym not found }
*/
router.get(
'/:gymId/presence-stats',
validate(rangeQuerySchema, 'query'),
asyncHandler(async (req, res) => {
const query = req.query as z.infer<typeof rangeQuerySchema>;
const result = await getGymPresenceTelemetry(prisma, req.params.gymId, resolveRange(query), {
userId: req.user!.id,
isAdmin: req.user!.isAdmin,
});
res.json(result);
}),
);
/**
* @openapi
* /gyms/{gymId}/stats/overview:

View File

@@ -439,6 +439,30 @@ export async function getGymStats(
};
}
/**
* Telemetria bytności dla widoku ogólnego siłowni (aplikacja): dostęp jak
* mapa urządzeń — REAL: każdy zalogowany; VIRTUAL: tylko menedżer (OWNER) lub
* admin (puste statystyki — bytność istnieje tylko dla REAL). 404 gdy brak siłowni.
*/
export async function getGymPresenceTelemetry(
prisma: PrismaClient,
gymId: string,
range: Required<RangeQuery>,
caller: { userId: string; isAdmin: boolean },
) {
const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { kind: true } });
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'REAL' && !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 getGymStats(prisma, gymId, range);
}
/**
* Przegląd statystyk właściciela siłowni (tylko REAL): telemetria bytności
* (bez top urządzeń — jest na podstronie urządzeń) + członkowie i napływ +

View File

@@ -588,6 +588,27 @@ export const openapi: Record<string, unknown> = {
},
},
},
'/gyms/{gymId}/presence-stats': {
get: {
tags: ['Gyms'],
summary:
'Presence telemetry of a gym (general view): day×hour heatmap, avg stay, visits/day, peak, live, top equipment. REAL visible to all logged-in users; VIRTUAL to managers only (empty — presence is REAL only). Default range: last 30 days',
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 { gym, stats: { visits, avgStayMinutes, heatmap: [{ day, hour, count }], topGyms, peak, topEquipment, live, visitsPerDay } }',
},
403: { description: 'VIRTUAL gym and the caller is not a manager' },
404: { description: 'Gym not found' },
},
},
},
'/gyms/{gymId}/stats/overview': {
get: {
tags: ['Gyms'],

View File

@@ -0,0 +1,176 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { prisma } from '../../src/lib/prisma.js';
import { buildApp, createUserWithToken, rand } from '../helpers.js';
interface PresenceStatsBody {
gym: { id: string; name: string; kind: string; capacity: number | null };
stats: {
visits: number;
avgStayMinutes: number | null;
heatmap: { day: number; hour: number; count: number }[];
topGyms: unknown[];
peak: number;
topEquipment: unknown[];
live: number;
visitsPerDay: number;
};
}
describe('gym presence-stats — telemetria bytności (widok ogólny)', () => {
let ownerId: string;
let ownerToken: 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: `Presence 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: `Presence Virtual ${rand()}`, kind: 'VIRTUAL' },
});
gymIds.push(gym.id);
await prisma.gymMembership.create({
data: { userId: ownerId, gymId: gym.id, roles: ['OWNER'] },
});
return gym;
}
/** Bytność CLOSED [checkedInAt, +2h] — deterministyczne kafle godzinowe. */
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);
}
function baseAt(daysAgo: number): Date {
const base = new Date(Date.now() - daysAgo * 86_400_000);
base.setHours(13, 5, 0, 0);
return base;
}
it('REAL: statystyki dostępne dla każdego zalogowanego (heatmapa + KPI)', async () => {
const app = buildApp();
const gym = await createRealGym();
const visitor = await createUserWithToken();
const dayA = baseAt(5);
const dayB = new Date(dayA.getTime() + 86_400_000);
await seedPresence(visitor.user.id, gym.id, dayA);
await seedPresence(ownerId, gym.id, dayB);
// bytność poza domyślnym zakresem 30 dni nie liczy się
await seedPresence(visitor.user.id, gym.id, baseAt(40));
const res = await app
.get(`/api/v1/gyms/${gym.id}/presence-stats`)
.set('Authorization', `Bearer ${strangerToken}`);
expect(res.status).toBe(200);
const body = res.body as PresenceStatsBody;
expect(body.gym).toMatchObject({ id: gym.id, kind: 'REAL' });
expect(body.stats.visits).toBe(2);
expect(body.stats.peak).toBe(1);
expect(body.stats.live).toBe(0);
// heatmapa: dokładnie dwie wizyty w godzinie 13, dni zgodne z datami (0=pon)
expect(body.stats.heatmap).toHaveLength(2);
for (const cell of body.stats.heatmap) {
expect(cell.hour).toBe(13);
expect(cell.count).toBe(1);
}
expect(body.stats.heatmap.map((c) => c.day).sort()).toEqual(
[dayA, dayB].map((d) => (d.getDay() + 6) % 7).sort(),
);
// śr. pobyt = 120 min; wizyt/dzień za 30 dni ≈ 0.1
expect(body.stats.avgStayMinutes).toBe(120);
expect(body.stats.visitsPerDay).toBe(0.1);
});
it('REAL: filtr from zawęża zakres', async () => {
const app = buildApp();
const gym = await createRealGym();
await seedPresence(ownerId, gym.id, baseAt(10));
const from = new Date(Date.now() - 2 * 86_400_000).toISOString();
const narrowed = await app
.get(`/api/v1/gyms/${gym.id}/presence-stats?from=${encodeURIComponent(from)}`)
.set('Authorization', `Bearer ${strangerToken}`);
expect(narrowed.status).toBe(200);
expect((narrowed.body as PresenceStatsBody).stats.visits).toBe(0);
expect((narrowed.body as PresenceStatsBody).stats.heatmap).toEqual([]);
});
it('404 dla nieistniejącej siłowni', async () => {
const app = buildApp();
const missing = await app
.get('/api/v1/gyms/does-not-exist/presence-stats')
.set('Authorization', `Bearer ${strangerToken}`);
expect(missing.status).toBe(404);
});
it('VIRTUAL: stranger 403, właściciel i admin dostają puste statystyki', async () => {
const app = buildApp();
const virtual = await createVirtualGym();
const denied = await app
.get(`/api/v1/gyms/${virtual.id}/presence-stats`)
.set('Authorization', `Bearer ${strangerToken}`);
expect(denied.status).toBe(403);
const byOwner = await app
.get(`/api/v1/gyms/${virtual.id}/presence-stats`)
.set('Authorization', `Bearer ${ownerToken}`);
expect(byOwner.status).toBe(200);
expect((byOwner.body as PresenceStatsBody).stats.visits).toBe(0);
const byAdmin = await app
.get(`/api/v1/gyms/${virtual.id}/presence-stats`)
.set('Authorization', `Bearer ${adminToken}`);
expect(byAdmin.status).toBe(200);
expect((byAdmin.body as PresenceStatsBody).stats.visits).toBe(0);
});
it('wymaga autoryzacji (401 bez tokenu)', async () => {
const app = buildApp();
const anon = await app.get('/api/v1/gyms/any/presence-stats');
expect(anon.status).toBe(401);
});
});