website refactor

This commit is contained in:
2026-01-21 16:52:43 +01:00
parent ac37871bef
commit 2325eef8b5
18 changed files with 835 additions and 47 deletions

View File

@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import type { LeagueRepository } from '../../domain/repositories/LeagueRepository';
import type { RaceRegistrationRepository } from '../../domain/repositories/RaceRegistrationRepository';
import type { RaceRepository } from '../../domain/repositories/RaceRepository';
import type { ResultRepository } from '../../domain/repositories/ResultRepository';
@@ -7,6 +8,9 @@ import { CompleteRaceUseCase, type CompleteRaceInput } from './CompleteRaceUseCa
describe('CompleteRaceUseCase', () => {
let useCase: CompleteRaceUseCase;
let leagueRepository: {
findById: Mock;
};
let raceRepository: {
findById: Mock;
update: Mock;
@@ -24,6 +28,9 @@ describe('CompleteRaceUseCase', () => {
let getDriverRating: Mock;
beforeEach(() => {
leagueRepository = {
findById: vi.fn(),
};
raceRepository = {
findById: vi.fn(),
update: vi.fn(),
@@ -39,11 +46,14 @@ describe('CompleteRaceUseCase', () => {
save: vi.fn(),
};
getDriverRating = vi.fn();
useCase = new CompleteRaceUseCase(raceRepository as unknown as RaceRepository,
useCase = new CompleteRaceUseCase(
leagueRepository as unknown as LeagueRepository,
raceRepository as unknown as RaceRepository,
raceRegistrationRepository as unknown as RaceRegistrationRepository,
resultRepository as unknown as ResultRepository,
standingRepository as unknown as StandingRepository,
getDriverRating);
getDriverRating
);
});
it('should complete race successfully when race exists and has registered drivers', async () => {
@@ -51,12 +61,17 @@ describe('CompleteRaceUseCase', () => {
raceId: 'race-1',
};
const mockLeague = {
id: 'league-1',
settings: { pointsSystem: 'f1-2024', customPoints: null },
};
const mockRace = {
id: 'race-1',
leagueId: 'league-1',
status: 'scheduled',
complete: vi.fn().mockReturnValue({ id: 'race-1', status: 'completed' }),
};
leagueRepository.findById.mockResolvedValue(mockLeague);
raceRepository.findById.mockResolvedValue(mockRace);
raceRegistrationRepository.getRegisteredDrivers.mockResolvedValue(['driver-1', 'driver-2']);
getDriverRating.mockImplementation((input) => {
@@ -74,6 +89,7 @@ describe('CompleteRaceUseCase', () => {
expect(result.isOk()).toBe(true);
const presented = result.unwrap();
expect(presented.raceId).toBe('race-1');
expect(leagueRepository.findById).toHaveBeenCalledWith('league-1');
expect(raceRepository.findById).toHaveBeenCalledWith('race-1');
expect(raceRegistrationRepository.getRegisteredDrivers).toHaveBeenCalledWith('race-1');
expect(getDriverRating).toHaveBeenCalledTimes(2);
@@ -139,4 +155,71 @@ describe('CompleteRaceUseCase', () => {
expect(error.code).toBe('REPOSITORY_ERROR');
expect(error.details?.message).toBe('DB error');
});
it('should use league\'s points system when calculating standings', async () => {
const command: CompleteRaceInput = {
raceId: 'race-1',
};
const mockLeague = {
id: 'league-1',
settings: { pointsSystem: 'indycar', customPoints: null },
};
const mockRace = {
id: 'race-1',
leagueId: 'league-1',
status: 'scheduled',
complete: vi.fn().mockReturnValue({ id: 'race-1', status: 'completed' }),
};
leagueRepository.findById.mockResolvedValue(mockLeague);
raceRepository.findById.mockResolvedValue(mockRace);
raceRegistrationRepository.getRegisteredDrivers.mockResolvedValue(['driver-1']);
getDriverRating.mockResolvedValue({ rating: 1600, ratingChange: null });
resultRepository.create.mockResolvedValue(undefined);
standingRepository.findByDriverIdAndLeagueId.mockResolvedValue(null);
standingRepository.save.mockResolvedValue(undefined);
raceRepository.update.mockResolvedValue(undefined);
const result = await useCase.execute(command);
expect(result.isOk()).toBe(true);
expect(standingRepository.save).toHaveBeenCalledTimes(1);
// Verify that the standing was saved with indycar points (50 for 1st place)
const savedStanding = standingRepository.save.mock.calls[0][0];
expect(savedStanding.points.toNumber()).toBe(50);
});
it('should use custom points system when calculating standings', async () => {
const command: CompleteRaceInput = {
raceId: 'race-1',
};
const mockLeague = {
id: 'league-1',
settings: { pointsSystem: 'custom', customPoints: { 1: 100, 2: 80 } },
};
const mockRace = {
id: 'race-1',
leagueId: 'league-1',
status: 'scheduled',
complete: vi.fn().mockReturnValue({ id: 'race-1', status: 'completed' }),
};
leagueRepository.findById.mockResolvedValue(mockLeague);
raceRepository.findById.mockResolvedValue(mockRace);
raceRegistrationRepository.getRegisteredDrivers.mockResolvedValue(['driver-1']);
getDriverRating.mockResolvedValue({ rating: 1600, ratingChange: null });
resultRepository.create.mockResolvedValue(undefined);
standingRepository.findByDriverIdAndLeagueId.mockResolvedValue(null);
standingRepository.save.mockResolvedValue(undefined);
raceRepository.update.mockResolvedValue(undefined);
const result = await useCase.execute(command);
expect(result.isOk()).toBe(true);
expect(standingRepository.save).toHaveBeenCalledTimes(1);
// Verify that the standing was saved with custom points (100 for 1st place)
const savedStanding = standingRepository.save.mock.calls[0][0];
expect(savedStanding.points.toNumber()).toBe(100);
});
});

View File

@@ -2,6 +2,8 @@ import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { Result as RaceResult } from '../../domain/entities/result/Result';
import { Standing } from '../../domain/entities/Standing';
import type { League } from '../../domain/entities/League';
import type { LeagueRepository } from '../../domain/repositories/LeagueRepository';
import type { RaceRegistrationRepository } from '../../domain/repositories/RaceRegistrationRepository';
import type { RaceRepository } from '../../domain/repositories/RaceRepository';
import type { ResultRepository } from '../../domain/repositories/ResultRepository';
@@ -40,6 +42,7 @@ interface DriverRatingOutput {
export class CompleteRaceUseCase {
constructor(
private readonly leagueRepository: LeagueRepository,
private readonly raceRepository: RaceRepository,
private readonly raceRegistrationRepository: RaceRegistrationRepository,
private readonly resultRepository: ResultRepository,
@@ -93,8 +96,17 @@ export class CompleteRaceUseCase {
await this.resultRepository.create(result);
}
// Get league to retrieve points system
const league = await this.leagueRepository.findById(race.leagueId);
if (!league) {
return Result.err({
code: 'REPOSITORY_ERROR',
details: { message: `League not found: ${race.leagueId}` },
});
}
// Update standings
await this.updateStandings(race.leagueId, results);
await this.updateStandings(league, results);
// Complete the race
const completedRace = race.complete();
@@ -175,7 +187,7 @@ export class CompleteRaceUseCase {
return results;
}
private async updateStandings(leagueId: string, results: RaceResult[]): Promise<void> {
private async updateStandings(league: League, results: RaceResult[]): Promise<void> {
// Group results by driver
const resultsByDriver = new Map<string, RaceResult[]>();
for (const result of results) {
@@ -187,23 +199,33 @@ export class CompleteRaceUseCase {
// Update or create standings for each driver
for (const [driverId, driverResults] of resultsByDriver) {
let standing = await this.standingRepository.findByDriverIdAndLeagueId(driverId, leagueId);
let standing = await this.standingRepository.findByDriverIdAndLeagueId(driverId, league.id.toString());
if (!standing) {
standing = Standing.create({
leagueId,
leagueId: league.id.toString(),
driverId,
});
}
// Get points system from league configuration
const pointsSystem = league.settings.customPoints ??
this.getPointsSystem(league.settings.pointsSystem);
// Add all results for this driver (should be just one for this race)
for (const result of driverResults) {
standing = standing.addRaceResult(result.position.toNumber(), {
1: 25, 2: 18, 3: 15, 4: 12, 5: 10, 6: 8, 7: 6, 8: 4, 9: 2, 10: 1
});
standing = standing.addRaceResult(result.position.toNumber(), pointsSystem);
}
await this.standingRepository.save(standing);
}
}
private getPointsSystem(pointsSystem: 'f1-2024' | 'indycar' | 'custom'): Record<number, number> {
const systems: Record<string, Record<number, number>> = {
'f1-2024': { 1: 25, 2: 18, 3: 15, 4: 12, 5: 10, 6: 8, 7: 6, 8: 4, 9: 2, 10: 1 },
'indycar': { 1: 50, 2: 40, 3: 35, 4: 32, 5: 30, 6: 28, 7: 26, 8: 24, 9: 22, 10: 20, 11: 19, 12: 18, 13: 17, 14: 16, 15: 15 },
};
return systems[pointsSystem] ?? systems['f1-2024'] ?? { 1: 25, 2: 18, 3: 15, 4: 12, 5: 10, 6: 8, 7: 6, 8: 4, 9: 2, 10: 1 };
}
}

View File

@@ -146,6 +146,41 @@ describe('GetLeagueScheduleUseCase', () => {
expect(resultValue.races).toHaveLength(0);
});
it('should present all races when no seasons exist for league', async () => {
const leagueId = 'league-1';
const league = { id: leagueId } as unknown as League;
const race1 = Race.create({
id: 'race-1',
leagueId,
scheduledAt: new Date('2025-01-10T20:00:00Z'),
track: 'Track 1',
car: 'Car 1',
});
const race2 = Race.create({
id: 'race-2',
leagueId,
scheduledAt: new Date('2025-01-15T20:00:00Z'),
track: 'Track 2',
car: 'Car 2',
});
leagueRepository.findById.mockResolvedValue(league);
seasonRepository.findByLeagueId.mockResolvedValue([]);
raceRepository.findByLeagueId.mockResolvedValue([race1, race2]);
const input: GetLeagueScheduleInput = { leagueId };
const result = await useCase.execute(input);
expect(result.isOk()).toBe(true);
const resultValue = result.unwrap();
expect(resultValue.league).toBe(league);
expect(resultValue.seasonId).toBe('no-season');
expect(resultValue.published).toBe(false);
expect(resultValue.races).toHaveLength(2);
expect(resultValue.races[0]?.race).toBe(race1);
expect(resultValue.races[1]?.race).toBe(race2);
});
it('should return LEAGUE_NOT_FOUND error when league does not exist', async () => {
const leagueId = 'missing-league';

View File

@@ -41,7 +41,7 @@ export class GetLeagueScheduleUseCase {
private async resolveSeasonForSchedule(params: {
leagueId: string;
requestedSeasonId?: string;
}): Promise<Result<Season, ApplicationErrorCode<GetLeagueScheduleErrorCode, { message: string }>>> {
}): Promise<Result<Season | null, ApplicationErrorCode<GetLeagueScheduleErrorCode, { message: string }>>> {
if (params.requestedSeasonId) {
const season = await this.seasonRepository.findById(params.requestedSeasonId);
if (!season || season.leagueId !== params.leagueId) {
@@ -56,10 +56,8 @@ export class GetLeagueScheduleUseCase {
const seasons = await this.seasonRepository.findByLeagueId(params.leagueId);
const activeSeason = seasons.find((s: Season) => s.status.isActive()) ?? seasons[0];
if (!activeSeason) {
return Result.err({
code: 'SEASON_NOT_FOUND',
details: { message: 'No seasons found for league' },
});
// Return null instead of error - this allows showing all races for the league
return Result.ok(null);
}
return Result.ok(activeSeason);
@@ -134,7 +132,9 @@ export class GetLeagueScheduleUseCase {
const season = seasonResult.unwrap();
const races = await this.raceRepository.findByLeagueId(leagueId);
const seasonRaces = this.filterRacesBySeasonWindow(season, races);
// If no season exists, show all races for the league
const seasonRaces = season ? this.filterRacesBySeasonWindow(season, races) : races;
const scheduledRaces: LeagueScheduledRace[] = seasonRaces.map(race => ({
race,
@@ -142,8 +142,8 @@ export class GetLeagueScheduleUseCase {
const result: GetLeagueScheduleResult = {
league,
seasonId: season.id,
published: season.schedulePublished ?? false,
seasonId: season?.id ?? 'no-season',
published: season?.schedulePublished ?? false,
races: scheduledRaces,
};