refactor racing use cases
This commit is contained in:
@@ -1,77 +1,140 @@
|
||||
import type { Logger, UseCaseOutputPort } from '@core/shared/application';
|
||||
import { Result } from '@core/shared/application/Result';
|
||||
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
|
||||
import type { NotificationService } from '../../../notifications/application/ports/NotificationService';
|
||||
import type { NotificationType } from '../../../notifications/domain/types/NotificationTypes';
|
||||
import type { RaceEvent } from '../../domain/entities/RaceEvent';
|
||||
import type { Result as RaceResult } from '../../domain/entities/Result';
|
||||
import type { MainRaceCompletedEvent } from '../../domain/events/MainRaceCompleted';
|
||||
import type { IRaceEventRepository } from '../../domain/repositories/IRaceEventRepository';
|
||||
import type { IResultRepository } from '../../domain/repositories/IResultRepository';
|
||||
import type { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';
|
||||
import type { ILeagueMembershipRepository } from '../../domain/repositories/ILeagueMembershipRepository';
|
||||
import type { IDriverRepository } from '../../domain/repositories/IDriverRepository';
|
||||
import { isLeagueStewardOrHigherRole } from '../../domain/types/LeagueRoles';
|
||||
|
||||
export type SendPerformanceSummaryInput = {
|
||||
leagueId: string;
|
||||
raceId: string;
|
||||
driverId: string;
|
||||
triggeredById: string;
|
||||
};
|
||||
|
||||
export type SendPerformanceSummaryResult = {
|
||||
leagueId: string;
|
||||
raceId: string;
|
||||
driverId: string;
|
||||
notificationsSent: number;
|
||||
};
|
||||
|
||||
export type SendPerformanceSummaryErrorCode =
|
||||
| 'LEAGUE_NOT_FOUND'
|
||||
| 'RACE_NOT_FOUND'
|
||||
| 'DRIVER_NOT_FOUND'
|
||||
| 'INSUFFICIENT_PERMISSIONS'
|
||||
| 'SUMMARY_NOT_AVAILABLE'
|
||||
| 'REPOSITORY_ERROR';
|
||||
|
||||
/**
|
||||
* Use Case: SendPerformanceSummaryUseCase
|
||||
*
|
||||
* Triggered by MainRaceCompleted domain event.
|
||||
* Sends immediate performance summary modal notifications to all drivers who participated in the main race.
|
||||
* Sends an immediate performance summary notification to a driver
|
||||
* for a specific race event.
|
||||
*/
|
||||
export class SendPerformanceSummaryUseCase {
|
||||
constructor(
|
||||
private readonly notificationService: NotificationService,
|
||||
private readonly raceEventRepository: IRaceEventRepository,
|
||||
private readonly resultRepository: IResultRepository,
|
||||
private readonly leagueRepository: ILeagueRepository,
|
||||
private readonly membershipRepository: ILeagueMembershipRepository,
|
||||
private readonly driverRepository: IDriverRepository,
|
||||
private readonly logger: Logger,
|
||||
private readonly output: UseCaseOutputPort<SendPerformanceSummaryResult>,
|
||||
) {}
|
||||
|
||||
async execute(event: MainRaceCompletedEvent): Promise<Result<void, ApplicationErrorCode<never>>> {
|
||||
const { raceEventId, sessionId, leagueId, driverIds } = event.eventData;
|
||||
async execute(
|
||||
input: SendPerformanceSummaryInput,
|
||||
): Promise<Result<void, ApplicationErrorCode<SendPerformanceSummaryErrorCode, { message: string }>>> {
|
||||
try {
|
||||
const league = await this.leagueRepository.findById(input.leagueId);
|
||||
if (!league) {
|
||||
return Result.err({ code: 'LEAGUE_NOT_FOUND', details: { message: 'League not found' } });
|
||||
}
|
||||
|
||||
const raceEvent = await this.raceEventRepository.findById(input.raceId);
|
||||
if (!raceEvent) {
|
||||
return Result.err({ code: 'RACE_NOT_FOUND', details: { message: 'Race event not found' } });
|
||||
}
|
||||
|
||||
const driver = await this.driverRepository.findById(input.driverId);
|
||||
if (!driver) {
|
||||
return Result.err({ code: 'DRIVER_NOT_FOUND', details: { message: 'Driver not found' } });
|
||||
}
|
||||
|
||||
if (input.triggeredById !== input.driverId) {
|
||||
const membership = await this.membershipRepository.getMembership(league.id, input.triggeredById);
|
||||
if (!membership || !isLeagueStewardOrHigherRole(membership.role)) {
|
||||
return Result.err({
|
||||
code: 'INSUFFICIENT_PERMISSIONS',
|
||||
details: { message: 'Insufficient permissions to send performance summary' },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const mainRaceSession = raceEvent.getMainRaceSession();
|
||||
if (!mainRaceSession || mainRaceSession.status !== 'completed') {
|
||||
return Result.err({
|
||||
code: 'SUMMARY_NOT_AVAILABLE',
|
||||
details: { message: 'Performance summary is not available for this race' },
|
||||
});
|
||||
}
|
||||
|
||||
const results = await this.resultRepository.findByRaceId(mainRaceSession.id);
|
||||
const driverResult = results.find(r => r.driverId === input.driverId);
|
||||
|
||||
if (!driverResult) {
|
||||
return Result.err({
|
||||
code: 'SUMMARY_NOT_AVAILABLE',
|
||||
details: { message: 'Performance summary is not available for this driver' },
|
||||
});
|
||||
}
|
||||
|
||||
let notificationsSent = 0;
|
||||
|
||||
await this.sendPerformanceSummaryNotification(input.driverId, raceEvent, driverResult, league.id);
|
||||
notificationsSent += 1;
|
||||
|
||||
const result: SendPerformanceSummaryResult = {
|
||||
leagueId: league.id,
|
||||
raceId: raceEvent.id,
|
||||
driverId: input.driverId,
|
||||
notificationsSent,
|
||||
};
|
||||
|
||||
this.output.present(result);
|
||||
|
||||
// Get race event to include context
|
||||
const raceEvent = await this.raceEventRepository.findById(raceEventId);
|
||||
if (!raceEvent) {
|
||||
// RaceEvent not found, skip
|
||||
return Result.ok(undefined);
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : 'Failed to send performance summary';
|
||||
this.logger.error('SendPerformanceSummaryUseCase.execute failed', error instanceof Error ? error : undefined);
|
||||
return Result.err({ code: 'REPOSITORY_ERROR', details: { message } });
|
||||
}
|
||||
|
||||
// Get results for the main race session to calculate performance data
|
||||
const results = await this.resultRepository.findByRaceId(sessionId);
|
||||
|
||||
// Send performance summary to each participating driver
|
||||
for (const driverId of driverIds) {
|
||||
const driverResult = results.find(r => r.driverId === driverId);
|
||||
|
||||
await this.sendPerformanceSummaryNotification(
|
||||
driverId,
|
||||
raceEvent,
|
||||
driverResult,
|
||||
leagueId
|
||||
);
|
||||
}
|
||||
|
||||
return Result.ok(undefined);
|
||||
}
|
||||
|
||||
private async sendPerformanceSummaryNotification(
|
||||
driverId: string,
|
||||
raceEvent: RaceEvent,
|
||||
driverResult: RaceResult | undefined,
|
||||
leagueId: string
|
||||
leagueId: string,
|
||||
): Promise<void> {
|
||||
const position = driverResult?.position ?? 'DNF';
|
||||
const positionChange = driverResult?.getPositionChange() ?? 0;
|
||||
const incidents = driverResult?.incidents ?? 0;
|
||||
|
||||
// Calculate provisional rating change (simplified version)
|
||||
const provisionalRatingChange = this.calculateProvisionalRatingChange(
|
||||
driverResult?.position,
|
||||
driverResult?.incidents
|
||||
);
|
||||
const provisionalRatingChange = this.calculateProvisionalRatingChange(driverResult?.position, driverResult?.incidents);
|
||||
|
||||
const title = `Race Complete: ${raceEvent.name}`;
|
||||
const body = this.buildPerformanceSummaryBody(
|
||||
position,
|
||||
positionChange,
|
||||
incidents,
|
||||
provisionalRatingChange
|
||||
);
|
||||
const body = this.buildPerformanceSummaryBody(position, positionChange, incidents, provisionalRatingChange);
|
||||
|
||||
await this.notificationService.sendNotification({
|
||||
recipientId: driverId,
|
||||
@@ -96,7 +159,7 @@ export class SendPerformanceSummaryUseCase {
|
||||
href: `/leagues/${leagueId}/races/${raceEvent.id}`,
|
||||
},
|
||||
],
|
||||
requiresResponse: false, // Can be dismissed, but shows performance data
|
||||
requiresResponse: false,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -104,27 +167,23 @@ export class SendPerformanceSummaryUseCase {
|
||||
position: number | 'DNF',
|
||||
positionChange: number,
|
||||
incidents: number,
|
||||
provisionalRatingChange: number
|
||||
provisionalRatingChange: number,
|
||||
): string {
|
||||
const positionText = position === 'DNF' ? 'DNF' : `P${position}`;
|
||||
const positionChangeText = positionChange > 0 ? `+${positionChange}` :
|
||||
positionChange < 0 ? `${positionChange}` : '±0';
|
||||
const positionChangeText = positionChange > 0 ? `+${positionChange}` : positionChange < 0 ? `${positionChange}` : '±0';
|
||||
const incidentsText = incidents === 0 ? 'Clean race!' : `${incidents} incident${incidents > 1 ? 's' : ''}`;
|
||||
const ratingText = provisionalRatingChange >= 0 ?
|
||||
`+${provisionalRatingChange} rating` :
|
||||
`${provisionalRatingChange} rating`;
|
||||
const ratingText = provisionalRatingChange >= 0 ? `+${provisionalRatingChange} rating` : `${provisionalRatingChange} rating`;
|
||||
|
||||
return `You finished ${positionText} (${positionChangeText} positions). ${incidentsText} Provisional ${ratingText}.`;
|
||||
}
|
||||
|
||||
private calculateProvisionalRatingChange(position?: number, incidents?: number): number {
|
||||
if (!position) return -10; // DNF penalty
|
||||
if (!position) return -10;
|
||||
|
||||
// Simplified rating calculation (matches existing GetRaceDetailUseCase logic)
|
||||
const baseChange = position <= 3 ? 25 : position <= 10 ? 10 : -5;
|
||||
const positionBonus = Math.max(0, (20 - position) * 2);
|
||||
const incidentPenalty = (incidents ?? 0) * -5;
|
||||
|
||||
return baseChange + positionBonus + incidentPenalty;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user