test: 302 tests unitaires + 20 E2E Playwright (couverture 94%)

- Unit : domain (GaugeCalculator, Enclos, Dragodinde, XpTable, Race, Tier...)
- Unit : application (commands, queries, CommandBus)
- Fonctionnel : breeding-workflow, enclos-management, timer-workflow
- Régression : gauge-tier, gauge-recharge, xp-timer, level-target, breeding
- E2E Playwright + Electron : navigation, timer, recharge jauge,
  accouplement, persistance des données

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-06 05:43:29 +02:00
parent 62ae4c54eb
commit 203c423f19
36 changed files with 3965 additions and 0 deletions

View File

@@ -0,0 +1,45 @@
import { describe, it, expect, vi } from 'vitest';
import { CommandBus } from '@application/handlers/CommandBus';
import { QueryBus } from '@application/handlers/QueryBus';
describe('CommandBus', () => {
it('dispatches to registered handler', () => {
const bus = new CommandBus();
const handler = vi.fn();
bus.register('start-timer', handler);
bus.execute({ type: 'start-timer', enclosId: 1 });
expect(handler).toHaveBeenCalledWith({ type: 'start-timer', enclosId: 1 });
});
it('throws on unknown command', () => {
const bus = new CommandBus();
expect(() => bus.execute({ type: 'unknown' })).toThrow('No handler for command: unknown');
});
it('has returns true for registered', () => {
const bus = new CommandBus();
bus.register('test', vi.fn());
expect(bus.has('test')).toBe(true);
expect(bus.has('other')).toBe(false);
});
});
describe('QueryBus', () => {
it('returns value from handler', () => {
const bus = new QueryBus();
bus.register('get-dashboard', () => ({ total: 42 }));
const result = bus.execute<{ total: number }>({ type: 'get-dashboard' });
expect(result.total).toBe(42);
});
it('throws on unknown query', () => {
const bus = new QueryBus();
expect(() => bus.execute({ type: 'unknown' })).toThrow('No handler for query: unknown');
});
it('has returns true for registered', () => {
const bus = new QueryBus();
bus.register('test', () => null);
expect(bus.has('test')).toBe(true);
});
});

View File

@@ -0,0 +1,822 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import type { AppState, StateRepository } from '@domain/ports/StateRepository';
import { EventBus } from '@domain/events/EventBus';
import { createEnclos, addDragodinde } from '@domain/entities/Enclos';
import { createStartTimerHandler } from '@application/commands/StartTimer';
import { createStopTimerHandler } from '@application/commands/StopTimer';
import { createCreateEnclosHandler } from '@application/commands/CreateEnclos';
import { createDeleteEnclosHandler } from '@application/commands/DeleteEnclos';
import { createAddDragodindeHandler } from '@application/commands/AddDragodinde';
import { createRemoveDragodindeHandler } from '@application/commands/RemoveDragodinde';
import { createToggleGaugeHandler, createUpdateGaugeLevelHandler } from '@application/commands/UpdateGauge';
import { createRegisterAccouplementHandler } from '@application/commands/RegisterAccouplement';
import { createUpdateSettingsHandler } from '@application/commands/UpdateSettings';
import { createResetStatsHandler } from '@application/commands/ResetStats';
import { createRechargeGaugeHandler } from '@application/commands/RechargeGauge';
import { createResetTimerHandler, createClearEnclosHandler, createRenameEnclosHandler, createNouvelleFourneeHandler } from '@application/commands/EnclosActions';
import { createSaveWorkflowHandler } from '@application/commands/SaveWorkflow';
import { createCompleteTimerHandler } from '@application/commands/CompleteTimer';
import { createDeleteWorkflowHandler } from '@application/commands/DeleteWorkflow';
import { createRenameDragodindeHandler, createUpdateDdStatHandler, createUpdateDdSerenTargetHandler, createUpdateDdLevelTargetHandler, createReorderDragodindeHandler } from '@application/commands/DragodindeActions';
import { createImportWorkflowsHandler } from '@application/commands/ImportWorkflows';
import { createReorderEnclosHandler } from '@application/commands/ReorderEnclos';
import { createUpdateWorkflowHandler } from '@application/commands/UpdateWorkflow';
import type { WorkflowItem } from '@application/queries/GetWorkflows';
function makeState(): AppState {
let enc = createEnclos(1);
enc = addDragodinde(enc);
enc.activeGauges = ['baffeur'];
enc.gaugeLevels.baffeur = 50000;
return {
enclos: [enc], activeId: 1, nextEnclosId: 2,
alarmSound: 'arpege', notifsEnabled: true, ntfyTopic: '',
archivedStats: [], inventaire: {}, workflows: [], accouplements: [],
};
}
function makeRepo(): StateRepository {
return { load: vi.fn(async () => null), save: vi.fn() };
}
describe('StartTimer', () => {
it('starts timer on enclos', () => {
const state = makeState();
const repo = makeRepo();
const handler = createStartTimerHandler(state, repo);
handler({ type: 'start-timer', enclosId: 1 });
expect(state.enclos[0]!.timer.running).toBe(true);
expect(state.enclos[0]!.timer.startTime).not.toBeNull();
expect(state.enclos[0]!.timer.snapGauges).toHaveProperty('baffeur', 50000);
expect(repo.save).toHaveBeenCalled();
});
it('ignores if already running', () => {
const state = makeState();
const repo = makeRepo();
const handler = createStartTimerHandler(state, repo);
handler({ type: 'start-timer', enclosId: 1 });
handler({ type: 'start-timer', enclosId: 1 }); // second call
expect(repo.save).toHaveBeenCalledTimes(1);
});
it('ignores if no gauges active', () => {
const state = makeState();
state.enclos[0]!.activeGauges = [];
const repo = makeRepo();
const handler = createStartTimerHandler(state, repo);
handler({ type: 'start-timer', enclosId: 1 });
expect(state.enclos[0]!.timer.running).toBe(false);
});
});
describe('StopTimer', () => {
it('stops running timer', () => {
const state = makeState();
const repo = makeRepo();
createStartTimerHandler(state, repo)({ type: 'start-timer', enclosId: 1 });
createStopTimerHandler(state, repo)({ type: 'stop-timer', enclosId: 1 });
expect(state.enclos[0]!.timer.running).toBe(false);
expect(state.enclos[0]!.timer.pausedAt).not.toBeNull();
});
});
describe('CreateEnclos', () => {
it('creates and activates new enclos', () => {
const state = makeState();
const repo = makeRepo();
createCreateEnclosHandler(state, repo)({ type: 'create-enclos' });
expect(state.enclos).toHaveLength(2);
expect(state.activeId).toBe(2);
expect(state.enclos[1]!.dragodindes).toHaveLength(1); // starts with 1 DD
});
});
describe('DeleteEnclos', () => {
it('deletes and switches active', () => {
const state = makeState();
const repo = makeRepo();
const events = new EventBus();
const handler = vi.fn();
events.on('enclos-deleted', handler);
createDeleteEnclosHandler(state, repo, events)({ type: 'delete-enclos', enclosId: 1 });
expect(state.enclos).toHaveLength(0);
expect(state.activeId).toBe('dashboard');
expect(handler).toHaveBeenCalled();
});
});
describe('AddDragodinde', () => {
it('adds DD to enclos', () => {
const state = makeState();
const repo = makeRepo();
createAddDragodindeHandler(state, repo)({ type: 'add-dragodinde', enclosId: 1 });
expect(state.enclos[0]!.dragodindes).toHaveLength(2);
});
});
describe('RemoveDragodinde', () => {
it('removes DD from enclos', () => {
const state = makeState();
const repo = makeRepo();
createRemoveDragodindeHandler(state, repo)({ type: 'remove-dragodinde', enclosId: 1, ddId: 1 });
expect(state.enclos[0]!.dragodindes).toHaveLength(0);
});
});
describe('ToggleGauge', () => {
it('toggles gauge on', () => {
const state = makeState();
state.enclos[0]!.activeGauges = [];
const repo = makeRepo();
createToggleGaugeHandler(state, repo)({ type: 'toggle-gauge', enclosId: 1, gaugeId: 'foudroyeur' });
expect(state.enclos[0]!.activeGauges).toContain('foudroyeur');
});
it('toggles gauge off', () => {
const state = makeState();
const repo = makeRepo();
createToggleGaugeHandler(state, repo)({ type: 'toggle-gauge', enclosId: 1, gaugeId: 'baffeur' });
expect(state.enclos[0]!.activeGauges).not.toContain('baffeur');
});
});
describe('UpdateGaugeLevel', () => {
it('clamps level between 0 and 100000', () => {
const state = makeState();
const repo = makeRepo();
createUpdateGaugeLevelHandler(state, repo)({ type: 'update-gauge-level', enclosId: 1, gaugeId: 'baffeur', level: 150000 });
expect(state.enclos[0]!.gaugeLevels.baffeur).toBe(100000);
});
});
describe('RegisterAccouplement', () => {
it('adds accouplement to state', () => {
const state = makeState();
const repo = makeRepo();
const events = new EventBus();
createRegisterAccouplementHandler(state, repo, events)({
type: 'register-accouplement',
parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', couples: 5, babiesObtained: 3,
});
expect(state.accouplements).toHaveLength(1);
expect(state.accouplements[0]!.baby).toBe('Dorée et Rousse');
});
});
describe('UpdateSettings', () => {
it('updates alarm sound', () => {
const state = makeState();
const repo = makeRepo();
createUpdateSettingsHandler(state, repo)({ type: 'update-settings', alarmSound: 'cloche' });
expect(state.alarmSound).toBe('cloche');
});
it('persists inventaire', () => {
const state = makeState();
const repo = makeRepo();
const inv = { Rousse: { m: 3, f: 2 }, Dorée: { m: 1, f: 4 } };
createUpdateSettingsHandler(state, repo)({ type: 'update-settings', inventaire: inv });
expect(state.inventaire).toEqual(inv);
expect(repo.save).toHaveBeenCalled();
});
it('ne touche pas aux autres champs si seul inventaire est fourni', () => {
const state = makeState();
const repo = makeRepo();
createUpdateSettingsHandler(state, repo)({ type: 'update-settings', inventaire: { Rousse: { m: 1, f: 0 } } });
expect(state.alarmSound).toBe('arpege');
expect(state.notifsEnabled).toBe(true);
});
});
describe('SaveWorkflow', () => {
it('crée un workflow avec matériaux et étapes', () => {
const state = makeState();
const repo = makeRepo();
const handler = createSaveWorkflowHandler(state, repo);
handler({
type: 'save-workflow',
target: 'Dorée et Rousse',
qty: 4,
materials: [{ race: 'Rousse', m: 4, f: 4 }, { race: 'Dorée', m: 4, f: 4 }],
steps: [{ baby: 'Dorée et Rousse', parentA: 'Rousse', parentB: 'Dorée', couples: 4, gen: 2 }],
repro: {},
});
expect(state.workflows).toHaveLength(1);
expect(state.workflows[0]!.target).toBe('Dorée et Rousse');
expect(state.workflows[0]!.qty).toBe(4);
expect(state.workflows[0]!.materials).toHaveLength(2);
expect(state.workflows[0]!.materials[0]!.needed).toBe(8); // m + f
expect(state.workflows[0]!.steps).toHaveLength(1);
expect(state.workflows[0]!.steps[0]!.gen).toBe(2);
expect(state.workflows[0]!.steps[0]!.crossings).toHaveLength(1);
expect(repo.save).toHaveBeenCalled();
});
it('groupe les étapes par génération', () => {
const state = makeState();
const repo = makeRepo();
createSaveWorkflowHandler(state, repo)({
type: 'save-workflow',
target: 'Ebène',
qty: 2,
materials: [],
steps: [
{ baby: 'Dorée et Rousse', parentA: 'Rousse', parentB: 'Dorée', couples: 4, gen: 2 },
{ baby: 'Amande et Dorée', parentA: 'Amande', parentB: 'Dorée', couples: 4, gen: 2 },
{ baby: 'Ebène', parentA: 'Amande et Dorée', parentB: 'Dorée et Rousse', couples: 2, gen: 3 },
],
repro: {},
});
const wf = state.workflows[0]!;
expect(wf.steps).toHaveLength(2); // gen 2 + gen 3
expect(wf.steps[0]!.gen).toBe(2);
expect(wf.steps[0]!.crossings).toHaveLength(2);
expect(wf.steps[1]!.gen).toBe(3);
expect(wf.steps[1]!.crossings).toHaveLength(1);
});
});
describe('ResetStats', () => {
it('clears stats and accouplements', () => {
const state = makeState();
state.archivedStats = [{ a: 1 }];
state.accouplements = [{ parentA: 'A', parentB: 'B', baby: 'C', gen: 2, couples: 1, babiesObtained: 1, date: '' }];
const repo = makeRepo();
createResetStatsHandler(state, repo)({ type: 'reset-stats' });
expect(state.archivedStats).toHaveLength(0);
expect(state.accouplements).toHaveLength(0);
});
});
describe('RechargeGauge', () => {
function makeRunningState(): AppState {
const state = makeState();
// Simuler un timer démarré
state.enclos[0]!.timer = {
running: true,
startTime: Date.now() - 3600_000, // démarré y'a 1h
pausedAt: null,
pausedMs: 0,
snapGauges: { baffeur: 50000 },
snapStats: {},
gaugeRecharges: {},
};
return state;
}
it('enregistre une recharge avec le elapsed courant', () => {
const state = makeRunningState();
const repo = makeRepo();
const handler = createRechargeGaugeHandler(state, repo);
handler({ type: 'recharge-gauge', enclosId: 1, gaugeId: 'baffeur', level: 90000 });
const recharges = state.enclos[0]!.timer.gaugeRecharges['baffeur'];
expect(recharges).toHaveLength(1);
expect(recharges![0]!.level).toBe(90000);
// atSec ≈ 3600 sec (1h de timer)
expect(recharges![0]!.atSec).toBeGreaterThan(3500);
expect(recharges![0]!.atSec).toBeLessThan(3700);
});
it('met à jour gaugeLevels pour l\'affichage', () => {
const state = makeRunningState();
const repo = makeRepo();
createRechargeGaugeHandler(state, repo)({ type: 'recharge-gauge', enclosId: 1, gaugeId: 'baffeur', level: 75000 });
expect(state.enclos[0]!.timer.gaugeRecharges['baffeur']![0]!.level).toBe(75000);
expect(repo.save).toHaveBeenCalled();
});
it('recharges proches (<2s) sont consolidées (saisie temps réel)', () => {
const state = makeRunningState();
const repo = makeRepo();
const handler = createRechargeGaugeHandler(state, repo);
handler({ type: 'recharge-gauge', enclosId: 1, gaugeId: 'baffeur', level: 70000 });
handler({ type: 'recharge-gauge', enclosId: 1, gaugeId: 'baffeur', level: 90000 });
// Les deux appels sont quasi-simultanés → consolidés en une seule entrée
const arr = state.enclos[0]!.timer.gaugeRecharges['baffeur']!;
expect(arr).toHaveLength(1);
expect(arr[0]!.level).toBe(90000);
});
it('ignore si le timer n\'est pas en cours', () => {
const state = makeState();
// timer non démarré
const repo = makeRepo();
createRechargeGaugeHandler(state, repo)({ type: 'recharge-gauge', enclosId: 1, gaugeId: 'baffeur', level: 90000 });
expect(state.enclos[0]!.timer.gaugeRecharges['baffeur']).toBeUndefined();
expect(repo.save).not.toHaveBeenCalled();
});
it('reset-timer efface les recharges', () => {
const state = makeRunningState();
const repo = makeRepo();
createRechargeGaugeHandler(state, repo)({ type: 'recharge-gauge', enclosId: 1, gaugeId: 'baffeur', level: 90000 });
expect(state.enclos[0]!.timer.gaugeRecharges['baffeur']).toHaveLength(1);
createResetTimerHandler(state, repo)({ type: 'reset-timer', enclosId: 1 });
expect(state.enclos[0]!.timer.gaugeRecharges).toEqual({});
});
});
describe('CompleteTimer', () => {
afterEach(() => {
vi.useRealTimers();
});
function makeRunningTimerState(): AppState {
const state = makeState();
const enc = state.enclos[0]!;
enc.activeGauges = ['foudroyeur'];
enc.gaugeLevels.foudroyeur = 80000;
enc.dragodindes[0]!.stats.endurance = 100;
enc.timer = {
running: true,
startTime: Date.now() - 7200_000, // démarré y'a 2h
pausedAt: null,
pausedMs: 0,
snapGauges: { foudroyeur: 80000 },
snapStats: { 1: { endurance: 100 } },
gaugeRecharges: {},
};
enc.alerted = {};
return state;
}
it('arrête le timer et persiste les stats finales', () => {
vi.useFakeTimers();
const now = Date.now();
vi.setSystemTime(now);
const state = makeState();
const enc = state.enclos[0]!;
enc.activeGauges = ['foudroyeur'];
enc.gaugeLevels.foudroyeur = 80000;
enc.dragodindes[0]!.stats.endurance = 100;
enc.timer = {
running: true,
startTime: now - 7200_000,
pausedAt: null,
pausedMs: 0,
snapGauges: { foudroyeur: 80000 },
snapStats: { 1: { endurance: 100 } },
gaugeRecharges: {},
};
enc.alerted = {};
const repo = makeRepo();
const events = new EventBus();
const handler = createCompleteTimerHandler(state, repo, events);
handler({ type: 'complete-timer', enclosId: 1 });
expect(enc.timer.running).toBe(false);
expect(enc.timer.pausedAt).toBe(now);
expect(enc.alerted['__done__']).toBe(true);
// endurance doit avoir augmenté par rapport à la valeur initiale
expect(enc.dragodindes[0]!.stats.endurance).toBeGreaterThan(100);
expect(repo.save).toHaveBeenCalled();
});
it('émet l\'événement timer-completed', () => {
vi.useFakeTimers();
vi.setSystemTime(Date.now());
const state = makeRunningTimerState();
const repo = makeRepo();
const events = new EventBus();
const eventHandler = vi.fn();
events.on('timer-completed', eventHandler);
createCompleteTimerHandler(state, repo, events)({ type: 'complete-timer', enclosId: 1 });
expect(eventHandler).toHaveBeenCalledWith(expect.objectContaining({ type: 'timer-completed' }));
});
it('ignore si l\'enclos n\'existe pas', () => {
const state = makeState();
const repo = makeRepo();
const events = new EventBus();
createCompleteTimerHandler(state, repo, events)({ type: 'complete-timer', enclosId: 999 });
expect(repo.save).not.toHaveBeenCalled();
});
it('ignore si le timer n\'est pas en cours', () => {
const state = makeState();
const repo = makeRepo();
const events = new EventBus();
createCompleteTimerHandler(state, repo, events)({ type: 'complete-timer', enclosId: 1 });
expect(repo.save).not.toHaveBeenCalled();
});
it('ignore si déjà complété (__done__)', () => {
const state = makeRunningTimerState();
state.enclos[0]!.alerted['__done__'] = true;
const repo = makeRepo();
const events = new EventBus();
createCompleteTimerHandler(state, repo, events)({ type: 'complete-timer', enclosId: 1 });
expect(repo.save).not.toHaveBeenCalled();
});
});
describe('DeleteWorkflow', () => {
it('supprime un workflow par id', () => {
const state = makeState();
state.workflows = [{ id: 42, name: 'wf1', target: 'Dorée', qty: 1, createdAt: 0, materials: [], steps: [] }] as WorkflowItem[];
const repo = makeRepo();
createDeleteWorkflowHandler(state, repo)({ type: 'delete-workflow', workflowId: 42 });
expect(state.workflows).toHaveLength(0);
expect(repo.save).toHaveBeenCalled();
});
it('ne fait rien si le workflow n\'existe pas', () => {
const state = makeState();
state.workflows = [{ id: 42, name: 'wf1', target: 'Dorée', qty: 1, createdAt: 0, materials: [], steps: [] }] as WorkflowItem[];
const repo = makeRepo();
createDeleteWorkflowHandler(state, repo)({ type: 'delete-workflow', workflowId: 999 });
expect(state.workflows).toHaveLength(1);
expect(repo.save).toHaveBeenCalled();
});
});
describe('RenameDragodinde', () => {
it('renomme une dragodinde', () => {
const state = makeState();
const repo = makeRepo();
createRenameDragodindeHandler(state, repo)({ type: 'rename-dragodinde', enclosId: 1, ddId: 1, name: 'Flamme' });
expect(state.enclos[0]!.dragodindes[0]!.name).toBe('Flamme');
expect(repo.save).toHaveBeenCalled();
});
it('trim le nom', () => {
const state = makeState();
const repo = makeRepo();
createRenameDragodindeHandler(state, repo)({ type: 'rename-dragodinde', enclosId: 1, ddId: 1, name: ' Flamme ' });
expect(state.enclos[0]!.dragodindes[0]!.name).toBe('Flamme');
});
it('ignore si le nom est vide ou whitespace', () => {
const state = makeState();
const repo = makeRepo();
createRenameDragodindeHandler(state, repo)({ type: 'rename-dragodinde', enclosId: 1, ddId: 1, name: ' ' });
expect(state.enclos[0]!.dragodindes[0]!.name).toBe('Dragodinde 1');
expect(repo.save).not.toHaveBeenCalled();
});
it('ignore si l\'enclos n\'existe pas', () => {
const state = makeState();
const repo = makeRepo();
createRenameDragodindeHandler(state, repo)({ type: 'rename-dragodinde', enclosId: 999, ddId: 1, name: 'X' });
expect(repo.save).not.toHaveBeenCalled();
});
it('ignore si la DD n\'existe pas', () => {
const state = makeState();
const repo = makeRepo();
createRenameDragodindeHandler(state, repo)({ type: 'rename-dragodinde', enclosId: 1, ddId: 999, name: 'X' });
expect(repo.save).not.toHaveBeenCalled();
});
});
describe('UpdateDdStat', () => {
it('met à jour une stat de la DD', () => {
const state = makeState();
const repo = makeRepo();
createUpdateDdStatHandler(state, repo)({ type: 'update-dd-stat', enclosId: 1, ddId: 1, stat: 'endurance', value: 5000 });
expect(state.enclos[0]!.dragodindes[0]!.stats.endurance).toBe(5000);
expect(repo.save).toHaveBeenCalled();
});
it('ignore si l\'enclos n\'existe pas', () => {
const state = makeState();
const repo = makeRepo();
createUpdateDdStatHandler(state, repo)({ type: 'update-dd-stat', enclosId: 999, ddId: 1, stat: 'endurance', value: 5000 });
expect(repo.save).not.toHaveBeenCalled();
});
it('ignore si la DD n\'existe pas', () => {
const state = makeState();
const repo = makeRepo();
createUpdateDdStatHandler(state, repo)({ type: 'update-dd-stat', enclosId: 1, ddId: 999, stat: 'endurance', value: 5000 });
expect(repo.save).not.toHaveBeenCalled();
});
});
describe('UpdateDdSerenTarget', () => {
it('définit une cible de sérénité', () => {
const state = makeState();
const repo = makeRepo();
createUpdateDdSerenTargetHandler(state, repo)({ type: 'update-dd-seren-target', enclosId: 1, ddId: 1, target: -2000 });
expect(state.enclos[0]!.dragodindes[0]!.sereniteTarget).toBe(-2000);
expect(repo.save).toHaveBeenCalled();
});
it('accepte null pour retirer la cible', () => {
const state = makeState();
state.enclos[0]!.dragodindes[0]!.sereniteTarget = -2000;
const repo = makeRepo();
createUpdateDdSerenTargetHandler(state, repo)({ type: 'update-dd-seren-target', enclosId: 1, ddId: 1, target: null });
expect(state.enclos[0]!.dragodindes[0]!.sereniteTarget).toBeNull();
});
it('ignore si l\'enclos n\'existe pas', () => {
const state = makeState();
const repo = makeRepo();
createUpdateDdSerenTargetHandler(state, repo)({ type: 'update-dd-seren-target', enclosId: 999, ddId: 1, target: -2000 });
expect(repo.save).not.toHaveBeenCalled();
});
it('ignore si la DD n\'existe pas', () => {
const state = makeState();
const repo = makeRepo();
createUpdateDdSerenTargetHandler(state, repo)({ type: 'update-dd-seren-target', enclosId: 1, ddId: 999, target: -2000 });
expect(repo.save).not.toHaveBeenCalled();
});
});
describe('UpdateDdLevelTarget', () => {
it('définit une cible de niveau', () => {
const state = makeState();
const repo = makeRepo();
createUpdateDdLevelTargetHandler(state, repo)({ type: 'update-dd-level-target', enclosId: 1, ddId: 1, target: 100 });
expect(state.enclos[0]!.dragodindes[0]!.levelTarget).toBe(100);
expect(repo.save).toHaveBeenCalled();
});
it('accepte null pour retirer la cible', () => {
const state = makeState();
state.enclos[0]!.dragodindes[0]!.levelTarget = 100;
const repo = makeRepo();
createUpdateDdLevelTargetHandler(state, repo)({ type: 'update-dd-level-target', enclosId: 1, ddId: 1, target: null });
expect(state.enclos[0]!.dragodindes[0]!.levelTarget).toBeNull();
});
it('ignore si l\'enclos n\'existe pas', () => {
const state = makeState();
const repo = makeRepo();
createUpdateDdLevelTargetHandler(state, repo)({ type: 'update-dd-level-target', enclosId: 999, ddId: 1, target: 100 });
expect(repo.save).not.toHaveBeenCalled();
});
});
describe('ReorderDragodinde', () => {
it('réordonne les DDs dans l\'enclos', () => {
const state = makeState();
// Ajouter une 2e DD
state.enclos[0] = addDragodinde(state.enclos[0]!);
const repo = makeRepo();
const dd1Id = state.enclos[0]!.dragodindes[0]!.id;
const dd2Id = state.enclos[0]!.dragodindes[1]!.id;
createReorderDragodindeHandler(state, repo)({ type: 'reorder-dragodinde', enclosId: 1, fromDdId: dd1Id, toDdId: dd2Id });
expect(state.enclos[0]!.dragodindes[0]!.id).toBe(dd2Id);
expect(state.enclos[0]!.dragodindes[1]!.id).toBe(dd1Id);
expect(repo.save).toHaveBeenCalled();
});
it('ignore si l\'enclos n\'existe pas', () => {
const state = makeState();
const repo = makeRepo();
createReorderDragodindeHandler(state, repo)({ type: 'reorder-dragodinde', enclosId: 999, fromDdId: 1, toDdId: 2 });
expect(repo.save).not.toHaveBeenCalled();
});
it('ignore si un des ddId n\'existe pas', () => {
const state = makeState();
const repo = makeRepo();
createReorderDragodindeHandler(state, repo)({ type: 'reorder-dragodinde', enclosId: 1, fromDdId: 1, toDdId: 999 });
expect(repo.save).not.toHaveBeenCalled();
});
});
describe('ImportWorkflows', () => {
it('importe des workflows dans la liste existante', () => {
const state = makeState();
const repo = makeRepo();
const wf: WorkflowItem = { id: 10, name: 'Import1', target: 'Dorée', qty: 2, createdAt: 0, materials: [], steps: [] };
createImportWorkflowsHandler(state, repo)({ type: 'import-workflows', workflows: [wf] });
expect(state.workflows).toHaveLength(1);
expect((state.workflows[0] as WorkflowItem).target).toBe('Dorée');
expect(repo.save).toHaveBeenCalled();
});
it('réattribue un id si doublon', () => {
const state = makeState();
const existingWf: WorkflowItem = { id: 10, name: 'Existant', target: 'Rousse', qty: 1, createdAt: 0, materials: [], steps: [] };
state.workflows = [existingWf] as any;
const repo = makeRepo();
const importWf: WorkflowItem = { id: 10, name: 'Import1', target: 'Dorée', qty: 2, createdAt: 0, materials: [], steps: [] };
createImportWorkflowsHandler(state, repo)({ type: 'import-workflows', workflows: [importWf] });
expect(state.workflows).toHaveLength(2);
// L'id du workflow importé doit avoir changé (plus 10)
expect((state.workflows[1] as WorkflowItem).id).not.toBe(10);
expect((state.workflows[1] as WorkflowItem).target).toBe('Dorée');
});
it('importe plusieurs workflows sans conflit d\'id', () => {
const state = makeState();
const repo = makeRepo();
const wf1: WorkflowItem = { id: 1, name: 'A', target: 'A', qty: 1, createdAt: 0, materials: [], steps: [] };
const wf2: WorkflowItem = { id: 2, name: 'B', target: 'B', qty: 1, createdAt: 0, materials: [], steps: [] };
createImportWorkflowsHandler(state, repo)({ type: 'import-workflows', workflows: [wf1, wf2] });
expect(state.workflows).toHaveLength(2);
});
});
describe('ReorderEnclos', () => {
it('réordonne les enclos', () => {
const state = makeState();
// Ajouter un 2e enclos
const enc2 = createEnclos(2, 'Enclos 2');
state.enclos.push(enc2);
const repo = makeRepo();
createReorderEnclosHandler(state, repo)({ type: 'reorder-enclos', fromIndex: 0, toIndex: 1 });
expect(state.enclos[0]!.id).toBe(2);
expect(state.enclos[1]!.id).toBe(1);
expect(repo.save).toHaveBeenCalled();
});
it('ignore si fromIndex est négatif', () => {
const state = makeState();
const repo = makeRepo();
createReorderEnclosHandler(state, repo)({ type: 'reorder-enclos', fromIndex: -1, toIndex: 0 });
expect(repo.save).not.toHaveBeenCalled();
});
it('ignore si toIndex est négatif', () => {
const state = makeState();
const repo = makeRepo();
createReorderEnclosHandler(state, repo)({ type: 'reorder-enclos', fromIndex: 0, toIndex: -1 });
expect(repo.save).not.toHaveBeenCalled();
});
it('ignore si fromIndex dépasse la taille du tableau', () => {
const state = makeState();
const repo = makeRepo();
createReorderEnclosHandler(state, repo)({ type: 'reorder-enclos', fromIndex: 5, toIndex: 0 });
expect(repo.save).not.toHaveBeenCalled();
});
it('ignore si toIndex dépasse la taille du tableau', () => {
const state = makeState();
const repo = makeRepo();
createReorderEnclosHandler(state, repo)({ type: 'reorder-enclos', fromIndex: 0, toIndex: 5 });
expect(repo.save).not.toHaveBeenCalled();
});
});
describe('UpdateWorkflow', () => {
function makeWorkflowState(): AppState {
const state = makeState();
const wf: WorkflowItem = {
id: 1, name: 'Workflow 1', target: 'Dorée', qty: 2, createdAt: 0,
materials: [{ name: 'Rousse', needed: 4, done: 0 }, { name: 'Dorée', needed: 4, done: 0 }],
steps: [{
gen: 2,
crossings: [{ race: 'Dorée et Rousse', needed: 2, parentA: 'Rousse', parentB: 'Dorée', couples: 2, repro: 0, done: 0 }],
}],
};
state.workflows = [wf] as any;
return state;
}
it('met à jour le done d\'un matériau', () => {
const state = makeWorkflowState();
const repo = makeRepo();
createUpdateWorkflowHandler(state, repo)({ type: 'update-workflow', workflowId: 1, materialIdx: 0, done: 3 });
expect((state.workflows[0] as WorkflowItem).materials[0]!.done).toBe(3);
expect(repo.save).toHaveBeenCalled();
});
it('met à jour le done d\'un crossing', () => {
const state = makeWorkflowState();
const repo = makeRepo();
createUpdateWorkflowHandler(state, repo)({ type: 'update-workflow', workflowId: 1, stepIdx: 0, crossingIdx: 0, done: 1 });
expect((state.workflows[0] as WorkflowItem).steps[0]!.crossings[0]!.done).toBe(1);
expect(repo.save).toHaveBeenCalled();
});
it('clamp done à 0 minimum pour matériau', () => {
const state = makeWorkflowState();
const repo = makeRepo();
createUpdateWorkflowHandler(state, repo)({ type: 'update-workflow', workflowId: 1, materialIdx: 0, done: -5 });
expect((state.workflows[0] as WorkflowItem).materials[0]!.done).toBe(0);
});
it('clamp done à 0 minimum pour crossing', () => {
const state = makeWorkflowState();
const repo = makeRepo();
createUpdateWorkflowHandler(state, repo)({ type: 'update-workflow', workflowId: 1, stepIdx: 0, crossingIdx: 0, done: -3 });
expect((state.workflows[0] as WorkflowItem).steps[0]!.crossings[0]!.done).toBe(0);
});
it('ignore si le workflow n\'existe pas', () => {
const state = makeWorkflowState();
const repo = makeRepo();
createUpdateWorkflowHandler(state, repo)({ type: 'update-workflow', workflowId: 999, materialIdx: 0, done: 3 });
// L'état ne change pas mais save est quand même appelé (pas de guard sur save)
expect((state.workflows[0] as WorkflowItem).materials[0]!.done).toBe(0);
});
it('ignore si materialIdx hors limites', () => {
const state = makeWorkflowState();
const repo = makeRepo();
createUpdateWorkflowHandler(state, repo)({ type: 'update-workflow', workflowId: 1, materialIdx: 99, done: 3 });
expect((state.workflows[0] as WorkflowItem).materials[0]!.done).toBe(0);
});
it('ignore si stepIdx ou crossingIdx hors limites', () => {
const state = makeWorkflowState();
const repo = makeRepo();
createUpdateWorkflowHandler(state, repo)({ type: 'update-workflow', workflowId: 1, stepIdx: 99, crossingIdx: 0, done: 1 });
expect((state.workflows[0] as WorkflowItem).steps[0]!.crossings[0]!.done).toBe(0);
});
});
describe('ClearEnclos', () => {
it('vide les DDs, jauges et timer de l\'enclos', () => {
const state = makeState();
const repo = makeRepo();
createClearEnclosHandler(state, repo)({ type: 'clear-enclos', enclosId: 1 });
const enc = state.enclos[0]!;
expect(enc.dragodindes).toHaveLength(0);
expect(enc.nextDdId).toBe(1);
expect(enc.activeGauges).toHaveLength(0);
expect(enc.gaugeLevels.baffeur).toBe(0);
expect(enc.timer.running).toBe(false);
expect(enc.timer.snapGauges).toEqual({});
expect(enc.alerted).toEqual({});
expect(repo.save).toHaveBeenCalled();
});
it('ignore si l\'enclos n\'existe pas', () => {
const state = makeState();
const repo = makeRepo();
createClearEnclosHandler(state, repo)({ type: 'clear-enclos', enclosId: 999 });
expect(repo.save).not.toHaveBeenCalled();
});
});
describe('RenameEnclos', () => {
it('renomme un enclos', () => {
const state = makeState();
const repo = makeRepo();
createRenameEnclosHandler(state, repo)({ type: 'rename-enclos', enclosId: 1, name: 'Mon enclos' });
expect(state.enclos[0]!.name).toBe('Mon enclos');
expect(repo.save).toHaveBeenCalled();
});
it('trim le nom', () => {
const state = makeState();
const repo = makeRepo();
createRenameEnclosHandler(state, repo)({ type: 'rename-enclos', enclosId: 1, name: ' Paddock ' });
expect(state.enclos[0]!.name).toBe('Paddock');
});
it('ignore si le nom est vide ou whitespace', () => {
const state = makeState();
const repo = makeRepo();
createRenameEnclosHandler(state, repo)({ type: 'rename-enclos', enclosId: 1, name: ' ' });
expect(state.enclos[0]!.name).toBe('Enclos 1');
expect(repo.save).not.toHaveBeenCalled();
});
it('ignore si l\'enclos n\'existe pas', () => {
const state = makeState();
const repo = makeRepo();
createRenameEnclosHandler(state, repo)({ type: 'rename-enclos', enclosId: 999, name: 'Test' });
expect(repo.save).not.toHaveBeenCalled();
});
});
describe('NouvelleFournee', () => {
it('réinitialise l\'enclos avec une DD fraîche et jauges à 0', () => {
const state = makeState();
const enc = state.enclos[0]!;
// Simuler un état "usé"
enc.gaugeLevels.baffeur = 80000;
enc.alerted['foudroyeur'] = true;
enc.timer = {
running: true, startTime: Date.now() - 1000, pausedAt: null, pausedMs: 0,
snapGauges: { baffeur: 80000 }, snapStats: {}, gaugeRecharges: {},
};
const repo = makeRepo();
createNouvelleFourneeHandler(state, repo)({ type: 'nouvelle-fournee', enclosId: 1 });
expect(enc.timer.running).toBe(false);
expect(enc.timer.startTime).toBeNull();
expect(enc.timer.gaugeRecharges).toEqual({});
expect(enc.alerted).toEqual({});
expect(enc.gaugeLevels.baffeur).toBe(0);
expect(enc.gaugeLevels.foudroyeur).toBe(0);
expect(enc.dragodindes).toHaveLength(1);
expect(enc.dragodindes[0]!.id).toBe(1);
expect(enc.dragodindes[0]!.stats.endurance).toBe(0);
expect(enc.nextDdId).toBe(2);
expect(repo.save).toHaveBeenCalled();
});
it('ignore si l\'enclos n\'existe pas', () => {
const state = makeState();
const repo = makeRepo();
createNouvelleFourneeHandler(state, repo)({ type: 'nouvelle-fournee', enclosId: 999 });
expect(repo.save).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,673 @@
import { describe, it, expect } from 'vitest';
import type { AppState } from '@domain/ports/StateRepository';
import { createEnclos, addDragodinde } from '@domain/entities/Enclos';
import { createGetDashboardHandler } from '@application/queries/GetDashboard';
import { createGetEnclosDetailHandler } from '@application/queries/GetEnclosDetail';
import { createGetTimerStateHandler } from '@application/queries/GetTimerState';
import { createGetBreedingOptionsHandler } from '@application/queries/GetBreedingOptions';
import { createGetReapproTreeHandler } from '@application/queries/GetReapproTree';
import { createGetInventaireHandler } from '@application/queries/GetInventaire';
import { createGetSettingsHandler } from '@application/queries/GetSettings';
import { createGetStatisticsHandler, TOTAL_RACES } from '@application/queries/GetStatistics';
import { createGetWorkflowsHandler } from '@application/queries/GetWorkflows';
function makeState(): AppState {
let enc = createEnclos(1);
enc = addDragodinde(enc);
return {
enclos: [enc], activeId: 1, nextEnclosId: 2,
alarmSound: 'arpege', notifsEnabled: true, ntfyTopic: '',
archivedStats: [], inventaire: {}, workflows: [],
accouplements: [
{ parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 5, babiesObtained: 3, date: '2026-01-01' },
],
};
}
describe('GetDashboard', () => {
it('aggregates stats', () => {
const state = makeState();
const handler = createGetDashboardHandler(state);
const r = handler({ type: 'get-dashboard' });
expect(r.totalCouples).toBe(5);
expect(r.totalBabies).toBe(3);
expect(r.enclosSummaries).toHaveLength(1);
expect(r.successRate).toBe(60);
expect(r.raceBreakdown['Dorée et Rousse']).toBe(3);
});
it('handles empty state', () => {
const state = makeState();
state.accouplements = [];
const r = createGetDashboardHandler(state)({ type: 'get-dashboard' });
expect(r.totalCouples).toBe(0);
expect(r.successRate).toBe(0);
});
});
describe('GetEnclosDetail', () => {
it('returns enclos by id', () => {
const state = makeState();
const handler = createGetEnclosDetailHandler(state);
const r = handler({ type: 'get-enclos-detail', enclosId: 1 });
expect(r).not.toBeNull();
expect(r!.id).toBe(1);
});
it('returns null for unknown id', () => {
const state = makeState();
const r = createGetEnclosDetailHandler(state)({ type: 'get-enclos-detail', enclosId: 999 });
expect(r).toBeNull();
});
});
describe('GetTimerState', () => {
it('returns timer state', () => {
const state = makeState();
const r = createGetTimerStateHandler(state)({ type: 'get-timer-state', enclosId: 1 });
expect(r).not.toBeNull();
expect(r!.running).toBe(false);
});
it('returns null for unknown enclos', () => {
const state = makeState();
const r = createGetTimerStateHandler(state)({ type: 'get-timer-state', enclosId: 999 });
expect(r).toBeNull();
});
});
describe('GetBreedingOptions', () => {
it('returns partners for Rousse', () => {
const handler = createGetBreedingOptionsHandler();
const r = handler({ type: 'get-breeding-options', race: 'Rousse' });
expect(r.partners.length).toBeGreaterThan(0);
expect(r.partners.some(p => p.partner === 'Dorée')).toBe(true);
});
});
describe('GetReapproTree', () => {
it('computes breeding plan', () => {
const handler = createGetReapproTreeHandler();
const r = handler({ type: 'get-reappro-tree', target: 'Dorée et Rousse', qty: 4, repro: {}, inverted: {} });
expect(r.steps).toHaveLength(1);
expect(r.totalGen1).toBe(8);
});
});
describe('GetInventaire', () => {
it('retourne le stock brut de l\'inventaire', () => {
const state = makeState();
state.inventaire = { Rousse: { m: 1, f: 0 }, Dorée: { m: 0, f: 1 } };
const handler = createGetInventaireHandler(state);
const r = handler({ type: 'get-inventaire' });
expect(r).toEqual({ Rousse: { m: 1, f: 0 }, Dorée: { m: 0, f: 1 } });
});
it('inventaire vide retourne objet vide', () => {
const state = makeState();
const r = createGetInventaireHandler(state)({ type: 'get-inventaire' });
expect(r).toEqual({});
});
it('reflète les changements de state.inventaire en temps réel', () => {
const state = makeState();
const handler = createGetInventaireHandler(state);
expect(handler({ type: 'get-inventaire' })).toEqual({});
state.inventaire = { Amande: { m: 3, f: 2 } };
expect(handler({ type: 'get-inventaire' })).toEqual({ Amande: { m: 3, f: 2 } });
});
});
// ── Helpers pour les dates relatives ──────────────────────────────
function daysAgo(n: number): string {
const d = new Date();
d.setDate(d.getDate() - n);
return d.toISOString().slice(0, 10);
}
function dayOfWeekName(dateStr: string): string {
const names = ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'];
const d = new Date(dateStr + 'T12:00:00');
return names[d.getDay()];
}
// ══════════════════════════════════════════════════════════════════
// GetDashboard — archivedStats path (lignes 44-51)
// ══════════════════════════════════════════════════════════════════
describe('GetDashboard — archivedStats', () => {
it('agrège accouplements + archivedStats', () => {
const state = makeState();
state.archivedStats = [
{ baby: 'Ebène', couples: 10, babiesObtained: 4 },
{ baby: 'Dorée et Rousse', couples: 3, babiesObtained: 1 },
];
const r = createGetDashboardHandler(state)({ type: 'get-dashboard' });
// accouplements: 5 couples, 3 babies + archived: 13 couples, 5 babies
expect(r.totalCouples).toBe(18);
expect(r.totalBabies).toBe(8);
expect(r.raceBreakdown['Ebène']).toBe(4);
expect(r.raceBreakdown['Dorée et Rousse']).toBe(4); // 3 + 1
expect(r.successRate).toBe(44); // Math.round(8/18*100)
});
it('ignore les entrées archivedStats sans baby', () => {
const state = makeState();
state.archivedStats = [
{ couples: 10, babiesObtained: 4 }, // pas de baby
];
const r = createGetDashboardHandler(state)({ type: 'get-dashboard' });
expect(r.totalCouples).toBe(5);
expect(r.totalBabies).toBe(3);
});
it('gère les champs manquants dans archivedStats', () => {
const state = makeState();
state.accouplements = [];
state.archivedStats = [
{ baby: 'Indigo' }, // couples et babiesObtained absents → default 0
];
const r = createGetDashboardHandler(state)({ type: 'get-dashboard' });
expect(r.totalCouples).toBe(0);
expect(r.totalBabies).toBe(0);
expect(r.raceBreakdown['Indigo']).toBe(0);
expect(r.successRate).toBe(0);
});
});
// ══════════════════════════════════════════════════════════════════
// GetSettings
// ══════════════════════════════════════════════════════════════════
describe('GetSettings', () => {
it('retourne les paramètres courants', () => {
const state = makeState();
const r = createGetSettingsHandler(state)({ type: 'get-settings' });
expect(r.alarmSound).toBe('arpege');
expect(r.notifsEnabled).toBe(true);
expect(r.ntfyTopic).toBe('');
});
it('reflète les changements de paramètres en temps réel', () => {
const state = makeState();
const handler = createGetSettingsHandler(state);
state.alarmSound = 'gong';
state.notifsEnabled = false;
state.ntfyTopic = 'mon-topic';
const r = handler({ type: 'get-settings' });
expect(r.alarmSound).toBe('gong');
expect(r.notifsEnabled).toBe(false);
expect(r.ntfyTopic).toBe('mon-topic');
});
});
// ══════════════════════════════════════════════════════════════════
// GetWorkflows
// ══════════════════════════════════════════════════════════════════
describe('GetWorkflows', () => {
it('retourne la liste des workflows', () => {
const state = makeState();
const wf = {
id: 1, name: 'Test WF', target: 'Ebène', qty: 2, createdAt: Date.now(),
materials: [{ name: 'Rousse', needed: 4, done: 2 }],
steps: [{ gen: 2, crossings: [{ race: 'Dorée et Rousse', needed: 2, parentA: 'Dorée', parentB: 'Rousse', couples: 2, repro: 1, done: 1 }] }],
};
state.workflows = [wf];
const r = createGetWorkflowsHandler(state)({ type: 'get-workflows' });
expect(r).toHaveLength(1);
expect(r[0]).toBe(wf);
});
it('retourne un tableau vide quand aucun workflow', () => {
const state = makeState();
const r = createGetWorkflowsHandler(state)({ type: 'get-workflows' });
expect(r).toEqual([]);
});
it('reflète les changements en temps réel', () => {
const state = makeState();
const handler = createGetWorkflowsHandler(state);
expect(handler({ type: 'get-workflows' })).toEqual([]);
state.workflows = [{ id: 42, name: 'WF2', target: 'Indigo', qty: 1, createdAt: 0, materials: [], steps: [] }];
expect(handler({ type: 'get-workflows' })).toHaveLength(1);
});
});
// ══════════════════════════════════════════════════════════════════
// GetStatistics
// ══════════════════════════════════════════════════════════════════
describe('GetStatistics', () => {
// ── Historique vide ────────────────────────────────────────────
it('historique vide retourne des KPI à zéro', () => {
const state = makeState();
state.accouplements = [];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
expect(r.totalBabies.value).toBe(0);
expect(r.totalCouples.value).toBe(0);
expect(r.successRate.value).toBe(0);
expect(r.racesCount.value).toBe(0);
expect(r.raceShares).toEqual([]);
expect(r.raceSuccessRates).toEqual([]);
expect(r.bestCouples).toEqual([]);
expect(r.genBreakdown).toEqual([]);
expect(r.weekdayActivity).toHaveLength(7);
expect(r.weekdayActivity.every(w => w.count === 0)).toBe(true);
});
// ── days=0 → tout l'historique, delta=null ──────────────────
it('days=0 retourne tout l\'historique sans delta', () => {
const state = makeState();
state.accouplements = [
{ parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 10, babiesObtained: 6, date: '2025-06-15' },
{ parentA: 'Amande', parentB: 'Dorée', baby: 'Amande et Dorée', gen: 2, couples: 8, babiesObtained: 3, date: '2025-01-10' },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
expect(r.days).toBe(0);
expect(r.totalBabies).toEqual({ value: 9, delta: null });
expect(r.totalCouples).toEqual({ value: 18, delta: null });
expect(r.successRate).toEqual({ value: 50, delta: null });
expect(r.racesCount).toEqual({ value: 2, delta: null });
});
// ── Exclusion Gen 1 ────────────────────────────────────────────
it('exclut les entrées Gen 1 (Rousse, Dorée, Amande)', () => {
const state = makeState();
state.accouplements = [
{ parentA: 'X', parentB: 'Y', baby: 'Rousse', gen: 1, couples: 100, babiesObtained: 50, date: daysAgo(1) },
{ parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 4, babiesObtained: 2, date: daysAgo(1) },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
expect(r.totalCouples.value).toBe(4);
expect(r.totalBabies.value).toBe(2);
});
it('exclut les entrées dont le baby est Gen 1 même si gen != 1', () => {
const state = makeState();
state.accouplements = [
{ parentA: 'A', parentB: 'B', baby: 'Amande', gen: 0, couples: 20, babiesObtained: 10, date: daysAgo(1) },
{ parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 5, babiesObtained: 3, date: daysAgo(1) },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
expect(r.totalCouples.value).toBe(5);
expect(r.totalBabies.value).toBe(3);
});
// ── Filtrage par période avec delta ─────────────────────────
it('days=7 filtre la période courante et calcule le delta', () => {
const state = makeState();
state.accouplements = [
// Période courante (7 derniers jours)
{ parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 10, babiesObtained: 6, date: daysAgo(2) },
// Période précédente (7 à 14 jours)
{ parentA: 'Amande', parentB: 'Dorée', baby: 'Amande et Dorée', gen: 2, couples: 8, babiesObtained: 2, date: daysAgo(10) },
// Trop ancien (hors des deux fenêtres)
{ parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 100, babiesObtained: 50, date: '2020-01-01' },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 7 });
expect(r.days).toBe(7);
expect(r.totalBabies.value).toBe(6);
expect(r.totalBabies.delta).toBe(6 - 2); // cur - prev
expect(r.totalCouples.value).toBe(10);
expect(r.totalCouples.delta).toBe(10 - 8);
});
// ── Default days=30 ─────────────────────────────────────────
it('days par défaut est 30', () => {
const state = makeState();
state.accouplements = [];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics' });
expect(r.days).toBe(30);
});
// ── archivedStats agrégation ──────────────────────────────────
it('inclut les archivedStats dans les statistiques', () => {
const state = makeState();
state.accouplements = [];
state.archivedStats = [
{ parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 7, babiesObtained: 4, date: daysAgo(1) },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
expect(r.totalCouples.value).toBe(7);
expect(r.totalBabies.value).toBe(4);
});
it('exclut les archivedStats Gen 1', () => {
const state = makeState();
state.accouplements = [];
state.archivedStats = [
{ baby: 'Rousse', gen: 1, couples: 50, babiesObtained: 25, date: daysAgo(1) },
{ baby: 'Dorée et Rousse', gen: 2, couples: 3, babiesObtained: 1, date: daysAgo(1) },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
expect(r.totalCouples.value).toBe(3);
expect(r.totalBabies.value).toBe(1);
});
it('archivedStats avec champs manquants utilise des défauts', () => {
const state = makeState();
state.accouplements = [];
state.archivedStats = [
{ baby: 'Ebène' }, // gen, couples, babiesObtained, date, parentA, parentB absents
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
// Ebène est Gen 3, ne sera pas exclu
expect(r.totalCouples.value).toBe(0);
expect(r.totalBabies.value).toBe(0);
});
it('ignore les archivedStats sans baby', () => {
const state = makeState();
state.accouplements = [];
state.archivedStats = [
{ couples: 10, babiesObtained: 5 },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
expect(r.totalCouples.value).toBe(0);
expect(r.totalBabies.value).toBe(0);
});
// ── Répartition des races (raceShares) ─────────────────────
it('calcule la répartition des races triée par count décroissant', () => {
const state = makeState();
state.accouplements = [
{ parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 10, babiesObtained: 7, date: daysAgo(1) },
{ parentA: 'Amande', parentB: 'Dorée', baby: 'Amande et Dorée', gen: 2, couples: 5, babiesObtained: 3, date: daysAgo(1) },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
expect(r.raceShares).toHaveLength(2);
expect(r.raceShares[0].race).toBe('Dorée et Rousse');
expect(r.raceShares[0].count).toBe(7);
expect(r.raceShares[0].pct).toBe(70); // 7/10*100
expect(r.raceShares[1].race).toBe('Amande et Dorée');
expect(r.raceShares[1].count).toBe(3);
expect(r.raceShares[1].pct).toBe(30);
});
// ── Taux de réussite par race ──────────────────────────────
it('calcule le taux de réussite par race', () => {
const state = makeState();
state.accouplements = [
{ parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 10, babiesObtained: 8, date: daysAgo(1) },
{ parentA: 'Amande', parentB: 'Dorée', baby: 'Amande et Dorée', gen: 2, couples: 10, babiesObtained: 3, date: daysAgo(1) },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
expect(r.raceSuccessRates).toHaveLength(2);
// Trié par rate décroissant
expect(r.raceSuccessRates[0].race).toBe('Dorée et Rousse');
expect(r.raceSuccessRates[0].rate).toBe(80);
expect(r.raceSuccessRates[1].race).toBe('Amande et Dorée');
expect(r.raceSuccessRates[1].rate).toBe(30);
});
// ── Meilleurs couples ──────────────────────────────────────
it('calcule les meilleurs couples et normalise l\'ordre A|B', () => {
const state = makeState();
state.accouplements = [
{ parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 5, babiesObtained: 4, date: daysAgo(1) },
{ parentA: 'Dorée', parentB: 'Rousse', baby: 'Dorée et Rousse', gen: 2, couples: 5, babiesObtained: 3, date: daysAgo(2) },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
// Les deux entrées doivent être fusionnées (clé normalisée)
expect(r.bestCouples).toHaveLength(1);
expect(r.bestCouples[0].couples).toBe(10);
expect(r.bestCouples[0].babies).toBe(7);
expect(r.bestCouples[0].rate).toBe(70);
});
it('ignore les couples sans parentA ou parentB', () => {
const state = makeState();
state.accouplements = [
{ parentA: '', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 5, babiesObtained: 3, date: daysAgo(1) },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
expect(r.bestCouples).toEqual([]);
});
it('limite les meilleurs couples à 10', () => {
const state = makeState();
state.accouplements = [];
// Créer 12 couples distincts
const races = [
'Dorée et Rousse', 'Amande et Rousse', 'Amande et Dorée',
'Ebène', 'Indigo',
'Indigo et Rousse', 'Ebène et Rousse', 'Amande et Indigo',
'Amande et Ebène', 'Dorée et Indigo', 'Dorée et Ebène',
'Ebène et Indigo',
];
for (let i = 0; i < 12; i++) {
state.accouplements.push({
parentA: `ParentA${i}`, parentB: `ParentB${i}`, baby: races[i],
gen: i < 3 ? 2 : i < 5 ? 3 : 4,
couples: 5, babiesObtained: 3, date: daysAgo(1),
});
}
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
expect(r.bestCouples).toHaveLength(10);
});
// ── Répartition par génération ──────────────────────────────
it('calcule la répartition par génération', () => {
const state = makeState();
state.accouplements = [
{ parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 10, babiesObtained: 5, date: daysAgo(1) },
{ parentA: 'Amande', parentB: 'Dorée', baby: 'Amande et Dorée', gen: 2, couples: 8, babiesObtained: 3, date: daysAgo(1) },
{ parentA: 'Amande et Dorée', parentB: 'Dorée et Rousse', baby: 'Ebène', gen: 3, couples: 6, babiesObtained: 2, date: daysAgo(1) },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
expect(r.genBreakdown).toHaveLength(2);
const gen2 = r.genBreakdown.find(g => g.gen === 2)!;
const gen3 = r.genBreakdown.find(g => g.gen === 3)!;
expect(gen2.babies).toBe(8);
expect(gen2.couples).toBe(18);
expect(gen2.races).toBe(2);
expect(gen3.babies).toBe(2);
expect(gen3.couples).toBe(6);
expect(gen3.races).toBe(1);
});
it('genBreakdown trié par gen croissant', () => {
const state = makeState();
state.accouplements = [
{ parentA: 'A', parentB: 'B', baby: 'Ebène', gen: 3, couples: 5, babiesObtained: 2, date: daysAgo(1) },
{ parentA: 'C', parentB: 'D', baby: 'Dorée et Rousse', gen: 2, couples: 5, babiesObtained: 3, date: daysAgo(1) },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
expect(r.genBreakdown[0].gen).toBe(2);
expect(r.genBreakdown[1].gen).toBe(3);
});
// ── Races manquantes ────────────────────────────────────────
it('calcule les races manquantes (exclut Gen 1 et races obtenues)', () => {
const state = makeState();
state.accouplements = [
{ parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 5, babiesObtained: 3, date: daysAgo(1) },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
// Dorée et Rousse obtenue → ne doit pas apparaître
expect(r.missingRaces.find(m => m.name === 'Dorée et Rousse')).toBeUndefined();
// Les Gen 1 ne doivent pas apparaître
expect(r.missingRaces.find(m => m.name === 'Rousse')).toBeUndefined();
expect(r.missingRaces.find(m => m.name === 'Dorée')).toBeUndefined();
expect(r.missingRaces.find(m => m.name === 'Amande')).toBeUndefined();
// Races non obtenues doivent apparaître
expect(r.missingRaces.find(m => m.name === 'Amande et Rousse')).toBeDefined();
expect(r.missingRaces.length).toBe(TOTAL_RACES - 1); // 63 - 1 obtenue
});
it('races manquantes utilise all (pas seulement la période courante)', () => {
const state = makeState();
state.accouplements = [
// Très ancien mais obtenu
{ parentA: 'A', parentB: 'B', baby: 'Ebène', gen: 3, couples: 5, babiesObtained: 1, date: '2020-01-01' },
// Récent
{ parentA: 'C', parentB: 'D', baby: 'Dorée et Rousse', gen: 2, couples: 5, babiesObtained: 2, date: daysAgo(1) },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 7 });
// Ebène obtenue même si hors période courante → exclue des manquantes
expect(r.missingRaces.find(m => m.name === 'Ebène')).toBeUndefined();
expect(r.missingRaces.length).toBe(TOTAL_RACES - 2);
});
it('races manquantes triées par gen croissant puis nom', () => {
const state = makeState();
state.accouplements = [];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
// Vérifier le tri
for (let i = 1; i < r.missingRaces.length; i++) {
const prev = r.missingRaces[i - 1];
const cur = r.missingRaces[i];
if (prev.gen === cur.gen) {
expect(prev.name.localeCompare(cur.name)).toBeLessThanOrEqual(0);
} else {
expect(prev.gen).toBeLessThan(cur.gen);
}
}
});
// ── Naissances par jour (dailyBirths) ──────────────────────
it('génère 30 jours de naissances quand days=0', () => {
const state = makeState();
state.accouplements = [];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
expect(r.dailyBirths).toHaveLength(30);
});
it('génère N jours de naissances quand days=N', () => {
const state = makeState();
state.accouplements = [];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 7 });
expect(r.dailyBirths).toHaveLength(7);
});
it('dailyBirths contient les naissances du jour', () => {
const today = daysAgo(0);
const state = makeState();
state.accouplements = [
{ parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 5, babiesObtained: 3, date: today },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 7 });
const todayEntry = r.dailyBirths.find(d => d.date === today);
expect(todayEntry).toBeDefined();
expect(todayEntry!.count).toBe(3);
});
it('dailyBirths remplit 0 pour les jours sans naissance', () => {
const state = makeState();
state.accouplements = [];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 7 });
expect(r.dailyBirths.every(d => d.count === 0)).toBe(true);
});
it('dailyBirths format label DD/MM', () => {
const state = makeState();
state.accouplements = [];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 7 });
for (const d of r.dailyBirths) {
expect(d.label).toMatch(/^\d{2}\/\d{2}$/);
}
});
// ── Activité par jour de la semaine ─────────────────────────
it('activité par jour de la semaine commence lundi et finit dimanche', () => {
const state = makeState();
state.accouplements = [];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
expect(r.weekdayActivity).toHaveLength(7);
expect(r.weekdayActivity[0].day).toBe('Lundi');
expect(r.weekdayActivity[6].day).toBe('Dimanche');
});
it('activité par jour de la semaine comptabilise les naissances', () => {
const today = daysAgo(0);
const todayName = dayOfWeekName(today);
const state = makeState();
state.accouplements = [
{ parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 5, babiesObtained: 7, date: today },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
const dayEntry = r.weekdayActivity.find(w => w.day === todayName);
expect(dayEntry).toBeDefined();
expect(dayEntry!.count).toBe(7);
});
// ── Entrées sans date valide ────────────────────────────────
it('entrées sans date ne cassent pas le weekdayActivity ni dailyBirths', () => {
const state = makeState();
state.accouplements = [
{ parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 5, babiesObtained: 3, date: '' },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
// Pas de crash, les compteurs weekday sont à 0
expect(r.weekdayActivity).toHaveLength(7);
expect(r.totalBabies.value).toBe(3); // toujours compté dans le total
});
// ── racesCount ne compte que les races avec babiesObtained > 0 ──
it('racesCount ne compte que les races avec au moins un bébé', () => {
const state = makeState();
state.accouplements = [
{ parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 10, babiesObtained: 5, date: daysAgo(1) },
{ parentA: 'Amande', parentB: 'Dorée', baby: 'Amande et Dorée', gen: 2, couples: 8, babiesObtained: 0, date: daysAgo(1) },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
expect(r.racesCount.value).toBe(1); // Seule Dorée et Rousse a des bébés
});
// ── raceSuccessRates avec couples=0 ─────────────────────────
it('raceSuccessRates rate=0 quand couples=0', () => {
const state = makeState();
state.accouplements = [
{ parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 0, babiesObtained: 0, date: daysAgo(1) },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
const dr = r.raceSuccessRates.find(rs => rs.race === 'Dorée et Rousse');
expect(dr).toBeDefined();
expect(dr!.rate).toBe(0);
});
// ── genBreakdown ne compte les races que si babiesObtained > 0 ──
it('genBreakdown.races ne compte que les races avec bébés', () => {
const state = makeState();
state.accouplements = [
{ parentA: 'A', parentB: 'B', baby: 'Dorée et Rousse', gen: 2, couples: 10, babiesObtained: 5, date: daysAgo(1) },
{ parentA: 'C', parentB: 'D', baby: 'Amande et Dorée', gen: 2, couples: 10, babiesObtained: 0, date: daysAgo(1) },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 0 });
const gen2 = r.genBreakdown.find(g => g.gen === 2)!;
expect(gen2.races).toBe(1); // Seule Dorée et Rousse
});
// ── Delta successRate ──────────────────────────────────────
it('delta successRate calcule la différence entre périodes', () => {
const state = makeState();
state.accouplements = [
// Période courante : 10 couples, 8 bébés → 80%
{ parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 10, babiesObtained: 8, date: daysAgo(2) },
// Période précédente : 10 couples, 5 bébés → 50%
{ parentA: 'Amande', parentB: 'Dorée', baby: 'Amande et Dorée', gen: 2, couples: 10, babiesObtained: 5, date: daysAgo(10) },
];
const r = createGetStatisticsHandler(state)({ type: 'get-statistics', days: 7 });
expect(r.successRate.value).toBe(80);
expect(r.successRate.delta).toBe(30); // 80 - 50
});
});