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)
This commit is contained in:
@@ -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<typeof rangeQuerySchema>;
|
||||
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));
|
||||
|
||||
@@ -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<typeof rangeQuerySchema>;
|
||||
const result = await getEquipmentUsage(prisma, req.params.gymId, resolveRange(query), {
|
||||
userId: req.user!.id,
|
||||
isAdmin: true,
|
||||
});
|
||||
res.json(result);
|
||||
}),
|
||||
);
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
@@ -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<EquipmentStat[]> {
|
||||
const windowsByUser = new Map<string, { start: number; end: number }[]>();
|
||||
): Promise<SessionInWindow[]> {
|
||||
const windowsByUser = new Map<string, PresenceWindow[]>();
|
||||
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<EquipmentStat[]> {
|
||||
const sessions = await sessionsInPresenceWindows(prisma, presences);
|
||||
const counts = new Map<string, EquipmentStat>();
|
||||
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<RangeQuery>,
|
||||
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<number, number> }
|
||||
>();
|
||||
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) };
|
||||
}
|
||||
|
||||
@@ -555,6 +555,27 @@ export const openapi: Record<string, unknown> = {
|
||||
},
|
||||
},
|
||||
},
|
||||
'/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<string, unknown> = {
|
||||
},
|
||||
},
|
||||
},
|
||||
'/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'],
|
||||
|
||||
Reference in New Issue
Block a user