Compare commits
43 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f653d12ff9 | |||
| dde68bbee1 | |||
| f33977c2f6 | |||
| c79c2e8fc5 | |||
| 9ae678e7f4 | |||
| 1b0ac5828d | |||
| c328383ec0 | |||
| 2e7d01552d | |||
| a288c37531 | |||
| 656126919b | |||
| 8104fd35ff | |||
| 9ad749782f | |||
| c5722bfe02 | |||
| 08745e2a7e | |||
| 6afc4cdae8 | |||
| c1283ae9fa | |||
| 4f0ef219ec | |||
| 2c91c9cb34 | |||
| 104f67d07e | |||
| ea0dc8aba0 | |||
| bdd7b1dd9a | |||
| cea7375e3b | |||
| e2850c20a3 | |||
| c9ce5d6e3a | |||
| 91a1fa5f51 | |||
| 9d15183601 | |||
| 55e64da38d | |||
| 8c6502d82c | |||
| 8143b91714 | |||
| d34f308ab8 | |||
| c742fa114d | |||
| 6e12e580e1 | |||
| d9550f1bf1 | |||
| 784b8b1205 | |||
| 0ae79f833e | |||
| d8d2154cbe | |||
| 8ad6db15dc | |||
| 8a35c6d2ae | |||
| 3206b4b824 | |||
| 5ee90345f5 | |||
| 46d889fbfb | |||
| 3cbb1536fc | |||
| 6ff1526650 |
@@ -1,14 +1,17 @@
|
|||||||
version: '3.9'
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
database:
|
database:
|
||||||
image: mariadb:latest
|
image: mariadb:latest
|
||||||
container_name: carga_db
|
container_name: carga_db
|
||||||
restart: always
|
restart: always
|
||||||
|
environment:
|
||||||
|
- MARIADB_ROOT_PASSWORD=root
|
||||||
|
- MARIADB_DATABASE=carga_test
|
||||||
|
- MARIADB_USER=miusuario
|
||||||
|
- MARIADB_PASSWORD=root
|
||||||
env_file:
|
env_file:
|
||||||
- ../.env
|
- ../.env
|
||||||
ports:
|
ports:
|
||||||
- "${DB_PORT}:3306"
|
- '${DB_PORT}:3306'
|
||||||
volumes:
|
volumes:
|
||||||
- mariadb_data:/var/lib/mysql
|
- mariadb_data:/var/lib/mysql
|
||||||
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
|
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
|
||||||
|
|||||||
Generated
+719
-595
File diff suppressed because it is too large
Load Diff
+3
-2
@@ -8,7 +8,7 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "nest build",
|
"build": "nest build",
|
||||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
"start": "nest start",
|
"start": "source ~/.nvm/nvm.sh && nvm use 22.10.0 && npm install && nest start",
|
||||||
"start:dev": "nest start --watch",
|
"start:dev": "nest start --watch",
|
||||||
"start:debug": "nest start --debug --watch",
|
"start:debug": "nest start --debug --watch",
|
||||||
"start:prod": "node dist/main",
|
"start:prod": "node dist/main",
|
||||||
@@ -38,10 +38,11 @@
|
|||||||
"mysql2": "^3.14.1",
|
"mysql2": "^3.14.1",
|
||||||
"nodemailer": "^7.0.3",
|
"nodemailer": "^7.0.3",
|
||||||
"passport": "^0.7.0",
|
"passport": "^0.7.0",
|
||||||
|
"passport-google-oauth20": "^2.0.0",
|
||||||
"passport-jwt": "^4.0.1",
|
"passport-jwt": "^4.0.1",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
"rxjs": "^7.8.1",
|
"rxjs": "^7.8.1",
|
||||||
"typeorm": "^0.3.24"
|
"typeorm": "^0.3.26"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/eslintrc": "^3.2.0",
|
"@eslint/eslintrc": "^3.2.0",
|
||||||
|
|||||||
@@ -1,14 +1,36 @@
|
|||||||
import { AuthDocumentation } from './auth.documentation';
|
import { AuthDocumentation } from './auth.documentation';
|
||||||
import { Controller, Post, Body, UseGuards, Request, Get } from '@nestjs/common';
|
import { Controller, Post, Body, UseGuards, Request, Get, Req, Res } from '@nestjs/common';
|
||||||
import { AuthService } from './auth.service';
|
import { AuthService } from './auth.service';
|
||||||
import { LoginDto } from './dto/login.dto';
|
import { LoginDto } from './dto/login.dto';
|
||||||
import { AuthGuard } from '@nestjs/passport';
|
import { AuthGuard } from '@nestjs/passport';
|
||||||
import { RegisterDto } from './dto/register.dto';
|
import { RegisterDto } from './dto/register.dto';
|
||||||
import { ApiBearerAuth } from '@nestjs/swagger';
|
import { ApiBearerAuth } from '@nestjs/swagger';
|
||||||
|
import { SetPasswordDto } from './dto/createPassword.dto';
|
||||||
|
import { Response } from 'express';
|
||||||
|
import { WhiteDto } from './dto/whiteList.dto';
|
||||||
|
import { GoogleAuthGuard } from './google-auth.guard';
|
||||||
|
|
||||||
|
interface Update{
|
||||||
|
id:string;
|
||||||
|
nombreNuevo:string;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
@Controller()
|
@Controller()
|
||||||
export class AuthController {
|
export class AuthController {
|
||||||
constructor(private readonly authService: AuthService) { }
|
constructor(private readonly authService: AuthService) { }
|
||||||
|
//Comentar en producciòn
|
||||||
|
|
||||||
|
@Post('update')
|
||||||
|
async update(@Body() user:Update) {
|
||||||
|
return this.authService.updateCorreo(user.id,user.nombreNuevo);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('findAll')
|
||||||
|
async findAll(){
|
||||||
|
this.authService.all()
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
@Post('login')
|
@Post('login')
|
||||||
@AuthDocumentation.login()
|
@AuthDocumentation.login()
|
||||||
@@ -37,12 +59,83 @@ export class AuthController {
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Post('register')
|
@Post('register')
|
||||||
@AuthDocumentation.register() // ver siguiente sección
|
@AuthDocumentation.register() // ver siguiente sección
|
||||||
async register(@Body() dto: RegisterDto) {
|
async register(@Body() dto: RegisterDto) {
|
||||||
return this.authService.register(dto);
|
return this.authService.register(dto);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post('white-list')
|
||||||
|
@AuthDocumentation.white()
|
||||||
|
async newRegister(@Body() dto:WhiteDto){
|
||||||
|
|
||||||
|
return this.authService.white(dto)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//Inicio de sesión con GOOGLE
|
||||||
|
|
||||||
|
@Get('google')
|
||||||
|
@UseGuards(AuthGuard('google'))
|
||||||
|
async googleLogin() {
|
||||||
|
return { msg: 'Redirigiendo a Google' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Callback de Google
|
||||||
|
// @Get('google/callback')
|
||||||
|
// @UseGuards(AuthGuard('google'))
|
||||||
|
// async googleCallback(@Req() req) {
|
||||||
|
// const user = req.user;
|
||||||
|
|
||||||
|
// if (user.needsPassword) {
|
||||||
|
// return {
|
||||||
|
// status: 'NEEDS_PASSWORD',
|
||||||
|
// email: user.correo,
|
||||||
|
// message: 'El usuario debe crear una contraseña antes de continuar',
|
||||||
|
// };
|
||||||
|
// }
|
||||||
|
|
||||||
|
// return this.authService.login(user); // genera JWT
|
||||||
|
// }
|
||||||
|
|
||||||
|
// auth.controller.ts
|
||||||
|
@Get('google/callback')
|
||||||
|
@UseGuards(GoogleAuthGuard)
|
||||||
|
async googleCallback(@Req() req, @Res() res: Response) {
|
||||||
|
const user = req.user;
|
||||||
|
|
||||||
|
if (user.needsPassword) {
|
||||||
|
|
||||||
|
return res.redirect(
|
||||||
|
`${process.env.FRONTEND_URL}/password?email=${user.correo}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const jwt = await this.authService.login(user);
|
||||||
|
|
||||||
|
|
||||||
|
return res.redirect(
|
||||||
|
`${process.env.FRONTEND_URL}/oauth-callback?token=${jwt.access_token}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//Inicio de sesión con GOOGLE
|
||||||
|
|
||||||
|
//Set-contraseña
|
||||||
|
// auth.controller.ts
|
||||||
|
|
||||||
|
|
||||||
|
@Post('set-password')
|
||||||
|
async setPassword(@Body() dto: SetPasswordDto) {
|
||||||
|
return this.authService.setPassword(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -101,4 +101,40 @@ export class AuthDocumentation {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static white() {
|
||||||
|
return applyDecorators(
|
||||||
|
ApiTags('Auth'),
|
||||||
|
ApiOperation({
|
||||||
|
summary: 'Registrar usuario',
|
||||||
|
description: 'Crea un nuevo usuario con correo y origen para una white list.'
|
||||||
|
}),
|
||||||
|
ApiConsumes('application/json'),
|
||||||
|
ApiBody({
|
||||||
|
schema: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
email: { type: 'string', format: 'email', example: 'nuevo@dominio.com' },
|
||||||
|
origen: { type: 'string', example: 'RED', description: 'Origen del usuario' }
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
ApiResponse({
|
||||||
|
status: 201,
|
||||||
|
description: 'Usuario creado correctamente',
|
||||||
|
schema: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
id_usuario: { type: 'number', example: 1 },
|
||||||
|
correo: { type: 'string', example: 'nuevo@dominio.com' },
|
||||||
|
origen: { type: 'string', example: 'RED' }
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
ApiResponse({ status: 409, description: 'El correo ya está registrado.' }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { AuthController } from './auth.controller';
|
|||||||
import { JwtStrategy } from './jwt.strategy';
|
import { JwtStrategy } from './jwt.strategy';
|
||||||
import { Origen, UsuariosDelSistema } from '../entities/entities';
|
import { Origen, UsuariosDelSistema } from '../entities/entities';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { GoogleStrategy } from './google.strategy';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -22,7 +23,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';
|
|||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
providers: [AuthService, JwtStrategy],
|
providers: [AuthService, JwtStrategy, GoogleStrategy],
|
||||||
controllers: [AuthController],
|
controllers: [AuthController],
|
||||||
})
|
})
|
||||||
export class AuthModule { }
|
export class AuthModule { }
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import { InjectRepository } from '@nestjs/typeorm';
|
|||||||
import { Origen, UsuariosDelSistema } from '../entities/entities';
|
import { Origen, UsuariosDelSistema } from '../entities/entities';
|
||||||
import * as bcrypt from 'bcrypt';
|
import * as bcrypt from 'bcrypt';
|
||||||
import { RegisterDto } from './dto/register.dto';
|
import { RegisterDto } from './dto/register.dto';
|
||||||
|
import { SetPasswordDto } from './dto/createPassword.dto';
|
||||||
|
import { WhiteDto } from './dto/whiteList.dto';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AuthService {
|
export class AuthService {
|
||||||
@@ -39,8 +41,23 @@ export class AuthService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async updateCorreo(id: string, nombreNuevo: string) {
|
||||||
|
|
||||||
|
const usuarios = await this.userRepo.findOne({ where: { id_usuario: id } })
|
||||||
|
|
||||||
|
if (!usuarios) { throw new Error("usuaro no existe") }
|
||||||
|
usuarios.correo = nombreNuevo;
|
||||||
|
|
||||||
|
return await this.userRepo.save(usuarios);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async all() {
|
||||||
|
|
||||||
|
const usuarios = await this.userRepo.find()
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
async register(dto: RegisterDto) {
|
async register(dto: RegisterDto) {
|
||||||
// 1) Verificar duplicado
|
// 1) Verificar duplicado
|
||||||
@@ -75,4 +92,93 @@ export class AuthService {
|
|||||||
const { contraseña, ...result } = saved;
|
const { contraseña, ...result } = saved;
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async white(dto: WhiteDto) {
|
||||||
|
// 1) Verificar duplicado
|
||||||
|
const exists = await this.userRepo.findOne({ where: { correo: dto.email } });
|
||||||
|
if (exists) {
|
||||||
|
throw new ConflictException('El correo ya está registrado');
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
let origen = await this.origenRepo.findOne({ where: { origen: dto.origen } });
|
||||||
|
|
||||||
|
if (!origen) {
|
||||||
|
origen = this.origenRepo.create({ origen: dto.origen });
|
||||||
|
origen = await this.origenRepo.save(origen);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// 3) Crear entidad Usuario
|
||||||
|
const user = this.userRepo.create({
|
||||||
|
correo: dto.email,
|
||||||
|
contraseña: undefined,
|
||||||
|
origen: origen,
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
// 4) Guardar en BD
|
||||||
|
const saved = await this.userRepo.save(user);
|
||||||
|
|
||||||
|
// 5) Devolver sin contraseña
|
||||||
|
const { contraseña, ...result } = saved;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async validateGoogleUser(email: string) {
|
||||||
|
const user = await this.userRepo.findOne({ where: { correo: email }, relations: ['origen'] });
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
// No permitir crear cuenta
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!user.contraseña) {
|
||||||
|
// Usuario existe pero nunca puso contraseña → permitirle definirla
|
||||||
|
return {
|
||||||
|
...user,
|
||||||
|
needsPassword: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Usuario con contraseña → login normal
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
//Poner contraseñas
|
||||||
|
// auth.service.ts
|
||||||
|
async setPassword(dto: SetPasswordDto) {
|
||||||
|
const user = await this.userRepo.findOne({
|
||||||
|
where: { correo: dto.email },
|
||||||
|
relations: ['origen'],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
throw new UnauthorizedException('Usuario no encontrado');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (user.contraseña) {
|
||||||
|
throw new ConflictException('Este usuario ya tiene contraseña');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hash contraseña nueva
|
||||||
|
const hash = await bcrypt.hash(dto.password, 10);
|
||||||
|
|
||||||
|
user.contraseña = hash;
|
||||||
|
const updated = await this.userRepo.save(user);
|
||||||
|
|
||||||
|
// Retornar con JWT inmediato (login automático)
|
||||||
|
const payload = { sub: updated.id_usuario, email: updated.correo, tipo: updated.origen.origen };
|
||||||
|
|
||||||
|
return {
|
||||||
|
access_token: this.jwtService.sign(payload),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
// dto/set-password.dto.ts
|
||||||
|
import { IsEmail, IsNotEmpty, MinLength } from 'class-validator';
|
||||||
|
|
||||||
|
export class SetPasswordDto {
|
||||||
|
@IsEmail()
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@IsNotEmpty()
|
||||||
|
@MinLength(6)
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { IsEmail, IsString, MinLength, MaxLength, IsOptional, IsNumber } from 'class-validator';
|
||||||
|
|
||||||
|
export class WhiteDto {
|
||||||
|
@IsEmail()
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(60)
|
||||||
|
origen: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||||
|
import { AuthGuard } from '@nestjs/passport';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class GoogleAuthGuard extends AuthGuard('google') {
|
||||||
|
handleRequest(err, user, info, context) {
|
||||||
|
const res = context.switchToHttp().getResponse();
|
||||||
|
|
||||||
|
if (err) {
|
||||||
|
// redirige directamente y corta la ejecución
|
||||||
|
res.redirect(`${process.env.FRONTEND_URL}?error=oauth_failed`);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
return user; // si existe, sigue normalmente
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
// google.strategy.ts
|
||||||
|
import { PassportStrategy } from '@nestjs/passport';
|
||||||
|
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||||
|
import { Strategy, VerifyCallback } from 'passport-google-oauth20';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
|
||||||
|
constructor(
|
||||||
|
private readonly authService: AuthService,
|
||||||
|
private readonly config: ConfigService,
|
||||||
|
) {
|
||||||
|
super({
|
||||||
|
clientID: config.get<string>('GOOGLE_CLIENT_ID'),
|
||||||
|
clientSecret: config.get<string>('GOOGLE_CLIENT_SECRET'),
|
||||||
|
callbackURL: config.get<string>('GOOGLE_CALLBACK_URL'),
|
||||||
|
scope: ['email', 'profile'],
|
||||||
|
failureRedirect: `${process.env.FRONTEND_URL}?error=oauth_failed`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async validate(
|
||||||
|
accessToken: string,
|
||||||
|
refreshToken: string,
|
||||||
|
profile: any,
|
||||||
|
done: VerifyCallback,
|
||||||
|
): Promise<any> {
|
||||||
|
try{
|
||||||
|
const { emails } = profile;
|
||||||
|
const email = emails[0].value;
|
||||||
|
|
||||||
|
const user = await this.authService.validateGoogleUser(email);
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return done(true, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return done(false, user);
|
||||||
|
}catch(err){
|
||||||
|
return done(true, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+46
-41
@@ -1,5 +1,14 @@
|
|||||||
import { ServActivos } from 'src/usuarios/entities/servActivos.entitie';
|
import { ServActivos } from 'src/usuarios/entities/servActivos.entitie';
|
||||||
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, OneToMany, JoinColumn, PrimaryColumn, OneToOne } from 'typeorm';
|
import {
|
||||||
|
Entity,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
Column,
|
||||||
|
ManyToOne,
|
||||||
|
OneToMany,
|
||||||
|
JoinColumn,
|
||||||
|
PrimaryColumn,
|
||||||
|
OneToOne,
|
||||||
|
} from 'typeorm';
|
||||||
|
|
||||||
@Entity({ name: 'origen' })
|
@Entity({ name: 'origen' })
|
||||||
export class Origen {
|
export class Origen {
|
||||||
@@ -9,22 +18,22 @@ export class Origen {
|
|||||||
@Column({ type: 'varchar', length: 30 })
|
@Column({ type: 'varchar', length: 30 })
|
||||||
origen: string;
|
origen: string;
|
||||||
|
|
||||||
@OneToMany(() => Movimiento, movimiento => movimiento.origen)
|
@OneToMany(() => Movimiento, (movimiento) => movimiento.origen)
|
||||||
movimientos: Movimiento[];
|
movimientos: Movimiento[];
|
||||||
|
|
||||||
@OneToMany(() => UsuariosDelSistema, uds => uds.origen)
|
@OneToMany(() => UsuariosDelSistema, (uds) => uds.origen)
|
||||||
usuariosDelSistema: UsuariosDelSistema[];
|
usuariosDelSistema: UsuariosDelSistema[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@Entity({ name: 'genero' })
|
@Entity({ name: 'genero' })
|
||||||
export class Genero {
|
export class Genero {
|
||||||
@PrimaryGeneratedColumn({ name: 'id_genero', type: 'int', })
|
@PrimaryGeneratedColumn({ name: 'id_genero', type: 'int' })
|
||||||
id_genero: number;
|
id_genero: number;
|
||||||
|
|
||||||
@Column({ type: 'varchar', length: 20, nullable: true })
|
@Column({ type: 'varchar', length: 20, nullable: true })
|
||||||
genero: string;
|
genero: string;
|
||||||
|
|
||||||
@OneToMany(() => Usuario, usuario => usuario.genero)
|
@OneToMany(() => Usuario, (usuario) => usuario.genero)
|
||||||
usuarios: Usuario[];
|
usuarios: Usuario[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,7 +48,7 @@ export class Carrera {
|
|||||||
@Column({ type: 'varchar', length: 6 })
|
@Column({ type: 'varchar', length: 6 })
|
||||||
clave: string;
|
clave: string;
|
||||||
|
|
||||||
@OneToMany(() => CarreraUsuario, cu => cu.carrera)
|
@OneToMany(() => CarreraUsuario, (cu) => cu.carrera)
|
||||||
carreraUsuarios: CarreraUsuario[];
|
carreraUsuarios: CarreraUsuario[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,7 +66,7 @@ export class Movimiento {
|
|||||||
@Column({
|
@Column({
|
||||||
type: 'varchar',
|
type: 'varchar',
|
||||||
length: 200,
|
length: 200,
|
||||||
nullable: true, // permite NULL
|
nullable: true, // permite NULL
|
||||||
})
|
})
|
||||||
observaciones?: string;
|
observaciones?: string;
|
||||||
|
|
||||||
@@ -67,20 +76,18 @@ export class Movimiento {
|
|||||||
@Column({
|
@Column({
|
||||||
type: 'varchar',
|
type: 'varchar',
|
||||||
length: 200,
|
length: 200,
|
||||||
nullable: true, // permite NULL
|
nullable: true, // permite NULL
|
||||||
})
|
})
|
||||||
reporte?: string;
|
reporte?: string;
|
||||||
|
|
||||||
@OneToMany(() => Usuario, usuario => usuario.movimiento)
|
@OneToMany(() => Usuario, (usuario) => usuario.movimiento)
|
||||||
usuario: Usuario[];
|
usuario: Usuario[];
|
||||||
|
|
||||||
|
@ManyToOne(() => Origen, (origen) => origen.movimientos)
|
||||||
@ManyToOne(() => Origen, origen => origen.movimientos)
|
|
||||||
@JoinColumn({ name: 'id_origen' })
|
@JoinColumn({ name: 'id_origen' })
|
||||||
origen: Origen;
|
origen: Origen;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Entity({ name: 'usuario' })
|
@Entity({ name: 'usuario' })
|
||||||
export class Usuario {
|
export class Usuario {
|
||||||
@PrimaryGeneratedColumn({ name: 'id_usuario', type: 'int' })
|
@PrimaryGeneratedColumn({ name: 'id_usuario', type: 'int' })
|
||||||
@@ -114,43 +121,51 @@ export class Usuario {
|
|||||||
})
|
})
|
||||||
rfc: string | null;
|
rfc: string | null;
|
||||||
|
|
||||||
@Column({ name: 'fecha_nacimiento', type: 'varchar', nullable: true, length: 8 })
|
@Column({
|
||||||
|
name: 'fecha_nacimiento',
|
||||||
|
type: 'varchar',
|
||||||
|
nullable: true,
|
||||||
|
length: 8,
|
||||||
|
})
|
||||||
fecha_nacimiento: string | null;
|
fecha_nacimiento: string | null;
|
||||||
|
|
||||||
@Column({ type: 'int', nullable: true, })
|
@Column({ type: 'int', nullable: true })
|
||||||
generacion: number | null;
|
generacion: number | null;
|
||||||
|
|
||||||
@ManyToOne(() => Genero, genero => genero.usuarios, { nullable: true })
|
@Column({
|
||||||
|
type: 'bit',
|
||||||
|
default: () => '1',
|
||||||
|
})
|
||||||
|
activo: boolean;
|
||||||
|
|
||||||
|
@ManyToOne(() => Genero, (genero) => genero.usuarios, { nullable: true })
|
||||||
@JoinColumn({ name: 'id_genero' })
|
@JoinColumn({ name: 'id_genero' })
|
||||||
genero: Genero | null;
|
genero: Genero | null;
|
||||||
|
|
||||||
|
@OneToMany(() => CarreraUsuario, (cu) => cu.usuario)
|
||||||
@OneToMany(() => CarreraUsuario, cu => cu.usuario)
|
|
||||||
carreraUsuarios: CarreraUsuario[];
|
carreraUsuarios: CarreraUsuario[];
|
||||||
|
|
||||||
@OneToMany(() => UsuarioTipoUsuario, utu => utu.usuario)
|
@OneToMany(() => UsuarioTipoUsuario, (utu) => utu.usuario)
|
||||||
usuarioTipos: UsuarioTipoUsuario[];
|
usuarioTipos: UsuarioTipoUsuario[];
|
||||||
|
|
||||||
@ManyToOne(() => Movimiento, movimiento => movimiento.usuario)
|
@ManyToOne(() => Movimiento, (movimiento) => movimiento.usuario)
|
||||||
@JoinColumn({ name: 'id_movimiento' })
|
@JoinColumn({ name: 'id_movimiento' })
|
||||||
movimiento: Movimiento;
|
movimiento: Movimiento;
|
||||||
|
|
||||||
@OneToOne(() => ServActivos, (servActivo) => servActivo.usuario,)
|
@OneToOne(() => ServActivos, (servActivo) => servActivo.usuario)
|
||||||
servActivo: ServActivos;
|
servActivo: ServActivos;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Entity({ name: 'carrera_usuario' })
|
@Entity({ name: 'carrera_usuario' })
|
||||||
export class CarreraUsuario {
|
export class CarreraUsuario {
|
||||||
@PrimaryGeneratedColumn({ name: 'id_carrera_usuario', type: 'int' })
|
@PrimaryGeneratedColumn({ name: 'id_carrera_usuario', type: 'int' })
|
||||||
id_carrera_usuario: number;
|
id_carrera_usuario: number;
|
||||||
|
|
||||||
@ManyToOne(() => Carrera, carrera => carrera.carreraUsuarios)
|
@ManyToOne(() => Carrera, (carrera) => carrera.carreraUsuarios)
|
||||||
@JoinColumn({ name: 'id_carrera' })
|
@JoinColumn({ name: 'id_carrera' })
|
||||||
carrera: Carrera;
|
carrera: Carrera;
|
||||||
|
|
||||||
@ManyToOne(() => Usuario, usuario => usuario.carreraUsuarios)
|
@ManyToOne(() => Usuario, (usuario) => usuario.carreraUsuarios)
|
||||||
@JoinColumn({ name: 'id_usuario' })
|
@JoinColumn({ name: 'id_usuario' })
|
||||||
usuario: Usuario;
|
usuario: Usuario;
|
||||||
}
|
}
|
||||||
@@ -162,23 +177,21 @@ export class UsuariosDelSistema {
|
|||||||
|
|
||||||
@Column({
|
@Column({
|
||||||
type: 'varchar',
|
type: 'varchar',
|
||||||
length: 100, // ajusta longitud según tu necesidad
|
length: 100, // ajusta longitud según tu necesidad
|
||||||
unique: true,
|
unique: true,
|
||||||
nullable: true,
|
nullable: true,
|
||||||
default: null,
|
default: null,
|
||||||
})
|
})
|
||||||
correo: string | null;
|
correo: string | null;
|
||||||
|
|
||||||
@Column({ type: 'varchar', length: 60 })
|
@Column({ type: 'varchar', length: 60, default: null })
|
||||||
contraseña: string;
|
contraseña: string;
|
||||||
|
|
||||||
@ManyToOne(() => Origen, origen => origen.usuariosDelSistema)
|
@ManyToOne(() => Origen, (origen) => origen.usuariosDelSistema)
|
||||||
@JoinColumn({ name: 'id_origen' })
|
@JoinColumn({ name: 'id_origen' })
|
||||||
origen: Origen;
|
origen: Origen;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Entity({ name: 'equipo' })
|
@Entity({ name: 'equipo' })
|
||||||
export class Equipo {
|
export class Equipo {
|
||||||
@PrimaryGeneratedColumn({ name: 'id_equipo', type: 'int' })
|
@PrimaryGeneratedColumn({ name: 'id_equipo', type: 'int' })
|
||||||
@@ -196,33 +209,25 @@ export class TipoUsuario {
|
|||||||
@PrimaryGeneratedColumn({ name: 'id_tipo_usuario', type: 'int' })
|
@PrimaryGeneratedColumn({ name: 'id_tipo_usuario', type: 'int' })
|
||||||
id_tipo_usuario: number;
|
id_tipo_usuario: number;
|
||||||
|
|
||||||
@Column({ name: 'tipo_usuario', type: 'varchar', length: 20 })
|
@Column({ name: 'tipo_usuario', type: 'varchar', length: 30 })
|
||||||
tipo_usuario: string;
|
tipo_usuario: string;
|
||||||
|
|
||||||
@OneToMany(() => UsuarioTipoUsuario, utu => utu.tipoUsuario)
|
@OneToMany(() => UsuarioTipoUsuario, (utu) => utu.tipoUsuario)
|
||||||
usuariosTipos: UsuarioTipoUsuario[];
|
usuariosTipos: UsuarioTipoUsuario[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Entity({ name: 'usuario_tipo_usuario' })
|
@Entity({ name: 'usuario_tipo_usuario' })
|
||||||
export class UsuarioTipoUsuario {
|
export class UsuarioTipoUsuario {
|
||||||
@PrimaryGeneratedColumn({ name: 'id_user_tipo_usuario', type: 'int' })
|
@PrimaryGeneratedColumn({ name: 'id_user_tipo_usuario', type: 'int' })
|
||||||
id_user_tipo_usuario: number;
|
id_user_tipo_usuario: number;
|
||||||
|
|
||||||
@ManyToOne(() => TipoUsuario, tipo => tipo.usuariosTipos)
|
@ManyToOne(() => TipoUsuario, (tipo) => tipo.usuariosTipos)
|
||||||
@JoinColumn({ name: 'id_tipo_usuario' })
|
@JoinColumn({ name: 'id_tipo_usuario' })
|
||||||
tipoUsuario: TipoUsuario;
|
tipoUsuario: TipoUsuario;
|
||||||
|
|
||||||
@ManyToOne(() => Usuario, usuario => usuario.usuarioTipos)
|
@ManyToOne(() => Usuario, (usuario) => usuario.usuarioTipos)
|
||||||
@JoinColumn({ name: 'id_usuario' })
|
@JoinColumn({ name: 'id_usuario' })
|
||||||
usuario: Usuario;
|
usuario: Usuario;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export { ServActivos };
|
export { ServActivos };
|
||||||
|
|
||||||
|
|||||||
+178
-107
@@ -1,5 +1,21 @@
|
|||||||
// src/excel/excel.controller.ts
|
// src/excel/excel.controller.ts
|
||||||
import { Controller, Post, Get, UseGuards, Request, Res, UploadedFile, UseInterceptors, HttpStatus, Param, ParseIntPipe, Body, BadRequestException } from '@nestjs/common';
|
import {
|
||||||
|
Controller,
|
||||||
|
Post,
|
||||||
|
Get,
|
||||||
|
UseGuards,
|
||||||
|
Request,
|
||||||
|
Res,
|
||||||
|
UploadedFile,
|
||||||
|
UseInterceptors,
|
||||||
|
HttpStatus,
|
||||||
|
Param,
|
||||||
|
ParseIntPipe,
|
||||||
|
Body,
|
||||||
|
BadRequestException,
|
||||||
|
Delete,
|
||||||
|
Query,
|
||||||
|
} from '@nestjs/common';
|
||||||
import { AuthGuard } from '@nestjs/passport';
|
import { AuthGuard } from '@nestjs/passport';
|
||||||
import { ApiBearerAuth } from '@nestjs/swagger';
|
import { ApiBearerAuth } from '@nestjs/swagger';
|
||||||
import { FileInterceptor } from '@nestjs/platform-express';
|
import { FileInterceptor } from '@nestjs/platform-express';
|
||||||
@@ -9,7 +25,6 @@ import { ExcelService } from './excel.service';
|
|||||||
import { MovimientoService } from '../movimiento/movimiento.service';
|
import { MovimientoService } from '../movimiento/movimiento.service';
|
||||||
import { MailService } from 'src/mail/mail.service';
|
import { MailService } from 'src/mail/mail.service';
|
||||||
import { CreateUsuarioDto } from 'src/usuarios/dto/create-usuario.dto';
|
import { CreateUsuarioDto } from 'src/usuarios/dto/create-usuario.dto';
|
||||||
import { Origen } from 'src/entities/entities';
|
|
||||||
import { UsuariosService } from 'src/usuarios/usuarios.service';
|
import { UsuariosService } from 'src/usuarios/usuarios.service';
|
||||||
|
|
||||||
@UseGuards(AuthGuard('jwt'))
|
@UseGuards(AuthGuard('jwt'))
|
||||||
@@ -20,46 +35,72 @@ export class ExcelController {
|
|||||||
private readonly excelService: ExcelService,
|
private readonly excelService: ExcelService,
|
||||||
private readonly movimientoService: MovimientoService,
|
private readonly movimientoService: MovimientoService,
|
||||||
private readonly mailService: MailService,
|
private readonly mailService: MailService,
|
||||||
private readonly usuarioService: UsuariosService // Asegúrate de importar el servicio de correo
|
private readonly usuarioService: UsuariosService, // Asegúrate de importar el servicio de correo
|
||||||
) { }
|
) {}
|
||||||
|
|
||||||
|
|
||||||
@Post('carga')
|
@Post('carga')
|
||||||
async cargaUsuario(@Request() req, @Body() usuario: CreateUsuarioDto) {
|
async cargaUsuario(@Request() req, @Body() usuario: CreateUsuarioDto) {
|
||||||
console.log('Usuario recibido:', usuario);
|
if (req.user.origen != 'LOAD' && req.user.origen != 'EXTERNO') {
|
||||||
if (req.user.origen != 'LOAD') {
|
throw new Error('Origen no permitido para carga');
|
||||||
throw new BadRequestException('Origen no permitido para carga')
|
|
||||||
}
|
}
|
||||||
const alta = await this.usuarioService.cargaIndividual(usuario, req.user.origen)
|
const alta = await this.usuarioService.cargaIndividual(
|
||||||
console.log('Alta de usuario:', alta);
|
usuario,
|
||||||
await this.movimientoService.updateStatus(alta.movId, 'SUCCESS')
|
req.user.origen,
|
||||||
|
req.user.email,
|
||||||
this.mailService.sendMail({
|
);
|
||||||
to: req.user.email, // Asegúrate de que el usuario tenga un email
|
if (!alta) {
|
||||||
subject: 'Carga de datos exitosa',
|
throw new Error('No se pudo realizar la carga del usuario');
|
||||||
text: "La carga de datos se ha realizado con éxito.",
|
}
|
||||||
html: `<p>La carga de datos se ha realizado con éxito. ` + alta,
|
await this.movimientoService.updateStatus(alta.movId, 'SUCCESS');
|
||||||
});
|
|
||||||
|
|
||||||
await this.excelService.enviarCargaMasiva();
|
|
||||||
|
|
||||||
|
await this.excelService.enviarInforme(
|
||||||
|
'LOAD',
|
||||||
|
'Carga Individual de datos en Servicios PCpuma',
|
||||||
|
`Se ha hecho una carga individual en el sistema por el usuario ${req.user.email}`,
|
||||||
|
);
|
||||||
|
if (alta.at) {
|
||||||
|
await this.excelService.enviarInforme(
|
||||||
|
'AT',
|
||||||
|
'Carga Individual de datos en Servicios PCpuma',
|
||||||
|
`Se ha hecho una carga individual en el sistema de ${usuario.tipo_usuario}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (alta.red) {
|
||||||
|
await this.excelService.enviarInforme(
|
||||||
|
'RED',
|
||||||
|
'Carga Individual de datos en Servicios PCpuma',
|
||||||
|
`Se ha hecho una carga individual en el sistema de ${usuario.tipo_usuario}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (alta.solicita) {
|
||||||
|
await this.excelService.enviarInforme(
|
||||||
|
'SOLICITA',
|
||||||
|
'Carga Individual de datos en Servicios PCpuma',
|
||||||
|
`Se ha hecho una carga individual en el sistema de ${usuario.tipo_usuario}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (alta.correo) {
|
||||||
|
await this.excelService.enviarInforme(
|
||||||
|
'CORREO',
|
||||||
|
'Carga Individual de datos en Servicios PCpuma',
|
||||||
|
`Se ha hecho una carga individual en el sistema de ${usuario.tipo_usuario}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Post('verify')
|
@Post('verify')
|
||||||
@UseInterceptors(FileInterceptor('file'))
|
@UseInterceptors(FileInterceptor('file'))
|
||||||
@ExcelDocumentation.verifyExcel()
|
@ExcelDocumentation.verifyExcel()
|
||||||
async verifyExcel(@UploadedFile() file: Express.Multer.File, @Request() req) {
|
async verifyExcel(@UploadedFile() file: Express.Multer.File, @Request() req) {
|
||||||
const userId: number = req.user.userId; // ahora sí existe
|
const userId: number = req.user.userId; // ahora sí existe
|
||||||
const status = await this.excelService.validateFile(file.buffer);
|
const status = await this.excelService.validateFile(file.buffer);
|
||||||
const errors = status.errors;
|
const errors = status.errors;
|
||||||
await this.movimientoService.log(
|
await this.movimientoService.log(
|
||||||
|
|
||||||
'VERIFY',
|
'VERIFY',
|
||||||
errors.length ? 'FAILED' : 'SUCCESS',
|
errors.length ? 'FAILED' : 'SUCCESS',
|
||||||
errors.join('; ')
|
errors.join('; '),
|
||||||
);
|
);
|
||||||
return { valid: errors.length === 0, errors };
|
return { valid: errors.length === 0, errors };
|
||||||
}
|
}
|
||||||
@@ -67,25 +108,36 @@ export class ExcelController {
|
|||||||
@Post('load')
|
@Post('load')
|
||||||
@UseInterceptors(FileInterceptor('file'))
|
@UseInterceptors(FileInterceptor('file'))
|
||||||
@ExcelDocumentation.loadExcel()
|
@ExcelDocumentation.loadExcel()
|
||||||
async loadExcel(@Request() req, @UploadedFile() file: Express.Multer.File) {
|
async loadExcel(
|
||||||
|
@Request() req,
|
||||||
|
@UploadedFile() file: Express.Multer.File,
|
||||||
|
@Query('function') funcion?: number,
|
||||||
|
) {
|
||||||
const origen = req.user.origen; // ahora sí existe
|
const origen = req.user.origen; // ahora sí existe
|
||||||
|
|
||||||
if (origen != 'LOAD') {
|
if (origen != 'LOAD') {
|
||||||
await this.movimientoService.log(
|
await this.movimientoService.log(
|
||||||
origen,
|
origen,
|
||||||
'FAILED',
|
'FAILED',
|
||||||
'Origen no permitido para carga'
|
'Origen no permitido para carga',
|
||||||
);
|
);
|
||||||
throw new Error('Origen no permitido para carga.');
|
throw new Error('Origen no permitido para carga.');
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const result = await this.excelService.loadFile(file.buffer);
|
let result;
|
||||||
|
if (funcion == 2) {
|
||||||
|
result = await this.excelService.loadFile2(file.buffer, req.user.email);
|
||||||
|
} else {
|
||||||
|
result = await this.excelService.loadFile(file.buffer, req.user.email);
|
||||||
|
}
|
||||||
|
|
||||||
//Actualizar el estado de los movimientos
|
//Actualizar el estado de los movimientos
|
||||||
if (!result) {
|
if (!result) {
|
||||||
this.mailService.sendMail({
|
this.mailService.sendMail({
|
||||||
to: req.user.email, // Asegúrate de que el usuario tenga un email
|
to: req.user.email, // Asegúrate de que el usuario tenga un email
|
||||||
subject: 'Carga de datos Fallida',
|
subject: 'Carga de datos Fallida',
|
||||||
text: "No se pudieron subir datos.",
|
text: 'No se pudieron subir datos.',
|
||||||
html: '<p>No se pudieron subir datos.</p>',
|
html: '',
|
||||||
});
|
});
|
||||||
throw new Error('No se pudo procesar el archivo.');
|
throw new Error('No se pudo procesar el archivo.');
|
||||||
}
|
}
|
||||||
@@ -94,43 +146,71 @@ export class ExcelController {
|
|||||||
this.mailService.sendMail({
|
this.mailService.sendMail({
|
||||||
to: req.user.email, // Asegúrate de que el usuario tenga un email
|
to: req.user.email, // Asegúrate de que el usuario tenga un email
|
||||||
subject: 'Carga de datos Fallida',
|
subject: 'Carga de datos Fallida',
|
||||||
text: "No se pudieron subir datos.",
|
text:
|
||||||
html: `<p> Se han insertado ${result.inserted} registros.</p>
|
'No se pudieron subir datos.' +
|
||||||
<p>Errores encontrados:</p>
|
`Se han insertado ${result.inserted} registros.
|
||||||
<ul>${result.errors.map(error => `<li>${error}</li>`).join('')}</ul>`,
|
Errores encontrados:
|
||||||
|
${result.errors.map((error) => `<li>${error}</li>`).join('')}`,
|
||||||
|
html: '',
|
||||||
});
|
});
|
||||||
|
|
||||||
return result
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(result.id_movimiento)
|
|
||||||
await this.movimientoService.updateStatus(
|
await this.movimientoService.updateStatus(
|
||||||
result.id_movimiento,
|
result.id_movimiento,
|
||||||
'SUCCESS',
|
'SUCCESS',
|
||||||
`inserted=${result.inserted}`
|
`inserted=${result.inserted}`,
|
||||||
);
|
);
|
||||||
|
|
||||||
this.mailService.sendMail({
|
this.mailService.sendMail({
|
||||||
to: req.user.email, // Asegúrate de que el usuario tenga un email
|
to: req.user.email, // Asegúrate de que el usuario tenga un email
|
||||||
subject: 'Carga de datos exitosa',
|
subject: 'Carga de datos exitosa',
|
||||||
text: "La carga de datos se ha realizado con éxito.",
|
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>
|
html: `<p> La carga de datos se ha realizado con éxito. Se han insertado ${result.inserted} registros.</p>
|
||||||
<p>Errores encontrados:</p>
|
<p>Usuarios At: ${result.conteoTiposAt}</p>
|
||||||
<ul>${result.errors.map(error => `<li>${error}</li>`).join('')}</ul>`,
|
<p>Usuarios Red: ${result.conteoTiposRed}</p>
|
||||||
|
<p>Usuarios Solicita: ${result.conteoTiposSolicita}</p>
|
||||||
|
<p>Usuarios Correo: ${result.conteoTiposCorreo}</p>
|
||||||
|
<ul>${result.errors.map((error) => `<li>${error}</li>`).join('')}</ul>`,
|
||||||
});
|
});
|
||||||
|
|
||||||
await this.excelService.enviarCargaMasiva();
|
// await this.excelService.enviarCargaMasiva();
|
||||||
|
|
||||||
|
if (result.conteoTiposAt > 0) {
|
||||||
|
await this.excelService.enviarInforme(
|
||||||
|
'AT',
|
||||||
|
'Carga de datos en Servicios PCpuma',
|
||||||
|
`Se ha hecho una carga en el sistema de \n ${result.conteoTiposAt} usarios`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (result.conteoTiposRed > 0) {
|
||||||
|
await this.excelService.enviarInforme(
|
||||||
|
'RED',
|
||||||
|
'Carga de datos en Servicios PCpuma',
|
||||||
|
`Se ha hecho una carga en el sistema \n ${result.conteoTiposRed} usarios`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return result
|
if (result.conteoTiposSolicita > 0) {
|
||||||
|
await this.excelService.enviarInforme(
|
||||||
|
'SOLICITA',
|
||||||
|
'Carga de datos en Servicios PCpuma',
|
||||||
|
`Se ha hecho una carga en el sistema \n ${result.conteoTiposSolicita} usarios`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.conteoTiposCorreo > 0) {
|
||||||
|
await this.excelService.enviarInforme(
|
||||||
|
'CORREO',
|
||||||
|
'Carga de datos en Servicios PCpuma',
|
||||||
|
`Se ha hecho una carga en el sistema \n ${result.conteoTiposCorreo} usarios`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await this.movimientoService.log(
|
await this.movimientoService.log('LOAD', 'FAILED', err.message);
|
||||||
|
|
||||||
'LOAD',
|
|
||||||
'FAILED',
|
|
||||||
err.message
|
|
||||||
);
|
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -139,49 +219,48 @@ export class ExcelController {
|
|||||||
@ExcelDocumentation.downloadExcel()
|
@ExcelDocumentation.downloadExcel()
|
||||||
async downloadData(@Request() req, @Res() res: Response) {
|
async downloadData(@Request() req, @Res() res: Response) {
|
||||||
const origen = req.user.origen; // ahora sí existe
|
const origen = req.user.origen; // ahora sí existe
|
||||||
console.log('Origen de descarga:', origen);
|
|
||||||
console.log('Usuario:', req.user);
|
|
||||||
|
|
||||||
if (origen == 'SOLICITA') {
|
if (origen == 'SOLICITA') {
|
||||||
try {
|
try {
|
||||||
const csv = await this.excelService.generateCsvSolicita();
|
const csv = await this.excelService.generateCsvSolicita();
|
||||||
await this.movimientoService.log(
|
await this.movimientoService.log(
|
||||||
|
|
||||||
origen,
|
origen,
|
||||||
'SUCCESS',
|
'SUCCESS',
|
||||||
'descarga de csv',
|
'descarga de csv',
|
||||||
`size=${csv.length}`
|
`size=${csv.length}`,
|
||||||
);
|
);
|
||||||
return res
|
return res
|
||||||
.status(HttpStatus.OK)
|
.status(HttpStatus.OK)
|
||||||
.header('Content-Type', 'text/csv')
|
.header('Content-Type', 'text/csv')
|
||||||
.header('Content-Disposition', 'attachment; filename="usuarios_solicita.csv"')
|
.header(
|
||||||
|
'Content-Disposition',
|
||||||
|
'attachment; filename="usuarios_solicita.csv"',
|
||||||
|
)
|
||||||
.send(csv);
|
.send(csv);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await this.movimientoService.log(
|
await this.movimientoService.log(
|
||||||
origen,
|
origen,
|
||||||
'FAILED',
|
'FAILED',
|
||||||
'Origen no permitido para descarga'
|
'Origen no permitido para descarga',
|
||||||
);
|
);
|
||||||
return res
|
return res.status(HttpStatus.FORBIDDEN).json({
|
||||||
.status(HttpStatus.FORBIDDEN)
|
statusCode: 403,
|
||||||
.json({ statusCode: 403, message: 'Origen no permitido para descarga.' });
|
message: 'Origen no permitido para descarga.',
|
||||||
|
});
|
||||||
}
|
}
|
||||||
} else if (origen == 'CORREO' || origen == 'LOAD') {
|
} else if (origen == 'CORREO' || origen == 'LOAD') {
|
||||||
try {
|
try {
|
||||||
const csv = await this.excelService.generateCsvCorreo();
|
const csv = await this.excelService.generateCsvCorreo();
|
||||||
await this.movimientoService.log(
|
await this.movimientoService.log(
|
||||||
|
|
||||||
origen,
|
origen,
|
||||||
'SUCCESS',
|
'SUCCESS',
|
||||||
'descarga de csv',
|
'descarga de csv',
|
||||||
`size=${csv.length}`
|
`size=${csv.length}`,
|
||||||
);
|
);
|
||||||
let filename
|
let filename;
|
||||||
if (origen == 'CORREO') {
|
if (origen == 'CORREO') {
|
||||||
filename = 'usuarios_correo.csv';
|
filename = 'usuarios_correo.csv';
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
filename = 'usuarios.csv';
|
filename = 'usuarios.csv';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -191,12 +270,7 @@ export class ExcelController {
|
|||||||
.header('Content-Disposition', `attachment; filename="${filename}"`)
|
.header('Content-Disposition', `attachment; filename="${filename}"`)
|
||||||
.send(csv);
|
.send(csv);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await this.movimientoService.log(
|
await this.movimientoService.log(origen, 'FAILED', err.message);
|
||||||
|
|
||||||
origen,
|
|
||||||
'FAILED',
|
|
||||||
err.message
|
|
||||||
);
|
|
||||||
return res
|
return res
|
||||||
.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||||
.json({ statusCode: 500, message: 'Error generando descarga.' });
|
.json({ statusCode: 500, message: 'Error generando descarga.' });
|
||||||
@@ -205,24 +279,21 @@ export class ExcelController {
|
|||||||
try {
|
try {
|
||||||
const csv = await this.excelService.generateCsvAT();
|
const csv = await this.excelService.generateCsvAT();
|
||||||
await this.movimientoService.log(
|
await this.movimientoService.log(
|
||||||
|
|
||||||
origen,
|
origen,
|
||||||
'SUCCESS',
|
'SUCCESS',
|
||||||
'descarga de csv',
|
'descarga de csv',
|
||||||
`size=${csv.length}`
|
`size=${csv.length}`,
|
||||||
);
|
);
|
||||||
return res
|
return res
|
||||||
.status(HttpStatus.OK)
|
.status(HttpStatus.OK)
|
||||||
.header('Content-Type', 'text/csv')
|
.header('Content-Type', 'text/csv')
|
||||||
.header('Content-Disposition', 'attachment; filename="usuarios_AT.csv"')
|
.header(
|
||||||
|
'Content-Disposition',
|
||||||
|
'attachment; filename="usuarios_AT.csv"',
|
||||||
|
)
|
||||||
.send(csv);
|
.send(csv);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await this.movimientoService.log(
|
await this.movimientoService.log(origen, 'FAILED', err.message);
|
||||||
|
|
||||||
origen,
|
|
||||||
'FAILED',
|
|
||||||
err.message
|
|
||||||
);
|
|
||||||
return res
|
return res
|
||||||
.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||||
.json({ statusCode: 500, message: 'Error generando descarga.' });
|
.json({ statusCode: 500, message: 'Error generando descarga.' });
|
||||||
@@ -231,48 +302,47 @@ export class ExcelController {
|
|||||||
try {
|
try {
|
||||||
const csv = await this.excelService.generateCsvRed();
|
const csv = await this.excelService.generateCsvRed();
|
||||||
await this.movimientoService.log(
|
await this.movimientoService.log(
|
||||||
|
|
||||||
origen,
|
origen,
|
||||||
'SUCCESS',
|
'SUCCESS',
|
||||||
'descarga de csv',
|
'descarga de csv',
|
||||||
`size=${csv.length}`
|
`size=${csv.length}`,
|
||||||
);
|
);
|
||||||
return res
|
return res
|
||||||
.status(HttpStatus.OK)
|
.status(HttpStatus.OK)
|
||||||
.header('Content-Type', 'text/csv')
|
.header('Content-Type', 'text/csv')
|
||||||
.header('Content-Disposition', 'attachment; filename="usuarios_red.csv"')
|
.header(
|
||||||
|
'Content-Disposition',
|
||||||
|
'attachment; filename="usuarios_red.csv"',
|
||||||
|
)
|
||||||
.send(csv);
|
.send(csv);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await this.movimientoService.log(
|
await this.movimientoService.log(origen, 'FAILED', err.message);
|
||||||
|
|
||||||
origen,
|
|
||||||
'FAILED',
|
|
||||||
err.message
|
|
||||||
);
|
|
||||||
return res
|
return res
|
||||||
.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||||
.json({ statusCode: 500, message: 'Error generando descarga.' });
|
.json({ statusCode: 500, message: 'Error generando descarga.' });
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
await this.movimientoService.log(
|
await this.movimientoService.log(
|
||||||
|
|
||||||
origen,
|
origen,
|
||||||
'FAILED',
|
'FAILED',
|
||||||
'Origen no permitido para descarga'
|
'Origen no permitido para descarga',
|
||||||
);
|
);
|
||||||
return res
|
return res.status(HttpStatus.FORBIDDEN).json({
|
||||||
.status(HttpStatus.FORBIDDEN)
|
statusCode: 403,
|
||||||
.json({ statusCode: 403, message: 'Origen no permitido para descarga.' });
|
message: 'Origen no permitido para descarga.',
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//Agregarlo en su propio controller
|
//Agregarlo en su propio controller
|
||||||
@Get('movimientos')
|
@Get('movimientos')
|
||||||
async getMovimientos(@Request() req) {
|
@ExcelDocumentation.getMovimientos()
|
||||||
|
async getMovimientos(
|
||||||
const movimientos = await this.movimientoService.findAll(req.user.origen);
|
@Request() req,
|
||||||
return movimientos;
|
@Query('page') page: number,
|
||||||
|
@Query('limit') limit: number,
|
||||||
|
) {
|
||||||
|
return this.movimientoService.findAll(req.user.origen, page, limit);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post('activar-servicios/:id_movimiento')
|
@Post('activar-servicios/:id_movimiento')
|
||||||
@@ -291,17 +361,18 @@ export class ExcelController {
|
|||||||
return { message: 'Servicios activados correctamente' };
|
return { message: 'Servicios activados correctamente' };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ExcelDocumentation.servAct()
|
||||||
@Get('cargaIndividual')
|
@Get('serv_act')
|
||||||
async cargarIndividual(
|
async serv() {
|
||||||
@Request() req) {
|
return await this.excelService.buscaAct();
|
||||||
const origen = req.user.origen; // ahora sí existe
|
|
||||||
return this.movimientoService.findAllCargaIndv(origen);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post('mov/:id_movimiento')
|
||||||
|
async MOV(@Param('id_movimiento', ParseIntPipe) id_movimiento: number) {
|
||||||
|
return await this.movimientoService.findAllWithRelations(id_movimiento);
|
||||||
|
}
|
||||||
|
// @Delete()
|
||||||
|
// async borrar(){
|
||||||
|
// return await this.excelService.borrarUsers()
|
||||||
|
// }
|
||||||
}
|
}
|
||||||
@@ -1,16 +1,55 @@
|
|||||||
import { applyDecorators } from '@nestjs/common';
|
import { applyDecorators } from '@nestjs/common';
|
||||||
import { ApiTags, ApiOperation, ApiConsumes, ApiBody, ApiResponse } from '@nestjs/swagger';
|
import {
|
||||||
|
ApiTags,
|
||||||
|
ApiOperation,
|
||||||
|
ApiConsumes,
|
||||||
|
ApiBody,
|
||||||
|
ApiResponse,
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiQuery,
|
||||||
|
} from '@nestjs/swagger';
|
||||||
|
|
||||||
export class ExcelDocumentation {
|
export class ExcelDocumentation {
|
||||||
/**
|
static getMovimientos() {
|
||||||
* Decorators Swagger para el endpoint POST /excel/verify
|
return applyDecorators(
|
||||||
*/
|
ApiBearerAuth(),
|
||||||
|
ApiOperation({
|
||||||
|
summary: 'Obtener movimientos',
|
||||||
|
description:
|
||||||
|
'Obtiene un listado paginado de movimientos según el origen del usuario autenticado.',
|
||||||
|
}),
|
||||||
|
ApiQuery({
|
||||||
|
name: 'page',
|
||||||
|
required: false,
|
||||||
|
type: Number,
|
||||||
|
example: 1,
|
||||||
|
description: 'Número de página',
|
||||||
|
}),
|
||||||
|
ApiQuery({
|
||||||
|
name: 'limit',
|
||||||
|
required: false,
|
||||||
|
type: Number,
|
||||||
|
example: 10,
|
||||||
|
description: 'Cantidad de registros por página',
|
||||||
|
}),
|
||||||
|
ApiResponse({
|
||||||
|
status: 200,
|
||||||
|
description: 'Listado de movimientos obtenido correctamente',
|
||||||
|
}),
|
||||||
|
ApiResponse({
|
||||||
|
status: 401,
|
||||||
|
description: 'No autorizado',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
static verifyExcel() {
|
static verifyExcel() {
|
||||||
return applyDecorators(
|
return applyDecorators(
|
||||||
ApiTags('Excel'),
|
ApiTags('Excel'),
|
||||||
ApiOperation({
|
ApiOperation({
|
||||||
summary: 'Verificar archivo Excel',
|
summary: 'Verificar archivo Excel',
|
||||||
description: 'Valida duplicados, filas en blanco y formato básico de los datos sin realizar carga en la base.'
|
description:
|
||||||
|
'Valida duplicados, filas en blanco y formato básico de los datos sin realizar carga en la base.',
|
||||||
}),
|
}),
|
||||||
ApiConsumes('multipart/form-data'),
|
ApiConsumes('multipart/form-data'),
|
||||||
ApiBody({
|
ApiBody({
|
||||||
@@ -20,10 +59,10 @@ export class ExcelDocumentation {
|
|||||||
file: {
|
file: {
|
||||||
type: 'string',
|
type: 'string',
|
||||||
format: 'binary',
|
format: 'binary',
|
||||||
description: 'Archivo Excel (.xlsx) con usuarios a validar'
|
description: 'Archivo Excel (.xlsx) con usuarios a validar',
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
}),
|
}),
|
||||||
ApiResponse({
|
ApiResponse({
|
||||||
status: 200,
|
status: 200,
|
||||||
@@ -35,12 +74,18 @@ export class ExcelDocumentation {
|
|||||||
errors: {
|
errors: {
|
||||||
type: 'array',
|
type: 'array',
|
||||||
items: { type: 'string' },
|
items: { type: 'string' },
|
||||||
example: ['Fila 2: cuenta duplicada "42515101".', 'Fila 3: fecha de nacimiento inválida "1988051".']
|
example: [
|
||||||
}
|
'Fila 2: cuenta duplicada "42515101".',
|
||||||
}
|
'Fila 3: fecha de nacimiento inválida "1988051".',
|
||||||
}
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
ApiResponse({
|
||||||
|
status: 400,
|
||||||
|
description: 'No se recibió archivo o formato inválido.',
|
||||||
}),
|
}),
|
||||||
ApiResponse({ status: 400, description: 'No se recibió archivo o formato inválido.' })
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,7 +97,8 @@ export class ExcelDocumentation {
|
|||||||
ApiTags('Excel'),
|
ApiTags('Excel'),
|
||||||
ApiOperation({
|
ApiOperation({
|
||||||
summary: 'Cargar archivo Excel',
|
summary: 'Cargar archivo Excel',
|
||||||
description: 'Valida y persiste los datos en la base de datos. Retorna el número de registros insertados.'
|
description:
|
||||||
|
'Valida y persiste los datos en la base de datos. Retorna el número de registros insertados.',
|
||||||
}),
|
}),
|
||||||
ApiConsumes('multipart/form-data'),
|
ApiConsumes('multipart/form-data'),
|
||||||
ApiBody({
|
ApiBody({
|
||||||
@@ -62,10 +108,10 @@ export class ExcelDocumentation {
|
|||||||
file: {
|
file: {
|
||||||
type: 'string',
|
type: 'string',
|
||||||
format: 'binary',
|
format: 'binary',
|
||||||
description: 'Archivo Excel (.xlsx) con usuarios a cargar'
|
description: 'Archivo Excel (.xlsx) con usuarios a cargar',
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
}),
|
}),
|
||||||
ApiResponse({
|
ApiResponse({
|
||||||
status: 201,
|
status: 201,
|
||||||
@@ -73,9 +119,9 @@ export class ExcelDocumentation {
|
|||||||
schema: {
|
schema: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
inserted: { type: 'number', example: 3 }
|
inserted: { type: 'number', example: 3 },
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
}),
|
}),
|
||||||
ApiResponse({
|
ApiResponse({
|
||||||
status: 400,
|
status: 400,
|
||||||
@@ -86,52 +132,58 @@ export class ExcelDocumentation {
|
|||||||
errors: {
|
errors: {
|
||||||
type: 'array',
|
type: 'array',
|
||||||
items: { type: 'string' },
|
items: { type: 'string' },
|
||||||
example: ['Fila 5: rfc contiene caracteres inválidos.']
|
example: ['Fila 5: rfc contiene caracteres inválidos.'],
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
static downloadExcel() {
|
static downloadExcel() {
|
||||||
return applyDecorators(
|
return applyDecorators(
|
||||||
ApiTags('Excel'),
|
ApiTags('Excel'),
|
||||||
//ApiBearerAuth('bearer'),
|
//ApiBearerAuth('bearer'),
|
||||||
ApiOperation({
|
ApiOperation({
|
||||||
summary: 'Descargar usuarios',
|
summary: 'Descargar usuarios',
|
||||||
description: 'Exporta todos los usuarios en un archivo TSV (o CSV) y registra el movimiento.'
|
description:
|
||||||
|
'Exporta todos los usuarios en un archivo TSV (o CSV) y registra el movimiento.',
|
||||||
}),
|
}),
|
||||||
ApiResponse({
|
ApiResponse({
|
||||||
status: 200,
|
status: 200,
|
||||||
description: 'TSV generado correctamente',
|
description: 'TSV generado correctamente',
|
||||||
content: {
|
content: {
|
||||||
'text/tab-separated-values': {
|
'text/tab-separated-values': {
|
||||||
schema: { type: 'string', example: 'num_cuenta\\tnombre\\t...\\n...' }
|
schema: {
|
||||||
}
|
type: 'string',
|
||||||
}
|
example: 'num_cuenta\\tnombre\\t...\\n...',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
ApiResponse({ status: 401, description: 'No autorizado' }),
|
ApiResponse({ status: 401, description: 'No autorizado' }),
|
||||||
ApiResponse({ status: 500, description: 'Error al generar descarga' }),
|
ApiResponse({ status: 500, description: 'Error al generar descarga' }),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static servAct() {
|
||||||
|
return applyDecorators(
|
||||||
|
ApiTags('Excel'),
|
||||||
|
ApiOperation({
|
||||||
|
summary: 'Obtener servicios activos',
|
||||||
|
description:
|
||||||
|
'Devuelve la lista de servicios activos registrados en el sistema',
|
||||||
|
}),
|
||||||
|
ApiResponse({
|
||||||
|
status: 200,
|
||||||
|
description: 'Lista de servicios activos',
|
||||||
|
// type: ServActivoDto, // si tienes DTO
|
||||||
|
// isArray: true,
|
||||||
|
}),
|
||||||
|
ApiResponse({
|
||||||
|
status: 401,
|
||||||
|
description: 'No autorizado',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+742
-253
File diff suppressed because it is too large
Load Diff
@@ -15,11 +15,10 @@ export class MailController {
|
|||||||
const result =
|
const result =
|
||||||
await this.mailService.sendMail(body)
|
await this.mailService.sendMail(body)
|
||||||
.then((value) => {
|
.then((value) => {
|
||||||
console.log("Se mandaron los correos", value);
|
|
||||||
|
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
console.log(err)
|
throw new Error(err)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -50,7 +50,6 @@ export class MailService {
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
console.log(mailOptions);
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+12
-1
@@ -1,12 +1,23 @@
|
|||||||
|
import * as crypto from "crypto";
|
||||||
|
|
||||||
|
|
||||||
|
//(global as any).crypto = crypto;
|
||||||
|
|
||||||
|
|
||||||
import { NestFactory } from '@nestjs/core';
|
import { NestFactory } from '@nestjs/core';
|
||||||
import { AppModule } from './app.module';
|
import { AppModule } from './app.module';
|
||||||
import { ValidationPipe } from '@nestjs/common';
|
import { ValidationPipe } from '@nestjs/common';
|
||||||
import { GlobalExceptionFilter } from './helpers/exception.filter';
|
import { GlobalExceptionFilter } from './helpers/exception.filter';
|
||||||
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
|
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
|
||||||
async function bootstrap() {
|
async function bootstrap() {
|
||||||
const app = await NestFactory.create(AppModule);
|
const app = await NestFactory.create(AppModule);
|
||||||
app.enableCors({ exposedHeaders: ['Content-Disposition'] });
|
app.enableCors({
|
||||||
|
origin: [process.env.FRONTEND_URL], // solo frontend permitido
|
||||||
|
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
|
||||||
|
credentials: true,
|
||||||
|
});
|
||||||
|
|
||||||
app.useGlobalPipes(
|
app.useGlobalPipes(
|
||||||
new ValidationPipe({
|
new ValidationPipe({
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ export class MovimientoService {
|
|||||||
private readonly origenRepo: Repository<Origen>,
|
private readonly origenRepo: Repository<Origen>,
|
||||||
@InjectRepository(Usuario)
|
@InjectRepository(Usuario)
|
||||||
private readonly usuarioRepo: Repository<Usuario>,
|
private readonly usuarioRepo: Repository<Usuario>,
|
||||||
) { }
|
) {}
|
||||||
|
|
||||||
/** Crea un registro de movimiento */
|
/** Crea un registro de movimiento */
|
||||||
async log(
|
async log(
|
||||||
@@ -54,7 +54,7 @@ export class MovimientoService {
|
|||||||
origenNombre: string,
|
origenNombre: string,
|
||||||
status: string,
|
status: string,
|
||||||
observaciones?: string,
|
observaciones?: string,
|
||||||
reporte?: string
|
reporte?: string,
|
||||||
): Promise<Movimiento> {
|
): Promise<Movimiento> {
|
||||||
const origenEntidad = await queryRunner.manager.findOne(Origen, {
|
const origenEntidad = await queryRunner.manager.findOne(Origen, {
|
||||||
where: { origen: origenNombre },
|
where: { origen: origenNombre },
|
||||||
@@ -76,17 +76,21 @@ export class MovimientoService {
|
|||||||
return await queryRunner.manager.save(nuevoMov);
|
return await queryRunner.manager.save(nuevoMov);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/** Actualiza el status de un movimiento existente */
|
/** Actualiza el status de un movimiento existente */
|
||||||
async updateStatus(id_movimiento: number, nuevoStatus: string, observaciones?: string): Promise<void> {
|
async updateStatus(
|
||||||
const movimiento = await this.movRepo.findOne({ where: { id_mov: id_movimiento } });
|
id_movimiento: number,
|
||||||
|
nuevoStatus: string,
|
||||||
|
observaciones?: string,
|
||||||
|
): Promise<void> {
|
||||||
|
const movimiento = await this.movRepo.findOne({
|
||||||
|
where: { id_mov: id_movimiento },
|
||||||
|
});
|
||||||
|
|
||||||
if (!movimiento) {
|
if (!movimiento) {
|
||||||
throw new Error(`Movimiento con ID ${id_movimiento} no encontrado`);
|
throw new Error(`Movimiento con ID ${id_movimiento} no encontrado`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log('movimiento' + movimiento);
|
||||||
movimiento.status = nuevoStatus;
|
movimiento.status = nuevoStatus;
|
||||||
movimiento.observaciones = observaciones || movimiento.observaciones; // opcional: actualizar observaciones
|
movimiento.observaciones = observaciones || movimiento.observaciones; // opcional: actualizar observaciones
|
||||||
movimiento.fecha_mov = new Date(); // opcional: actualizar fecha
|
movimiento.fecha_mov = new Date(); // opcional: actualizar fecha
|
||||||
@@ -94,7 +98,38 @@ export class MovimientoService {
|
|||||||
await this.movRepo.save(movimiento);
|
await this.movRepo.save(movimiento);
|
||||||
}
|
}
|
||||||
|
|
||||||
async findAll(origen: string): Promise<{ move: any[]; button: boolean }> {
|
async findAll(
|
||||||
|
origen: string,
|
||||||
|
page: number = 1,
|
||||||
|
limit: number = 10,
|
||||||
|
): Promise<{
|
||||||
|
move: any[];
|
||||||
|
button: boolean;
|
||||||
|
total?: number;
|
||||||
|
lastPage?: number;
|
||||||
|
}> {
|
||||||
|
if (origen === 'LOAD') {
|
||||||
|
const [movimientos, total] = await this.movRepo.findAndCount({
|
||||||
|
where: {
|
||||||
|
origen: { origen: 'LOAD' },
|
||||||
|
status: 'SUCCESS',
|
||||||
|
reporte: 'CARGA MASIVA DE USUARIOS',
|
||||||
|
},
|
||||||
|
skip: (page - 1) * limit,
|
||||||
|
take: limit,
|
||||||
|
order: { fecha_mov: 'DESC' }, // opcional
|
||||||
|
});
|
||||||
|
|
||||||
|
// si quieres incluir también mov y mov2 en la misma paginación:
|
||||||
|
// const todosLosMovimientos = [...movimientos, ...mov, ...mov2]; (y luego slice)
|
||||||
|
|
||||||
|
return {
|
||||||
|
move: movimientos,
|
||||||
|
button: false,
|
||||||
|
total,
|
||||||
|
lastPage: Math.ceil(total / limit),
|
||||||
|
};
|
||||||
|
}
|
||||||
const statusFieldMap = {
|
const statusFieldMap = {
|
||||||
AT: 'ATStatus',
|
AT: 'ATStatus',
|
||||||
RED: 'RedStatus',
|
RED: 'RedStatus',
|
||||||
@@ -109,8 +144,6 @@ export class MovimientoService {
|
|||||||
SOLICITA: 'Prestamos',
|
SOLICITA: 'Prestamos',
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const field = statusFieldMap[origen as keyof typeof statusFieldMap];
|
const field = statusFieldMap[origen as keyof typeof statusFieldMap];
|
||||||
const origenField = FieldMap[origen as keyof typeof FieldMap];
|
const origenField = FieldMap[origen as keyof typeof FieldMap];
|
||||||
|
|
||||||
@@ -120,7 +153,6 @@ export class MovimientoService {
|
|||||||
origen: { origen: 'LOAD' },
|
origen: { origen: 'LOAD' },
|
||||||
status: 'SUCCESS',
|
status: 'SUCCESS',
|
||||||
reporte: 'CARGA MASIVA DE USUARIOS',
|
reporte: 'CARGA MASIVA DE USUARIOS',
|
||||||
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -129,26 +161,17 @@ export class MovimientoService {
|
|||||||
origen: { origen: 'SISTEMA' },
|
origen: { origen: 'SISTEMA' },
|
||||||
status: 'SUCCESS',
|
status: 'SUCCESS',
|
||||||
reporte: 'CARGA MASIVA WEB SERVICE',
|
reporte: 'CARGA MASIVA WEB SERVICE',
|
||||||
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const mov2 = await this.movRepo.find({
|
const mov2 = await this.movRepo.find({
|
||||||
where: {
|
where: {
|
||||||
|
|
||||||
reporte: 'CARGA INDIVIDUAL DE USUARIOS',
|
reporte: 'CARGA INDIVIDUAL DE USUARIOS',
|
||||||
status: 'SUCCESS',
|
status: 'SUCCESS',
|
||||||
|
|
||||||
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
console.log('movimientos:', mov2)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const todosLosMovimientos = [...movimientos, ...mov, ...mov2];
|
const todosLosMovimientos = [...movimientos, ...mov, ...mov2];
|
||||||
console.log(todosLosMovimientos)
|
|
||||||
return { move: todosLosMovimientos, button: false };
|
return { move: todosLosMovimientos, button: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -158,10 +181,11 @@ export class MovimientoService {
|
|||||||
reporte: 'CARGA MASIVA DE USUARIOS',
|
reporte: 'CARGA MASIVA DE USUARIOS',
|
||||||
status: 'SUCCESS',
|
status: 'SUCCESS',
|
||||||
usuario: {
|
usuario: {
|
||||||
|
activo: true,
|
||||||
servActivo: {
|
servActivo: {
|
||||||
[origenField]: true,
|
[origenField]: true,
|
||||||
|
|
||||||
[field]: 'Inactivo'
|
[field]: 'Inactivo',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -172,22 +196,23 @@ export class MovimientoService {
|
|||||||
reporte: 'CARGA MASIVA WEB SERVICE',
|
reporte: 'CARGA MASIVA WEB SERVICE',
|
||||||
status: 'SUCCESS',
|
status: 'SUCCESS',
|
||||||
usuario: {
|
usuario: {
|
||||||
|
activo: true,
|
||||||
servActivo: {
|
servActivo: {
|
||||||
[origenField]: true,
|
[origenField]: true,
|
||||||
[field]: 'Inactivo'
|
[field]: 'Inactivo',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const mov2 = await this.movRepo.find({
|
const mov2 = await this.movRepo.find({
|
||||||
where: {
|
where: {
|
||||||
|
|
||||||
reporte: 'CARGA INDIVIDUAL DE USUARIOS',
|
reporte: 'CARGA INDIVIDUAL DE USUARIOS',
|
||||||
status: 'SUCCESS',
|
status: 'SUCCESS',
|
||||||
usuario: {
|
usuario: {
|
||||||
|
activo: true,
|
||||||
servActivo: {
|
servActivo: {
|
||||||
[origenField]: true,
|
[origenField]: true,
|
||||||
[field]: 'Inactivo'
|
[field]: 'Inactivo',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -199,7 +224,6 @@ export class MovimientoService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async findAllCargaIndv(origen): Promise<Usuario[]> {
|
async findAllCargaIndv(origen): Promise<Usuario[]> {
|
||||||
|
|
||||||
const statusFieldMap = {
|
const statusFieldMap = {
|
||||||
AT: 'ATStatus',
|
AT: 'ATStatus',
|
||||||
RED: 'RedStatus',
|
RED: 'RedStatus',
|
||||||
@@ -214,10 +238,6 @@ export class MovimientoService {
|
|||||||
SOLICITA: 'Prestamos',
|
SOLICITA: 'Prestamos',
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const field = statusFieldMap[origen as keyof typeof statusFieldMap];
|
const field = statusFieldMap[origen as keyof typeof statusFieldMap];
|
||||||
|
|
||||||
const origenField = FieldMap[origen as keyof typeof FieldMap];
|
const origenField = FieldMap[origen as keyof typeof FieldMap];
|
||||||
@@ -228,8 +248,8 @@ export class MovimientoService {
|
|||||||
|
|
||||||
const usuarios = await this.usuarioRepo.find({
|
const usuarios = await this.usuarioRepo.find({
|
||||||
where: {
|
where: {
|
||||||
|
activo: true,
|
||||||
movimiento: {
|
movimiento: {
|
||||||
|
|
||||||
reporte: 'CARGA INDIVIDUAL DE USUARIOS',
|
reporte: 'CARGA INDIVIDUAL DE USUARIOS',
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -237,18 +257,27 @@ export class MovimientoService {
|
|||||||
[field]: 'Inactivo',
|
[field]: 'Inactivo',
|
||||||
[origenField]: true,
|
[origenField]: true,
|
||||||
},
|
},
|
||||||
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
return usuarios;
|
return usuarios;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async findAllWithRelations(id: number): Promise<Movimiento[]> {
|
||||||
|
return await this.movRepo.find({
|
||||||
|
where: { id_mov: id },
|
||||||
|
relations: [
|
||||||
|
'usuario',
|
||||||
|
'origen',
|
||||||
|
'usuario.servActivo',
|
||||||
|
'usuario.carreraUsuarios',
|
||||||
|
'usuario.carreraUsuarios.carrera',
|
||||||
|
'usuario.usuarioTipos',
|
||||||
|
'usuario.usuarioTipos.tipoUsuario',
|
||||||
|
],
|
||||||
|
order: {
|
||||||
|
fecha_mov: 'DESC',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,11 @@ export class UsuariosController {
|
|||||||
finsdAll() {
|
finsdAll() {
|
||||||
return this.usuariosService.enviarSolicitud();
|
return this.usuariosService.enviarSolicitud();
|
||||||
}
|
}
|
||||||
|
@Get("mov/:move")
|
||||||
|
findByMov(@Param('move') move:number){
|
||||||
|
return this.usuariosService.findByMov(move);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@Get(':noCuenta')
|
@Get(':noCuenta')
|
||||||
findOne(@Param('noCuenta') noCuenta: string) {
|
findOne(@Param('noCuenta') noCuenta: string) {
|
||||||
|
|||||||
+281
-289
@@ -2,7 +2,14 @@ import { Injectable, Logger, NotFoundException } from '@nestjs/common';
|
|||||||
import { CreateUsuarioDto } from './dto/create-usuario.dto';
|
import { CreateUsuarioDto } from './dto/create-usuario.dto';
|
||||||
import { UpdateUsuarioDto } from './dto/update-usuario.dto';
|
import { UpdateUsuarioDto } from './dto/update-usuario.dto';
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { Carrera, CarreraUsuario, Genero, TipoUsuario, Usuario, UsuarioTipoUsuario } from 'src/entities/entities';
|
import {
|
||||||
|
Carrera,
|
||||||
|
CarreraUsuario,
|
||||||
|
Genero,
|
||||||
|
TipoUsuario,
|
||||||
|
Usuario,
|
||||||
|
UsuarioTipoUsuario,
|
||||||
|
} from 'src/entities/entities';
|
||||||
import { Repository } from 'typeorm';
|
import { Repository } from 'typeorm';
|
||||||
import { ServActivos } from './entities/servActivos.entitie';
|
import { ServActivos } from './entities/servActivos.entitie';
|
||||||
import { MovimientoService } from 'src/movimiento/movimiento.service';
|
import { MovimientoService } from 'src/movimiento/movimiento.service';
|
||||||
@@ -11,9 +18,6 @@ import { error } from 'console';
|
|||||||
import { Cron } from '@nestjs/schedule';
|
import { Cron } from '@nestjs/schedule';
|
||||||
import { ExcelService } from 'src/excel/excel.service';
|
import { ExcelService } from 'src/excel/excel.service';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class UsuariosService {
|
export class UsuariosService {
|
||||||
private readonly logger = new Logger(UsuariosService.name);
|
private readonly logger = new Logger(UsuariosService.name);
|
||||||
@@ -36,17 +40,32 @@ export class UsuariosService {
|
|||||||
private readonly movimientoService: MovimientoService,
|
private readonly movimientoService: MovimientoService,
|
||||||
private readonly mailService: MailService,
|
private readonly mailService: MailService,
|
||||||
private readonly excelService: ExcelService, // Asegúrate de importar el servicio de Excel
|
private readonly excelService: ExcelService, // Asegúrate de importar el servicio de Excel
|
||||||
|
) {}
|
||||||
) { }
|
|
||||||
|
|
||||||
altaIndividual(createUsuarioDto: CreateUsuarioDto) {
|
altaIndividual(createUsuarioDto: CreateUsuarioDto) {
|
||||||
return 'This action adds a new usuario';
|
return 'This action adds a new usuario';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async findByMov(id: number) {
|
||||||
|
const usuarios = await this.usuarioRepository.find({
|
||||||
|
where: {
|
||||||
|
//movimiento:{id_mov:id},
|
||||||
|
|
||||||
|
servActivo: {
|
||||||
|
PrestamosStatus: 'Inactivo', // solo los que no tienen servicio activo
|
||||||
|
Prestamos: true, // solo los que tienen el servicio de préstamos activo
|
||||||
|
},
|
||||||
|
},
|
||||||
|
relations: ['usuarioTipos', 'usuarioTipos.tipoUsuario', 'servActivo'],
|
||||||
|
});
|
||||||
|
if (!usuarios)
|
||||||
|
throw new Error('No existe suauarios relacionados a ese movimiento');
|
||||||
|
return usuarios;
|
||||||
|
}
|
||||||
|
|
||||||
async findOneStatus(noCuenta: string) {
|
async findOneStatus(noCuenta: string) {
|
||||||
const usuario = await this.usuarioRepository.findOne({
|
const usuario = await this.usuarioRepository.findOne({
|
||||||
where: { num_cuenta: noCuenta },
|
where: { num_cuenta: noCuenta },
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!usuario) {
|
if (!usuario) {
|
||||||
@@ -54,11 +73,20 @@ export class UsuariosService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const servActivo = await this.servActivosRepository.findOne({
|
const servActivo = await this.servActivosRepository.findOne({
|
||||||
where: { usuario: { id_usuario: usuario.id_usuario } },
|
where: { usuario: { activo: true, id_usuario: usuario.id_usuario } },
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!servActivo) {
|
if (!servActivo) {
|
||||||
throw new NotFoundException('Servicios no encontrados para el usuario');
|
return {
|
||||||
|
usuario: `${usuario.nombre} ${usuario.a_paterno} ${usuario.a_materno}`,
|
||||||
|
resultado: [
|
||||||
|
{
|
||||||
|
servicio: 'Ninguno',
|
||||||
|
status: 'El usuario no está activo este semestre',
|
||||||
|
fecha_activacion: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const resultado: {
|
const resultado: {
|
||||||
@@ -82,44 +110,33 @@ export class UsuariosService {
|
|||||||
resultado.push({
|
resultado.push({
|
||||||
servicio: nombre,
|
servicio: nombre,
|
||||||
status: 'Inactivo',
|
status: 'Inactivo',
|
||||||
fecha_activacion: "",
|
fecha_activacion: '',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
await mapServicio('Red', servActivo.RedStatus);
|
await mapServicio('Red', servActivo.RedStatus);
|
||||||
await mapServicio('Correo', servActivo.CorreoStatus);
|
await mapServicio('Correo', servActivo.CorreoStatus);
|
||||||
await mapServicio('Préstamo de equipo PC Puma', servActivo.PrestamosStatus);
|
await mapServicio('Préstamo de equipo PC Puma', servActivo.PrestamosStatus);
|
||||||
await mapServicio('Préstamo de equipo en CEDETEC', servActivo.ATStatus);
|
await mapServicio('Préstamo de equipo en CEDETEC', servActivo.ATStatus);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if (resultado.length === 0) {
|
if (resultado.length === 0) {
|
||||||
return [{
|
return [
|
||||||
servicio: 'Ninguno',
|
{
|
||||||
status: 'No hay servicios activos para este usuario',
|
servicio: 'Ninguno',
|
||||||
fecha_activacion: null,
|
status: 'No hay servicios activos para este usuario',
|
||||||
}];
|
fecha_activacion: null,
|
||||||
|
},
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return { resultado, usuario: usuario.nombre };
|
return { resultado, usuario: usuario.nombre };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
update(id: number, updateUsuarioDto: UpdateUsuarioDto) {
|
update(id: number, updateUsuarioDto: UpdateUsuarioDto) {
|
||||||
return `This action updates a #${id} usuario`;
|
return `This action updates a #${id} usuario`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Cron('0 0 0 10,25 * *')
|
@Cron('0 0 0 10,25 * *')
|
||||||
async tareaMensual() {
|
async tareaMensual() {
|
||||||
this.logger.log('Ejecutando consulta mensual de profesores');
|
this.logger.log('Ejecutando consulta mensual de profesores');
|
||||||
@@ -131,10 +148,9 @@ export class UsuariosService {
|
|||||||
'SISTEMA',
|
'SISTEMA',
|
||||||
'LOADING',
|
'LOADING',
|
||||||
'Enviando solicitud de consulta masiva de profesores al WebService',
|
'Enviando solicitud de consulta masiva de profesores al WebService',
|
||||||
'CARGA MASIVA WEB SERVICE'
|
'CARGA MASIVA WEB SERVICE',
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
interface DatosEntrada {
|
interface DatosEntrada {
|
||||||
Nombre: string;
|
Nombre: string;
|
||||||
ApellidoPaterno: string;
|
ApellidoPaterno: string;
|
||||||
@@ -152,289 +168,226 @@ export class UsuariosService {
|
|||||||
fechaNacimiento: string;
|
fechaNacimiento: string;
|
||||||
rfc: string;
|
rfc: string;
|
||||||
genero: string;
|
genero: string;
|
||||||
correoPersonal: string;
|
|
||||||
nombramiento: string;
|
|
||||||
unidadResponsable: string;
|
|
||||||
curp: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const apiUrl = process.env.API_URL;
|
const apiUrl = process.env.API_URL;
|
||||||
if (!apiUrl) {
|
if (!apiUrl) return;
|
||||||
console.error("API_URL no está definida en las variables de entorno");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const entrada: DatosEntrada = {
|
const entrada: DatosEntrada = {
|
||||||
Nombre: "",
|
Nombre: '',
|
||||||
ApellidoPaterno: "",
|
ApellidoPaterno: '',
|
||||||
ApellidoMaterno: "",
|
ApellidoMaterno: '',
|
||||||
NumeroTrabajador: "",
|
NumeroTrabajador: '',
|
||||||
RFC: ""
|
RFC: '',
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(apiUrl, {
|
const response = await fetch(apiUrl, {
|
||||||
method: "POST",
|
method: 'POST',
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(entrada)
|
body: JSON.stringify(entrada),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response.status === 400) {
|
if (!response.ok) return;
|
||||||
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) throw new Error("Error en la petición: " + response.statusText);
|
const profesores: DatosRespuesta[] = await response.json();
|
||||||
|
|
||||||
const json: DatosRespuesta[] = await response.json();
|
|
||||||
|
|
||||||
let nuevos = 0;
|
let nuevos = 0;
|
||||||
let actualizados = 0;
|
let actualizados = 0;
|
||||||
|
|
||||||
let existe = await this.tipoUsuarioRepository.findOne({ where: { tipo_usuario: 'Profesor' } });
|
/* ==========================
|
||||||
if (!existe) {
|
TIPO USUARIO PROFESOR
|
||||||
const tipoUsuario = this.tipoUsuarioRepository.create({ tipo_usuario: 'Profesor' });
|
========================== */
|
||||||
existe = await this.tipoUsuarioRepository.save(tipoUsuario);
|
let tipoProfesor = await this.tipoUsuarioRepository.findOne({
|
||||||
|
where: { tipo_usuario: 'Profesor' },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!tipoProfesor) {
|
||||||
|
tipoProfesor = await this.tipoUsuarioRepository.save(
|
||||||
|
this.tipoUsuarioRepository.create({ tipo_usuario: 'Profesor' }),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const prof of json) {
|
/* ==========================
|
||||||
try {
|
CACHE DE CARRERAS
|
||||||
if (!prof.rfc || !prof.nombre) {
|
========================== */
|
||||||
console.warn('Profesor con datos incompletos detectado:', prof);
|
const carreraCache = new Map<string, any>();
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const existente = await this.usuarioRepository.findOne({
|
for (const prof of profesores) {
|
||||||
where: { rfc: prof.rfc },
|
if (!prof.rfc || !prof.nombre) continue;
|
||||||
relations: ['genero']
|
|
||||||
|
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) {
|
if (!carrera) {
|
||||||
let genero: Genero | null = null;
|
carrera = await this.carreraRepository.save(
|
||||||
if (prof.genero === 'M' || prof.genero === 'F') {
|
this.carreraRepository.create({
|
||||||
const generoTexto = prof.genero === 'M' ? 'Masculino' : 'Femenino';
|
carrera: nombreCarrera,
|
||||||
genero = await this.generoRepository.findOne({ where: { genero: generoTexto } });
|
clave: '',
|
||||||
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() } })
|
carreraCache.set(nombreCarrera, carrera);
|
||||||
|
}
|
||||||
|
|
||||||
if (!carrera) {
|
/* ==========================
|
||||||
const nuevaCarrera = await this.carreraRepository.create({ carrera: prof.nombreCarrera.trim(), clave: '' });
|
USUARIO NUEVO
|
||||||
carrera = await this.carreraRepository.save(nuevaCarrera);
|
========================== */
|
||||||
}
|
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(
|
||||||
const nuevo = await this.usuarioRepository.create({
|
this.usuarioRepository.create({
|
||||||
num_cuenta: prof.numeroTrabajador == '' ? undefined : prof.numeroTrabajador,
|
num_cuenta: prof.numeroTrabajador || undefined,
|
||||||
nombre: prof.nombre,
|
nombre: prof.nombre,
|
||||||
a_paterno: prof.apellidoPaterno,
|
a_paterno: prof.apellidoPaterno,
|
||||||
a_materno: prof.apellidoMaterno,
|
a_materno: prof.apellidoMaterno,
|
||||||
rfc: prof.rfc,
|
rfc: prof.rfc,
|
||||||
fecha_nacimiento: prof.fechaNacimiento,
|
fecha_nacimiento: prof.fechaNacimiento,
|
||||||
genero,
|
genero,
|
||||||
|
movimiento: mov,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
movimiento: mov
|
await this.servActivosRepository.save(
|
||||||
});
|
this.servActivosRepository.create({
|
||||||
|
usuario: nuevoUsuario,
|
||||||
const savedUser = await this.usuarioRepository.save(nuevo);
|
AT: !!prof.numeroTrabajador,
|
||||||
|
Red: !!prof.numeroTrabajador,
|
||||||
const servActivo = await this.servActivosRepository.create({
|
Prestamos: !!prof.numeroTrabajador,
|
||||||
|
Correo: true,
|
||||||
ATStatus: 'Inactivo',
|
ATStatus: 'Inactivo',
|
||||||
RedStatus: 'Inactivo',
|
RedStatus: 'Inactivo',
|
||||||
PrestamosStatus: 'Inactivo',
|
PrestamosStatus: 'Inactivo',
|
||||||
CorreoStatus: 'Inactivo',
|
CorreoStatus: 'Inactivo',
|
||||||
usuario: savedUser,
|
}),
|
||||||
AT: prof.numeroTrabajador !== '',
|
);
|
||||||
Red: prof.numeroTrabajador !== '',
|
|
||||||
Prestamos: prof.numeroTrabajador !== '',
|
|
||||||
Correo: true
|
|
||||||
});
|
|
||||||
|
|
||||||
await this.servActivosRepository.save(servActivo);
|
await this.carreraUsuario.save(
|
||||||
|
this.carreraUsuario.create({
|
||||||
|
usuario: nuevoUsuario,
|
||||||
|
carrera,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
const userCarrera = await this.carreraUsuario.create({ carrera, usuario: savedUser });
|
await this.usuarioTipoUsuario.save(
|
||||||
const usuarioTipo = await this.usuarioTipoUsuario.create({ tipoUsuario: existe, usuario: savedUser });
|
this.usuarioTipoUsuario.create({
|
||||||
|
usuario: nuevoUsuario,
|
||||||
|
tipoUsuario: tipoProfesor,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
await this.carreraUsuario.save(userCarrera);
|
nuevos++;
|
||||||
await this.usuarioTipoUsuario.save(usuarioTipo);
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
nuevos++;
|
/* ==========================
|
||||||
} else {
|
USUARIO EXISTENTE
|
||||||
let cambios = false;
|
========================== */
|
||||||
|
let cambios = false;
|
||||||
|
|
||||||
|
const servActivo = await this.servActivosRepository.findOne({
|
||||||
|
where: { usuario: { id_usuario: usuario.id_usuario } },
|
||||||
|
});
|
||||||
|
|
||||||
if (existente.nombre !== prof.nombre) {
|
const activarServicios = () => {
|
||||||
existente.nombre = prof.nombre;
|
if (!servActivo) return;
|
||||||
const servActivo = await this.servActivosRepository.findOne({ where: { usuario: { id_usuario: existente.id_usuario } } });
|
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 (servActivo) {
|
if (usuario.a_paterno !== prof.apellidoPaterno) {
|
||||||
servActivo.Red = true;
|
usuario.a_paterno = prof.apellidoPaterno;
|
||||||
servActivo.AT = true;
|
activarServicios();
|
||||||
servActivo.Prestamos = true;
|
cambios = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (usuario.a_materno !== prof.apellidoMaterno) {
|
||||||
|
usuario.a_materno = prof.apellidoMaterno;
|
||||||
|
activarServicios();
|
||||||
|
cambios = true;
|
||||||
|
}
|
||||||
|
|
||||||
servActivo.ATStatus = 'Inactivo';
|
if (usuario.fecha_nacimiento !== prof.fechaNacimiento) {
|
||||||
servActivo.PrestamosStatus = 'Inactivo';
|
usuario.fecha_nacimiento = prof.fechaNacimiento;
|
||||||
servActivo.RedStatus = 'Inactivo';
|
activarServicios();
|
||||||
await this.servActivosRepository.save(servActivo);
|
cambios = true;
|
||||||
} else {
|
}
|
||||||
console.warn('No se encontró el servicio activo para el usuario:', existente);
|
|
||||||
}
|
|
||||||
cambios = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (existente.a_paterno !== prof.apellidoPaterno) {
|
if (
|
||||||
existente.a_paterno = prof.apellidoPaterno;
|
prof.numeroTrabajador &&
|
||||||
const servActivo = await this.servActivosRepository.findOne({ where: { usuario: { id_usuario: existente.id_usuario } } });
|
usuario.num_cuenta !== prof.numeroTrabajador
|
||||||
|
) {
|
||||||
|
usuario.num_cuenta = prof.numeroTrabajador;
|
||||||
|
activarServicios();
|
||||||
|
cambios = true;
|
||||||
|
}
|
||||||
|
|
||||||
if (servActivo) {
|
if (cambios) {
|
||||||
servActivo.Red = true;
|
usuario.movimiento = mov;
|
||||||
servActivo.AT = true;
|
await this.usuarioRepository.save(usuario);
|
||||||
servActivo.Prestamos = true;
|
if (servActivo) await this.servActivosRepository.save(servActivo);
|
||||||
|
actualizados++;
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.movimientoService.updateStatus(mov.id_mov, 'SUCCESS', 'Carga masiva de web Service completa: ' + `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: '<p></p>'
|
|
||||||
})
|
|
||||||
|
|
||||||
this.excelService.enviarCargaMasiva();
|
await this.movimientoService.updateStatus(
|
||||||
|
mov.id_mov,
|
||||||
|
'SUCCESS',
|
||||||
|
`Carga masiva finalizada. Nuevos: ${nuevos}, Actualizados: ${actualizados}`,
|
||||||
|
);
|
||||||
|
|
||||||
return `Importación finalizada. Nuevos: ${nuevos}, Actualizados: ${actualizados}`;
|
return `Importación finalizada. Nuevos: ${nuevos}, Actualizados: ${actualizados}`;
|
||||||
|
|
||||||
} catch (error) {
|
} 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;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async cargaIndividual(
|
||||||
async cargaIndividual(usuario: CreateUsuarioDto, origen: string) {
|
usuario: CreateUsuarioDto,
|
||||||
const queryRunner = this.usuarioRepository.manager.connection.createQueryRunner();
|
origen: string,
|
||||||
|
user: string,
|
||||||
|
) {
|
||||||
|
const queryRunner =
|
||||||
|
this.usuarioRepository.manager.connection.createQueryRunner();
|
||||||
await queryRunner.connect();
|
await queryRunner.connect();
|
||||||
await queryRunner.startTransaction();
|
await queryRunner.startTransaction();
|
||||||
|
|
||||||
@@ -448,24 +401,49 @@ export class UsuariosService {
|
|||||||
throw new Error('Ya existe este usuario');
|
throw new Error('Ya existe este usuario');
|
||||||
}
|
}
|
||||||
|
|
||||||
const mov = await this.movimientoService.logger(queryRunner, origen, 'LOADING', undefined, 'CARGA INDIVIDUAL DE USUARIOS');
|
const mov = await this.movimientoService.logger(
|
||||||
|
queryRunner,
|
||||||
|
origen,
|
||||||
|
'LOADING',
|
||||||
|
'la carga se hizo por: ' + user,
|
||||||
|
'CARGA INDIVIDUAL DE USUARIOS',
|
||||||
|
);
|
||||||
|
|
||||||
let genero: Genero | null = null;
|
let genero: Genero | null = null;
|
||||||
if (usuario.genero === 'M' || usuario.genero === 'F') {
|
if (usuario.genero === 'M' || usuario.genero === 'F') {
|
||||||
const generoTexto = usuario.genero === 'M' ? 'Masculino' : 'Femenino';
|
const generoTexto = usuario.genero === 'M' ? 'Masculino' : 'Femenino';
|
||||||
genero = await queryRunner.manager.findOne(Genero, { where: { genero: generoTexto } });
|
genero = await queryRunner.manager.findOne(Genero, {
|
||||||
|
where: { genero: generoTexto },
|
||||||
|
});
|
||||||
if (!genero) {
|
if (!genero) {
|
||||||
genero = queryRunner.manager.create(Genero, { genero: generoTexto });
|
genero = queryRunner.manager.create(Genero, { genero: generoTexto });
|
||||||
await queryRunner.manager.save(genero);
|
await queryRunner.manager.save(genero);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let carrera = await queryRunner.manager.findOne(Carrera, { where: { carrera: usuario.carrera } });
|
let carrera;
|
||||||
if (!carrera) {
|
if (usuario.carrera != undefined) {
|
||||||
const nuevaCarrera = queryRunner.manager.create(Carrera, { carrera: usuario.carrera, clave: usuario.clave_carrera });
|
carrera = await queryRunner.manager.findOne(Carrera, {
|
||||||
carrera = await queryRunner.manager.save(nuevaCarrera);
|
where: { carrera: usuario.carrera },
|
||||||
}
|
});
|
||||||
|
|
||||||
|
if (!carrera) {
|
||||||
|
carrera = await queryRunner.manager.findOne(Carrera, {
|
||||||
|
where: { carrera: '' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
carrera = await queryRunner.manager.findOne(Carrera, {
|
||||||
|
where: { carrera: '' },
|
||||||
|
});
|
||||||
|
if (!carrera) {
|
||||||
|
const nuevaCarrera = queryRunner.manager.create(Carrera, {
|
||||||
|
carrera: '',
|
||||||
|
clave: '',
|
||||||
|
});
|
||||||
|
carrera = await queryRunner.manager.save(nuevaCarrera);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const nuevo = queryRunner.manager.create(Usuario, {
|
const nuevo = queryRunner.manager.create(Usuario, {
|
||||||
num_cuenta: usuario.num_cuenta ?? usuario.usuario,
|
num_cuenta: usuario.num_cuenta ?? usuario.usuario,
|
||||||
@@ -482,16 +460,33 @@ export class UsuariosService {
|
|||||||
|
|
||||||
const savedUser = await queryRunner.manager.save(nuevo);
|
const savedUser = await queryRunner.manager.save(nuevo);
|
||||||
|
|
||||||
const userCarrera = queryRunner.manager.create(CarreraUsuario, { carrera, usuario: savedUser });
|
const userCarrera = queryRunner.manager.create(CarreraUsuario, {
|
||||||
|
carrera,
|
||||||
|
usuario: savedUser,
|
||||||
|
});
|
||||||
|
await queryRunner.manager.save(userCarrera);
|
||||||
|
|
||||||
const FieldMap = [
|
const FieldMap = [
|
||||||
'Diplomado', 'Extra Largo', 'Servicio Social', 'Idiomas R (UNAM)', 'Idiomas Sabatino',
|
'Diplomado',
|
||||||
'Reinscrito', 'Posgrado', 'Intercambio UNAM', 'Movilidad', 'Ampliación de Conocimiento',
|
'Extra Largo',
|
||||||
'Licenciatura', 'Profesor', 'Trabajadores', 'Caso especial',
|
'Servicio Social',
|
||||||
|
'Idiomas R (UNAM)',
|
||||||
|
'Idiomas Sabatino',
|
||||||
|
'Reinscrito',
|
||||||
|
'Posgrado',
|
||||||
|
'Intercambio UNAM',
|
||||||
|
'Movilidad',
|
||||||
|
'Ampliación de Conocimiento',
|
||||||
|
'Licenciatura',
|
||||||
|
'Profesor',
|
||||||
|
'Trabajadores',
|
||||||
|
'Caso especial',
|
||||||
];
|
];
|
||||||
|
|
||||||
if (!FieldMap.includes(usuario.tipo_usuario)) {
|
if (!FieldMap.includes(usuario.tipo_usuario)) {
|
||||||
throw new Error(`Tipo de usuario no permitido: ${usuario.tipo_usuario}`);
|
throw new Error(
|
||||||
|
`Tipo de usuario no permitido: ${usuario.tipo_usuario}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verifica si el tipo de usuario ya existe
|
// Verifica si el tipo de usuario ya existe
|
||||||
@@ -514,14 +509,13 @@ export class UsuariosService {
|
|||||||
});
|
});
|
||||||
await queryRunner.manager.save(usuarioTipo);
|
await queryRunner.manager.save(usuarioTipo);
|
||||||
|
|
||||||
|
let at: boolean = false;
|
||||||
|
let correo: boolean = false;
|
||||||
|
let red: boolean = false;
|
||||||
|
let solicita: boolean = false;
|
||||||
|
|
||||||
switch (usuario.tipo_usuario.trim()) {
|
switch (usuario.tipo_usuario.trim()) {
|
||||||
|
|
||||||
case 'Diplomado':
|
case 'Diplomado':
|
||||||
|
|
||||||
const servActivosDiplomado = this.servActivosRepository.create({
|
const servActivosDiplomado = this.servActivosRepository.create({
|
||||||
Correo: true,
|
Correo: true,
|
||||||
usuario: savedUser,
|
usuario: savedUser,
|
||||||
@@ -530,8 +524,8 @@ export class UsuariosService {
|
|||||||
CorreoStatus: 'Inactivo',
|
CorreoStatus: 'Inactivo',
|
||||||
PrestamosStatus: 'Inactivo',
|
PrestamosStatus: 'Inactivo',
|
||||||
});
|
});
|
||||||
|
correo = true;
|
||||||
await queryRunner.manager.save(servActivosDiplomado);
|
await queryRunner.manager.save(servActivosDiplomado);
|
||||||
|
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'Extra Largo':
|
case 'Extra Largo':
|
||||||
@@ -543,8 +537,9 @@ export class UsuariosService {
|
|||||||
ATStatus: 'Inactivo',
|
ATStatus: 'Inactivo',
|
||||||
CorreoStatus: 'Inactivo',
|
CorreoStatus: 'Inactivo',
|
||||||
PrestamosStatus: 'Inactivo',
|
PrestamosStatus: 'Inactivo',
|
||||||
|
|
||||||
});
|
});
|
||||||
|
solicita = true;
|
||||||
|
correo = true;
|
||||||
await queryRunner.manager.save(servActivosExtraLargo);
|
await queryRunner.manager.save(servActivosExtraLargo);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
@@ -559,11 +554,12 @@ export class UsuariosService {
|
|||||||
CorreoStatus: 'Inactivo',
|
CorreoStatus: 'Inactivo',
|
||||||
PrestamosStatus: 'Inactivo',
|
PrestamosStatus: 'Inactivo',
|
||||||
});
|
});
|
||||||
|
at = true;
|
||||||
|
red = true;
|
||||||
|
correo = true;
|
||||||
await queryRunner.manager.save(servActivosServicio);
|
await queryRunner.manager.save(servActivosServicio);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
case 'Idiomas R (UNAM)':
|
case 'Idiomas R (UNAM)':
|
||||||
case 'Idiomas Sabatino':
|
case 'Idiomas Sabatino':
|
||||||
const servActivosIdiomas = this.servActivosRepository.create({
|
const servActivosIdiomas = this.servActivosRepository.create({
|
||||||
@@ -575,13 +571,12 @@ export class UsuariosService {
|
|||||||
CorreoStatus: 'Inactivo',
|
CorreoStatus: 'Inactivo',
|
||||||
PrestamosStatus: 'Inactivo',
|
PrestamosStatus: 'Inactivo',
|
||||||
});
|
});
|
||||||
|
red = true;
|
||||||
|
correo = true;
|
||||||
await queryRunner.manager.save(servActivosIdiomas);
|
await queryRunner.manager.save(servActivosIdiomas);
|
||||||
|
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
case 'Reinscrito':
|
case 'Reinscrito':
|
||||||
case 'Posgrado':
|
case 'Posgrado':
|
||||||
case 'Intercambio UNAM':
|
case 'Intercambio UNAM':
|
||||||
@@ -590,7 +585,6 @@ export class UsuariosService {
|
|||||||
case 'Licenciatura':
|
case 'Licenciatura':
|
||||||
case 'Profesor':
|
case 'Profesor':
|
||||||
const servActivos = this.servActivosRepository.create({
|
const servActivos = this.servActivosRepository.create({
|
||||||
|
|
||||||
Red: true,
|
Red: true,
|
||||||
AT: true,
|
AT: true,
|
||||||
Correo: true,
|
Correo: true,
|
||||||
@@ -601,36 +595,34 @@ export class UsuariosService {
|
|||||||
CorreoStatus: 'Inactivo',
|
CorreoStatus: 'Inactivo',
|
||||||
PrestamosStatus: 'Inactivo',
|
PrestamosStatus: 'Inactivo',
|
||||||
});
|
});
|
||||||
|
at = true;
|
||||||
|
red = true;
|
||||||
|
correo = true;
|
||||||
|
solicita = true;
|
||||||
await queryRunner.manager.save(servActivos);
|
await queryRunner.manager.save(servActivos);
|
||||||
|
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
|
||||||
case 'Caso especial':
|
case 'Caso especial':
|
||||||
case 'Trabajadores':
|
case 'Trabajadores':
|
||||||
const servActivosTrabajadores = this.servActivosRepository.create({
|
const servActivosTrabajadores = this.servActivosRepository.create({
|
||||||
Red: true,
|
Red: true,
|
||||||
usuario: savedUser,
|
usuario: savedUser,
|
||||||
RedStatus: 'Inactivo',
|
RedStatus: 'Inactivo',
|
||||||
|
|
||||||
});
|
});
|
||||||
|
red = true;
|
||||||
await queryRunner.manager.save(servActivosTrabajadores);
|
await queryRunner.manager.save(servActivosTrabajadores);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
console.log(savedUser)
|
|
||||||
await queryRunner.commitTransaction();
|
await queryRunner.commitTransaction();
|
||||||
|
|
||||||
return { saved: savedUser, movId: mov.id_mov };
|
return { saved: savedUser, movId: mov.id_mov, at, correo, red, solicita };
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await queryRunner.rollbackTransaction();
|
await queryRunner.rollbackTransaction();
|
||||||
throw error;
|
throw new Error('Error en la carga individual: ' + error.message);
|
||||||
} finally {
|
} finally {
|
||||||
await queryRunner.release();
|
await queryRunner.release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user