fix data flow issues
This commit is contained in:
150
core/payments/application/services/SponsorBillingService.ts
Normal file
150
core/payments/application/services/SponsorBillingService.ts
Normal file
@@ -0,0 +1,150 @@
|
||||
import type { IPaymentRepository } from '@core/payments/domain/repositories/IPaymentRepository';
|
||||
import { PaymentStatus, PaymentType, PayerType } from '@core/payments/domain/entities/Payment';
|
||||
import type { ISeasonSponsorshipRepository } from '@core/racing/domain/repositories/ISeasonSponsorshipRepository';
|
||||
|
||||
export interface SponsorBillingStats {
|
||||
totalSpent: number;
|
||||
pendingAmount: number;
|
||||
nextPaymentDate: string | null;
|
||||
nextPaymentAmount: number | null;
|
||||
activeSponsorships: number;
|
||||
averageMonthlySpend: number;
|
||||
}
|
||||
|
||||
export interface SponsorInvoiceSummary {
|
||||
id: string;
|
||||
invoiceNumber: string;
|
||||
date: string;
|
||||
dueDate: string;
|
||||
amount: number;
|
||||
vatAmount: number;
|
||||
totalAmount: number;
|
||||
status: 'paid' | 'pending' | 'overdue' | 'failed';
|
||||
description: string;
|
||||
sponsorshipType: 'league' | 'team' | 'driver' | 'race' | 'platform';
|
||||
pdfUrl: string;
|
||||
}
|
||||
|
||||
export interface SponsorPaymentMethodSummary {
|
||||
id: string;
|
||||
type: 'card' | 'bank' | 'sepa';
|
||||
last4: string;
|
||||
brand?: string;
|
||||
isDefault: boolean;
|
||||
expiryMonth?: number;
|
||||
expiryYear?: number;
|
||||
bankName?: string;
|
||||
}
|
||||
|
||||
export interface SponsorBillingSummary {
|
||||
paymentMethods: SponsorPaymentMethodSummary[];
|
||||
invoices: SponsorInvoiceSummary[];
|
||||
stats: SponsorBillingStats;
|
||||
}
|
||||
|
||||
/**
|
||||
* Application Service: SponsorBillingService
|
||||
*
|
||||
* Aggregates sponsor-facing billing information from payments and season sponsorships.
|
||||
*/
|
||||
export class SponsorBillingService {
|
||||
constructor(
|
||||
private readonly paymentRepository: IPaymentRepository,
|
||||
private readonly seasonSponsorshipRepository: ISeasonSponsorshipRepository,
|
||||
) {}
|
||||
|
||||
async getSponsorBilling(sponsorId: string): Promise<SponsorBillingSummary> {
|
||||
// In this in-memory implementation we derive billing data from payments
|
||||
// where the sponsor is the payer.
|
||||
const payments = await this.paymentRepository.findByFilters({
|
||||
payerId: sponsorId,
|
||||
type: PaymentType.SPONSORSHIP,
|
||||
});
|
||||
|
||||
const sponsorships = await this.seasonSponsorshipRepository.findBySponsorId(sponsorId);
|
||||
|
||||
const invoices: SponsorInvoiceSummary[] = payments.map((payment, index) => {
|
||||
const createdAt = payment.createdAt ?? new Date();
|
||||
const dueDate = new Date(createdAt.getTime());
|
||||
dueDate.setDate(dueDate.getDate() + 14);
|
||||
|
||||
const vatAmount = +(payment.amount * 0.19).toFixed(2);
|
||||
const totalAmount = +(payment.amount + vatAmount).toFixed(2);
|
||||
|
||||
let status: 'paid' | 'pending' | 'overdue' | 'failed' = 'pending';
|
||||
if (payment.status === PaymentStatus.COMPLETED) status = 'paid';
|
||||
else if (payment.status === PaymentStatus.FAILED || payment.status === PaymentStatus.REFUNDED) status = 'failed';
|
||||
|
||||
const now = new Date();
|
||||
if (status === 'pending' && dueDate < now) {
|
||||
status = 'overdue';
|
||||
}
|
||||
|
||||
return {
|
||||
id: payment.id,
|
||||
invoiceNumber: `GP-${createdAt.getFullYear()}-${String(index + 1).padStart(6, '0')}`,
|
||||
date: createdAt.toISOString(),
|
||||
dueDate: dueDate.toISOString(),
|
||||
amount: payment.amount,
|
||||
vatAmount,
|
||||
totalAmount,
|
||||
status,
|
||||
description: 'Sponsorship payment',
|
||||
sponsorshipType: 'league',
|
||||
pdfUrl: '#',
|
||||
};
|
||||
});
|
||||
|
||||
const totalSpent = invoices
|
||||
.filter(i => i.status === 'paid')
|
||||
.reduce((sum, i) => sum + i.totalAmount, 0);
|
||||
|
||||
const pendingAmount = invoices
|
||||
.filter(i => i.status === 'pending' || i.status === 'overdue')
|
||||
.reduce((sum, i) => sum + i.totalAmount, 0);
|
||||
|
||||
const pendingInvoices = invoices.filter(i => i.status === 'pending' || i.status === 'overdue');
|
||||
const nextPending = pendingInvoices.length > 0
|
||||
? pendingInvoices.reduce((earliest, current) => (current.dueDate < earliest.dueDate ? current : earliest))
|
||||
: null;
|
||||
|
||||
const stats: SponsorBillingStats = {
|
||||
totalSpent,
|
||||
pendingAmount,
|
||||
nextPaymentDate: nextPending ? nextPending.dueDate : null,
|
||||
nextPaymentAmount: nextPending ? nextPending.totalAmount : null,
|
||||
activeSponsorships: sponsorships.filter(s => s.status === 'active').length,
|
||||
averageMonthlySpend: this.calculateAverageMonthlySpend(invoices),
|
||||
};
|
||||
|
||||
// NOTE: Payment methods are not yet persisted in core. For now, we expose
|
||||
// an empty list so the UI can still render correctly. A dedicated
|
||||
// payment-methods port can be added later when the concept exists in core.
|
||||
const paymentMethods: SponsorPaymentMethodSummary[] = [];
|
||||
|
||||
return {
|
||||
paymentMethods,
|
||||
invoices,
|
||||
stats,
|
||||
};
|
||||
}
|
||||
|
||||
private calculateAverageMonthlySpend(invoices: SponsorInvoiceSummary[]): number {
|
||||
if (invoices.length === 0) return 0;
|
||||
|
||||
const sorted = [...invoices].sort((a, b) => a.date.localeCompare(b.date));
|
||||
const first = new Date(sorted[0].date);
|
||||
const last = new Date(sorted[sorted.length - 1].date);
|
||||
|
||||
const months = this.monthDiff(first, last) || 1;
|
||||
const total = sorted.reduce((sum, inv) => sum + inv.totalAmount, 0);
|
||||
|
||||
return Math.round((total / months) * 100) / 100;
|
||||
}
|
||||
|
||||
private monthDiff(d1: Date, d2: Date): number {
|
||||
const years = d2.getFullYear() - d1.getFullYear();
|
||||
const months = d2.getMonth() - d1.getMonth();
|
||||
return years * 12 + months + 1;
|
||||
}
|
||||
}
|
||||
3
core/racing/application/dto/ReopenRaceCommandDTO.ts
Normal file
3
core/racing/application/dto/ReopenRaceCommandDTO.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export interface ReopenRaceCommandDTO {
|
||||
raceId: string;
|
||||
}
|
||||
55
core/racing/application/use-cases/ReopenRaceUseCase.ts
Normal file
55
core/racing/application/use-cases/ReopenRaceUseCase.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import type { IRaceRepository } from '../../domain/repositories/IRaceRepository';
|
||||
import type { AsyncUseCase } from '@core/shared/application';
|
||||
import type { Logger } from '@core/shared/application';
|
||||
import { Result } from '@core/shared/application/Result';
|
||||
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
|
||||
import type { ReopenRaceCommandDTO } from '../dto/ReopenRaceCommandDTO';
|
||||
|
||||
/**
|
||||
* Use Case: ReopenRaceUseCase
|
||||
*
|
||||
* Encapsulates the workflow for re-opening a race:
|
||||
* - loads the race by id
|
||||
* - returns error if the race does not exist
|
||||
* - delegates transition rules to the Race domain entity via `reopen()`
|
||||
* - persists the updated race via the repository.
|
||||
*/
|
||||
export class ReopenRaceUseCase
|
||||
implements AsyncUseCase<ReopenRaceCommandDTO, void, string> {
|
||||
constructor(
|
||||
private readonly raceRepository: IRaceRepository,
|
||||
private readonly logger: Logger,
|
||||
) {}
|
||||
|
||||
async execute(command: ReopenRaceCommandDTO): Promise<Result<void, ApplicationErrorCode<string>>> {
|
||||
const { raceId } = command;
|
||||
this.logger.debug(`[ReopenRaceUseCase] Executing for raceId: ${raceId}`);
|
||||
|
||||
try {
|
||||
const race = await this.raceRepository.findById(raceId);
|
||||
if (!race) {
|
||||
this.logger.warn(`[ReopenRaceUseCase] Race with ID ${raceId} not found.`);
|
||||
return Result.err({ code: 'RACE_NOT_FOUND' });
|
||||
}
|
||||
|
||||
const reopenedRace = race.reopen();
|
||||
await this.raceRepository.update(reopenedRace);
|
||||
this.logger.info(`[ReopenRaceUseCase] Race ${raceId} re-opened successfully.`);
|
||||
return Result.ok(undefined);
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message.includes('already scheduled')) {
|
||||
this.logger.warn(`[ReopenRaceUseCase] Domain error re-opening race ${raceId}: ${error.message}`);
|
||||
return Result.err({ code: 'RACE_ALREADY_SCHEDULED' });
|
||||
}
|
||||
if (error instanceof Error && error.message.includes('running race')) {
|
||||
this.logger.warn(`[ReopenRaceUseCase] Domain error re-opening race ${raceId}: ${error.message}`);
|
||||
return Result.err({ code: 'CANNOT_REOPEN_RUNNING_RACE' });
|
||||
}
|
||||
this.logger.error(
|
||||
`[ReopenRaceUseCase] Unexpected error re-opening race ${raceId}`,
|
||||
error instanceof Error ? error : new Error(String(error)),
|
||||
);
|
||||
return Result.err({ code: 'UNEXPECTED_ERROR' });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -240,6 +240,48 @@ export class Race implements IEntity<string> {
|
||||
return Race.create(props);
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-open a previously completed or cancelled race
|
||||
*/
|
||||
reopen(): Race {
|
||||
if (this.status === 'scheduled') {
|
||||
throw new RacingDomainInvariantError('Race is already scheduled');
|
||||
}
|
||||
|
||||
if (this.status === 'running') {
|
||||
throw new RacingDomainInvariantError('Cannot re-open a running race');
|
||||
}
|
||||
|
||||
const base = {
|
||||
id: this.id,
|
||||
leagueId: this.leagueId,
|
||||
scheduledAt: this.scheduledAt,
|
||||
track: this.track,
|
||||
car: this.car,
|
||||
sessionType: this.sessionType,
|
||||
status: 'scheduled' as RaceStatus,
|
||||
};
|
||||
|
||||
const withTrackId =
|
||||
this.trackId !== undefined ? { ...base, trackId: this.trackId } : base;
|
||||
const withCarId =
|
||||
this.carId !== undefined ? { ...withTrackId, carId: this.carId } : withTrackId;
|
||||
const withSof =
|
||||
this.strengthOfField !== undefined
|
||||
? { ...withCarId, strengthOfField: this.strengthOfField }
|
||||
: withCarId;
|
||||
const withRegistered =
|
||||
this.registeredCount !== undefined
|
||||
? { ...withSof, registeredCount: this.registeredCount }
|
||||
: withSof;
|
||||
const props =
|
||||
this.maxParticipants !== undefined
|
||||
? { ...withRegistered, maxParticipants: this.maxParticipants }
|
||||
: withRegistered;
|
||||
|
||||
return Race.create(props);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update SOF and participant count
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user