278 lines
10 KiB
TypeScript
278 lines
10 KiB
TypeScript
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||
import {
|
||
checkIn,
|
||
checkOut,
|
||
expireStale,
|
||
getMyStats,
|
||
touch,
|
||
} from '../../src/services/presence.js';
|
||
|
||
const NOW = new Date(2026, 9, 22, 12, 0, 0);
|
||
|
||
function presenceRow(overrides: Record<string, unknown> = {}) {
|
||
return {
|
||
id: 'p1',
|
||
userId: 'u1',
|
||
gymId: 'g1',
|
||
status: 'ACTIVE',
|
||
source: 'MANUAL',
|
||
checkedInAt: NOW,
|
||
lastActivityAt: NOW,
|
||
closedAt: null,
|
||
...overrides,
|
||
};
|
||
}
|
||
|
||
function mockPrisma() {
|
||
const prisma: any = {
|
||
gym: { findUnique: vi.fn(), findMany: vi.fn() },
|
||
gymPresence: {
|
||
findFirst: vi.fn(),
|
||
findMany: vi.fn(),
|
||
create: vi.fn(),
|
||
update: vi.fn(),
|
||
updateMany: vi.fn(),
|
||
count: vi.fn(),
|
||
},
|
||
trainingSession: { findMany: vi.fn() },
|
||
$executeRaw: vi.fn().mockResolvedValue(1),
|
||
$transaction: vi.fn(),
|
||
};
|
||
prisma.$transaction.mockImplementation(async (cb: (tx: unknown) => Promise<unknown>) =>
|
||
cb(prisma),
|
||
);
|
||
prisma.gym.findUnique.mockResolvedValue({ id: 'g1', name: 'Siłownia', kind: 'REAL' });
|
||
prisma.gymPresence.create.mockImplementation(async ({ data }: any) =>
|
||
presenceRow({ id: 'p-new', ...data, status: 'ACTIVE', checkedInAt: NOW, lastActivityAt: NOW }),
|
||
);
|
||
prisma.gymPresence.update.mockImplementation(async ({ where, data }: any) =>
|
||
presenceRow({ id: where.id, ...data }),
|
||
);
|
||
prisma.gymPresence.updateMany.mockResolvedValue({ count: 1 });
|
||
prisma.trainingSession.findMany.mockResolvedValue([]);
|
||
return prisma;
|
||
}
|
||
|
||
beforeEach(() => {
|
||
vi.useFakeTimers();
|
||
vi.setSystemTime(NOW);
|
||
});
|
||
|
||
afterEach(() => {
|
||
vi.useRealTimers();
|
||
});
|
||
|
||
describe('checkIn', () => {
|
||
it('404 when the gym does not exist', async () => {
|
||
const prisma = mockPrisma();
|
||
prisma.gym.findUnique.mockResolvedValue(null);
|
||
await expect(checkIn(prisma, 'u1', 'g1', 'MANUAL')).rejects.toMatchObject({ status: 404 });
|
||
});
|
||
|
||
it('400 for VIRTUAL gyms (only REAL accept check-ins)', async () => {
|
||
const prisma = mockPrisma();
|
||
prisma.gym.findUnique.mockResolvedValue({ id: 'g1', name: 'V', kind: 'VIRTUAL' });
|
||
await expect(checkIn(prisma, 'u1', 'g1', 'MANUAL')).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'Check-in is available only for real gyms',
|
||
});
|
||
expect(prisma.gymPresence.create).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('is idempotent when already checked in to the same gym', async () => {
|
||
const prisma = mockPrisma();
|
||
prisma.gymPresence.findFirst.mockResolvedValue(presenceRow({ id: 'p1' }));
|
||
const { presence } = await checkIn(prisma, 'u1', 'g1', 'MANUAL');
|
||
expect(presence.id).toBe('p1');
|
||
expect(prisma.gymPresence.create).not.toHaveBeenCalled();
|
||
expect(prisma.gymPresence.update).not.toHaveBeenCalled();
|
||
expect(prisma.gymPresence.updateMany).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('closes the old presence when moving A->B and opens a new one', async () => {
|
||
const prisma = mockPrisma();
|
||
prisma.gymPresence.findFirst
|
||
.mockResolvedValueOnce(presenceRow({ id: 'p-a', gymId: 'gA' })) // ACTIVE w innej siłowni
|
||
.mockResolvedValueOnce(null); // brak EXPIRED w docelowej
|
||
const { presence } = await checkIn(prisma, 'u1', 'gB', 'MANUAL');
|
||
expect(prisma.gymPresence.update).toHaveBeenCalledWith({
|
||
where: { id: 'p-a' },
|
||
data: { status: 'CLOSED', closedAt: NOW },
|
||
});
|
||
expect(prisma.gymPresence.create).toHaveBeenCalledWith({
|
||
data: { userId: 'u1', gymId: 'gB', source: 'MANUAL' },
|
||
});
|
||
expect(presence.id).toBe('p-new');
|
||
});
|
||
|
||
it('revives an EXPIRED presence via gap-merge when <=15 min since last activity', async () => {
|
||
const prisma = mockPrisma();
|
||
const expired = presenceRow({
|
||
id: 'p-old',
|
||
status: 'EXPIRED',
|
||
lastActivityAt: new Date(NOW.getTime() - 10 * 60 * 1000),
|
||
closedAt: null,
|
||
});
|
||
prisma.gymPresence.findFirst.mockImplementation(async ({ where }: any) => {
|
||
if (where.status === 'ACTIVE') return null;
|
||
if (where.status === 'EXPIRED' && where.lastActivityAt) return expired;
|
||
return null;
|
||
});
|
||
const { presence } = await checkIn(prisma, 'u1', 'g1', 'MANUAL');
|
||
expect(presence.id).toBe('p-old');
|
||
expect(prisma.gymPresence.create).not.toHaveBeenCalled();
|
||
expect(prisma.gymPresence.update).toHaveBeenCalledWith({
|
||
where: { id: 'p-old' },
|
||
data: { status: 'ACTIVE', lastActivityAt: NOW, closedAt: null, source: 'MANUAL' },
|
||
});
|
||
});
|
||
|
||
it('starts a new segment when the expired presence is older than 15 min', async () => {
|
||
const prisma = mockPrisma();
|
||
prisma.gymPresence.findFirst.mockResolvedValue(null); // merge wyklucza >15 min (filtr w where)
|
||
const { presence } = await checkIn(prisma, 'u1', 'g1', 'MANUAL');
|
||
expect(presence.id).toBe('p-new');
|
||
expect(prisma.gymPresence.create).toHaveBeenCalled();
|
||
// filtr okna merge musi ograniczać EXPIRED do 15 minut
|
||
const expiredQuery = prisma.gymPresence.findFirst.mock.calls.find(
|
||
([args]: any) => args.where.status === 'EXPIRED',
|
||
);
|
||
expect(expiredQuery![0].where.lastActivityAt.gte).toEqual(
|
||
new Date(NOW.getTime() - 15 * 60 * 1000),
|
||
);
|
||
});
|
||
|
||
it('merge promotes the source to QR if either check-in was QR', async () => {
|
||
const prisma = mockPrisma();
|
||
const expired = presenceRow({
|
||
id: 'p-old',
|
||
status: 'EXPIRED',
|
||
source: 'QR',
|
||
lastActivityAt: new Date(NOW.getTime() - 5 * 60 * 1000),
|
||
});
|
||
prisma.gymPresence.findFirst.mockImplementation(async ({ where }: any) => {
|
||
if (where.status === 'EXPIRED') return expired;
|
||
return null;
|
||
});
|
||
await checkIn(prisma, 'u1', 'g1', 'MANUAL');
|
||
expect(prisma.gymPresence.update).toHaveBeenCalledWith({
|
||
where: { id: 'p-old' },
|
||
data: expect.objectContaining({ source: 'QR' }),
|
||
});
|
||
});
|
||
|
||
it('serializes concurrent check-ins per user with an advisory lock', async () => {
|
||
const prisma = mockPrisma();
|
||
prisma.gymPresence.findFirst.mockResolvedValue(null);
|
||
await checkIn(prisma, 'u1', 'g1', 'QR');
|
||
expect(prisma.$executeRaw).toHaveBeenCalled();
|
||
expect(prisma.$executeRaw.mock.calls[0][0].join('')).toContain('pg_advisory_xact_lock');
|
||
});
|
||
});
|
||
|
||
describe('checkOut', () => {
|
||
it('closes the active presence (ACTIVE -> CLOSED)', async () => {
|
||
const prisma = mockPrisma();
|
||
const result = await checkOut(prisma, 'u1');
|
||
expect(prisma.gymPresence.updateMany).toHaveBeenCalledWith({
|
||
where: { userId: 'u1', status: 'ACTIVE' },
|
||
data: { status: 'CLOSED', closedAt: NOW },
|
||
});
|
||
expect(result).toEqual({ checkedOut: true });
|
||
});
|
||
|
||
it('is a no-op without an active presence', async () => {
|
||
const prisma = mockPrisma();
|
||
prisma.gymPresence.updateMany.mockResolvedValue({ count: 0 });
|
||
const result = await checkOut(prisma, 'u1');
|
||
expect(result).toEqual({ checkedOut: false });
|
||
});
|
||
});
|
||
|
||
describe('touch', () => {
|
||
it('refreshes lastActivityAt of the active presence', async () => {
|
||
const prisma = mockPrisma();
|
||
const result = await touch(prisma, 'u1');
|
||
expect(prisma.gymPresence.updateMany).toHaveBeenCalledWith({
|
||
where: { userId: 'u1', status: 'ACTIVE' },
|
||
data: { lastActivityAt: NOW },
|
||
});
|
||
expect(result).toEqual({ touched: true });
|
||
});
|
||
|
||
it('is a no-op without an active presence', async () => {
|
||
const prisma = mockPrisma();
|
||
prisma.gymPresence.updateMany.mockResolvedValue({ count: 0 });
|
||
const result = await touch(prisma, 'u1');
|
||
expect(result).toEqual({ touched: false });
|
||
});
|
||
});
|
||
|
||
describe('expireStale', () => {
|
||
it('releases slots idle for more than 30 min (ACTIVE -> EXPIRED)', async () => {
|
||
const prisma = mockPrisma();
|
||
const count = await expireStale(prisma, NOW);
|
||
expect(prisma.gymPresence.updateMany).toHaveBeenCalledWith({
|
||
where: { status: 'ACTIVE', lastActivityAt: { lt: new Date(NOW.getTime() - 30 * 60 * 1000) } },
|
||
data: { status: 'EXPIRED' },
|
||
});
|
||
expect(count).toBe(1);
|
||
});
|
||
});
|
||
|
||
describe('getMyStats', () => {
|
||
it('returns empty aggregates when the user has no visits', async () => {
|
||
const prisma = mockPrisma();
|
||
prisma.gymPresence.findMany.mockResolvedValue([]);
|
||
const { stats } = await getMyStats(prisma, 'u1', {});
|
||
expect(stats).toEqual({
|
||
visits: 0,
|
||
avgStayMinutes: null,
|
||
heatmap: [],
|
||
topGyms: [],
|
||
peak: 0,
|
||
topEquipment: [],
|
||
});
|
||
});
|
||
|
||
it('aggregates visits, avg stay, peak, top gyms and derives top equipment from session windows', async () => {
|
||
const prisma = mockPrisma();
|
||
const monday = new Date(2026, 9, 19, 18, 0, 0); // poniedziałek 18:00 lokalnie
|
||
prisma.gymPresence.findMany.mockResolvedValue([
|
||
presenceRow({ id: 'p1', checkedInAt: monday, lastActivityAt: new Date(monday.getTime() + 60 * 60 * 1000) }),
|
||
presenceRow({
|
||
id: 'p2',
|
||
checkedInAt: new Date(2026, 9, 19, 18, 30, 0),
|
||
lastActivityAt: new Date(2026, 9, 19, 19, 0, 0),
|
||
}),
|
||
]);
|
||
prisma.gym.findMany.mockResolvedValue([{ id: 'g1', name: 'Siłownia' }]);
|
||
// sesja startedAt w oknie bytności → ćwiczenie z urządzeniem
|
||
prisma.trainingSession.findMany.mockResolvedValue([
|
||
{
|
||
startedAt: new Date(2026, 9, 19, 18, 10, 0),
|
||
day: { week: { plan: { userId: 'u1' } } },
|
||
exercises: [{ exercise: { equipment: [{ id: 'e1', name: 'Sztanga', nameEn: 'Barbell' }] } }],
|
||
},
|
||
// sesja poza oknem — nie liczy się
|
||
{
|
||
startedAt: new Date(2026, 9, 19, 22, 0, 0),
|
||
day: { week: { plan: { userId: 'u1' } } },
|
||
exercises: [{ exercise: { equipment: [{ id: 'e2', name: 'Hantle', nameEn: null }] } }],
|
||
},
|
||
]);
|
||
const { stats } = await getMyStats(prisma, 'u1', {});
|
||
expect(stats.visits).toBe(2);
|
||
// p1: 60 min, p2: 30 min → średnia 45
|
||
expect(stats.avgStayMinutes).toBe(45);
|
||
// peak: nakładające się okna → 2 jednocześnie
|
||
expect(stats.peak).toBe(2);
|
||
expect(stats.topGyms).toEqual([{ gymId: 'g1', gymName: 'Siłownia', visits: 2 }]);
|
||
expect(stats.topEquipment).toEqual([
|
||
{ equipmentId: 'e1', name: 'Sztanga', nameEn: 'Barbell', count: 1 },
|
||
]);
|
||
// heatmapa: poniedziałek (dzień 0) × godzina 18
|
||
expect(stats.heatmap).toContainEqual({ day: 0, hour: 18, count: 2 });
|
||
});
|
||
});
|