import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { BaseRepository } from '@edr/api-common'; import { Repository, Between } from 'typeorm'; import { MaintenanceSchedule, MaintenanceStatus } from './entities/maintenance-schedule.entity'; import { MaintenanceCost } from './entities/maintenance-cost.entity'; @Injectable() export class MaintenanceRepository extends BaseRepository { constructor( @InjectRepository(MaintenanceSchedule) private readonly scheduleRepository: Repository, @InjectRepository(MaintenanceCost) private readonly costRepository: Repository, ) { super(scheduleRepository); } async getUpcomingMaintenance(vehicleId: string, daysAhead: number = 30) { const futureDate = new Date(Date.now() + daysAhead * 24 * 60 * 60 * 1000); return this.scheduleRepository.find({ where: { vehicleId, scheduledDate: Between(new Date(), futureDate), status: MaintenanceStatus.SCHEDULED, }, order: { scheduledDate: 'ASC' }, }); } async getMaintenanceCosts(vehicleId: string, startDate: Date, endDate: Date) { return this.costRepository.find({ where: { vehicleId, incurredDate: Between(startDate, endDate), }, order: { incurredDate: 'DESC' }, }); } async getTotalMaintenanceCost(vehicleId: string, startDate: Date, endDate: Date) { const result = await this.costRepository .createQueryBuilder() .select('SUM(cost_amount)', 'total') .where('vehicle_id = :vehicleId', { vehicleId }) .andWhere('incurred_date BETWEEN :startDate AND :endDate', { startDate, endDate }) .getRawOne(); return result?.total || 0; } }