Se realizaron correcciones

This commit is contained in:
evenegas
2026-01-06 07:20:11 -06:00
parent 5567a26ed6
commit bc4146a07d
9 changed files with 155 additions and 212 deletions
+4 -10
View File
@@ -25,10 +25,10 @@ import { FilterCasoEspecialDto } from './dto/filter-caso-especial.dto';
@Controller('caso-especial')
export class CasoEspecialController {
constructor(private readonly casoEspecialService: CasoEspecialService) {}
constructor(private readonly casoEspecialService: CasoEspecialService) { }
@Post()
@UseGuards(AuthGuard('jwt')) // reemplaza verificaToken
@UseGuards(AuthGuard('jwt'))
@UseInterceptors(
FileInterceptor('archivos', {
storage: diskStorage({
@@ -45,15 +45,9 @@ export class CasoEspecialController {
@Body('alumno') alumno: CreateCasoEspecialDto,
) {
try {
const data = await this.casoEspecialService.create(alumno, file.filename);
return {
statusCode: 201,
message: 'Archivo subido con éxito',
data,
};
return await this.casoEspecialService.create(alumno, file.filename);
} catch (err) {
// Si hay error, eliminar archivo subido
if (file && file.filename) {
if (file?.filename) {
fs.unlinkSync(`./server/uploads/${file.filename}`);
}
throw new BadRequestException(err.message);
+31 -33
View File
@@ -32,7 +32,7 @@ export class CasoEspecialService {
private validacion: ValidacionService,
private gmail: gmail,
private drive: DriveService,
) {}
) { }
async create(body: CreateCasoEspecialDto, file: string) {
const {
@@ -52,62 +52,59 @@ export class CasoEspecialService {
motivo = '',
} = body;
const usuario = await this.usuarioRepository.findOneBy({
idUsuario: idUsuario,
const usuario = await this.usuarioRepository.findOne({
where: { idUsuario },
relations: ['tipoUsuario'],
});
if (!usuario)
throw new NotFoundException('Este alumno no existe en la db.');
if (usuario.tipoUsuario.idTipoUsuario !== 3)
throw new BadRequestException('Este usuario no es de tipo Alumno.');
const carrera = await this.carreraRepository.findOneBy({
idCarrera: idCarrera,
});
const carrera = await this.carreraRepository.findOneBy({ idCarrera });
if (!carrera)
throw new NotFoundException('Esta carrera no existe en la db.');
const casoExistente = await this.casoEspecialRepository.findOne({
where: { usuario: usuario },
where: { usuario: { idUsuario } },
});
if (casoExistente)
throw new BadRequestException('Este alumno ya tiene un Caso Especial.');
const path = `./server/uploads/${file}`;
const carpeta = await this.drive.folder(numeroCuenta);
if (!carpeta) {
throw new Error('No se pudo crear la carpeta en Drive.');
}
if (!carpeta) throw new Error('No se pudo crear la carpeta en Drive.');
const archivoZip = await this.drive.uploadFile(
path,
`archivos.zip`,
'archivos.zip',
'application/zip',
carpeta,
);
const status = await this.statusRepository.findOne({
where: { idStatus: idStatus },
});
if (!status) throw new NotFoundException('Este status no existe en la db.');
if (archivoZip === null)
if (!archivoZip)
throw new Error('No se pudo subir el archivo a Drive.');
const status = await this.statusRepository.findOneBy({ idStatus });
if (!status)
throw new NotFoundException('Este status no existe en la db.');
const nuevoCaso = this.casoEspecialRepository.create({
correo: correo,
telefono: telefono,
institucion: institucion,
dependencia: dependencia,
motivo: motivo,
direccion: direccion,
fechaInicio: fechaInicio,
fechaFin: fechaFin,
fechaNacimiento: fechaNacimiento,
carpeta: carpeta,
archivoZip: archivoZip,
usuario: usuario,
carrera: carrera,
status: status,
creditos: creditos,
correo,
telefono,
institucion,
dependencia,
motivo,
direccion,
fechaInicio,
fechaFin,
fechaNacimiento,
carpeta,
archivoZip,
usuario,
carrera,
status,
creditos,
});
await this.casoEspecialRepository.save(nuevoCaso);
@@ -117,6 +114,7 @@ export class CasoEspecialService {
};
}
async findAllFiltered(dto: FilterCasoEspecialDto) {
const { pagina = 1, idStatus, nombre = '', numeroCuenta = '' } = dto;
+10 -3
View File
@@ -24,10 +24,11 @@ import { CrearServicioDto } from './dto/create-servicio.dto';
import { Response } from 'express';
import { ServiciosAdminDto } from './dto/servicios-admin.dto';
import { ServiciosResponsableDto } from './dto/servicios-responsable.dto';
import { RegistroValidadoDto } from './dto/registro-validado.dto';
@Controller('servicio')
export class ServicioController {
constructor(private readonly servicioService: ServicioService) {}
constructor(private readonly servicioService: ServicioService) { }
// ------------------ POST ------------------
@@ -44,6 +45,13 @@ export class ServicioController {
return { ok: true };
}
@Post('registro-validado')
async registroValidado(
@Body() dto: RegistroValidadoDto,
): Promise<{ message: string }> {
return this.servicioService.registroValidado(dto);
}
@Post('nuevo')
@UseGuards(AuthGuard('jwt'))
@UseInterceptors(FileInterceptor('cartaAceptacion'))
@@ -104,7 +112,7 @@ export class ServicioController {
@Get('reporte')
@UseGuards(AuthGuard('jwt'))
async generarReporte(
@Query('inicio') inicio: string,
@Query('inicio') inicio: string,
@Query('fin') fin: string,
@Res() res: Response) {
const path = await this.servicioService.generarReporte(inicio, fin);
@@ -199,4 +207,3 @@ export class ServicioController {
return this.servicioService.update(data, files);
}
}
+3 -2
View File
@@ -15,10 +15,11 @@ import { Carrera } from 'src/carrera/entities/carrera.entity';
import { Auth } from 'googleapis';
import { AuthService } from 'src/auth/auth.service';
import { AuthModule } from 'src/auth/auth.module';
import { Status } from 'src/status/entities/status.entity';
@Module({
imports: [
TypeOrmModule.forFeature([Servicio, Usuario, Programa, Carrera]),
TypeOrmModule.forFeature([Servicio, Usuario, Programa, Carrera, Status]),
AuthModule,
],
controllers: [ServicioController],
@@ -31,4 +32,4 @@ import { AuthModule } from 'src/auth/auth.module';
],
exports: [TypeOrmModule],
})
export class ServicioModule {}
export class ServicioModule { }
+68 -101
View File
@@ -22,7 +22,8 @@ import { RegistroValidadoDto } from './dto/registro-validado.dto';
import * as fs from 'fs';
import { ServiciosAdminDto } from './dto/servicios-admin.dto';
import { ServiciosResponsableDto } from './dto/servicios-responsable.dto';
import { SendMailDto } from 'src/helpers.services/dto/send-email.dto';
import { SendMailDto } from 'src/helpers.services/dto/send-email.dto';
import { Status } from 'src/status/entities/status.entity';
const {
canceladoAlumno,
canceladoResponsable,
@@ -43,6 +44,9 @@ export class ServicioService {
@InjectRepository(Carrera)
private carreraRepo: Repository<Carrera>,
@InjectRepository(Status)
private statusRepo: Repository<Status>,
private validacionService: ValidacionService,
private driveService: DriveService,
@@ -52,7 +56,7 @@ export class ServicioService {
private archivoService: ArchivoService,
private authService: AuthService,
) {}
) { }
async obtenerServicioAlumno(idUsuario: number) {
const usuario = await this.usuarioRepo.findOne({
@@ -653,7 +657,7 @@ export class ServicioService {
*/
// Hacemos una validacion en el nombre
const nombreArchivo = `./server/uploads/${this.validacionService.validacionBasicaStr(file.filename, 'archivo', true, 1000)}`;
const archivoPath = `./server/uploads/${nombreArchivo}`;
// Validacion de tipo de archivo
@@ -668,11 +672,11 @@ export class ServicioService {
const progInterno = dto.programaInterno
? this.validacionService.validarAlfanumerico(
dto.programaInterno,
'programa interno',
true,
250,
)
dto.programaInterno,
'programa interno',
true,
250,
)
: '';
const prof = dto.profesor
? this.validacionService.validarTexto(dto.profesor, 'profesor', true, 50)
@@ -757,28 +761,22 @@ export class ServicioService {
idServicio: number,
mensaje: string,
): Promise<{ message: string }> {
let correoResponsable: any = {};
let correoAlumno: any = {};
let correoResponsable: any;
let correoAlumno: any;
let emailResponsable = '';
const sendCorreoResponsableDto: SendMailDto = {
to: correoResponsable,
subject: correoResponsable.subject,
fecha_recibido: new Date(),
text: correoResponsable.msj,
html: '',
adjuntos: undefined,
};
const servicio = await this.servicioRepo.findOne({
where: { idServicio },
relations: ['usuario', 'programa', 'programa.usuario'],
relations: ['usuario', 'programa', 'programa.usuario', 'status'],
});
if (!servicio) {
throw new NotFoundException('No existe este Servicio Social.');
}
switch (servicio.status?.idStatus) {
const statusId = servicio.status.idStatus;
switch (statusId) {
case 1:
correoAlumno = preRegistroRechazadoAlumno(
mensaje,
@@ -790,18 +788,9 @@ export class ServicioService {
servicio.usuario.nombre,
);
emailResponsable = servicio.programa.usuario.usuario; // correo del responsable
emailResponsable = servicio.programa.usuario.usuario;
const sendCorreoAlumnoDto: SendMailDto = {
to: servicio.correo,
subject: correoAlumno.subject,
fecha_recibido: new Date(),
text: correoAlumno.msj,
html: '',
adjuntos: undefined,
};
// Enviar correo al alumno
// correo alumno
await this.gmailService.enviarCorreo({
subject: correoAlumno.subject,
to: servicio.correo,
@@ -835,7 +824,7 @@ export class ServicioService {
throw new BadRequestException('Id status no válido.');
}
// Enviar correo al responsable
// correo responsable
await this.gmailService.enviarCorreo({
subject: correoResponsable.subject,
to: emailResponsable,
@@ -843,57 +832,51 @@ export class ServicioService {
fecha_recibido: new Date(),
});
// Actualizar estado del servicio
const statusRechazado = await this.statusRepo.findOneBy({ idStatus: 7 });
if (!statusRechazado) {
throw new NotFoundException('El estatus de rechazado no existe.');
}
await this.servicioRepo.update(idServicio, {
status: { idStatus: 7 }, // si tienes relación con Status
status: statusRechazado,
cartaAceptacion: '',
});
return { message: 'Se rechazó correctamente la Carta de Aceptación.' };
return {
message: 'Se rechazó correctamente la Carta de Aceptación.',
};
}
async rechazarInforme(
idServicio: number,
mensaje: string,
): Promise<{ message: string }> {
let correoResponsable: any = {};
let correoAlumno: any = {};
let correoResponsable: any;
let correoAlumno: any;
let emailResponsable = '';
const sendCorreoResponsableDto: SendMailDto = {
to: correoResponsable,
subject: correoResponsable.subject,
fecha_recibido: new Date(),
text: correoResponsable.msj,
html: '',
adjuntos: undefined,
};
const servicio = await this.servicioRepo.findOne({
where: { idServicio },
relations: ['usuario', 'programa', 'programa.usuario'],
relations: ['usuario', 'programa', 'programa.usuario', 'status'],
});
if (!servicio)
if (!servicio) {
throw new NotFoundException('No existe este Servicio Social.');
}
const sendCorreoAlumnoDto: SendMailDto = {
to: servicio.correo,
subject: correoAlumno.subject,
fecha_recibido: new Date(),
text: correoAlumno.msj,
html: '',
adjuntos: undefined,
};
switch (servicio.status?.idStatus) {
case 5: {
correoAlumno = terminoRechazadoAlumno(mensaje, servicio.usuario.nombre);
switch (servicio.status.idStatus) {
case 5:
correoAlumno = terminoRechazadoAlumno(
mensaje,
servicio.usuario.nombre,
);
correoResponsable = terminoRechazadoResponsable(
mensaje,
servicio.usuario.nombre,
);
emailResponsable = servicio.programa.usuario.usuario; // correo responsable
emailResponsable = servicio.programa.usuario.usuario;
await this.gmailService.enviarCorreo({
subject: correoAlumno.subject,
@@ -902,7 +885,6 @@ export class ServicioService {
fecha_recibido: new Date(),
});
break;
}
case 1:
case 2:
@@ -933,7 +915,6 @@ export class ServicioService {
throw new BadRequestException('Id status no válido.');
}
// Enviar correo al responsable
await this.gmailService.enviarCorreo({
subject: correoResponsable.subject,
to: emailResponsable,
@@ -941,54 +922,40 @@ export class ServicioService {
fecha_recibido: new Date(),
});
// Actualizar estado del servicio
await this.servicioRepo.update(idServicio, {
status: { idStatus: 9 }, // nuevo estado (rechazado)
status: { idStatus: 9 },
informeGlobal: '',
});
return { message: 'Se rechazó correctamente el Informe Global.' };
return {
message: 'Se rechazó correctamente el Informe Global.',
};
}
async rechazarTermino(
idServicio: number,
mensaje: string,
): Promise<{ message: string }> {
let correoResponsable: any = {};
let correoAlumno: any = {};
let correoResponsable: any;
let correoAlumno: any;
let emailResponsable = '';
const sendCorreoResponsableDto: SendMailDto = {
to: correoResponsable,
subject: correoResponsable.subject,
fecha_recibido: new Date(),
text: correoResponsable.msj,
html: '',
adjuntos: undefined,
};
const servicio = await this.servicioRepo.findOne({
where: { idServicio },
relations: ['usuario', 'programa', 'programa.usuario'],
relations: ['usuario', 'programa', 'programa.usuario', 'status'],
});
if (!servicio)
if (!servicio) {
throw new NotFoundException('No existe este Servicio Social.');
}
const sendCorreoAlumnoDto: SendMailDto = {
to: servicio.correo,
subject: correoAlumno.subject,
fecha_recibido: new Date(),
text: correoAlumno.msj,
html: '',
adjuntos: undefined,
};
const idStatus = servicio.status?.idStatus;
switch (idStatus) {
case 5: {
correoAlumno = terminoRechazadoAlumno(mensaje, servicio.usuario.nombre);
switch (servicio.status.idStatus) {
case 5:
correoAlumno = terminoRechazadoAlumno(
mensaje,
servicio.usuario.nombre,
);
correoResponsable = terminoRechazadoResponsable(
mensaje,
servicio.usuario.nombre,
@@ -1002,7 +969,6 @@ export class ServicioService {
fecha_recibido: new Date(),
});
break;
}
case 1:
case 2:
@@ -1033,7 +999,6 @@ export class ServicioService {
throw new BadRequestException('Id status no válido.');
}
// Enviar correo al responsable
await this.gmailService.enviarCorreo({
subject: correoResponsable.subject,
to: emailResponsable,
@@ -1041,15 +1006,17 @@ export class ServicioService {
fecha_recibido: new Date(),
});
// Actualizar el servicio
await this.servicioRepo.update(idServicio, {
status: { idStatus: 8 }, // Rechazado (Carta de Término)
status: { idStatus: 8 },
cartaTermino: '',
});
return { message: 'Se rechazó correctamente la Carta de Término.' };
return {
message: 'Se rechazó correctamente la Carta de Término.',
};
}
async registro(idServicio: number): Promise<{ message: string }> {
let password = await this.authService.generarPassword();
if (process.env.MODE === 'pruebas') password = 'qwertyui';
@@ -1419,7 +1386,7 @@ export class ServicioService {
dataUpdate.cartaAceptacion = result === null ? undefined : result;
}
}
} catch (err) {}
} catch (err) { }
try {
if (files?.['cartaTermino']?.[0]?.filename) {
@@ -1433,7 +1400,7 @@ export class ServicioService {
dataUpdate.cartaTermino = result === null ? undefined : result;
}
}
} catch (err) {}
} catch (err) { }
try {
if (files?.['informeGlobal']?.[0]?.filename) {
@@ -1445,7 +1412,7 @@ export class ServicioService {
);
dataUpdate.informeGlobal = result === null ? undefined : result;
}
} catch (err) {}
} catch (err) { }
// ---- 📆 Validaciones de campos del body ----
if (body.correo) dataUpdate.correo = body.correo;
+6 -6
View File
@@ -20,13 +20,13 @@ import { UpdateUsuarioDto } from './dto/update-usuario.dto';
@Controller('usuario')
export class UsuarioController {
constructor(private readonly usuarioService: UsuarioService) {}
constructor(private readonly usuarioService: UsuarioService) { }
/*Get('todos')
//@UseGuards(AuthGuard('jwt'))
async obtenerTodosLosServicios() {
return this.usuarioService.obtenerTodosLosUsuarios();
}*/ //No subir en produccion
/*Get('todos')
//@UseGuards(AuthGuard('jwt'))
async obtenerTodosLosServicios() {
return this.usuarioService.obtenerTodosLosUsuarios();
}*/ //No subir en produccion
@Post('crearUsuario')
@UsePipes(new ValidationPipe({ transform: true }))
+25 -19
View File
@@ -60,7 +60,7 @@ export class UsuarioService {
private readonly tipoUsurioRepo: Repository<TipoUsuario>,
private readonly gmail: gmail,
private readonly authService: AuthService,
) {}
) { }
async escolares(numeroDeCuenta: string) {
let response;
@@ -79,17 +79,23 @@ export class UsuarioService {
});
*/
response = {
data: {
nombre: 'nombre',
carrconst: 'Carrera',
avance: '80',
},
data: {
nombre: 'nombre',
carrconst: 'Carrera',
avance: '80',
},
};
} else {
response = await axios.post(
`${process.env.ESCOLARES}${numeroDeCuenta}`,
{ password: process.env.ESCOLARES_PASS },
process.env.ESCOLARES_PASS,
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
},
);
}
} catch (error) {
throw new UnauthorizedException(
@@ -174,7 +180,7 @@ export class UsuarioService {
}
// Preparar correo
const { preRegistro } = require('../helpers.services/msjCorreos');
const { preRegistro } = require('../helpers.services/msjCorreos');
let correo = preRegistro(password, usuario.nombre);
// Enviar correo
@@ -198,7 +204,7 @@ export class UsuarioService {
const password = await this.authService.generarPassword();
// Buscar usuario
const usuario = await this.userRepo.findOne({ where: { idUsuario },relations: ['tipoUsuario'] });
const usuario = await this.userRepo.findOne({ where: { idUsuario }, relations: ['tipoUsuario'] });
if (!usuario) {
throw new NotFoundException('No existe este Usuario.');
@@ -258,7 +264,7 @@ export class UsuarioService {
const dataUpdate: Partial<Usuario> = {};
// Buscar responsable
const responsable = await this.userRepo.findOne({
const responsable = await this.userRepo.findOne({
where: { idUsuario },
relations: ['tipoUsuario'],
});
@@ -354,13 +360,13 @@ export class UsuarioService {
};
}
/*c obtenerTodosLosUsuarios() {
return await this.userRepo.find({
relations: ['tipoUsuario'],
take: 10,
order: {
idUsuario: 'DESC', // Ordenar por el más reciente primero
},
});
}*/ // no subir a produccion
/*c obtenerTodosLosUsuarios() {
return await this.userRepo.find({
relations: ['tipoUsuario'],
take: 10,
order: {
idUsuario: 'DESC', // Ordenar por el más reciente primero
},
});
}*/ // no subir a produccion
}