332 lines
10 KiB
TypeScript
332 lines
10 KiB
TypeScript
// src/excel/excel.controller.ts
|
|
import { Controller, Post, Get, UseGuards, Request, Res, UploadedFile, UseInterceptors, HttpStatus, Param, ParseIntPipe, Body, BadRequestException, Delete } from '@nestjs/common';
|
|
import { AuthGuard } from '@nestjs/passport';
|
|
import { ApiBearerAuth } from '@nestjs/swagger';
|
|
import { FileInterceptor } from '@nestjs/platform-express';
|
|
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')
|
|
@Controller('excel')
|
|
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')
|
|
|
|
await 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} </p>`,
|
|
});
|
|
|
|
await this.excelService.enviarCargaMasiva();
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
@Post('verify')
|
|
@UseInterceptors(FileInterceptor('file'))
|
|
@ExcelDocumentation.verifyExcel()
|
|
async verifyExcel(@UploadedFile() file: Express.Multer.File, @Request() req) {
|
|
const userId: number = req.user.userId; // ahora sí existe
|
|
const status = await this.excelService.validateFile(file.buffer);
|
|
const errors = status.errors;
|
|
await this.movimientoService.log(
|
|
|
|
'VERIFY',
|
|
errors.length ? 'FAILED' : 'SUCCESS',
|
|
errors.join('; ')
|
|
);
|
|
return { valid: errors.length === 0, errors };
|
|
}
|
|
|
|
@Post('load')
|
|
@UseInterceptors(FileInterceptor('file'))
|
|
@ExcelDocumentation.loadExcel()
|
|
async loadExcel(@Request() req, @UploadedFile() file: Express.Multer.File) {
|
|
const origen = req.user.origen; // ahora sí existe
|
|
|
|
if (origen != 'LOAD') {
|
|
await this.movimientoService.log(
|
|
origen,
|
|
'FAILED',
|
|
'Origen no permitido para carga'
|
|
);
|
|
throw new Error('Origen no permitido para carga.');
|
|
}
|
|
try {
|
|
|
|
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
|
|
}
|
|
|
|
console.log(result.id_movimiento)
|
|
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();
|
|
|
|
|
|
await this.excelService.enviarInforme('AT',"Carga de datos en Servicios PCpuma",
|
|
`Se ha hecho una carga en el sistema \n ${result.conteoTiposAt}`
|
|
)
|
|
|
|
await this.excelService.enviarInforme('RED',"Carga de datos en Servicios PCpuma",
|
|
`Se ha hecho una carga en el sistema \n ${result.conteoTiposRed}`
|
|
)
|
|
|
|
await this.excelService.enviarInforme('SOLICITA',"Carga de datos en Servicios PCpuma",
|
|
`Se ha hecho una carga en el sistema \n ${result.conteoTiposCorreo}`
|
|
)
|
|
|
|
await this.excelService.enviarInforme('CORREO',"Carga de datos en Servicios PCpuma",
|
|
`Se ha hecho una carga en el sistema \n ${result.conteoTiposCorreo}`
|
|
)
|
|
|
|
|
|
|
|
return result
|
|
|
|
} catch (err) {
|
|
await this.movimientoService.log(
|
|
|
|
'LOAD',
|
|
'FAILED',
|
|
err.message
|
|
);
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
@Get('download')
|
|
@ExcelDocumentation.downloadExcel()
|
|
async downloadData(@Request() req, @Res() res: Response) {
|
|
const origen = req.user.origen; // ahora sí existe
|
|
console.log('Origen de descarga:', origen);
|
|
console.log('Usuario:', req.user);
|
|
|
|
if (origen == 'SOLICITA') {
|
|
try {
|
|
const csv = await this.excelService.generateCsvSolicita();
|
|
await this.movimientoService.log(
|
|
|
|
origen,
|
|
'SUCCESS',
|
|
'descarga de csv',
|
|
`size=${csv.length}`
|
|
);
|
|
return res
|
|
.status(HttpStatus.OK)
|
|
.header('Content-Type', 'text/csv')
|
|
.header('Content-Disposition', 'attachment; filename="usuarios_solicita.csv"')
|
|
.send(csv);
|
|
} catch (err) {
|
|
await this.movimientoService.log(
|
|
origen,
|
|
'FAILED',
|
|
'Origen no permitido para descarga'
|
|
);
|
|
return res
|
|
.status(HttpStatus.FORBIDDEN)
|
|
.json({ statusCode: 403, message: 'Origen no permitido para descarga.' });
|
|
}
|
|
} else if (origen == 'CORREO' || origen == 'LOAD') {
|
|
try {
|
|
const csv = await this.excelService.generateCsvCorreo();
|
|
await this.movimientoService.log(
|
|
|
|
origen,
|
|
'SUCCESS',
|
|
'descarga de csv',
|
|
`size=${csv.length}`
|
|
);
|
|
let filename
|
|
if (origen == 'CORREO') {
|
|
filename = 'usuarios_correo.csv';
|
|
}
|
|
else {
|
|
filename = 'usuarios.csv';
|
|
}
|
|
|
|
return res
|
|
.status(HttpStatus.OK)
|
|
.header('Content-Type', 'text/csv')
|
|
.header('Content-Disposition', `attachment; filename="${filename}"`)
|
|
.send(csv);
|
|
} catch (err) {
|
|
await this.movimientoService.log(
|
|
|
|
origen,
|
|
'FAILED',
|
|
err.message
|
|
);
|
|
return res
|
|
.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
|
.json({ statusCode: 500, message: 'Error generando descarga.' });
|
|
}
|
|
} else if (origen == 'AT') {
|
|
try {
|
|
const csv = await this.excelService.generateCsvAT();
|
|
await this.movimientoService.log(
|
|
|
|
origen,
|
|
'SUCCESS',
|
|
'descarga de csv',
|
|
`size=${csv.length}`
|
|
);
|
|
return res
|
|
.status(HttpStatus.OK)
|
|
.header('Content-Type', 'text/csv')
|
|
.header('Content-Disposition', 'attachment; filename="usuarios_AT.csv"')
|
|
.send(csv);
|
|
} catch (err) {
|
|
await this.movimientoService.log(
|
|
|
|
origen,
|
|
'FAILED',
|
|
err.message
|
|
);
|
|
return res
|
|
.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
|
.json({ statusCode: 500, message: 'Error generando descarga.' });
|
|
}
|
|
} else if (origen == 'RED') {
|
|
try {
|
|
const csv = await this.excelService.generateCsvRed();
|
|
await this.movimientoService.log(
|
|
|
|
origen,
|
|
'SUCCESS',
|
|
'descarga de csv',
|
|
`size=${csv.length}`
|
|
);
|
|
return res
|
|
.status(HttpStatus.OK)
|
|
.header('Content-Type', 'text/csv')
|
|
.header('Content-Disposition', 'attachment; filename="usuarios_red.csv"')
|
|
.send(csv);
|
|
} catch (err) {
|
|
await this.movimientoService.log(
|
|
|
|
origen,
|
|
'FAILED',
|
|
err.message
|
|
);
|
|
return res
|
|
.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
|
.json({ statusCode: 500, message: 'Error generando descarga.' });
|
|
}
|
|
} else {
|
|
await this.movimientoService.log(
|
|
|
|
origen,
|
|
'FAILED',
|
|
'Origen no permitido para descarga'
|
|
);
|
|
return res
|
|
.status(HttpStatus.FORBIDDEN)
|
|
.json({ statusCode: 403, message: 'Origen no permitido para descarga.' });
|
|
}
|
|
|
|
}
|
|
|
|
//Agregarlo en su propio controller
|
|
@Get('movimientos')
|
|
async getMovimientos(@Request() req) {
|
|
|
|
const movimientos = await this.movimientoService.findAll(req.user.origen);
|
|
return movimientos;
|
|
}
|
|
|
|
@Post('activar-servicios/:id_movimiento')
|
|
async activarServicios(
|
|
@Param('id_movimiento', ParseIntPipe) id_movimiento: number,
|
|
@Request() req,
|
|
): Promise<{ message: string }> {
|
|
const origen = req.user.origen;
|
|
|
|
if (!origen) {
|
|
throw new Error('No se encontró origen en el JWT');
|
|
}
|
|
|
|
await this.excelService.activarServicios(id_movimiento, origen);
|
|
|
|
return { message: 'Servicios activados correctamente' };
|
|
}
|
|
|
|
|
|
@Get('cargaIndividual')
|
|
async cargarIndividual(
|
|
@Request() req) {
|
|
const origen = req.user.origen; // ahora sí existe
|
|
return this.movimientoService.findAllCargaIndv(origen);
|
|
|
|
}
|
|
|
|
// @Delete()
|
|
// async borrar(){
|
|
// return await this.excelService.borrarUsers()
|
|
// }
|
|
|
|
|
|
|
|
|
|
|
|
} |