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:
@@ -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) };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user