miinventario-v2/apps/backend/src/modules/admin/services/admin-providers.service.ts
rckrdmrd 1a53b5c4d3 [MIINVENTARIO] feat: Initial commit - Sistema de inventario con análisis de video IA
- Backend NestJS con módulos de autenticación, inventario, créditos
- Frontend React con dashboard y componentes UI
- Base de datos PostgreSQL con migraciones
- Tests E2E configurados
- Configuración de Docker y deployment

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 02:25:48 -06:00

83 lines
2.3 KiB
TypeScript

import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { IaProvider } from '../entities/ia-provider.entity';
import { UpdateProviderDto } from '../dto/provider.dto';
import { AuditLogService } from './audit-log.service';
@Injectable()
export class AdminProvidersService {
constructor(
@InjectRepository(IaProvider)
private providerRepository: Repository<IaProvider>,
private auditLogService: AuditLogService,
) {}
async findAll(): Promise<IaProvider[]> {
return this.providerRepository.find({
order: { name: 'ASC' },
});
}
async findOne(id: string): Promise<IaProvider> {
const provider = await this.providerRepository.findOne({ where: { id } });
if (!provider) {
throw new NotFoundException('Proveedor IA no encontrado');
}
return provider;
}
async findDefault(): Promise<IaProvider | null> {
return this.providerRepository.findOne({
where: { isDefault: true, isActive: true },
});
}
async update(
id: string,
dto: UpdateProviderDto,
userId: string,
): Promise<IaProvider> {
const provider = await this.findOne(id);
const previousValue = { ...provider };
// If setting as default, unset other defaults
if (dto.isDefault === true) {
await this.providerRepository.update(
{ isDefault: true },
{ isDefault: false },
);
}
// Cannot unset the only default
if (dto.isDefault === false && provider.isDefault) {
const otherDefaults = await this.providerRepository.count({
where: { isDefault: true },
});
if (otherDefaults <= 1) {
throw new BadRequestException('Debe haber al menos un proveedor por defecto');
}
}
Object.assign(provider, dto);
const updated = await this.providerRepository.save(provider);
await this.auditLogService.log({
userId,
action: 'UPDATE_PROVIDER',
resource: 'ia_providers',
resourceId: id,
previousValue,
newValue: { ...updated },
});
return updated;
}
async getProviderByCode(code: string): Promise<IaProvider | null> {
return this.providerRepository.findOne({
where: { code, isActive: true },
});
}
}