import { BadRequestException, forwardRef, Inject, Injectable, } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { Modulo } from '../modulo/entity/modulo.entity'; import { Operador } from '../operador/entity/operador.entity'; import { Passcode } from './entity/passcode.entity'; import { Prestamo } from '../prestamo/entity/prestamo.entity'; import { PrestamoService } from '../prestamo/prestamo.service'; @Injectable() export class PasscodeService { constructor( @InjectRepository(Passcode) private repository: Repository, @Inject(forwardRef(() => PrestamoService)) private prestamoService: PrestamoService, ) {} create(prestamo: Prestamo) { return this.repository .save(this.repository.create({ prestamo })) .then((passcodeInterno) => { const aux = { 1: '00000', 2: '0000', 3: '000', 4: '00', 5: '0', 6: '', }; passcodeInterno.passcode = `0${prestamo.equipo.carrito.id_carrito}${ aux[passcodeInterno.id_passcode.toString().length] }${passcodeInterno.id_passcode}${Math.floor( Math.random() * 99999 + 10000, )}`; return this.repository.save(passcodeInterno); }); } devolverEquipo(operador: Operador, modulo: Modulo, passcode: string) { return this.findByPasscode(passcode, true) .then((passcodeInterno) => this.prestamoService.regresar( operador, modulo, passcodeInterno.prestamo, 1, ), ) .then((_) => ({ code: 1 })); } async entregarEquipo( operador: Operador, modulo: Modulo, passcode: string, estatus: number, ) { const passcodeInterno = await this.findByPasscode(passcode, false); if (estatus) { if (passcodeInterno.abrio != (estatus === 1)) passcodeInterno.abrio = estatus === 1; return this.prestamoService .entregar(operador, modulo, passcodeInterno.prestamo.id_prestamo) .then((_) => this.repository.save(passcodeInterno)) .then((_) => ({ code: 1 })); } } findByPasscode(passcode: string, abrio?: boolean, id_locker?: string) { let door = ''; return this.repository .findOne({ where: { passcode, abrio } }) .then(async (passcode) => { if (!passcode) throw new BadRequestException({ message: `Este passcode no existe`, code: 6, }); if (id_locker) { await this.prestamoService .findById(passcode.prestamo.id_prestamo) .then((prestamo) => { if (prestamo.equipo.carrito.id_carrito != parseInt(id_locker)) throw new BadRequestException({ message: `El id_locker no corresponde`, code: 4, }); door = prestamo.equipo.equipo.substring(1, 3); }); return { ...passcode, code: 1, id_locker, door: parseInt(door) }; } return passcode; }); } findByPrestamo(prestamo: Prestamo) { return this.repository.findOne({ where: { prestamo } }); } }