se actualizo la funcion de carga masiva

This commit is contained in:
evenegas
2026-01-09 12:54:22 -06:00
parent cea7375e3b
commit bdd7b1dd9a
+157 -278
View File
@@ -40,7 +40,7 @@ export class UsuariosService {
private readonly movimientoService: MovimientoService,
private readonly mailService: MailService,
private readonly excelService: ExcelService, // Asegúrate de importar el servicio de Excel
) {}
) { }
altaIndividual(createUsuarioDto: CreateUsuarioDto) {
return 'This action adds a new usuario';
@@ -159,17 +159,10 @@ export class UsuariosService {
fechaNacimiento: string;
rfc: string;
genero: string;
correoPersonal: string;
nombramiento: string;
unidadResponsable: string;
curp: string;
}
const apiUrl = process.env.API_URL;
if (!apiUrl) {
console.error('API_URL no está definida en las variables de entorno');
return;
}
if (!apiUrl) return;
const entrada: DatosEntrada = {
Nombre: '',
@@ -186,314 +179,200 @@ export class UsuariosService {
body: JSON.stringify(entrada),
});
if (response.status === 400) {
const errorText = await response.text();
console.error('Error 400:', errorText);
return;
} else if (response.status === 204) {
console.log(
'No se encontraron datos conforme a los criterios de búsqueda',
);
return;
}
if (!response.ok) return;
if (!response.ok)
throw new Error('Error en la petición: ' + response.statusText);
const json: DatosRespuesta[] = await response.json();
const profesores: DatosRespuesta[] = await response.json();
let nuevos = 0;
let actualizados = 0;
let existe = await this.tipoUsuarioRepository.findOne({
/* ==========================
TIPO USUARIO PROFESOR
========================== */
let tipoProfesor = await this.tipoUsuarioRepository.findOne({
where: { tipo_usuario: 'Profesor' },
});
if (!existe) {
const tipoUsuario = this.tipoUsuarioRepository.create({
tipo_usuario: 'Profesor',
});
existe = await this.tipoUsuarioRepository.save(tipoUsuario);
if (!tipoProfesor) {
tipoProfesor = await this.tipoUsuarioRepository.save(
this.tipoUsuarioRepository.create({ tipo_usuario: 'Profesor' }),
);
}
for (const prof of json) {
try {
if (!prof.rfc || !prof.nombre) {
console.warn('Profesor con datos incompletos detectado:', prof);
continue;
}
/* ==========================
CACHE DE CARRERAS
========================== */
const carreraCache = new Map<string, any>();
const existente = await this.usuarioRepository.findOne({
where: { rfc: prof.rfc },
relations: ['genero'],
for (const prof of profesores) {
if (!prof.rfc || !prof.nombre) continue;
const usuario = await this.usuarioRepository.findOne({
where: { rfc: prof.rfc },
relations: ['genero'],
});
/* ==========================
NORMALIZAR CARRERA
========================== */
const nombreCarrera = prof.nombreCarrera?.trim().toUpperCase();
let carrera = carreraCache.get(nombreCarrera);
if (!carrera && nombreCarrera) {
carrera = await this.carreraRepository.findOne({
where: { carrera: nombreCarrera },
});
if (!existente) {
let genero: Genero | null = null;
if (prof.genero === 'M' || prof.genero === 'F') {
const generoTexto =
prof.genero === 'M' ? 'Masculino' : 'Femenino';
genero = await this.generoRepository.findOne({
where: { genero: generoTexto },
});
if (!genero) {
genero = await this.generoRepository.create({
genero: generoTexto,
});
await this.generoRepository.save(genero);
}
}
let carrera = await this.carreraRepository.findOne({
where: { carrera: prof.nombreCarrera.trim() },
});
if (!carrera) {
const nuevaCarrera = await this.carreraRepository.create({
carrera: prof.nombreCarrera.trim(),
if (!carrera) {
carrera = await this.carreraRepository.save(
this.carreraRepository.create({
carrera: nombreCarrera,
clave: '',
});
carrera = await this.carreraRepository.save(nuevaCarrera);
}
}),
);
}
const nuevo = await this.usuarioRepository.create({
num_cuenta:
prof.numeroTrabajador == '' ? undefined : prof.numeroTrabajador,
carreraCache.set(nombreCarrera, carrera);
}
/* ==========================
USUARIO NUEVO
========================== */
if (!usuario) {
let genero;
if (prof.genero === 'M' || prof.genero === 'F') {
const generoTexto = prof.genero === 'M' ? 'Masculino' : 'Femenino';
genero =
(await this.generoRepository.findOne({
where: { genero: generoTexto },
})) ??
(await this.generoRepository.save(
this.generoRepository.create({ genero: generoTexto }),
));
}
const nuevoUsuario = await this.usuarioRepository.save(
this.usuarioRepository.create({
num_cuenta: prof.numeroTrabajador || undefined,
nombre: prof.nombre,
a_paterno: prof.apellidoPaterno,
a_materno: prof.apellidoMaterno,
rfc: prof.rfc,
fecha_nacimiento: prof.fechaNacimiento,
genero,
movimiento: mov,
});
}),
);
const savedUser = await this.usuarioRepository.save(nuevo);
const servActivo = await this.servActivosRepository.create({
await this.servActivosRepository.save(
this.servActivosRepository.create({
usuario: nuevoUsuario,
AT: !!prof.numeroTrabajador,
Red: !!prof.numeroTrabajador,
Prestamos: !!prof.numeroTrabajador,
Correo: true,
ATStatus: 'Inactivo',
RedStatus: 'Inactivo',
PrestamosStatus: 'Inactivo',
CorreoStatus: 'Inactivo',
usuario: savedUser,
AT: prof.numeroTrabajador !== '',
Red: prof.numeroTrabajador !== '',
Prestamos: prof.numeroTrabajador !== '',
Correo: true,
});
await this.servActivosRepository.save(servActivo);
const userCarrera = await this.carreraUsuario.create({
carrera,
usuario: savedUser,
});
const usuarioTipo = await this.usuarioTipoUsuario.create({
tipoUsuario: existe,
usuario: savedUser,
});
await this.carreraUsuario.save(userCarrera);
await this.usuarioTipoUsuario.save(usuarioTipo);
nuevos++;
} else {
let cambios = false;
if (existente.nombre !== prof.nombre) {
existente.nombre = prof.nombre;
const servActivo = await this.servActivosRepository.findOne({
where: { usuario: { id_usuario: existente.id_usuario } },
});
if (servActivo) {
servActivo.Red = true;
servActivo.AT = true;
servActivo.Prestamos = true;
servActivo.ATStatus = 'Inactivo';
servActivo.PrestamosStatus = 'Inactivo';
servActivo.RedStatus = 'Inactivo';
await this.servActivosRepository.save(servActivo);
} else {
console.warn(
'No se encontró el servicio activo para el usuario:',
existente,
);
}
cambios = true;
}
if (existente.a_paterno !== prof.apellidoPaterno) {
existente.a_paterno = prof.apellidoPaterno;
const servActivo = await this.servActivosRepository.findOne({
where: { usuario: { id_usuario: existente.id_usuario } },
});
if (servActivo) {
servActivo.Red = true;
servActivo.AT = true;
servActivo.Prestamos = true;
servActivo.ATStatus = 'Inactivo';
servActivo.PrestamosStatus = 'Inactivo';
servActivo.RedStatus = 'Inactivo';
await this.servActivosRepository.save(servActivo);
} else {
console.warn(
'No se encontró el servicio activo para el usuario:',
existente,
);
}
cambios = true;
}
if (existente.a_materno !== prof.apellidoMaterno) {
existente.a_materno = prof.apellidoMaterno;
const servActivo = await this.servActivosRepository.findOne({
where: { usuario: { id_usuario: existente.id_usuario } },
});
if (servActivo) {
servActivo.Red = true;
servActivo.AT = true;
servActivo.Prestamos = true;
servActivo.ATStatus = 'Inactivo';
servActivo.PrestamosStatus = 'Inactivo';
servActivo.RedStatus = 'Inactivo';
await this.servActivosRepository.save(servActivo);
} else {
console.warn(
'No se encontró el servicio activo para el usuario:',
existente,
);
}
cambios = true;
}
if (existente.rfc !== prof.rfc) {
existente.rfc = prof.rfc;
const servActivo = await this.servActivosRepository.findOne({
where: { usuario: { id_usuario: existente.id_usuario } },
});
if (servActivo) {
servActivo.Red = true;
servActivo.Prestamos = true;
servActivo.PrestamosStatus = 'Inactivo';
servActivo.RedStatus = 'Inactivo';
await this.servActivosRepository.save(servActivo);
} else {
console.warn(
'No se encontró el servicio activo para el usuario:',
existente,
);
}
cambios = true;
}
if (existente.fecha_nacimiento !== prof.fechaNacimiento) {
existente.fecha_nacimiento = prof.fechaNacimiento;
const servActivo = await this.servActivosRepository.findOne({
where: { usuario: { id_usuario: existente.id_usuario } },
});
if (servActivo) {
servActivo.Prestamos = true;
servActivo.Correo = true;
servActivo.PrestamosStatus = 'Inactivo';
servActivo.CorreoStatus = 'Inactivo';
await this.servActivosRepository.save(servActivo);
} else {
console.warn(
'No se encontró el servicio activo para el usuario:',
existente,
);
}
cambios = true;
}
if (
prof.numeroTrabajador &&
existente.num_cuenta !== prof.numeroTrabajador
) {
existente.num_cuenta = prof.numeroTrabajador;
const servActivo = await this.servActivosRepository.findOne({
where: { usuario: { id_usuario: existente.id_usuario } },
});
if (servActivo) {
servActivo.Red = true;
servActivo.AT = true;
servActivo.Correo = true;
servActivo.Prestamos = true;
servActivo.CorreoStatus = 'Inactivo';
servActivo.ATStatus = 'Inactivo';
servActivo.PrestamosStatus = 'Inactivo';
servActivo.RedStatus = 'Inactivo';
await this.servActivosRepository.save(servActivo);
} else {
console.warn(
'No se encontró el servicio activo para el usuario:',
existente,
);
}
cambios = true;
}
if (cambios) {
existente.movimiento = mov;
await this.usuarioRepository.save(existente);
actualizados++;
}
}
console.log(
`Progreso -> Nuevos: ${nuevos}, Actualizados: ${actualizados}`,
}),
);
} catch (innerError) {
console.error('Error procesando profesor:', prof, innerError);
await this.carreraUsuario.save(
this.carreraUsuario.create({
usuario: nuevoUsuario,
carrera,
}),
);
await this.usuarioTipoUsuario.save(
this.usuarioTipoUsuario.create({
usuario: nuevoUsuario,
tipoUsuario: tipoProfesor,
}),
);
nuevos++;
continue;
}
/* ==========================
USUARIO EXISTENTE
========================== */
let cambios = false;
const servActivo = await this.servActivosRepository.findOne({
where: { usuario: { id_usuario: usuario.id_usuario } },
});
const activarServicios = () => {
if (!servActivo) return;
servActivo.AT = true;
servActivo.Red = true;
servActivo.Prestamos = true;
servActivo.Correo = true;
servActivo.ATStatus = 'Inactivo';
servActivo.RedStatus = 'Inactivo';
servActivo.PrestamosStatus = 'Inactivo';
servActivo.CorreoStatus = 'Inactivo';
};
if (usuario.nombre !== prof.nombre) {
usuario.nombre = prof.nombre;
activarServicios();
cambios = true;
}
if (usuario.a_paterno !== prof.apellidoPaterno) {
usuario.a_paterno = prof.apellidoPaterno;
activarServicios();
cambios = true;
}
if (usuario.a_materno !== prof.apellidoMaterno) {
usuario.a_materno = prof.apellidoMaterno;
activarServicios();
cambios = true;
}
if (usuario.fecha_nacimiento !== prof.fechaNacimiento) {
usuario.fecha_nacimiento = prof.fechaNacimiento;
activarServicios();
cambios = true;
}
if (
prof.numeroTrabajador &&
usuario.num_cuenta !== prof.numeroTrabajador
) {
usuario.num_cuenta = prof.numeroTrabajador;
activarServicios();
cambios = true;
}
if (cambios) {
usuario.movimiento = mov;
await this.usuarioRepository.save(usuario);
if (servActivo) await this.servActivosRepository.save(servActivo);
actualizados++;
}
}
this.movimientoService.updateStatus(
await this.movimientoService.updateStatus(
mov.id_mov,
'SUCCESS',
'Carga masiva de web Service completa: ' +
`Nuevos: ${nuevos}, Actualizados: ${actualizados}`,
`Carga masiva finalizada. Nuevos: ${nuevos}, Actualizados: ${actualizados}`,
);
if (!process.env.EMAIL_USER) {
throw new Error();
}
this.mailService.sendMail({
to: process.env.EMAIL_USER,
subject: 'Carga de datos exitosa',
text:
'Carga masiva de web Service completa: ' +
`Nuevos: ${nuevos}, Actualizados: ${actualizados}`,
html: '',
});
this.excelService.enviarCargaMasiva({ nuevos, actualizados });
return `Importación finalizada. Nuevos: ${nuevos}, Actualizados: ${actualizados}`;
} catch (error) {
this.logger.error(
'Error al consultar profesores desde el WebService',
error,
);
this.logger.error('Error en carga masiva de profesores', error);
throw error;
}
}
async cargaIndividual(
usuario: CreateUsuarioDto,
origen: string,