se agrego drive correctamente

This commit is contained in:
evenegas
2026-01-08 11:33:55 -06:00
parent 9386fbc88d
commit 8f68aadd8a
2 changed files with 80 additions and 59 deletions
+50 -29
View File
@@ -8,49 +8,49 @@ import validator from "validator";
@Injectable()
export class ValidacionService {
constructor(
@InjectRepository(Servicio)
private servicioRepository:Repository<Servicio>,
){}
constructor(
@InjectRepository(Servicio)
private servicioRepository: Repository<Servicio>,
) { }
caracterEspecial(char) {
caracterEspecial(char) {
const charset = [' ', '.', ',', ':', ';', '?', '¿', '!', '¡', '(', ')', '"', "'", '-', '_', '/', '#', '%', '\n'];
return charset.includes(char);
}
yaExiste(campo, m) {
yaExiste(campo, m) {
throw new Error(`Ya se encuentra en uso ${m ? 'el' : 'la'} ${campo}.`);
}
noValido(campo, m, razon) {
noValido(campo, m, razon) {
throw new Error(`${m ? 'El' : 'La'} ${campo} no es valid${m ? 'o' : 'a'}, ${razon}.`);
}
noHay(variable, campo, m) {
noHay(variable, campo, m) {
if (!variable) throw new Error(`No se mando ${m ? 'el' : 'la'} ${campo}.`);
}
validacionBasicaStr(texto, campo, m, length) {
validacionBasicaStr(texto, campo, m, length) {
this.noHay(texto, campo, m);
if (typeof texto !== 'string') this.noValido(campo, m, 'no se mando una string');
if (length && texto.length > length) this.noValido(campo, m, 'tiene más caracteres de lo permitido');
return texto;
}
validarNumeroEntero(numero, campo, m: boolean = true) {
validarNumeroEntero(numero, campo, m: boolean = true) {
this.noHay(numero, campo, m);
if (typeof numero === 'number') numero = numero.toString();
if (!validator.isNumeric(numero, { no_symbols: true })) this.noValido(campo, m, 'no es un número entero válido');
return Number(numero);
}
validarCorreo(correo: any, length?: any, campo: string = 'correo', m: boolean = true) {
validarCorreo(correo: any, length?: any, campo: string = 'correo', m: boolean = true) {
this.validacionBasicaStr(correo, campo, m, length);
if (!validator.isEmail(correo)) this.noValido(campo, m, 'no es un correo válido');
return correo;
}
validarTexto(texto, campo, m, length) {
validarTexto(texto, campo, m, length) {
this.validacionBasicaStr(texto, campo, m, length);
for (const char of texto) {
if (!validator.isAlpha(char, 'es-ES') && char !== ' ' && char !== '.') {
@@ -60,7 +60,7 @@ export class ValidacionService {
return texto;
}
validarAlfanumerico(texto, campo, m, length) {
validarAlfanumerico(texto, campo, m, length) {
this.validacionBasicaStr(texto, campo, m, length);
for (const char of texto) {
if (!this.caracterEspecial(char) && !validator.isAlphanumeric(char, 'es-ES')) {
@@ -70,7 +70,7 @@ export class ValidacionService {
return texto;
}
validarNumeroCuenta(numeroCuenta, campo = 'numero de cuenta', m = true) {
validarNumeroCuenta(numeroCuenta, campo = 'numero de cuenta', m = true) {
this.validacionBasicaStr(numeroCuenta, campo, m, 9);
if (!validator.isNumeric(numeroCuenta, { no_symbols: true })) {
this.noValido(campo, m, 'tiene caracteres que no son números');
@@ -78,14 +78,14 @@ export class ValidacionService {
return numeroCuenta;
}
validarFecha(fecha, campo, m) {
validarFecha(fecha, campo, m) {
const fechaMoment = moment(fecha);
this.noHay(fecha, campo, m);
if (!fechaMoment.isValid()) this.noValido(campo, m, 'no es una fecha válida');
return fechaMoment;
}
validarNumero(numero, campo, m, length, no_symbols = true, makeNumber = false) {
validarNumero(numero, campo, m, length, no_symbols = true, makeNumber = false) {
this.validacionBasicaStr(numero, campo, m, length);
if (!validator.isNumeric(numero, { no_symbols })) {
this.noValido(campo, m, 'tiene caracteres que no son números');
@@ -93,26 +93,47 @@ export class ValidacionService {
return makeNumber ? Number(numero) : numero;
}
validarObjetoVacio(obj) {
validarObjetoVacio(obj) {
return Object.keys(obj).length === 0;
}
async validarPreTermino(idServicio) {
const res = await this.servicioRepository.findOne({ where: { idServicio } });
async validarPreTermino(idServicio: number) {
const res = await this.servicioRepository.findOne({
where: { idServicio },
relations: [
'cuestionarioPrograma',
'cuestionarioPrograma2',
'cuestionarioAlumno',
'cuestionarioAlumno2',
],
});
if (!res) return '';
const tieneCuestionarioPrograma =
!!res.cuestionarioPrograma?.idCuestionarioPrograma ||
!!res.cuestionarioPrograma2?.idCuestionarioPrograma2;
const tieneCuestionarioAlumno =
!!res.cuestionarioAlumno?.idCuestionarioAlumno ||
!!res.cuestionarioAlumno2?.idCuestionarioAlumno2;
const tieneDocumentos =
!!res.cartaTermino && !!res.informeGlobal;
if (tieneCuestionarioPrograma && tieneCuestionarioAlumno && tieneDocumentos) {
await this.servicioRepository.update(idServicio, {
status: { idStatus: 5 },
});
if (
(res?.cuestionarioPrograma.idCuestionarioPrograma || res?.cuestionarioPrograma2.idCuestionarioPrograma2) &&
(res.cuestionarioAlumno.idCuestionarioAlumno || res.cuestionarioAlumno2.idCuestionarioAlumno2) &&
res.cartaTermino &&
res.informeGlobal
) {
await this.servicioRepository.update({ idServicio }, { status: {idStatus:5} });
return 'Este Servicio Social pasó a Término, espera a que COESI autorice tu liberación.';
}
return '';
}
validarCuestionarioAlumno2(body) {
validarCuestionarioAlumno2(body) {
const optionalKeys = ['p5', 'p8', 'p16', 'p18'];
if (Array.isArray(body.p1)) body.p1 = body.p1.join(', ');
@@ -143,7 +164,7 @@ export class ValidacionService {
return body;
}
validarCuestionarioPrograma2(body) {
validarCuestionarioPrograma2(body) {
const camposOpcionales = ['p6'];
if (Array.isArray(body.p1)) body.p1 = body.p1.join(', ');
@@ -166,7 +187,7 @@ export class ValidacionService {
throw new Error(`Falta la respuesta para la pregunta ${key}.`);
}
}
return body;
}
}
+30 -30
View File
@@ -1,6 +1,7 @@
import {
BadRequestException,
Injectable,
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common';
import { CrearServicioDto } from './dto/create-servicio.dto';
@@ -358,13 +359,10 @@ export class ServicioService {
idServicioParam: number,
archivo: Express.Multer.File,
): Promise<{ message: string }> {
// 🔹 Validar idServicio
const idServicio: number = this.validacionService.validarNumeroEntero(
idServicioParam,
'id servicio',
);
// Agregue estas lineas
const idServicio: number =
this.validacionService.validarNumeroEntero(idServicioParam, 'id servicio');
if (!archivo) {
throw new BadRequestException('No se recibió el archivo');
}
@@ -374,17 +372,7 @@ export class ServicioService {
}
const rutaArchivo = `./server/uploads/${archivo.filename}`;
// Hasta aqui termine de agregar las lineas
// 🔹 Validar archivo y generar path local
// const rutaArchivo: string = `./server/uploads/${this.validacionService.validacionBasicaStr(
// archivo,
// 'archivo',
// true,
// 1000,
// )}`;
// 🔹 Buscar servicio
const servicio = await this.servicioRepo.findOne({
where: { idServicio },
relations: ['status'],
@@ -394,22 +382,30 @@ export class ServicioService {
throw new NotFoundException('Este servicio no existe.');
}
if (!servicio.status?.idStatus) {
throw new BadRequestException('El servicio no tiene un status válido.');
}
if (servicio.cartaTermino) {
throw new BadRequestException('Ya se subió la Carta de Termino.');
}
// 🔹 Validar status y subir archivo si corresponde
let archivoSubido;
let archivoSubido: string;
switch (servicio.status.idStatus) {
case 4:
case 8:
archivoSubido = await this.driveService.uploadFile(
rutaArchivo,
'Carta_Termino.pdf',
'application/pdf',
servicio.carpeta,
);
try {
archivoSubido = await this.driveService.uploadFile(
rutaArchivo,
'Carta_Termino.pdf',
'application/pdf',
servicio.carpeta,
);
} catch (err) {
if (fs.existsSync(rutaArchivo)) fs.unlinkSync(rutaArchivo);
throw err;
}
break;
case 1:
@@ -427,29 +423,33 @@ export class ServicioService {
case 7:
case 9:
throw new BadRequestException(
'Este Servicio Social se encuentra rechazado. No se puede avanzar hasta que se corrija lo necesario.',
'Este Servicio Social se encuentra rechazado.',
);
case 10:
throw new BadRequestException(
'Este Servicio Social está cancelado. Comunícate con COESI para solucionar tu problema.',
'Este Servicio Social está cancelado.',
);
default:
throw new BadRequestException('Id status no válido.');
}
// 🔹 Actualizar el servicio con la carta subida
await this.servicioRepo.update(idServicio, { cartaTermino: archivoSubido });
if (!archivoSubido) {
throw new InternalServerErrorException('Error al subir archivo.');
}
await this.servicioRepo.update(idServicio, {
cartaTermino: archivoSubido,
});
// 🔹 Ejecutar validaciones adicionales (pre-termino)
const resultadoPreTermino =
await this.validacionService.validarPreTermino(idServicio);
// 🔹 Retornar mensaje
return {
message: `Se subió la Carta de Termino correctamente. ${resultadoPreTermino}`,
};
}
async generarGustavoBazPrada(yearParam: number): Promise<string> {
// 🔹 Validar año
const year: number = this.validacionService.validarNumero(