Se corrigió envio de correos y creacion de controller servicio

This commit is contained in:
2025-10-21 14:54:31 -06:00
parent 86b0096350
commit de24bdeec0
11 changed files with 709 additions and 432 deletions
+231 -66
View File
@@ -11,7 +11,6 @@ import { Servicio } from './entities/servicio.entity';
import { Usuario } from 'src/usuario/entities/usuario.entity';
import { ValidacionService } from 'src/helpers.services/validacion.service';
import { gmail } from 'src/helpers.services/gmail.service';
import { SendCorreoDto } from 'src/helpers.services/dto/send-email.dto';
import { DriveService } from 'src/drive/drive.service';
import moment from 'moment';
import { ArchivoService } from 'src/helpers.services/archivo.service';
@@ -22,6 +21,8 @@ import { AuthService } from 'src/auth/auth.service';
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';
@Injectable()
export class ServicioService {
@@ -211,7 +212,7 @@ export class ServicioService {
const correoAlumno = canceladoAlumno(mensaje, alumno.nombre);
const correoResponsable = canceladoResponsable(mensaje, alumno.nombre);
const sendCorreoAlumnoDto: SendCorreoDto = {
const sendCorreoAlumnoDto: SendMailDto = {
to: servicio.correo,
subject: correoAlumno.subject,
fecha_recibido: new Date(),
@@ -220,7 +221,7 @@ export class ServicioService {
adjuntos: undefined,
};
const sendCorreoResponsableDto: SendCorreoDto = {
const sendCorreoResponsableDto: SendMailDto = {
to: responsable.usuario,
subject: correoResponsable.subject,
fecha_recibido: new Date(),
@@ -234,17 +235,11 @@ export class ServicioService {
}
if (servicio.correo) {
await this.gmailService.send(
sendCorreoAlumnoDto,
process.env.TOKEN_GMAIL,
);
await this.gmailService.enviarCorreo(sendCorreoAlumnoDto);
}
if (responsable.usuario) {
await this.gmailService.send(
sendCorreoResponsableDto,
process.env.TOKEN_GMAIL,
);
await this.gmailService.enviarCorreo(sendCorreoResponsableDto);
}
// Desactivar al usuario (alumno)
@@ -588,16 +583,12 @@ export class ServicioService {
const correoAlumno = terminoValidado(servicio.usuario.nombre);
if (servicio.correo) {
await this.gmailService.sendMail(
{
to: servicio.correo,
subject: correoAlumno.subject,
text: correoAlumno.msj,
html: '',
fecha_recibido: new Date(),
},
process.env.TOKEN_GMAIL,
);
await this.gmailService.enviarCorreo({
to: servicio.correo,
subject: correoAlumno.subject,
text: correoAlumno.msj,
fecha_recibido: new Date(),
});
}
break;
@@ -763,11 +754,12 @@ export class ServicioService {
emailResponsable = servicio.programa.usuario.usuario; // correo del responsable
// Enviar correo al alumno
await this.gmailService.enviarCorreo(
correoAlumno.subject,
servicio.correo,
correoAlumno.msj,
);
await this.gmailService.enviarCorreo({
subject: correoAlumno.subject,
to: servicio.correo,
text: correoAlumno.msj,
fecha_recibido: new Date(),
});
break;
case 2:
@@ -796,11 +788,12 @@ export class ServicioService {
}
// Enviar correo al responsable
await this.gmailService.enviarCorreo(
correoResponsable.subject,
emailResponsable,
correoResponsable.msj,
);
await this.gmailService.enviarCorreo({
subject: correoResponsable.subject,
to: emailResponsable,
text: correoResponsable.msj,
fecha_recibido: new Date(),
});
// Actualizar estado del servicio
await this.servicioRepo.update(idServicio, {
@@ -836,11 +829,12 @@ export class ServicioService {
);
emailResponsable = servicio.programa.usuario.usuario; // correo responsable
await this.gmailService.enviarCorreo(
correoAlumno.subject,
servicio.correo,
correoAlumno.msj,
);
await this.gmailService.enviarCorreo({
subject: correoAlumno.subject,
to: servicio.correo,
text: correoAlumno.msj,
fecha_recibido: new Date(),
});
break;
}
@@ -874,11 +868,12 @@ export class ServicioService {
}
// Enviar correo al responsable
await this.gmailService.enviarCorreo(
correoResponsable.subject,
emailResponsable,
correoResponsable.msj,
);
await this.gmailService.enviarCorreo({
subject: correoResponsable.subject,
to: emailResponsable,
text: correoResponsable.msj,
fecha_recibido: new Date(),
});
// Actualizar estado del servicio
await this.servicioRepo.update(idServicio, {
@@ -916,11 +911,12 @@ export class ServicioService {
);
emailResponsable = servicio.programa.usuario.usuario;
await this.gmailService.enviarCorreo(
correoAlumno.subject,
servicio.correo,
correoAlumno.msj,
);
await this.gmailService.enviarCorreo({
subject: correoAlumno.subject,
to: servicio.correo,
text: correoAlumno.msj,
fecha_recibido: new Date(),
});
break;
}
@@ -954,11 +950,12 @@ export class ServicioService {
}
// Enviar correo al responsable
await this.gmailService.enviarCorreo(
correoResponsable.subject,
emailResponsable,
correoResponsable.msj,
);
await this.gmailService.enviarCorreo({
subject: correoResponsable.subject,
to: emailResponsable,
text: correoResponsable.msj,
fecha_recibido: new Date(),
});
// Actualizar el servicio
await this.servicioRepo.update(idServicio, {
@@ -988,11 +985,12 @@ export class ServicioService {
case 1:
correoData = preRegistro(password, servicio.usuario.nombre);
idUsuario = servicio.usuario.idUsuario;
await this.gmailService.enviarCorreo(
correoData.subject,
servicio.correo,
correoData.msj,
);
await this.gmailService.enviarCorreo({
subject: correoData.subject,
to: servicio.correo,
text: correoData.msj,
fecha_recibido: new Date(),
});
break;
case 2:
@@ -1061,11 +1059,12 @@ export class ServicioService {
servicio.usuario.nombre,
);
emailResponsable = servicio.programa.usuario.usuario;
await this.gmailService.enviarCorreo(
correoAlumno.subject,
servicio.correo,
correoAlumno.msj,
);
await this.gmailService.enviarCorreo({
subject: correoAlumno.subject,
to: servicio.correo,
text: correoAlumno.msj,
fecha_recibido: new Date(),
});
break;
case 1:
@@ -1097,11 +1096,12 @@ export class ServicioService {
throw new BadRequestException('Id status no válido.');
}
await this.gmailService.enviarCorreo(
correoResponsable.subject,
emailResponsable,
correoResponsable.msj,
);
await this.gmailService.enviarCorreo({
subject: correoResponsable.subject,
to: emailResponsable,
text: correoResponsable.msj,
fecha_recibido: new Date(),
});
// Determinar estatus según modo
const tempStatus = process.env.MODE === 'pruebas' ? 4 : 3;
@@ -1202,4 +1202,169 @@ export class ServicioService {
return { count, serviciosAdmin: servicios };
}
async obtenerServiciosResponsable(dto: ServiciosResponsableDto) {
const {
idUsuario,
idStatus,
nombre = '',
numeroCuenta = '',
pagina = 1,
} = dto;
// 1️⃣ Validar que el usuario exista y sea responsable
const responsable = await this.usuarioRepo.findOne({
where: { idUsuario },
});
if (!responsable) throw new NotFoundException('No existe este usuario.');
if (responsable.tipoUsuario.idTipoUsuario !== 2)
throw new BadRequestException('No es un usuario tipo responsable.');
// 2️⃣ Crear el query builder
const query = this.servicioRepo
.createQueryBuilder('servicio')
.innerJoinAndSelect('servicio.usuario', 'usuario')
.innerJoinAndSelect('servicio.programa', 'programa')
.innerJoinAndSelect('servicio.carrera', 'carrera')
.innerJoinAndSelect('servicio.status', 'status')
.where('programa.idUsuario = :idUsuario', { idUsuario })
.andWhere('usuario.usuario LIKE :numeroCuenta', {
numeroCuenta: `%${numeroCuenta}%`,
})
.andWhere('usuario.nombre LIKE :nombre', { nombre: `%${nombre}%` });
// 3️⃣ Filtro de estatus
if (idStatus) {
query.andWhere('status.idStatus = :idStatus', { idStatus });
} else {
query.andWhere('status.idStatus != :status', { status: 10 });
}
// 4️⃣ Orden, paginación y selección de campos
query
.select([
'servicio.idServicio',
'servicio.fechaInicio',
'servicio.fechaFin',
'servicio.cartaTermino',
'servicio.createdAt',
'servicio.idCuestionarioPrograma',
'servicio.idCuestionarioPrograma2',
'usuario.idUsuario',
'usuario.usuario',
'usuario.nombre',
'carrera.idCarrera',
'carrera.carrera',
'status.idStatus',
'status.status',
])
.orderBy('servicio.updatedAt', 'DESC')
.skip(25 * (pagina - 1))
.take(25);
// 5️⃣ Ejecutar y obtener datos + total
const [rows, count] = await query.getManyAndCount();
// 6️⃣ Retornar resultado en el mismo formato que antes
return { count, serviciosResponsable: rows };
}
async update(
body: UpdateServicioDto,
files: Record<string, Express.Multer.File[]>,
) {
const idServicio = body.idServicio;
const servicio = await this.servicioRepo.findOne({ where: { idServicio } });
if (!servicio)
throw new NotFoundException(
'Este Servicio Social no existe en la base de datos.',
);
let dataUpdate: Partial<Servicio> = {};
// ---- 📁 Subida de archivos a Drive ----
try {
if (files?.['cartaAceptacion']?.[0]?.filename) {
{
const result = await this.driveService.uploadFile(
`./server/uploads/${files['cartaAceptacion'][0].filename}`,
`Carta_Aceptacion.pdf`,
'application/pdf',
servicio.carpeta,
);
dataUpdate.cartaAceptacion = result === null ? undefined : result;
}
}
} catch (err) {}
try {
if (files?.['cartaTermino']?.[0]?.filename) {
{
const result = await this.driveService.uploadFile(
`./server/uploads/${files['cartaTermino'][0].filename}`,
`Carta_Termino.pdf`,
'application/pdf',
servicio.carpeta,
);
dataUpdate.cartaTermino = result === null ? undefined : result;
}
}
} catch (err) {}
try {
if (files?.['informeGlobal']?.[0]?.filename) {
const result = await this.driveService.uploadFile(
`./server/uploads/${files['informeGlobal'][0].filename}`,
`Informe_Global.pdf`,
'application/pdf',
servicio.carpeta,
);
dataUpdate.informeGlobal = result === null ? undefined : result;
}
} catch (err) {}
// ---- 📆 Validaciones de campos del body ----
if (body.correo) dataUpdate.correo = body.correo;
if (body.fechaInicio) dataUpdate.fechaInicio = body.fechaInicio;
if (body.fechaFin) dataUpdate.fechaFin = body.fechaFin;
if (body.fechaNacimiento) dataUpdate.fechaNacimiento = body.fechaNacimiento;
if (body.direccion)
dataUpdate.direccion = this.validacionService.validarAlfanumerico(
body.direccion,
'dirección',
false,
200,
);
if (body.telefono)
dataUpdate.telefono = this.validacionService.validarNumero(
body.telefono,
'teléfono',
true,
15,
);
if (this.validacionService.validarObjetoVacio(dataUpdate)) {
throw new BadRequestException(
'No se envió nada para actualizar este Servicio Social.',
);
}
// ---- 🧱 Actualización en la base ----
await this.servicioRepo
.createQueryBuilder()
.update(Servicio)
.set(dataUpdate)
.where('idServicio = :idServicio', { idServicio })
.execute();
// ---- ✅ Validar si se requiere "pre-término" ----
if (dataUpdate.cartaTermino || dataUpdate.informeGlobal) {
await this.validacionService.validarPreTermino(idServicio);
}
return {
message: 'Se guardaron correctamente los cambios de este servicio.',
};
}
}