|
| 1 | +import { Injectable, NotFoundException } from '@nestjs/common'; |
| 2 | +import { InjectRepository } from '@nestjs/typeorm'; |
| 3 | +import { Repository } from 'typeorm'; |
| 4 | +import { AssetAudit } from './entities/asset-audit.entity'; |
| 5 | +import { CreateAssetAuditDto } from './dto/create-asset-audit.dto'; |
| 6 | +import { UpdateAssetAuditDto } from './dto/update-asset-audit.dto'; |
| 7 | +import { AssetsService } from '../assets/assets.service'; |
| 8 | + |
| 9 | +@Injectable() |
| 10 | +export class AssetAuditsService { |
| 11 | + constructor( |
| 12 | + @InjectRepository(AssetAudit) private readonly assetAuditRepository: Repository<AssetAudit>, |
| 13 | + private readonly assetsService: AssetsService, |
| 14 | + ) {} |
| 15 | + |
| 16 | + async create(createAssetAuditDto: CreateAssetAuditDto): Promise<AssetAudit> { |
| 17 | + const { assetId } = createAssetAuditDto; |
| 18 | + const asset = await this.assetsService.findOne(assetId); |
| 19 | + if (!asset) { |
| 20 | + throw new NotFoundException(`Asset with ID ${assetId} not found.`); |
| 21 | + } |
| 22 | + const assetAudit = this.assetAuditRepository.create({ ...createAssetAuditDto, asset }); |
| 23 | + return this.assetAuditRepository.save(assetAudit); |
| 24 | + } |
| 25 | + |
| 26 | + async findAll(): Promise<AssetAudit[]> { |
| 27 | + return this.assetAuditRepository.find({ relations: ['asset'] }); |
| 28 | + } |
| 29 | + |
| 30 | + async findOne(id: string): Promise<AssetAudit> { |
| 31 | + const assetAudit = await this.assetAuditRepository.findOne({ where: { id }, relations: ['asset'] }); |
| 32 | + if (!assetAudit) { |
| 33 | + throw new NotFoundException(`Asset Audit with ID ${id} not found.`); |
| 34 | + } |
| 35 | + return assetAudit; |
| 36 | + } |
| 37 | + |
| 38 | + async update(id: string, updateAssetAuditDto: UpdateAssetAuditDto): Promise<AssetAudit> { |
| 39 | + const assetAudit = await this.findOne(id); |
| 40 | + const updated = Object.assign(assetAudit, updateAssetAuditDto); |
| 41 | + return this.assetAuditRepository.save(updated); |
| 42 | + } |
| 43 | + |
| 44 | + async remove(id: string): Promise<void> { |
| 45 | + const result = await this.assetAuditRepository.delete(id); |
| 46 | + if (result.affected === 0) { |
| 47 | + throw new NotFoundException(`Asset Audit with ID ${id} not found.`); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + async getAuditedVsMissingReport(): Promise<any> { |
| 52 | + const totalAssets = await this.assetsService.countAll(); |
| 53 | + const auditedAssets = await this.assetAuditRepository.count(); |
| 54 | + |
| 55 | + const missingAssets = totalAssets - auditedAssets; |
| 56 | + |
| 57 | + return { |
| 58 | + totalAssets, |
| 59 | + auditedAssets, |
| 60 | + missingAssets, |
| 61 | + percentageAudited: totalAssets > 0 ? (auditedAssets / totalAssets) * 100 : 0, |
| 62 | + percentageMissing: totalAssets > 0 ? (missingAssets / totalAssets) * 100 : 0, |
| 63 | + }; |
| 64 | + } |
| 65 | +} |
0 commit comments