Files
FitOS/api/test/unit/scheduler.test.ts

174 lines
6.1 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { startScheduler } from '../../src/services/scheduler.js';
const planDayUpdateMany = vi.fn();
const sessionUpdateMany = vi.fn();
const sessionFindMany = vi.fn();
const planFindMany = vi.fn();
const planUpdate = vi.fn();
const presenceUpdateMany = vi.fn();
const exceptionDeleteMany = vi.fn();
const prisma = {
planDay: { updateMany: planDayUpdateMany },
trainingSession: { updateMany: sessionUpdateMany, findMany: sessionFindMany },
trainingPlan: { findMany: planFindMany, update: planUpdate },
gymPresence: { updateMany: presenceUpdateMany },
gymException: { deleteMany: exceptionDeleteMany },
} as never;
const NOW = new Date(2026, 7, 22, 12, 0, 0);
async function tickOnce() {
startScheduler(prisma);
await vi.advanceTimersByTimeAsync(60_000);
await vi.advanceTimersByTimeAsync(60_000);
}
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(NOW);
planDayUpdateMany.mockReset().mockResolvedValue({ count: 0 });
sessionUpdateMany.mockReset().mockResolvedValue({ count: 0 });
sessionFindMany.mockReset().mockResolvedValue([]);
planFindMany.mockReset().mockResolvedValue([]);
planUpdate.mockReset().mockResolvedValue({});
presenceUpdateMany.mockReset().mockResolvedValue({ count: 0 });
exceptionDeleteMany.mockReset().mockResolvedValue({ count: 0 });
});
afterEach(() => {
vi.useRealTimers();
});
describe('scheduler', () => {
it('auto-expires planned days before today, but not days with an in-progress session', async () => {
await tickOnce();
expect(planDayUpdateMany).toHaveBeenCalledWith({
where: {
status: 'PLANNED',
removedAt: null,
date: { lt: new Date(2026, 7, 22) },
// północ nie może przerwać trwającego treningu — dzień z sesją IN_PROGRESS
// nie wygasa; domknie go ukończenie sesji albo reguła 24h
sessions: { none: { status: 'IN_PROGRESS' } },
// dni wstrzymanego planu to pauza — nie wygasają, przesuwamy je przy wznowieniu
week: { plan: { status: { not: 'SUSPENDED' } } },
},
data: { status: 'SKIPPED', skippedAt: expect.any(Date) },
});
expect(planDayUpdateMany.mock.calls[0][0].data.skippedAt).toEqual(NOW);
});
it('abandons in-progress sessions of expired (skipped) days', async () => {
await tickOnce();
expect(sessionUpdateMany).toHaveBeenCalledWith({
where: { status: 'IN_PROGRESS', day: { status: 'SKIPPED' } },
data: { status: 'ABANDONED', endedAt: expect.any(Date) },
});
});
it('auto-abandons in-progress sessions older than 24h and skips their days', async () => {
sessionFindMany.mockResolvedValue([
{ id: 's1', dayId: 'd1' },
{ id: 's2', dayId: 'd2' },
]);
await tickOnce();
const cutoff = new Date(NOW.getTime() - 24 * 60 * 60 * 1000);
expect(sessionFindMany).toHaveBeenCalledWith({
where: { status: 'IN_PROGRESS', startedAt: { lt: cutoff } },
select: { id: true, dayId: true },
});
expect(sessionUpdateMany).toHaveBeenCalledWith({
// warunek status w where: nie nadpisze sesji zakończonej w międzyczasie
where: { id: { in: ['s1', 's2'] }, status: 'IN_PROGRESS' },
data: { status: 'ABANDONED', endedAt: expect.any(Date) },
});
// dzień porzuconej sesji nie może zostać ponownie wykonany (jak przy ręcznym abandon),
// ale dni z przyszłą datą zostają PLANNED — stąd filtr po dacie
expect(planDayUpdateMany).toHaveBeenLastCalledWith({
where: {
id: { in: ['d1', 'd2'] },
status: 'PLANNED',
removedAt: null,
date: { lt: new Date(2026, 7, 23) },
},
data: { status: 'SKIPPED', skippedAt: expect.any(Date) },
});
});
it('does not skip days when no stale sessions exist', async () => {
await tickOnce();
// jedyne wywołania to auto-wygasanie (where po dacie) — brak drugiej tury po stale ids
for (const [args] of planDayUpdateMany.mock.calls) {
expect(args.where).not.toHaveProperty('id');
}
});
it('auto-completes an active plan when all days are closed', async () => {
planFindMany.mockResolvedValue([
{
id: 'plan-1',
weeks: [
{
days: [{ status: 'COMPLETED' }, { status: 'SKIPPED', skipResolvedAt: new Date() }],
},
],
},
]);
await tickOnce();
expect(planUpdate).toHaveBeenCalledWith({
where: { id: 'plan-1' },
data: { status: 'COMPLETED' },
});
});
it('does not auto-complete while a skip is unresolved (decision dialog pending)', async () => {
planFindMany.mockResolvedValue([
{
id: 'plan-1',
weeks: [{ days: [{ status: 'COMPLETED' }, { status: 'SKIPPED', skipResolvedAt: null }] }],
},
]);
await tickOnce();
expect(planUpdate).not.toHaveBeenCalled();
});
it('keeps a plan active while days are still planned', async () => {
planFindMany.mockResolvedValue([{ id: 'plan-1', weeks: [{ days: [{ status: 'PLANNED' }] }] }]);
await tickOnce();
expect(planUpdate).not.toHaveBeenCalled();
});
it('ignores plans without days', async () => {
planFindMany.mockResolvedValue([{ id: 'plan-1', weeks: [] }]);
await tickOnce();
expect(planUpdate).not.toHaveBeenCalled();
});
it('swallows tick errors (does not crash the interval)', async () => {
planDayUpdateMany.mockRejectedValue(new Error('db down'));
await expect(tickOnce()).resolves.toBeUndefined();
expect(sessionUpdateMany).not.toHaveBeenCalled();
});
it('expires presence slots after 30 min without activity', async () => {
presenceUpdateMany.mockResolvedValue({ count: 3 });
await tickOnce();
expect(presenceUpdateMany).toHaveBeenCalledWith({
where: {
status: 'ACTIVE',
lastActivityAt: { lt: new Date(NOW.getTime() - 30 * 60 * 1000) },
},
data: { status: 'EXPIRED' },
});
});
it('presence expiry failure does not crash the tick', async () => {
presenceUpdateMany.mockRejectedValue(new Error('db down'));
await expect(tickOnce()).resolves.toBeUndefined();
// reszta sweepów wykonała się mimo awarii licznika "teraz"
expect(planDayUpdateMany).toHaveBeenCalled();
});
});