|
| 1 | +import { Injectable, NotFoundException } from '@nestjs/common'; |
| 2 | +import { InjectRepository } from '@nestjs/typeorm'; |
| 3 | +import { Repository, LessThanOrEqual } from 'typeorm'; |
| 4 | +import { License } from '../entities/license.entity'; |
| 5 | +import { CreateLicenseDto } from '../dto/create-license.dto'; |
| 6 | +import { LessThan } from 'typeorm'; |
| 7 | +import { addDays } from 'date-fns'; |
| 8 | + |
| 9 | +@Injectable() |
| 10 | +export class LicensesService { |
| 11 | + constructor( |
| 12 | + @InjectRepository(License) |
| 13 | + private readonly licenseRepository: Repository<License>, |
| 14 | + ) {} |
| 15 | + |
| 16 | + async create(createDto: CreateLicenseDto): Promise<License> { |
| 17 | + const license = this.licenseRepository.create(createDto); |
| 18 | + return this.licenseRepository.save(license); |
| 19 | + } |
| 20 | + |
| 21 | + async findAllForAsset(assetId: string): Promise<License[]> { |
| 22 | + return this.licenseRepository.find({ where: { assetId } }); |
| 23 | + } |
| 24 | + |
| 25 | + async findOne(id: string): Promise<License> { |
| 26 | + const license = await this.licenseRepository.findOne({ where: { id } }); |
| 27 | + if (!license) { |
| 28 | + throw new NotFoundException(`License with ID "${id}" not found.`); |
| 29 | + } |
| 30 | + return license; |
| 31 | + } |
| 32 | + |
| 33 | + async remove(id: string): Promise<{ deleted: boolean }> { |
| 34 | + const result = await this.licenseRepository.delete(id); |
| 35 | + if (result.affected === 0) { |
| 36 | + throw new NotFoundException(`License with ID "${id}" not found.`); |
| 37 | + } |
| 38 | + return { deleted: true }; |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * Finds all licenses that will expire within the next 30 days and have not been notified yet. |
| 43 | + */ |
| 44 | + async findLicensesNearingExpiry(): Promise<License[]> { |
| 45 | + const thirtyDaysFromNow = addDays(new Date(), 30); |
| 46 | + return this.licenseRepository.find({ |
| 47 | + where: { |
| 48 | + expiryDate: LessThanOrEqual(thirtyDaysFromNow), |
| 49 | + isExpiryNotified: false, |
| 50 | + }, |
| 51 | + }); |
| 52 | + } |
| 53 | + |
| 54 | + async markAsNotified(licenseIds: string[]): Promise<void> { |
| 55 | + if (licenseIds.length === 0) return; |
| 56 | + await this.licenseRepository.update(licenseIds, { isExpiryNotified: true }); |
| 57 | + } |
| 58 | +} |
0 commit comments