Se agregaron validaciones
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
// src/excel/excel.controller.ts
|
||||
import { Controller, Post, Get, UseGuards, Request, Res, UploadedFile, UseInterceptors, HttpStatus, Param, ParseIntPipe } from '@nestjs/common';
|
||||
import { Controller, Post, Get, UseGuards, Request, Res, UploadedFile, UseInterceptors, HttpStatus, Param, ParseIntPipe, Body, BadRequestException } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
@@ -7,6 +7,10 @@ import { Response } from 'express';
|
||||
import { ExcelDocumentation } from './excel.documentation';
|
||||
import { ExcelService } from './excel.service';
|
||||
import { MovimientoService } from '../movimiento/movimiento.service';
|
||||
import { MailService } from 'src/mail/mail.service';
|
||||
import { CreateUsuarioDto } from 'src/usuarios/dto/create-usuario.dto';
|
||||
import { Origen } from 'src/entities/entities';
|
||||
import { UsuariosService } from 'src/usuarios/usuarios.service';
|
||||
|
||||
@UseGuards(AuthGuard('jwt'))
|
||||
@ApiBearerAuth('bearer')
|
||||
@@ -15,8 +19,35 @@ export class ExcelController {
|
||||
constructor(
|
||||
private readonly excelService: ExcelService,
|
||||
private readonly movimientoService: MovimientoService,
|
||||
private readonly mailService: MailService,
|
||||
private readonly usuarioService: UsuariosService // Asegúrate de importar el servicio de correo
|
||||
) { }
|
||||
|
||||
|
||||
@Post('carga')
|
||||
async cargaUsuario(@Request() req, @Body() usuario: CreateUsuarioDto) {
|
||||
console.log('Usuario recibido:', usuario);
|
||||
if (req.user.origen != 'LOAD') {
|
||||
throw new BadRequestException('Origen no permitido para carga')
|
||||
}
|
||||
const alta = await this.usuarioService.cargaIndividual(usuario, req.user.origen)
|
||||
console.log('Alta de usuario:', alta);
|
||||
await this.movimientoService.updateStatus(alta.movId, 'SUCCESS')
|
||||
|
||||
this.mailService.sendMail({
|
||||
to: req.user.email, // Asegúrate de que el usuario tenga un email
|
||||
subject: 'Carga de datos exitosa',
|
||||
text: "La carga de datos se ha realizado con éxito.",
|
||||
html: `<p>La carga de datos se ha realizado con éxito. ` + alta,
|
||||
});
|
||||
|
||||
await this.excelService.enviarCargaMasiva();
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Post('verify')
|
||||
@UseInterceptors(FileInterceptor('file'))
|
||||
@ExcelDocumentation.verifyExcel()
|
||||
@@ -40,7 +71,7 @@ export class ExcelController {
|
||||
const origen = req.user.origen; // ahora sí existe
|
||||
if (origen != 'LOAD') {
|
||||
await this.movimientoService.log(
|
||||
'LOAD',
|
||||
origen,
|
||||
'FAILED',
|
||||
'Origen no permitido para carga'
|
||||
);
|
||||
@@ -50,13 +81,46 @@ export class ExcelController {
|
||||
const result = await this.excelService.loadFile(file.buffer);
|
||||
//Actualizar el estado de los movimientos
|
||||
if (!result) {
|
||||
this.mailService.sendMail({
|
||||
to: req.user.email, // Asegúrate de que el usuario tenga un email
|
||||
subject: 'Carga de datos Fallida',
|
||||
text: "No se pudieron subir datos.",
|
||||
html: '<p>No se pudieron subir datos.</p>',
|
||||
});
|
||||
throw new Error('No se pudo procesar el archivo.');
|
||||
}
|
||||
|
||||
if (result.inserted == 0) {
|
||||
this.mailService.sendMail({
|
||||
to: req.user.email, // Asegúrate de que el usuario tenga un email
|
||||
subject: 'Carga de datos Fallida',
|
||||
text: "No se pudieron subir datos.",
|
||||
html: `<p> Se han insertado ${result.inserted} registros.</p>
|
||||
<p>Errores encontrados:</p>
|
||||
<ul>${result.errors.map(error => `<li>${error}</li>`).join('')}</ul>`,
|
||||
});
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
await this.movimientoService.updateStatus(
|
||||
result.id_movimiento,
|
||||
'SUCCESS',
|
||||
`inserted=${result.inserted}`
|
||||
);
|
||||
|
||||
this.mailService.sendMail({
|
||||
to: req.user.email, // Asegúrate de que el usuario tenga un email
|
||||
subject: 'Carga de datos exitosa',
|
||||
text: "La carga de datos se ha realizado con éxito.",
|
||||
html: `<p>La carga de datos se ha realizado con éxito. Se han insertado ${result.inserted} registros.</p>
|
||||
<p>Errores encontrados:</p>
|
||||
<ul>${result.errors.map(error => `<li>${error}</li>`).join('')}</ul>`,
|
||||
});
|
||||
|
||||
await this.excelService.enviarCargaMasiva();
|
||||
|
||||
|
||||
return result
|
||||
|
||||
} catch (err) {
|
||||
@@ -196,8 +260,9 @@ export class ExcelController {
|
||||
|
||||
//Agregarlo en su propio controller
|
||||
@Get('movimientos')
|
||||
async getMovimientos() {
|
||||
const movimientos = await this.movimientoService.findAll();
|
||||
async getMovimientos(@Request() req) {
|
||||
|
||||
const movimientos = await this.movimientoService.findAll(req.user.origen);
|
||||
return movimientos;
|
||||
}
|
||||
|
||||
@@ -217,4 +282,15 @@ export class ExcelController {
|
||||
return { message: 'Servicios activados correctamente' };
|
||||
}
|
||||
|
||||
|
||||
@Get('cargaIndividual')
|
||||
async cargarIndividual(
|
||||
@Request() req) {
|
||||
const origen = req.user.origen; // ahora sí existe
|
||||
return this.movimientoService.findAllCargaIndv(origen);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -2,17 +2,21 @@ import { Module } from '@nestjs/common';
|
||||
import { ExcelService } from './excel.service';
|
||||
import { ExcelController } from './excel.controller';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Usuario, Genero, Carrera, CarreraUsuario, UsuarioTipoUsuario, TipoUsuario } from '../entities/entities';
|
||||
import { Usuario, Genero, Carrera, CarreraUsuario, UsuarioTipoUsuario, TipoUsuario, UsuariosDelSistema } from '../entities/entities';
|
||||
import { MovimientoModule } from 'src/movimiento/movimiento.module';
|
||||
import { ServActivos } from 'src/usuarios/entities/servActivos.entitie';
|
||||
import { MailModule } from 'src/mail/mail.module';
|
||||
import { UsuariosService } from 'src/usuarios/usuarios.service';
|
||||
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Usuario, Genero, Carrera, CarreraUsuario, UsuarioTipoUsuario, TipoUsuario, ServActivos]),
|
||||
MovimientoModule
|
||||
TypeOrmModule.forFeature([Usuario, Genero, Carrera, CarreraUsuario, UsuarioTipoUsuario, TipoUsuario, ServActivos, UsuariosDelSistema]),
|
||||
MovimientoModule,
|
||||
MailModule,
|
||||
|
||||
],
|
||||
providers: [ExcelService],
|
||||
providers: [ExcelService, UsuariosService],
|
||||
controllers: [ExcelController],
|
||||
})
|
||||
export class ExcelModule { }
|
||||
|
||||
+130
-5
@@ -3,11 +3,12 @@ import { Injectable, BadRequestException, Logger } from '@nestjs/common';
|
||||
import { Workbook } from 'exceljs';
|
||||
import { In, Repository } from 'typeorm';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { CarreraUsuario, TipoUsuario, Usuario, UsuarioTipoUsuario } from '../entities/entities';
|
||||
import { CarreraUsuario, TipoUsuario, Usuario, UsuariosDelSistema, UsuarioTipoUsuario } from '../entities/entities';
|
||||
import { Genero } from '../entities/entities';
|
||||
import { Carrera } from '../entities/entities';
|
||||
import { MovimientoService } from 'src/movimiento/movimiento.service';
|
||||
import { ServActivos } from 'src/usuarios/entities/servActivos.entitie';
|
||||
import { MailService } from 'src/mail/mail.service';
|
||||
|
||||
export interface UsuarioRow {
|
||||
cuenta: string;
|
||||
@@ -44,7 +45,10 @@ export class ExcelService {
|
||||
private readonly tipoUsuarioRepo: Repository<TipoUsuario>,
|
||||
@InjectRepository(ServActivos)
|
||||
private readonly servActivosRepo: Repository<ServActivos>,
|
||||
@InjectRepository(UsuariosDelSistema)
|
||||
private readonly usuariosDelSistemaRepo: Repository<UsuariosDelSistema>,
|
||||
private readonly movimientoService: MovimientoService,
|
||||
private readonly mailService: MailService
|
||||
|
||||
// … inyecta otros repositorios si los usarás
|
||||
) { }
|
||||
@@ -197,17 +201,24 @@ export class ExcelService {
|
||||
const status = this.validateRows(file);
|
||||
const errs = status.errors;
|
||||
const rows = status.rowsGood;
|
||||
let carga
|
||||
if (rows.length == 0) {
|
||||
throw new BadRequestException('No se encontraron filas válidas para cargar. ' + errs);
|
||||
}
|
||||
|
||||
|
||||
const movimiento = await this.movimientoService.log(
|
||||
|
||||
'LOAD',
|
||||
'LOADING',
|
||||
undefined
|
||||
undefined,
|
||||
`CARGA MASIVA DE USUARIOS`,
|
||||
true, // flag para indicar que es una carga masiva
|
||||
);
|
||||
|
||||
|
||||
|
||||
|
||||
let contador: number = 0;
|
||||
|
||||
for (const r of rows) {
|
||||
//0.1
|
||||
@@ -217,6 +228,7 @@ export class ExcelService {
|
||||
|
||||
if (userExists) {
|
||||
errs.push(`Cuenta ${r.cuenta} ya existe, se omite.`);
|
||||
contador++;
|
||||
continue; // si ya existe, no lo insertamos
|
||||
}
|
||||
|
||||
@@ -290,7 +302,71 @@ export class ExcelService {
|
||||
// 6) ServActivos (si es necesario)
|
||||
switch (r.tipo.trim()) {
|
||||
|
||||
case 'Diplomado':
|
||||
const servActivosDiplomado = this.servActivosRepo.create({
|
||||
Correo: true,
|
||||
usuario: user,
|
||||
RedStatus: 'Inactivo',
|
||||
ATStatus: 'Inactivo',
|
||||
CorreoStatus: 'Inactivo',
|
||||
PrestamosStatus: 'Inactivo',
|
||||
});
|
||||
await this.servActivosRepo.save(servActivosDiplomado);
|
||||
|
||||
break;
|
||||
|
||||
case 'Extra Largo':
|
||||
const servActivosExtraLargo = this.servActivosRepo.create({
|
||||
Prestamos: true,
|
||||
Correo: true,
|
||||
usuario: user,
|
||||
RedStatus: 'Inactivo',
|
||||
ATStatus: 'Inactivo',
|
||||
CorreoStatus: 'Inactivo',
|
||||
PrestamosStatus: 'Inactivo',
|
||||
});
|
||||
await this.servActivosRepo.save(servActivosExtraLargo);
|
||||
break;
|
||||
|
||||
case 'Servicio Social':
|
||||
const servActivosServicio = this.servActivosRepo.create({
|
||||
Red: true,
|
||||
AT: true,
|
||||
Correo: true,
|
||||
usuario: user,
|
||||
RedStatus: 'Inactivo',
|
||||
ATStatus: 'Inactivo',
|
||||
CorreoStatus: 'Inactivo',
|
||||
PrestamosStatus: 'Inactivo',
|
||||
});
|
||||
await this.servActivosRepo.save(servActivosServicio);
|
||||
break;
|
||||
|
||||
|
||||
|
||||
case 'Idiomas R (UNAM)':
|
||||
case 'Idiomas Sabatino':
|
||||
const servActivosIdiomas = this.servActivosRepo.create({
|
||||
Red: true,
|
||||
Correo: true,
|
||||
usuario: user,
|
||||
RedStatus: 'Inactivo',
|
||||
ATStatus: 'Inactivo',
|
||||
CorreoStatus: 'Inactivo',
|
||||
PrestamosStatus: 'Inactivo',
|
||||
});
|
||||
await this.servActivosRepo.save(servActivosIdiomas);
|
||||
|
||||
break;
|
||||
|
||||
|
||||
|
||||
|
||||
case 'Reinscrito':
|
||||
case 'Posgrado':
|
||||
case 'Intercambio UNAM':
|
||||
case 'Movilidad':
|
||||
case 'Ampliación de Conocimiento':
|
||||
case 'Licenciatura':
|
||||
case 'Profesor':
|
||||
const servActivos = this.servActivosRepo.create({
|
||||
@@ -324,7 +400,10 @@ export class ExcelService {
|
||||
|
||||
|
||||
}
|
||||
return { inserted: rows.length, id_movimiento: movimiento.id_mov, errors: errs };
|
||||
|
||||
|
||||
|
||||
return { inserted: rows.length - contador, id_movimiento: movimiento.id_mov, errors: errs };
|
||||
}
|
||||
|
||||
|
||||
@@ -558,7 +637,8 @@ export class ExcelService {
|
||||
}).join('\n');
|
||||
|
||||
const tablaCompleta = header + rows;
|
||||
|
||||
console.log(tablaCompleta);
|
||||
console.log('Usuarios encontrados:', usuarios);
|
||||
return tablaCompleta;
|
||||
}
|
||||
|
||||
@@ -586,6 +666,7 @@ export class ExcelService {
|
||||
},
|
||||
servActivo: {
|
||||
ATStatus: 'Inactivo',
|
||||
AT: true
|
||||
},
|
||||
},
|
||||
relations: [
|
||||
@@ -674,6 +755,50 @@ export class ExcelService {
|
||||
|
||||
}
|
||||
|
||||
async enviarCargaMasiva(): Promise<void> {
|
||||
const usuarios_red = await this.usuariosDelSistemaRepo.findOne({ where: { origen: { origen: 'RED' } } });
|
||||
const usuarios_at = await this.usuariosDelSistemaRepo.findOne({ where: { origen: { origen: 'AT' } } });
|
||||
const usuarios_correo = await this.usuariosDelSistemaRepo.findOne({ where: { origen: { origen: 'CORREO' } } });
|
||||
const usuarios_solicita = await this.usuariosDelSistemaRepo.findOne({ where: { origen: { origen: 'SOLICITA' } } });
|
||||
if (!usuarios_red || !usuarios_at || !usuarios_correo || !usuarios_solicita) {
|
||||
throw new BadRequestException('No se encontraron usuarios para enviar correo');
|
||||
}
|
||||
|
||||
// Aquí puedes enviar el correo usando MailService
|
||||
await this.mailService.sendMail({
|
||||
to: usuarios_red.correo ?? '',
|
||||
subject: 'Carga de Usuarios',
|
||||
text: 'Se ha realizado una carga de usuarios en el sistema.',
|
||||
html: '',
|
||||
});
|
||||
await this.mailService.sendMail({
|
||||
to: usuarios_at.correo ?? '',
|
||||
subject: 'Carga de Usuarios',
|
||||
text: 'Se ha realizado una carga de usuarios en el sistema.',
|
||||
html: '',
|
||||
});
|
||||
await this.mailService.sendMail({
|
||||
to: usuarios_correo.correo ?? '',
|
||||
subject: 'Carga de Usuarios',
|
||||
text: 'Se ha realizado una carga de usuarios en el sistema.',
|
||||
html: '',
|
||||
});
|
||||
await this.mailService.sendMail({
|
||||
to: usuarios_solicita.correo ?? '',
|
||||
subject: 'Carga de Usuarios',
|
||||
text: 'Se ha realizado una carga de usuarios en el sistema.',
|
||||
html: '',
|
||||
});
|
||||
|
||||
|
||||
|
||||
console.log(`Correo enviados`);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user