Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ff4364a55f | |||
| 4be22ac054 | |||
| c08dc2e7e3 | |||
| 772a4e2344 | |||
| 100695148a | |||
| 780bde0b61 | |||
| 95d4fa506c | |||
| 4510999453 | |||
| 1f76cb5c5b | |||
| e72b71e479 | |||
| a7ab20be29 | |||
| 3eafb38f1f |
@@ -0,0 +1,18 @@
|
||||
API_PORT = 4000
|
||||
JWT_SECRET = "your_jwt_secret"
|
||||
JWT_EXPIRES_IN = "1h"
|
||||
DB_HOST = localhost
|
||||
DB_PORT = 32769
|
||||
DB_USER = root
|
||||
DB_PASS = root
|
||||
DB_NAME = carga_test
|
||||
DB_SYNC = true
|
||||
//api
|
||||
API_URL = //URL web service
|
||||
|
||||
|
||||
//Gmail configuration, llaves de acceso
|
||||
EMAIL_USER =
|
||||
CLIENT_ID =
|
||||
CLIENT_SECRET =
|
||||
REFRESH_TOKEN =
|
||||
Generated
+52
@@ -15,6 +15,7 @@
|
||||
"@nestjs/jwt": "^11.0.0",
|
||||
"@nestjs/passport": "^11.0.5",
|
||||
"@nestjs/platform-express": "^11.1.3",
|
||||
"@nestjs/schedule": "^6.0.0",
|
||||
"@nestjs/swagger": "^11.2.0",
|
||||
"@nestjs/typeorm": "^11.0.0",
|
||||
"bcrypt": "^6.0.0",
|
||||
@@ -24,6 +25,7 @@
|
||||
"exceljs": "^4.4.0",
|
||||
"multer": "^2.0.1",
|
||||
"mysql2": "^3.14.1",
|
||||
"nodemailer": "^7.0.3",
|
||||
"passport": "^0.7.0",
|
||||
"passport-jwt": "^4.0.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
@@ -2657,6 +2659,19 @@
|
||||
"@nestjs/core": "^11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@nestjs/schedule": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@nestjs/schedule/-/schedule-6.0.0.tgz",
|
||||
"integrity": "sha512-aQySMw6tw2nhitELXd3EiRacQRgzUKD9mFcUZVOJ7jPLqIBvXOyvRWLsK9SdurGA+jjziAlMef7iB5ZEFFoQpw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cron": "4.3.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@nestjs/common": "^10.0.0 || ^11.0.0",
|
||||
"@nestjs/core": "^10.0.0 || ^11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@nestjs/schematics": {
|
||||
"version": "11.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@nestjs/schematics/-/schematics-11.0.5.tgz",
|
||||
@@ -3566,6 +3581,12 @@
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/luxon": {
|
||||
"version": "3.6.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/luxon/-/luxon-3.6.2.tgz",
|
||||
"integrity": "sha512-R/BdP7OxEMc44l2Ex5lSXHoIXTB2JLNa3y2QISIbr58U/YcsffyQrYW//hZSdrfxrjRZj3GcUoxMPGdO8gSYuw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/methods": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz",
|
||||
@@ -6158,6 +6179,19 @@
|
||||
"devOptional": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/cron": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/cron/-/cron-4.3.0.tgz",
|
||||
"integrity": "sha512-ciiYNLfSlF9MrDqnbMdRWFiA6oizSF7kA1osPP9lRzNu0Uu+AWog1UKy7SkckiDY2irrNjeO6qLyKnXC8oxmrw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/luxon": "~3.6.0",
|
||||
"luxon": "~3.6.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.x"
|
||||
}
|
||||
},
|
||||
"node_modules/cross-spawn": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||
@@ -9504,6 +9538,15 @@
|
||||
"url": "https://github.com/sponsors/wellwelwel"
|
||||
}
|
||||
},
|
||||
"node_modules/luxon": {
|
||||
"version": "3.6.1",
|
||||
"resolved": "https://registry.npmjs.org/luxon/-/luxon-3.6.1.tgz",
|
||||
"integrity": "sha512-tJLxrKJhO2ukZ5z0gyjY1zPh3Rh88Ej9P7jNrZiHMUXHae1yvI2imgOZtL1TO8TW6biMMKfTtAOoEJANgtWBMQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/magic-string": {
|
||||
"version": "0.30.17",
|
||||
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.17.tgz",
|
||||
@@ -9935,6 +9978,15 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/nodemailer": {
|
||||
"version": "7.0.3",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.3.tgz",
|
||||
"integrity": "sha512-Ajq6Sz1x7cIK3pN6KesGTah+1gnwMnx5gKl3piQlQQE/PwyJ4Mbc8is2psWYxK3RJTVeqsDaCv8ZzXLCDHMTZw==",
|
||||
"license": "MIT-0",
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/normalize-path": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
"@nestjs/jwt": "^11.0.0",
|
||||
"@nestjs/passport": "^11.0.5",
|
||||
"@nestjs/platform-express": "^11.1.3",
|
||||
"@nestjs/schedule": "^6.0.0",
|
||||
"@nestjs/swagger": "^11.2.0",
|
||||
"@nestjs/typeorm": "^11.0.0",
|
||||
"bcrypt": "^6.0.0",
|
||||
@@ -35,6 +36,7 @@
|
||||
"exceljs": "^4.4.0",
|
||||
"multer": "^2.0.1",
|
||||
"mysql2": "^3.14.1",
|
||||
"nodemailer": "^7.0.3",
|
||||
"passport": "^0.7.0",
|
||||
"passport-jwt": "^4.0.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
|
||||
+9
-2
@@ -10,10 +10,14 @@ import { ExcelModule } from './excel/excel.module';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { MovimientoModule } from './movimiento/movimiento.module';
|
||||
import { UsuariosModule } from './usuarios/usuarios.module';
|
||||
import { MailService } from './mail/mail.service';
|
||||
import { MailModule } from './mail/mail.module';
|
||||
import { ScheduleModule } from '@nestjs/schedule';
|
||||
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ScheduleModule.forRoot(),
|
||||
ConfigModule.forRoot({ isGlobal: true }),
|
||||
TypeOrmModule.forRootAsync({
|
||||
imports: [ConfigModule],
|
||||
@@ -27,6 +31,7 @@ import { UsuariosModule } from './usuarios/usuarios.module';
|
||||
// no prints en claro en prod:
|
||||
password: config.get('DB_PASS', ''),
|
||||
database: config.get('DB_NAME', 'test'),
|
||||
dropSchema: false, // solo para desarrollo
|
||||
};
|
||||
Logger.log('[DB CONFIG] ' + JSON.stringify({
|
||||
...dbConfig,
|
||||
@@ -39,9 +44,10 @@ import { UsuariosModule } from './usuarios/usuarios.module';
|
||||
|
||||
logging: ['error', 'warn', 'info', 'query', 'schema'],
|
||||
logger: 'advanced-console',
|
||||
|
||||
retryAttempts: 5,
|
||||
retryDelay: 2000,
|
||||
dropSchema: true, // solo para desarrollo
|
||||
|
||||
};
|
||||
},
|
||||
}),
|
||||
@@ -51,7 +57,8 @@ import { UsuariosModule } from './usuarios/usuarios.module';
|
||||
ExcelModule,
|
||||
AuthModule,
|
||||
MovimientoModule,
|
||||
UsuariosModule
|
||||
UsuariosModule,
|
||||
MailModule
|
||||
|
||||
],
|
||||
controllers: [AppController],
|
||||
|
||||
@@ -77,7 +77,7 @@ export class AuthDocumentation {
|
||||
properties: {
|
||||
email: { type: 'string', format: 'email', example: 'nuevo@dominio.com' },
|
||||
password: { type: 'string', example: 'Password123' },
|
||||
origen: { type: 'string', example: 'redes', description: 'Origen del usuario' }
|
||||
origen: { type: 'string', example: 'RED', description: 'Origen del usuario' }
|
||||
|
||||
}
|
||||
}
|
||||
@@ -91,7 +91,7 @@ export class AuthDocumentation {
|
||||
id_usuario: { type: 'number', example: 1 },
|
||||
correo: { type: 'string', example: 'nuevo@dominio.com' },
|
||||
|
||||
origen: { type: 'string', example: 'redes' }
|
||||
origen: { type: 'string', example: 'RED' }
|
||||
|
||||
|
||||
}
|
||||
|
||||
+60
-33
@@ -1,4 +1,5 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, OneToMany, JoinColumn, PrimaryColumn } from 'typeorm';
|
||||
import { ServActivos } from 'src/usuarios/entities/servActivos.entitie';
|
||||
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, OneToMany, JoinColumn, PrimaryColumn, OneToOne } from 'typeorm';
|
||||
|
||||
@Entity({ name: 'origen' })
|
||||
export class Origen {
|
||||
@@ -42,6 +43,44 @@ export class Carrera {
|
||||
carreraUsuarios: CarreraUsuario[];
|
||||
}
|
||||
|
||||
@Entity({ name: 'movimiento' })
|
||||
export class Movimiento {
|
||||
@PrimaryGeneratedColumn({ name: 'id_mov', type: 'int' })
|
||||
id_mov: number;
|
||||
|
||||
@Column({ name: 'fecha_mov', type: 'datetime' })
|
||||
fecha_mov: Date;
|
||||
|
||||
@Column({ type: 'varchar', length: 100 })
|
||||
status: string;
|
||||
|
||||
@Column({
|
||||
type: 'varchar',
|
||||
length: 200,
|
||||
nullable: true, // permite NULL
|
||||
})
|
||||
observaciones?: string;
|
||||
|
||||
@Column({ type: 'bit' })
|
||||
flag: boolean;
|
||||
|
||||
@Column({
|
||||
type: 'varchar',
|
||||
length: 200,
|
||||
nullable: true, // permite NULL
|
||||
})
|
||||
reporte?: string;
|
||||
|
||||
@OneToMany(() => Usuario, usuario => usuario.movimiento)
|
||||
usuario: Usuario[];
|
||||
|
||||
|
||||
@ManyToOne(() => Origen, origen => origen.movimientos)
|
||||
@JoinColumn({ name: 'id_origen' })
|
||||
origen: Origen;
|
||||
}
|
||||
|
||||
|
||||
@Entity({ name: 'usuario' })
|
||||
export class Usuario {
|
||||
@PrimaryGeneratedColumn({ name: 'id_usuario', type: 'int' })
|
||||
@@ -49,7 +88,6 @@ export class Usuario {
|
||||
|
||||
@Column({
|
||||
type: 'varchar',
|
||||
length: 9,
|
||||
unique: true,
|
||||
nullable: true,
|
||||
default: null,
|
||||
@@ -65,6 +103,9 @@ export class Usuario {
|
||||
@Column({ name: 'a_materno', type: 'varchar', length: 60 })
|
||||
a_materno: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 20, nullable: true, default: null })
|
||||
contraseña: string | null;
|
||||
|
||||
@Column({
|
||||
type: 'varchar',
|
||||
length: 15,
|
||||
@@ -89,7 +130,17 @@ export class Usuario {
|
||||
|
||||
@OneToMany(() => UsuarioTipoUsuario, utu => utu.usuario)
|
||||
usuarioTipos: UsuarioTipoUsuario[];
|
||||
|
||||
@ManyToOne(() => Movimiento, movimiento => movimiento.usuario)
|
||||
@JoinColumn({ name: 'id_movimiento' })
|
||||
movimiento: Movimiento;
|
||||
|
||||
@OneToOne(() => ServActivos, (servActivo) => servActivo.usuario,)
|
||||
servActivo: ServActivos;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Entity({ name: 'carrera_usuario' })
|
||||
export class CarreraUsuario {
|
||||
@PrimaryGeneratedColumn({ name: 'id_carrera_usuario', type: 'int' })
|
||||
@@ -152,6 +203,12 @@ export class TipoUsuario {
|
||||
usuariosTipos: UsuarioTipoUsuario[];
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@Entity({ name: 'usuario_tipo_usuario' })
|
||||
export class UsuarioTipoUsuario {
|
||||
@PrimaryGeneratedColumn({ name: 'id_user_tipo_usuario', type: 'int' })
|
||||
@@ -166,36 +223,6 @@ export class UsuarioTipoUsuario {
|
||||
usuario: Usuario;
|
||||
}
|
||||
|
||||
@Entity({ name: 'movimiento' })
|
||||
export class Movimiento {
|
||||
@PrimaryGeneratedColumn({ name: 'id_mov', type: 'int' })
|
||||
id_mov: number;
|
||||
|
||||
@Column({ name: 'fecha_mov', type: 'datetime' })
|
||||
fecha_mov: Date;
|
||||
export { ServActivos };
|
||||
|
||||
@Column({ type: 'varchar', length: 100 })
|
||||
status: string;
|
||||
|
||||
@Column({
|
||||
type: 'varchar',
|
||||
length: 200,
|
||||
nullable: true, // permite NULL
|
||||
})
|
||||
observaciones?: string;
|
||||
|
||||
@Column({ type: 'bit' })
|
||||
flag: boolean;
|
||||
|
||||
@Column({
|
||||
type: 'varchar',
|
||||
length: 200,
|
||||
nullable: true, // permite NULL
|
||||
})
|
||||
reporte?: string;
|
||||
|
||||
|
||||
@ManyToOne(() => Origen, origen => origen.movimientos)
|
||||
@JoinColumn({ name: 'id_origen' })
|
||||
origen: Origen;
|
||||
}
|
||||
|
||||
+135
-20
@@ -1,5 +1,5 @@
|
||||
// src/excel/excel.controller.ts
|
||||
import { Controller, Post, Get, UseGuards, Request, Res, UploadedFile, UseInterceptors, HttpStatus } from '@nestjs/common';
|
||||
import { Controller, Post, Get, UseGuards, Request, Res, UploadedFile, UseInterceptors, HttpStatus, Param, ParseIntPipe, Body, BadRequestException } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
@@ -7,6 +7,10 @@ import { Response } from 'express';
|
||||
import { ExcelDocumentation } from './excel.documentation';
|
||||
import { ExcelService } from './excel.service';
|
||||
import { MovimientoService } from '../movimiento/movimiento.service';
|
||||
import { MailService } from 'src/mail/mail.service';
|
||||
import { CreateUsuarioDto } from 'src/usuarios/dto/create-usuario.dto';
|
||||
import { Origen } from 'src/entities/entities';
|
||||
import { UsuariosService } from 'src/usuarios/usuarios.service';
|
||||
|
||||
@UseGuards(AuthGuard('jwt'))
|
||||
@ApiBearerAuth('bearer')
|
||||
@@ -15,14 +19,42 @@ export class ExcelController {
|
||||
constructor(
|
||||
private readonly excelService: ExcelService,
|
||||
private readonly movimientoService: MovimientoService,
|
||||
private readonly mailService: MailService,
|
||||
private readonly usuarioService: UsuariosService // Asegúrate de importar el servicio de correo
|
||||
) { }
|
||||
|
||||
|
||||
@Post('carga')
|
||||
async cargaUsuario(@Request() req, @Body() usuario: CreateUsuarioDto) {
|
||||
console.log('Usuario recibido:', usuario);
|
||||
if (req.user.origen != 'LOAD') {
|
||||
throw new BadRequestException('Origen no permitido para carga')
|
||||
}
|
||||
const alta = await this.usuarioService.cargaIndividual(usuario, req.user.origen)
|
||||
console.log('Alta de usuario:', alta);
|
||||
await this.movimientoService.updateStatus(alta.movId, 'SUCCESS')
|
||||
|
||||
this.mailService.sendMail({
|
||||
to: req.user.email, // Asegúrate de que el usuario tenga un email
|
||||
subject: 'Carga de datos exitosa',
|
||||
text: "La carga de datos se ha realizado con éxito.",
|
||||
html: `<p>La carga de datos se ha realizado con éxito. ` + alta,
|
||||
});
|
||||
|
||||
await this.excelService.enviarCargaMasiva();
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Post('verify')
|
||||
@UseInterceptors(FileInterceptor('file'))
|
||||
@ExcelDocumentation.verifyExcel()
|
||||
async verifyExcel(@UploadedFile() file: Express.Multer.File, @Request() req) {
|
||||
const userId: number = req.user.userId; // ahora sí existe
|
||||
const errors = await this.excelService.validateFile(file.buffer);
|
||||
const status = await this.excelService.validateFile(file.buffer);
|
||||
const errors = status.errors;
|
||||
await this.movimientoService.log(
|
||||
|
||||
'VERIFY',
|
||||
@@ -39,7 +71,7 @@ export class ExcelController {
|
||||
const origen = req.user.origen; // ahora sí existe
|
||||
if (origen != 'LOAD') {
|
||||
await this.movimientoService.log(
|
||||
'LOAD',
|
||||
origen,
|
||||
'FAILED',
|
||||
'Origen no permitido para carga'
|
||||
);
|
||||
@@ -47,14 +79,51 @@ export class ExcelController {
|
||||
}
|
||||
try {
|
||||
const result = await this.excelService.loadFile(file.buffer);
|
||||
await this.movimientoService.log(
|
||||
//Actualizar el estado de los movimientos
|
||||
if (!result) {
|
||||
this.mailService.sendMail({
|
||||
to: req.user.email, // Asegúrate de que el usuario tenga un email
|
||||
subject: 'Carga de datos Fallida',
|
||||
text: "No se pudieron subir datos.",
|
||||
html: '<p>No se pudieron subir datos.</p>',
|
||||
});
|
||||
throw new Error('No se pudo procesar el archivo.');
|
||||
}
|
||||
|
||||
'LOAD',
|
||||
if (result.inserted == 0) {
|
||||
this.mailService.sendMail({
|
||||
to: req.user.email, // Asegúrate de que el usuario tenga un email
|
||||
subject: 'Carga de datos Fallida',
|
||||
text: "No se pudieron subir datos.",
|
||||
html: `<p> Se han insertado ${result.inserted} registros.</p>
|
||||
<p>Errores encontrados:</p>
|
||||
<ul>${result.errors.map(error => `<li>${error}</li>`).join('')}</ul>`,
|
||||
});
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
console.log(result.id_movimiento)
|
||||
await this.movimientoService.updateStatus(
|
||||
result.id_movimiento,
|
||||
'SUCCESS',
|
||||
undefined,
|
||||
`inserted=${result.inserted}`
|
||||
);
|
||||
return result;
|
||||
|
||||
this.mailService.sendMail({
|
||||
to: req.user.email, // Asegúrate de que el usuario tenga un email
|
||||
subject: 'Carga de datos exitosa',
|
||||
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>
|
||||
<p>Errores encontrados:</p>
|
||||
<ul>${result.errors.map(error => `<li>${error}</li>`).join('')}</ul>`,
|
||||
});
|
||||
|
||||
await this.excelService.enviarCargaMasiva();
|
||||
|
||||
|
||||
return result
|
||||
|
||||
} catch (err) {
|
||||
await this.movimientoService.log(
|
||||
|
||||
@@ -80,13 +149,13 @@ export class ExcelController {
|
||||
|
||||
origen,
|
||||
'SUCCESS',
|
||||
undefined,
|
||||
'descarga de csv',
|
||||
`size=${csv.length}`
|
||||
);
|
||||
return res
|
||||
.status(HttpStatus.OK)
|
||||
.header('Content-Type', 'text/tab-separated-values')
|
||||
.header('Content-Disposition', 'attachment; filename="usuarios_solicita.tsv"')
|
||||
.header('Content-Type', 'text/csv')
|
||||
.header('Content-Disposition', 'attachment; filename="usuarios_solicita.csv"')
|
||||
.send(csv);
|
||||
} catch (err) {
|
||||
await this.movimientoService.log(
|
||||
@@ -98,20 +167,28 @@ export class ExcelController {
|
||||
.status(HttpStatus.FORBIDDEN)
|
||||
.json({ statusCode: 403, message: 'Origen no permitido para descarga.' });
|
||||
}
|
||||
} else if (origen == 'CORREO') {
|
||||
} else if (origen == 'CORREO' || origen == 'LOAD') {
|
||||
try {
|
||||
const csv = await this.excelService.generateCsvCorreo();
|
||||
await this.movimientoService.log(
|
||||
|
||||
origen,
|
||||
'SUCCESS',
|
||||
undefined,
|
||||
'descarga de csv',
|
||||
`size=${csv.length}`
|
||||
);
|
||||
let filename
|
||||
if (origen == 'CORREO') {
|
||||
filename = 'usuarios_correo.csv';
|
||||
}
|
||||
else {
|
||||
filename = 'usuarios.csv';
|
||||
}
|
||||
|
||||
return res
|
||||
.status(HttpStatus.OK)
|
||||
.header('Content-Type', 'text/tab-separated-values')
|
||||
.header('Content-Disposition', 'attachment; filename="usuarios.tsv"')
|
||||
.header('Content-Type', 'text/csv')
|
||||
.header('Content-Disposition', `attachment; filename="${filename}"`)
|
||||
.send(csv);
|
||||
} catch (err) {
|
||||
await this.movimientoService.log(
|
||||
@@ -131,13 +208,13 @@ export class ExcelController {
|
||||
|
||||
origen,
|
||||
'SUCCESS',
|
||||
undefined,
|
||||
'descarga de csv',
|
||||
`size=${csv.length}`
|
||||
);
|
||||
return res
|
||||
.status(HttpStatus.OK)
|
||||
.header('Content-Type', 'text/tab-separated-values')
|
||||
.header('Content-Disposition', 'attachment; filename="usuarios_at.tsv"')
|
||||
.header('Content-Type', 'text/csv')
|
||||
.header('Content-Disposition', 'attachment; filename="usuarios_AT.csv"')
|
||||
.send(csv);
|
||||
} catch (err) {
|
||||
await this.movimientoService.log(
|
||||
@@ -157,13 +234,13 @@ export class ExcelController {
|
||||
|
||||
origen,
|
||||
'SUCCESS',
|
||||
undefined,
|
||||
'descarga de csv',
|
||||
`size=${csv.length}`
|
||||
);
|
||||
return res
|
||||
.status(HttpStatus.OK)
|
||||
.header('Content-Type', 'text/tab-separated-values')
|
||||
.header('Content-Disposition', 'attachment; filename="usuarios_red.tsv"')
|
||||
.header('Content-Type', 'text/csv')
|
||||
.header('Content-Disposition', 'attachment; filename="usuarios_red.csv"')
|
||||
.send(csv);
|
||||
} catch (err) {
|
||||
await this.movimientoService.log(
|
||||
@@ -189,4 +266,42 @@ export class ExcelController {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//Agregarlo en su propio controller
|
||||
@Get('movimientos')
|
||||
async getMovimientos(@Request() req) {
|
||||
|
||||
const movimientos = await this.movimientoService.findAll(req.user.origen);
|
||||
return movimientos;
|
||||
}
|
||||
|
||||
@Post('activar-servicios/:id_movimiento')
|
||||
async activarServicios(
|
||||
@Param('id_movimiento', ParseIntPipe) id_movimiento: number,
|
||||
@Request() req,
|
||||
): Promise<{ message: string }> {
|
||||
const origen = req.user.origen;
|
||||
|
||||
if (!origen) {
|
||||
throw new Error('No se encontró origen en el JWT');
|
||||
}
|
||||
|
||||
await this.excelService.activarServicios(id_movimiento, origen);
|
||||
|
||||
return { message: 'Servicios activados correctamente' };
|
||||
}
|
||||
|
||||
|
||||
@Get('cargaIndividual')
|
||||
async cargarIndividual(
|
||||
@Request() req) {
|
||||
const origen = req.user.origen; // ahora sí existe
|
||||
return this.movimientoService.findAllCargaIndv(origen);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -2,15 +2,21 @@ import { Module } from '@nestjs/common';
|
||||
import { ExcelService } from './excel.service';
|
||||
import { ExcelController } from './excel.controller';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Usuario, Genero, Carrera, CarreraUsuario, UsuarioTipoUsuario, TipoUsuario } from '../entities/entities';
|
||||
import { Usuario, Genero, Carrera, CarreraUsuario, UsuarioTipoUsuario, TipoUsuario, UsuariosDelSistema } from '../entities/entities';
|
||||
import { MovimientoModule } from 'src/movimiento/movimiento.module';
|
||||
import { ServActivos } from 'src/usuarios/entities/servActivos.entitie';
|
||||
import { MailModule } from 'src/mail/mail.module';
|
||||
import { UsuariosService } from 'src/usuarios/usuarios.service';
|
||||
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Usuario, Genero, Carrera, CarreraUsuario, UsuarioTipoUsuario, TipoUsuario]),
|
||||
MovimientoModule
|
||||
TypeOrmModule.forFeature([Usuario, Genero, Carrera, CarreraUsuario, UsuarioTipoUsuario, TipoUsuario, ServActivos, UsuariosDelSistema]),
|
||||
MovimientoModule,
|
||||
MailModule,
|
||||
|
||||
],
|
||||
providers: [ExcelService],
|
||||
providers: [ExcelService, UsuariosService],
|
||||
controllers: [ExcelController],
|
||||
})
|
||||
export class ExcelModule { }
|
||||
|
||||
+364
-138
@@ -1,11 +1,14 @@
|
||||
// src/excel/excel.service.ts
|
||||
import { Injectable, BadRequestException, Logger } from '@nestjs/common';
|
||||
import { Workbook } from 'exceljs';
|
||||
import { In, Repository } from 'typeorm';
|
||||
import { DataSource, In, Repository } from 'typeorm';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { CarreraUsuario, TipoUsuario, Usuario, UsuarioTipoUsuario } from '../entities/entities';
|
||||
import { CarreraUsuario, TipoUsuario, Usuario, UsuariosDelSistema, UsuarioTipoUsuario } from '../entities/entities';
|
||||
import { Genero } from '../entities/entities';
|
||||
import { Carrera } from '../entities/entities';
|
||||
import { MovimientoService } from 'src/movimiento/movimiento.service';
|
||||
import { ServActivos } from 'src/usuarios/entities/servActivos.entitie';
|
||||
import { MailService } from 'src/mail/mail.service';
|
||||
|
||||
export interface UsuarioRow {
|
||||
cuenta: string;
|
||||
@@ -40,6 +43,14 @@ export class ExcelService {
|
||||
private readonly usuarioTipoUsuarioRepo: Repository<UsuarioTipoUsuario>,
|
||||
@InjectRepository(TipoUsuario)
|
||||
private readonly tipoUsuarioRepo: Repository<TipoUsuario>,
|
||||
@InjectRepository(ServActivos)
|
||||
private readonly servActivosRepo: Repository<ServActivos>,
|
||||
@InjectRepository(UsuariosDelSistema)
|
||||
private readonly usuariosDelSistemaRepo: Repository<UsuariosDelSistema>,
|
||||
private readonly movimientoService: MovimientoService,
|
||||
private readonly mailService: MailService,
|
||||
private readonly dataSource: DataSource
|
||||
|
||||
// … inyecta otros repositorios si los usarás
|
||||
) { }
|
||||
|
||||
@@ -101,33 +112,46 @@ export class ExcelService {
|
||||
validateRows(rows: UsuarioRow[]) {
|
||||
const errors: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
const rowsGood: UsuarioRow[] = [];
|
||||
let flagError: boolean = false;
|
||||
|
||||
rows.forEach((r, i) => {
|
||||
const rowNum = i + 2; // por el encabezado
|
||||
|
||||
// Campos que no pueden quedar vacíos
|
||||
['cuenta', 'nombreCompleto'].forEach(field => {
|
||||
['cuenta', 'tipo'].forEach(field => {
|
||||
const raw = (r as any)[field];
|
||||
const str = raw != null ? raw.toString().trim() : '';
|
||||
if (!str) {
|
||||
errors.push(`Fila ${rowNum}: campo "${field}" está vacío.`);
|
||||
flagError = true;
|
||||
}
|
||||
});
|
||||
|
||||
// El número de cuenta debe ser de nueve dígitos para los alumnos
|
||||
if (r.cuenta && !/^\d{9}$/.test(r.cuenta.toString().trim()) && r.tipo.trim() === 'Licenciatura') {
|
||||
errors.push(`Fila ${rowNum}: cuenta "${r.cuenta}" debe tener 9 dígitos.`);
|
||||
flagError = true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Duplicados de "cuenta"
|
||||
const cuentaStr = r.cuenta != null ? r.cuenta.toString().trim() : '';
|
||||
if (seen.has(cuentaStr)) {
|
||||
errors.push(`Fila ${rowNum}: cuenta duplicada "${cuentaStr}".`);
|
||||
flagError = true;
|
||||
} else {
|
||||
seen.add(cuentaStr);
|
||||
}
|
||||
|
||||
// Numérico en cuenta y generación
|
||||
|
||||
|
||||
|
||||
const genStr = r.gen != null ? r.gen.toString().trim() : '';
|
||||
if (genStr && !/^[0-9]{4}$/.test(genStr)) {
|
||||
errors.push(`Fila ${rowNum}: generación inválida "${genStr}".`);
|
||||
flagError = true;
|
||||
}
|
||||
|
||||
|
||||
@@ -135,16 +159,29 @@ export class ExcelService {
|
||||
const fechaStr = r.fechnac != null ? r.fechnac.toString().trim() : '';
|
||||
if (!/^[0-9]{8}$/.test(fechaStr)) {
|
||||
errors.push(`Fila ${rowNum}: fecha de nacimiento inválida "${fechaStr}".`);
|
||||
flagError = true;
|
||||
}
|
||||
|
||||
// RFC alfanumérico
|
||||
const rfcStr = r.rfc != null ? r.rfc.toString().trim() : '';
|
||||
if (rfcStr && !/^[A-Z0-9]+$/.test(rfcStr)) {
|
||||
errors.push(`Fila ${rowNum}: RFC contiene caracteres no válidos.`);
|
||||
flagError = true;
|
||||
}
|
||||
|
||||
if (!flagError) {
|
||||
rowsGood.push(r)
|
||||
} else {
|
||||
flagError = false; // reset para la siguiente fila
|
||||
}
|
||||
|
||||
|
||||
|
||||
});
|
||||
|
||||
return errors;
|
||||
console.log(rowsGood);
|
||||
|
||||
return { errors, rowsGood };
|
||||
}
|
||||
|
||||
|
||||
@@ -153,92 +190,180 @@ export class ExcelService {
|
||||
*/
|
||||
async validateFile(buffer: Buffer) {
|
||||
const rows = await this.parseFile(buffer);
|
||||
const errs = this.validateRows(rows);
|
||||
return errs;
|
||||
const status = this.validateRows(rows);
|
||||
return status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Valida y luego persiste usuarios y relaciones básicas
|
||||
*/
|
||||
async loadFile(buffer: Buffer) {
|
||||
const rows = await this.parseFile(buffer);
|
||||
const errs = this.validateRows(rows);
|
||||
if (errs.length) {
|
||||
throw new BadRequestException({ errors: errs });
|
||||
const file = await this.parseFile(buffer);
|
||||
const status = this.validateRows(file);
|
||||
const errs = status.errors;
|
||||
const rows = status.rowsGood;
|
||||
|
||||
if (rows.length === 0) {
|
||||
throw new BadRequestException('No se encontraron filas válidas para cargar. ' + errs);
|
||||
}
|
||||
|
||||
for (const r of rows) {
|
||||
// 1) Género (crea o reutiliza)
|
||||
let genero = await this.generoRepo.findOne({ where: { genero: r.sexo } });
|
||||
if (!genero) {
|
||||
genero = this.generoRepo.create({ genero: r.sexo });
|
||||
await this.generoRepo.save(genero);
|
||||
}
|
||||
const queryRunner = this.dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
|
||||
// 2) Carrera (por clave)
|
||||
let carrera = await this.carreraRepo.findOne({
|
||||
where: { clave: r.clave },
|
||||
});
|
||||
if (!carrera) {
|
||||
carrera = this.carreraRepo.create({
|
||||
clave: r.clave,
|
||||
carrera: r.nomCarr.slice(0, 100),
|
||||
try {
|
||||
const movimiento = await this.movimientoService.logger(
|
||||
queryRunner,
|
||||
'LOAD',
|
||||
'LOADING',
|
||||
undefined,
|
||||
'CARGA MASIVA DE USUARIOS'
|
||||
);
|
||||
|
||||
let contador = 0;
|
||||
|
||||
for (const r of rows) {
|
||||
|
||||
const whereCond: Array<{ num_cuenta?: string; rfc?: string }> = [{ num_cuenta: r.cuenta }];
|
||||
if (r.rfc) {
|
||||
whereCond.push({ rfc: r.rfc });
|
||||
}
|
||||
|
||||
const userExists = await queryRunner.manager.findOne(Usuario, {
|
||||
where: whereCond,
|
||||
});
|
||||
await this.carreraRepo.save(carrera);
|
||||
}
|
||||
|
||||
let tipo = await this.tipoUsuarioRepo.findOne({
|
||||
where: { tipo_usuario: r.tipo.trim() },
|
||||
});
|
||||
if (!tipo) {
|
||||
tipo = this.tipoUsuarioRepo.create({
|
||||
tipo_usuario: r.tipo.trim(),
|
||||
|
||||
|
||||
if (userExists) {
|
||||
errs.push(`Cuenta ${r.cuenta} ya existe, se omite.`);
|
||||
contador++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!r.tipo || !r.nombres || !r.apellidopa || !r.apellidoma) {
|
||||
errs.push(`Fila con cuenta ${r.cuenta} tiene campos faltantes.`);
|
||||
contador++;
|
||||
continue;
|
||||
}
|
||||
|
||||
let genero = await queryRunner.manager.findOne(Genero, { where: { genero: r.sexo } });
|
||||
if (!genero) {
|
||||
genero = queryRunner.manager.create(Genero, { genero: r.sexo });
|
||||
await queryRunner.manager.save(genero);
|
||||
}
|
||||
|
||||
let carrera
|
||||
if (r.clave || r.nomCarr) {
|
||||
carrera = await queryRunner.manager.findOne(Carrera, { where: { clave: r.clave } });
|
||||
if (!carrera) {
|
||||
carrera = queryRunner.manager.create(Carrera, {
|
||||
clave: r.clave,
|
||||
carrera: r.nomCarr.slice(0, 100),
|
||||
});
|
||||
await queryRunner.manager.save(carrera);
|
||||
}
|
||||
|
||||
} else {
|
||||
carrera = null;
|
||||
}
|
||||
|
||||
let tipo = await queryRunner.manager.findOne(TipoUsuario, {
|
||||
where: { tipo_usuario: r.tipo.trim() },
|
||||
});
|
||||
await this.tipoUsuarioRepo.save(tipo);
|
||||
if (!tipo) {
|
||||
tipo = queryRunner.manager.create(TipoUsuario, { tipo_usuario: r.tipo.trim() });
|
||||
await queryRunner.manager.save(tipo);
|
||||
}
|
||||
|
||||
const generacion = /^[0-9]{4}$/.test(r.gen?.toString().trim())
|
||||
? parseInt(r.gen.toString().trim(), 10)
|
||||
: null;
|
||||
|
||||
const usuario = queryRunner.manager.create(Usuario, {
|
||||
num_cuenta: r.cuenta,
|
||||
nombre: r.nombres.trim().split(' ')[0],
|
||||
a_paterno: r.apellidopa,
|
||||
a_materno: r.apellidoma,
|
||||
rfc: r.rfc,
|
||||
fecha_nacimiento: r.fechnac,
|
||||
generacion,
|
||||
genero,
|
||||
movimiento,
|
||||
});
|
||||
const user = await queryRunner.manager.save(usuario);
|
||||
|
||||
if (carrera) {
|
||||
const carreraUsuario = queryRunner.manager.create(CarreraUsuario, {
|
||||
usuario: user,
|
||||
carrera,
|
||||
});
|
||||
await queryRunner.manager.save(carreraUsuario);
|
||||
}
|
||||
|
||||
const usuarioTipo = queryRunner.manager.create(UsuarioTipoUsuario, {
|
||||
usuario: user,
|
||||
tipoUsuario: tipo,
|
||||
});
|
||||
await queryRunner.manager.save(usuarioTipo);
|
||||
|
||||
const servData = {
|
||||
usuario: user,
|
||||
RedStatus: 'Inactivo',
|
||||
ATStatus: 'Inactivo',
|
||||
CorreoStatus: 'Inactivo',
|
||||
PrestamosStatus: 'Inactivo',
|
||||
};
|
||||
|
||||
switch (r.tipo.trim()) {
|
||||
case 'Diplomado':
|
||||
Object.assign(servData, { Correo: true });
|
||||
break;
|
||||
case 'Extra Largo':
|
||||
Object.assign(servData, { Correo: true, Prestamos: true });
|
||||
break;
|
||||
case 'Servicio Social':
|
||||
Object.assign(servData, { Correo: true, AT: true, Red: true });
|
||||
break;
|
||||
case 'Idiomas R (UNAM)':
|
||||
case 'Idiomas Sabatino':
|
||||
Object.assign(servData, { Correo: true, Red: true });
|
||||
break;
|
||||
case 'Reinscrito':
|
||||
case 'Posgrado':
|
||||
case 'Intercambio UNAM':
|
||||
case 'Movilidad':
|
||||
case 'Ampliación de Conocimiento':
|
||||
case 'Licenciatura':
|
||||
case 'Profesor':
|
||||
Object.assign(servData, { Correo: true, AT: true, Red: true, Prestamos: true });
|
||||
break;
|
||||
case 'Trabajadores':
|
||||
Object.assign(servData, { Red: true });
|
||||
break;
|
||||
|
||||
|
||||
}
|
||||
|
||||
const serv = queryRunner.manager.create(ServActivos, servData);
|
||||
await queryRunner.manager.save(serv);
|
||||
}
|
||||
|
||||
const generacion = /^[0-9]{4}$/.test(r.gen?.toString().trim())
|
||||
? parseInt(r.gen.toString().trim(), 10)
|
||||
: null;
|
||||
// 3) Usuario
|
||||
const usuario = this.usuarioRepo.create({
|
||||
num_cuenta: r.cuenta,
|
||||
nombre: r.nombres.trim().split(' ')[0], // ajusta si quieres
|
||||
a_paterno: r.apellidopa,
|
||||
a_materno: r.apellidoma,
|
||||
rfc: r.rfc,
|
||||
fecha_nacimiento: r.fechnac,
|
||||
generacion: generacion,
|
||||
genero,
|
||||
|
||||
});
|
||||
await this.usuarioRepo.save(usuario);
|
||||
|
||||
|
||||
|
||||
// 4) Relacion usuario–carrxera (tabla intermedia)
|
||||
const carreraUsuario = this.carreraUsuarioRepo.create({
|
||||
usuario,
|
||||
carrera,
|
||||
});
|
||||
await this.carreraUsuarioRepo.save(carreraUsuario);
|
||||
|
||||
// 5) Tipo de usuario
|
||||
|
||||
const usuarioTipo = this.usuarioTipoUsuarioRepo.create({
|
||||
usuario,
|
||||
tipoUsuario: tipo,
|
||||
});
|
||||
await this.usuarioTipoUsuarioRepo.save(usuarioTipo);
|
||||
|
||||
|
||||
await queryRunner.commitTransaction();
|
||||
return { inserted: rows.length - contador, id_movimiento: movimiento.id_mov, errors: errs };
|
||||
} catch (err) {
|
||||
await queryRunner.rollbackTransaction();
|
||||
throw err;
|
||||
} finally {
|
||||
await queryRunner.release();
|
||||
}
|
||||
|
||||
return { inserted: rows.length };
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// async generateCsv(): Promise<string> {
|
||||
// const users = await this.usuarioRepo.find({
|
||||
// relations: ['genero', 'carreraUsuarios'], // si quieres más info
|
||||
@@ -293,43 +418,50 @@ export class ExcelService {
|
||||
tipo_usuario: In(tipos),
|
||||
},
|
||||
},
|
||||
servActivo: {
|
||||
CorreoStatus: 'Inactivo',
|
||||
Correo: true,
|
||||
},
|
||||
},
|
||||
relations: [
|
||||
'genero',
|
||||
'carreraUsuarios', // relación intermedia
|
||||
'carreraUsuarios.carrera', // carrera asociada a través de la intermedia
|
||||
'carreraUsuarios',
|
||||
'carreraUsuarios.carrera',
|
||||
'usuarioTipos',
|
||||
'usuarioTipos.tipoUsuario',
|
||||
],
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
const header = [
|
||||
'num_cuenta', 'nombre', 'a_paterno', 'a_materno',
|
||||
'carreras', 'rfc', 'fecha_nacimiento', 'generacion'
|
||||
].join('\t') + '\n';
|
||||
'carreras', 'rfc', 'fecha_nacimiento', 'generacion', 'tipos_usuario'
|
||||
].join(',') + '\n';
|
||||
|
||||
const rows = usuarios.map(u => {
|
||||
const carreras = (u.carreraUsuarios ?? [])
|
||||
.map(cu => cu.carrera?.carrera ?? '') // obtenemos solo el nombre
|
||||
.join(', '); // une todas las carreras en un solo string
|
||||
.map(cu => cu.carrera?.carrera ?? '')
|
||||
.join(' | ');
|
||||
|
||||
const tiposUsuario = (u.usuarioTipos ?? [])
|
||||
.map(utu => utu.tipoUsuario?.tipo_usuario ?? '')
|
||||
.join(' | ');
|
||||
|
||||
return [
|
||||
u.num_cuenta,
|
||||
u.nombre,
|
||||
u.a_paterno,
|
||||
u.a_materno,
|
||||
u.num_cuenta ?? '',
|
||||
u.nombre ?? '',
|
||||
u.a_paterno ?? '',
|
||||
u.a_materno ?? '',
|
||||
carreras,
|
||||
u.rfc ?? '',
|
||||
u.fecha_nacimiento,
|
||||
u.generacion?.toString() ?? ''
|
||||
].join('\t');
|
||||
u.fecha_nacimiento ?? '',
|
||||
u.generacion?.toString() ?? '',
|
||||
tiposUsuario
|
||||
].join(',');
|
||||
}).join('\n');
|
||||
|
||||
const tablaCompleta = header + rows;
|
||||
|
||||
return tablaCompleta;
|
||||
|
||||
}
|
||||
|
||||
async generateCsvSolicita(): Promise<string> {
|
||||
@@ -355,52 +487,43 @@ export class ExcelService {
|
||||
tipo_usuario: In(tipos),
|
||||
},
|
||||
},
|
||||
servActivo: {
|
||||
PrestamosStatus: 'Inactivo', // solo los que no tienen servicio activo
|
||||
Prestamos: true, // solo los que tienen el servicio de préstamos activo
|
||||
}
|
||||
},
|
||||
relations: [
|
||||
'genero',
|
||||
'carreraUsuarios', // relación intermedia
|
||||
'carreraUsuarios.carrera', // carrera asociada a través de la intermedia
|
||||
'usuarioTipos',
|
||||
'usuarioTipos.tipoUsuario',
|
||||
],
|
||||
|
||||
});
|
||||
|
||||
const usuariosTipo = await this.usuarioRepo.find({
|
||||
|
||||
relations: [
|
||||
'genero',
|
||||
'carreraUsuarios', // relación intermedia
|
||||
'carreraUsuarios.carrera',
|
||||
'usuarioTipos', // relación con tipo de usuario
|
||||
'usuarioTipos.tipoUsuario', // tipo de usuario asociado
|
||||
],
|
||||
|
||||
});
|
||||
|
||||
console.log('Usuarios encontrados:', usuariosTipo);
|
||||
|
||||
console.log('Usuarios encontrados:', usuarios);
|
||||
|
||||
|
||||
|
||||
|
||||
const header = [
|
||||
'num_cuenta', 'nombre', 'a_paterno', 'a_materno',
|
||||
'carreras', 'rfc'
|
||||
].join('\t') + '\n';
|
||||
'carreras', 'rfc', 'tipos_usuario'
|
||||
].join(',') + '\n';
|
||||
|
||||
const rows = usuarios.map(u => {
|
||||
const carreras = (u.carreraUsuarios ?? [])
|
||||
.map(cu => cu.carrera?.carrera ?? '') // obtenemos solo el nombre
|
||||
.join(', '); // une todas las carreras en un solo string
|
||||
.join(' | '); // une todas las carreras en un solo string
|
||||
|
||||
const tiposUsuario = (u.usuarioTipos ?? [])
|
||||
.map(utu => utu.tipoUsuario?.tipo_usuario ?? '')
|
||||
.join(' | '); // une todos los tipos de usuario en un solo string
|
||||
|
||||
return [
|
||||
u.num_cuenta,
|
||||
u.nombre,
|
||||
u.a_paterno,
|
||||
u.a_materno,
|
||||
carreras,
|
||||
u.num_cuenta ?? '',
|
||||
u.nombre ?? '',
|
||||
u.a_paterno ?? '',
|
||||
u.a_materno ?? '',
|
||||
carreras ?? '',
|
||||
u.rfc ?? '',
|
||||
].join('\t');
|
||||
tiposUsuario
|
||||
].join(',');
|
||||
}).join('\n');
|
||||
|
||||
const tablaCompleta = header + rows;
|
||||
@@ -424,6 +547,7 @@ export class ExcelService {
|
||||
'Posgrado',
|
||||
'Reinscrito',
|
||||
'Licenciatura',
|
||||
'Caso Especial',
|
||||
];
|
||||
|
||||
const usuarios = await this.usuarioRepo.find({
|
||||
@@ -433,11 +557,17 @@ export class ExcelService {
|
||||
tipo_usuario: In(tipos),
|
||||
},
|
||||
},
|
||||
servActivo: {
|
||||
RedStatus: 'Inactivo',
|
||||
Red: true, // solo los que tienen el servicio de red activo
|
||||
}
|
||||
},
|
||||
relations: [
|
||||
'genero',
|
||||
'carreraUsuarios', // relación intermedia
|
||||
'carreraUsuarios.carrera', // carrera asociada a través de la intermedia
|
||||
'usuarioTipos',
|
||||
'usuarioTipos.tipoUsuario',
|
||||
],
|
||||
|
||||
});
|
||||
@@ -446,18 +576,26 @@ export class ExcelService {
|
||||
|
||||
|
||||
const header = [
|
||||
'num_cuenta', 'fecha_nacimiento'
|
||||
].join('\t') + '\n';
|
||||
'num_cuenta', 'fecha_nacimiento', 'contraseña', 'tipos_usuario'
|
||||
].join(',') + '\n';
|
||||
|
||||
const rows = usuarios.map(u => {
|
||||
|
||||
const tiposUsuario = (u.usuarioTipos ?? [])
|
||||
.map(utu => utu.tipoUsuario?.tipo_usuario ?? '')
|
||||
.join(' | ');
|
||||
|
||||
return [
|
||||
u.num_cuenta,
|
||||
u.fecha_nacimiento,
|
||||
].join('\t');
|
||||
u.contraseña ?? '',
|
||||
tiposUsuario
|
||||
].join(',');
|
||||
}).join('\n');
|
||||
|
||||
const tablaCompleta = header + rows;
|
||||
|
||||
console.log(tablaCompleta);
|
||||
console.log('Usuarios encontrados:', usuarios);
|
||||
return tablaCompleta;
|
||||
}
|
||||
|
||||
@@ -483,11 +621,17 @@ export class ExcelService {
|
||||
tipo_usuario: In(tipos),
|
||||
},
|
||||
},
|
||||
servActivo: {
|
||||
ATStatus: 'Inactivo',
|
||||
AT: true
|
||||
},
|
||||
},
|
||||
relations: [
|
||||
'genero',
|
||||
'carreraUsuarios', // relación intermedia
|
||||
'carreraUsuarios.carrera', // carrera asociada a través de la intermedia
|
||||
'usuarioTipos',
|
||||
'usuarioTipos.tipoUsuario',
|
||||
],
|
||||
|
||||
});
|
||||
@@ -497,23 +641,28 @@ export class ExcelService {
|
||||
|
||||
const header = [
|
||||
'num_cuenta', 'nombre', 'a_paterno', 'a_materno',
|
||||
'carreras', 'rfc', 'fecha_nacimiento', 'generacion'
|
||||
].join('\t') + '\n';
|
||||
'carreras', 'fecha_nacimiento', 'generacion', 'tipos_usuario'
|
||||
].join(',') + '\n';
|
||||
|
||||
const rows = usuarios.map(u => {
|
||||
const carreras = (u.carreraUsuarios ?? [])
|
||||
.map(cu => cu.carrera?.carrera ?? '') // obtenemos solo el nombre
|
||||
.join(', '); // une todas las carreras en un solo string
|
||||
.join(' | '); // une todas las carreras en un solo string
|
||||
|
||||
const tiposUsuario = (u.usuarioTipos ?? [])
|
||||
.map(utu => utu.tipoUsuario?.tipo_usuario ?? '')
|
||||
.join(' | '); // une todos los tipos de usuario en un solo string
|
||||
|
||||
return [
|
||||
u.num_cuenta,
|
||||
u.nombre,
|
||||
u.a_paterno,
|
||||
u.a_materno,
|
||||
carreras,
|
||||
u.fecha_nacimiento,
|
||||
u.generacion?.toString() ?? ''
|
||||
].join('\t');
|
||||
u.num_cuenta ?? '',
|
||||
u.nombre ?? '',
|
||||
u.a_paterno ?? '',
|
||||
u.a_materno ?? '',
|
||||
carreras ?? '',
|
||||
u.fecha_nacimiento ?? '',
|
||||
u.generacion?.toString() ?? '',
|
||||
tiposUsuario
|
||||
].join(',');
|
||||
}).join('\n');
|
||||
|
||||
const tablaCompleta = header + rows;
|
||||
@@ -523,13 +672,90 @@ export class ExcelService {
|
||||
|
||||
|
||||
|
||||
//Funcion que se le debe hacer su propio módulo
|
||||
async activarServicios(id_movimiento: number, origen: string): Promise<void> {
|
||||
if (!['AT', 'SOLICITA', 'CORREO', 'RED'].includes(origen)) {
|
||||
throw new BadRequestException(`Origen ${origen} no válido`);
|
||||
}
|
||||
|
||||
const usuarios = await this.usuarioRepo.find({
|
||||
where: { movimiento: { id_mov: id_movimiento } },
|
||||
});
|
||||
|
||||
if (!usuarios || usuarios.length === 0) {
|
||||
throw new BadRequestException('No se encontró el usuario asociado al movimiento');
|
||||
}
|
||||
|
||||
for (const usuario of usuarios) {
|
||||
const servActivos = await this.servActivosRepo.findOne({
|
||||
where: { usuario: { id_usuario: usuario.id_usuario } },
|
||||
});
|
||||
|
||||
if (!servActivos) {
|
||||
throw new BadRequestException(
|
||||
`No se encontraron servicios activos para el usuario con ID ${usuario.id_usuario}`,
|
||||
);
|
||||
}
|
||||
|
||||
const timestamp = 'Activo ' + new Date().toISOString();
|
||||
|
||||
if (origen === 'AT' && servActivos.AT) {
|
||||
servActivos.ATStatus = timestamp;
|
||||
} else if (origen === 'RED' && servActivos.Red) {
|
||||
servActivos.RedStatus = timestamp;
|
||||
} else if (origen === 'CORREO' && servActivos.Correo) {
|
||||
servActivos.CorreoStatus = timestamp;
|
||||
} else if (origen === 'SOLICITA' && servActivos.Prestamos) {
|
||||
servActivos.PrestamosStatus = timestamp;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
await this.servActivosRepo.save(servActivos);
|
||||
console.log(`Servicio ${servActivos}`);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
async enviarCargaMasiva(): Promise<void> {
|
||||
const usuarios_red = await this.usuariosDelSistemaRepo.findOne({ where: { origen: { origen: 'RED' } } });
|
||||
const usuarios_at = await this.usuariosDelSistemaRepo.findOne({ where: { origen: { origen: 'AT' } } });
|
||||
const usuarios_correo = await this.usuariosDelSistemaRepo.findOne({ where: { origen: { origen: 'CORREO' } } });
|
||||
const usuarios_solicita = await this.usuariosDelSistemaRepo.findOne({ where: { origen: { origen: 'SOLICITA' } } });
|
||||
if (!usuarios_red || !usuarios_at || !usuarios_correo || !usuarios_solicita) {
|
||||
throw new BadRequestException('No se encontraron usuarios para enviar correo');
|
||||
}
|
||||
|
||||
// Aquí puedes enviar el correo usando MailService
|
||||
await this.mailService.sendMail({
|
||||
to: usuarios_red.correo ?? '',
|
||||
subject: 'Carga de Usuarios',
|
||||
text: 'Se ha realizado una carga de usuarios en el sistema.',
|
||||
html: '',
|
||||
});
|
||||
await this.mailService.sendMail({
|
||||
to: usuarios_at.correo ?? '',
|
||||
subject: 'Carga de Usuarios',
|
||||
text: 'Se ha realizado una carga de usuarios en el sistema.',
|
||||
html: '',
|
||||
});
|
||||
await this.mailService.sendMail({
|
||||
to: usuarios_correo.correo ?? '',
|
||||
subject: 'Carga de Usuarios',
|
||||
text: 'Se ha realizado una carga de usuarios en el sistema.',
|
||||
html: '',
|
||||
});
|
||||
await this.mailService.sendMail({
|
||||
to: usuarios_solicita.correo ?? '',
|
||||
subject: 'Carga de Usuarios',
|
||||
text: 'Se ha realizado una carga de usuarios en el sistema.',
|
||||
html: '',
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
console.log(`Correo enviados`);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { IsString, IsEmail, IsDate, IsOptional } from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
export class SendCorreoDto {
|
||||
@IsEmail()
|
||||
to: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
subject: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
text: string;
|
||||
|
||||
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
html: string;
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// src/excel/excel.controller.ts
|
||||
import { Controller, Post, Get, UseGuards, Request, Res, UploadedFile, UseInterceptors, HttpStatus, Param, ParseIntPipe, Body } from '@nestjs/common';
|
||||
import { SendCorreoDto } from './dto/send-email.dto';
|
||||
import { MailService } from './mail.service';
|
||||
|
||||
|
||||
@Controller('mail')
|
||||
export class MailController {
|
||||
constructor(
|
||||
private readonly mailService: MailService
|
||||
) { }
|
||||
|
||||
@Post('send')
|
||||
async sendMail(@Body() body: SendCorreoDto) {
|
||||
const result =
|
||||
await this.mailService.sendMail(body)
|
||||
.then((value) => {
|
||||
console.log("Se mandaron los correos", value);
|
||||
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log(err)
|
||||
})
|
||||
|
||||
|
||||
// sistem
|
||||
return result;
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// src/movimiento/movimiento.module.ts
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MailService } from './mail.service';
|
||||
import { MailController } from './mail.controller';
|
||||
|
||||
@Module({
|
||||
imports: [],
|
||||
controllers: [MailController],
|
||||
providers: [MailService],
|
||||
exports: [MailService],
|
||||
})
|
||||
export class MailModule { }
|
||||
@@ -0,0 +1,76 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import * as nodemailer from 'nodemailer';
|
||||
import { SendCorreoDto } from 'src/mail/dto/send-email.dto';
|
||||
|
||||
|
||||
|
||||
|
||||
@Injectable()
|
||||
export class MailService {
|
||||
|
||||
async sendMail(sendEmail: SendCorreoDto) {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
const transporter = nodemailer.createTransport({
|
||||
|
||||
|
||||
service: 'gmail',
|
||||
auth: {
|
||||
type: 'OAuth2',
|
||||
user: process.env.EMAIL_USER, // tu correo de Gmail
|
||||
clientId: process.env.CLIENT_ID, // tu Client ID de OAuth2
|
||||
clientSecret: process.env.CLIENT_SECRET, // tu Client Secret de OAuth2
|
||||
refreshToken: process.env.REFRESH_TOKEN, // tu Refresh Token de OAuth2
|
||||
//accessToken: sistem.accessToken, // opcional
|
||||
},
|
||||
pool: true,
|
||||
maxConnections: 1,
|
||||
maxMessages: 100,
|
||||
rateDelta: 2000,
|
||||
rateLimit: 1
|
||||
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
const mailOptions = {
|
||||
from: process.env.EMAIL_USER, // tu correo de Gmail
|
||||
to: sendEmail.to,
|
||||
subject: sendEmail.subject,
|
||||
text: sendEmail.text,
|
||||
html: sendEmail.html,
|
||||
};
|
||||
|
||||
|
||||
console.log(mailOptions);
|
||||
|
||||
|
||||
|
||||
|
||||
let resMail = await transporter.sendMail(mailOptions);
|
||||
if (!resMail) throw new Error("")
|
||||
|
||||
|
||||
const statusTexto = resMail.accepted.length > 0 ? "Enviado" : "Fallido";
|
||||
|
||||
|
||||
|
||||
if (!resMail) {
|
||||
throw new Error("fallo")
|
||||
}
|
||||
|
||||
|
||||
return (statusTexto);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
+4
-4
@@ -6,7 +6,7 @@ import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
app.enableCors();
|
||||
app.enableCors({ exposedHeaders: ['Content-Disposition'] });
|
||||
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
@@ -23,9 +23,9 @@ async function bootstrap() {
|
||||
)
|
||||
.setVersion('1.0')
|
||||
.addBearerAuth(
|
||||
{
|
||||
type: 'http',
|
||||
scheme: 'bearer',
|
||||
{
|
||||
type: 'http',
|
||||
scheme: 'bearer',
|
||||
bearerFormat: 'JWT',
|
||||
name: 'Authorization',
|
||||
in: 'header',
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { MovimientoService } from './movimiento.service';
|
||||
import { Movimiento, Origen } from '../entities/entities';
|
||||
import { Movimiento, Origen, Usuario } from '../entities/entities';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Movimiento, Origen])],
|
||||
imports: [TypeOrmModule.forFeature([Movimiento, Origen, Usuario])],
|
||||
providers: [MovimientoService],
|
||||
exports: [MovimientoService],
|
||||
})
|
||||
export class MovimientoModule {}
|
||||
export class MovimientoModule { }
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { Movimiento } from '../entities/entities';
|
||||
import { QueryRunner, Repository } from 'typeorm';
|
||||
import { Movimiento, Usuario } from '../entities/entities';
|
||||
import { Origen } from '../entities/entities';
|
||||
|
||||
@Injectable()
|
||||
@@ -11,6 +11,8 @@ export class MovimientoService {
|
||||
private readonly movRepo: Repository<Movimiento>,
|
||||
@InjectRepository(Origen)
|
||||
private readonly origenRepo: Repository<Origen>,
|
||||
@InjectRepository(Usuario)
|
||||
private readonly usuarioRepo: Repository<Usuario>,
|
||||
) { }
|
||||
|
||||
/** Crea un registro de movimiento */
|
||||
@@ -20,19 +22,233 @@ export class MovimientoService {
|
||||
observaciones?: string,
|
||||
reporte?: string,
|
||||
flag = false,
|
||||
) {
|
||||
): Promise<Movimiento> {
|
||||
// 1) Obtén el origen o falla si no existe
|
||||
const origin = await this.origenRepo.findOne({ where: { origen } });
|
||||
if (!origin) throw new Error(`Origen desconocido: ${origen}`);
|
||||
let origenRepo = origin;
|
||||
if (!origin) {
|
||||
const newOrigin = this.origenRepo.create({ origen });
|
||||
origenRepo = await this.origenRepo.save(newOrigin);
|
||||
}
|
||||
if (!origenRepo) {
|
||||
throw new Error(`No se pudo obtener o crear el origen: ${origen}`);
|
||||
}
|
||||
|
||||
// 2) Inserta directamente usando los campos de FK
|
||||
await this.movRepo.insert({
|
||||
// 2) Crea el objeto movimiento
|
||||
const movimiento = this.movRepo.create({
|
||||
fecha_mov: new Date(),
|
||||
status,
|
||||
observaciones, // aquí usas el valor que vino como parámetro
|
||||
reporte, // idem
|
||||
observaciones,
|
||||
reporte,
|
||||
flag,
|
||||
origen: { id_origen: origin.id_origen },
|
||||
origen: { id_origen: origenRepo.id_origen },
|
||||
});
|
||||
|
||||
// 3) Guarda y devuelve el ID
|
||||
const saved = await this.movRepo.save(movimiento);
|
||||
return saved;
|
||||
}
|
||||
|
||||
async logger(
|
||||
queryRunner: QueryRunner,
|
||||
origenNombre: string,
|
||||
status: string,
|
||||
observaciones?: string,
|
||||
reporte?: string
|
||||
): Promise<Movimiento> {
|
||||
const origenEntidad = await queryRunner.manager.findOne(Origen, {
|
||||
where: { origen: origenNombre },
|
||||
});
|
||||
|
||||
if (!origenEntidad) {
|
||||
throw new Error(`Origen no encontrado: ${origenNombre}`);
|
||||
}
|
||||
|
||||
const nuevoMov = queryRunner.manager.create(Movimiento, {
|
||||
fecha_mov: new Date(),
|
||||
status,
|
||||
observaciones,
|
||||
reporte,
|
||||
origen: origenEntidad,
|
||||
flag: false,
|
||||
});
|
||||
|
||||
return await queryRunner.manager.save(nuevoMov);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/** Actualiza el status de un movimiento existente */
|
||||
async updateStatus(id_movimiento: number, nuevoStatus: string, observaciones?: string): Promise<void> {
|
||||
const movimiento = await this.movRepo.findOne({ where: { id_mov: id_movimiento } });
|
||||
|
||||
if (!movimiento) {
|
||||
throw new Error(`Movimiento con ID ${id_movimiento} no encontrado`);
|
||||
}
|
||||
|
||||
movimiento.status = nuevoStatus;
|
||||
movimiento.observaciones = observaciones || movimiento.observaciones; // opcional: actualizar observaciones
|
||||
movimiento.fecha_mov = new Date(); // opcional: actualizar fecha
|
||||
|
||||
await this.movRepo.save(movimiento);
|
||||
}
|
||||
|
||||
async findAll(origen: string): Promise<{ move: any[]; button: boolean }> {
|
||||
const statusFieldMap = {
|
||||
AT: 'ATStatus',
|
||||
RED: 'RedStatus',
|
||||
CORREO: 'CorreoStatus',
|
||||
SOLICITA: 'PrestamosStatus',
|
||||
} as const;
|
||||
|
||||
const FieldMap = {
|
||||
AT: 'AT',
|
||||
RED: 'Red',
|
||||
CORREO: 'Correo',
|
||||
SOLICITA: 'Prestamos',
|
||||
} as const;
|
||||
|
||||
|
||||
|
||||
const field = statusFieldMap[origen as keyof typeof statusFieldMap];
|
||||
const origenField = FieldMap[origen as keyof typeof FieldMap];
|
||||
|
||||
if (!field) {
|
||||
const movimientos = await this.movRepo.find({
|
||||
where: {
|
||||
origen: { origen: 'LOAD' },
|
||||
status: 'SUCCESS',
|
||||
reporte: 'CARGA MASIVA DE USUARIOS',
|
||||
|
||||
},
|
||||
});
|
||||
|
||||
const mov = await this.movRepo.find({
|
||||
where: {
|
||||
origen: { origen: 'SISTEMA' },
|
||||
status: 'SUCCESS',
|
||||
reporte: 'CARGA MASIVA WEB SERVICE',
|
||||
|
||||
},
|
||||
});
|
||||
|
||||
const mov2 = await this.movRepo.find({
|
||||
where: {
|
||||
|
||||
reporte: 'CARGA INDIVIDUAL DE USUARIOS',
|
||||
status: 'SUCCESS',
|
||||
|
||||
|
||||
},
|
||||
});
|
||||
console.log('movimientos:', mov2)
|
||||
|
||||
|
||||
|
||||
|
||||
const todosLosMovimientos = [...movimientos, ...mov, ...mov2];
|
||||
console.log(todosLosMovimientos)
|
||||
return { move: todosLosMovimientos, button: false };
|
||||
}
|
||||
|
||||
const movimientos = await this.movRepo.find({
|
||||
where: {
|
||||
origen: { origen: 'LOAD' },
|
||||
reporte: 'CARGA MASIVA DE USUARIOS',
|
||||
status: 'SUCCESS',
|
||||
usuario: {
|
||||
servActivo: {
|
||||
[origenField]: true,
|
||||
|
||||
[field]: 'Inactivo'
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const mov = await this.movRepo.find({
|
||||
where: {
|
||||
origen: { origen: 'SISTEMA' },
|
||||
reporte: 'CARGA MASIVA WEB SERVICE',
|
||||
status: 'SUCCESS',
|
||||
usuario: {
|
||||
servActivo: {
|
||||
[origenField]: true,
|
||||
[field]: 'Inactivo'
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const mov2 = await this.movRepo.find({
|
||||
where: {
|
||||
|
||||
reporte: 'CARGA INDIVIDUAL DE USUARIOS',
|
||||
status: 'SUCCESS',
|
||||
usuario: {
|
||||
servActivo: {
|
||||
[origenField]: true,
|
||||
[field]: 'Inactivo'
|
||||
},
|
||||
},
|
||||
},
|
||||
relations: ['usuario'],
|
||||
});
|
||||
const todosLosMovimientos = [...movimientos, ...mov, ...mov2];
|
||||
|
||||
return { move: todosLosMovimientos, button: true };
|
||||
}
|
||||
|
||||
async findAllCargaIndv(origen): Promise<Usuario[]> {
|
||||
|
||||
const statusFieldMap = {
|
||||
AT: 'ATStatus',
|
||||
RED: 'RedStatus',
|
||||
CORREO: 'CorreoStatus',
|
||||
SOLICITA: 'PrestamosStatus',
|
||||
} as const;
|
||||
|
||||
const FieldMap = {
|
||||
AT: 'AT',
|
||||
RED: 'Red',
|
||||
CORREO: 'Correo',
|
||||
SOLICITA: 'Prestamos',
|
||||
} as const;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
const field = statusFieldMap[origen as keyof typeof statusFieldMap];
|
||||
|
||||
const origenField = FieldMap[origen as keyof typeof FieldMap];
|
||||
|
||||
if (!field) {
|
||||
throw new Error(`Origen desconocido: ${origen}`);
|
||||
}
|
||||
|
||||
const usuarios = await this.usuarioRepo.find({
|
||||
where: {
|
||||
movimiento: {
|
||||
|
||||
reporte: 'CARGA INDIVIDUAL DE USUARIOS',
|
||||
},
|
||||
|
||||
servActivo: {
|
||||
[field]: 'Inactivo',
|
||||
[origenField]: true,
|
||||
},
|
||||
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
return usuarios;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1 +1,53 @@
|
||||
export class CreateUsuarioDto {}
|
||||
import { IsNumber, IsOptional, IsString, Length } from "class-validator";
|
||||
|
||||
export class CreateUsuarioDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
num_cuenta?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
usuario?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
carrera?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
contraseña?: string;
|
||||
|
||||
@IsString()
|
||||
tipo_usuario: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
clave_carrera?: string;
|
||||
|
||||
@IsString()
|
||||
nombre: string;
|
||||
|
||||
@IsString()
|
||||
a_paterno: string;
|
||||
|
||||
@IsString()
|
||||
a_materno: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Length(10, 13)
|
||||
rfc?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Length(8, 8)
|
||||
fecha_nacimiento?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
generacion?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
genero?: string;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Usuario } from "src/entities/entities";
|
||||
import { Column, Entity, JoinColumn, OneToOne, PrimaryGeneratedColumn } from "typeorm";
|
||||
|
||||
@Entity({ name: 'servActivos' })
|
||||
export class ServActivos {
|
||||
@PrimaryGeneratedColumn({ name: 'id_servActivos' })
|
||||
id_servActivos: number;
|
||||
|
||||
@OneToOne(() => Usuario, (usuario) => usuario.servActivo, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'id_usuario' })
|
||||
usuario: Usuario;
|
||||
|
||||
|
||||
@Column({ type: 'boolean', default: false })
|
||||
Red: boolean;
|
||||
|
||||
@Column({ type: 'boolean', default: false })
|
||||
Prestamos: boolean;
|
||||
|
||||
@Column({ type: 'boolean', default: false })
|
||||
AT: boolean;
|
||||
|
||||
@Column({ type: 'boolean', default: false })
|
||||
Correo: boolean;
|
||||
|
||||
@Column({ type: 'varchar', length: 40, nullable: true })
|
||||
RedStatus: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 40, nullable: true })
|
||||
PrestamosStatus: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 40, nullable: true })
|
||||
ATStatus: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 40, nullable: true })
|
||||
CorreoStatus: string;
|
||||
|
||||
|
||||
}
|
||||
@@ -12,10 +12,18 @@ export class UsuariosController {
|
||||
|
||||
|
||||
|
||||
@Post('users')
|
||||
finsdAll() {
|
||||
return this.usuariosService.enviarSolicitud();
|
||||
}
|
||||
|
||||
@Get(':noCuenta')
|
||||
findOne(@Param('noCuenta') noCuenta: string) {
|
||||
return this.usuariosService.findOne(noCuenta);
|
||||
return this.usuariosService.findOneStatus(noCuenta);
|
||||
}
|
||||
|
||||
|
||||
|
||||
// @UseGuards(AuthGuard('jwt'))
|
||||
// @ApiBearerAuth('bearer')
|
||||
// @Post()
|
||||
|
||||
@@ -2,15 +2,20 @@ import { Module } from '@nestjs/common';
|
||||
import { UsuariosService } from './usuarios.service';
|
||||
import { UsuariosController } from './usuarios.controller';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Carrera, CarreraUsuario, Genero, Usuario } from 'src/entities/entities';
|
||||
import { Carrera, CarreraUsuario, Genero, TipoUsuario, Usuario, UsuariosDelSistema, UsuarioTipoUsuario } from 'src/entities/entities';
|
||||
import { MovimientoModule } from 'src/movimiento/movimiento.module';
|
||||
import { ServActivos } from './entities/servActivos.entitie';
|
||||
import { MailService } from 'src/mail/mail.service';
|
||||
import { ExcelService } from 'src/excel/excel.service';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Usuario, Genero, Carrera, CarreraUsuario]),
|
||||
TypeOrmModule.forFeature([Usuario, Genero, Carrera, CarreraUsuario, ServActivos, TipoUsuario, UsuarioTipoUsuario, UsuariosDelSistema]),
|
||||
MovimientoModule
|
||||
|
||||
],
|
||||
controllers: [UsuariosController],
|
||||
providers: [UsuariosService],
|
||||
providers: [UsuariosService, MailService, ExcelService],
|
||||
exports: [TypeOrmModule.forFeature([ServActivos])],
|
||||
})
|
||||
export class UsuariosModule { }
|
||||
|
||||
@@ -1,30 +1,50 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { CreateUsuarioDto } from './dto/create-usuario.dto';
|
||||
import { UpdateUsuarioDto } from './dto/update-usuario.dto';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { CarreraUsuario, Usuario } from 'src/entities/entities';
|
||||
import { Carrera, CarreraUsuario, Genero, TipoUsuario, Usuario, UsuarioTipoUsuario } from 'src/entities/entities';
|
||||
import { Repository } from 'typeorm';
|
||||
import { ServActivos } from './entities/servActivos.entitie';
|
||||
import { MovimientoService } from 'src/movimiento/movimiento.service';
|
||||
import { MailService } from 'src/mail/mail.service';
|
||||
import { error } from 'console';
|
||||
import { Cron } from '@nestjs/schedule';
|
||||
import { ExcelService } from 'src/excel/excel.service';
|
||||
|
||||
|
||||
|
||||
|
||||
@Injectable()
|
||||
export class UsuariosService {
|
||||
private readonly logger = new Logger(UsuariosService.name);
|
||||
|
||||
constructor(
|
||||
@InjectRepository(Usuario)
|
||||
private readonly usuarioRepository: Repository<Usuario>,
|
||||
@InjectRepository(Carrera)
|
||||
private readonly carreraRepository: Repository<Carrera>,
|
||||
@InjectRepository(ServActivos)
|
||||
private readonly servActivosRepository: Repository<ServActivos>,
|
||||
@InjectRepository(TipoUsuario)
|
||||
private readonly tipoUsuarioRepository: Repository<TipoUsuario>,
|
||||
@InjectRepository(Genero)
|
||||
private readonly generoRepository: Repository<Genero>,
|
||||
@InjectRepository(CarreraUsuario)
|
||||
private readonly carreraUsuarioRepository: Repository<CarreraUsuario>,
|
||||
private readonly carreraUsuario: Repository<CarreraUsuario>,
|
||||
@InjectRepository(UsuarioTipoUsuario)
|
||||
private readonly usuarioTipoUsuario: Repository<UsuarioTipoUsuario>,
|
||||
private readonly movimientoService: MovimientoService,
|
||||
private readonly mailService: MailService,
|
||||
private readonly excelService: ExcelService, // Asegúrate de importar el servicio de Excel
|
||||
|
||||
) { }
|
||||
|
||||
altaIndividual(createUsuarioDto: CreateUsuarioDto) {
|
||||
return 'This action adds a new usuario';
|
||||
}
|
||||
|
||||
async findOne(noCuenta: string) {
|
||||
async findOneStatus(noCuenta: string) {
|
||||
const usuario = await this.usuarioRepository.findOne({
|
||||
relations: [
|
||||
'genero',
|
||||
'carreraUsuarios',
|
||||
'carreraUsuarios.carrera',
|
||||
],
|
||||
where: { num_cuenta: noCuenta },
|
||||
|
||||
});
|
||||
@@ -33,27 +53,584 @@ export class UsuariosService {
|
||||
throw new NotFoundException('Usuario no encontrado');
|
||||
}
|
||||
|
||||
// Transformar a formato plano
|
||||
const resultadoPlano = {
|
||||
num_cuenta: usuario.num_cuenta,
|
||||
nombre: usuario.nombre,
|
||||
a_paterno: usuario.a_paterno,
|
||||
a_materno: usuario.a_materno,
|
||||
fecha_nacimiento: usuario.fecha_nacimiento,
|
||||
generacion: usuario.generacion,
|
||||
genero: usuario.genero?.genero ?? '',
|
||||
carreras: (usuario.carreraUsuarios ?? [])
|
||||
.map(cu => cu.carrera?.carrera)
|
||||
.filter(Boolean)
|
||||
.join(', '), // todas las carreras como string plano
|
||||
const servActivo = await this.servActivosRepository.findOne({
|
||||
where: { usuario: { id_usuario: usuario.id_usuario } },
|
||||
});
|
||||
|
||||
if (!servActivo) {
|
||||
throw new NotFoundException('Servicios no encontrados para el usuario');
|
||||
}
|
||||
|
||||
const resultado: {
|
||||
servicio: string;
|
||||
status: string;
|
||||
fecha_activacion: string;
|
||||
}[] = [];
|
||||
|
||||
const mapServicio = (nombre: string, estado: string | undefined) => {
|
||||
if (!estado) return;
|
||||
|
||||
if (estado.startsWith('Activo')) {
|
||||
const fechaCompleta = estado.substring(7); // "2025-06-25T14:26:21.427Z"
|
||||
const fechaSolo = fechaCompleta.substring(0, 10); // "2025-06-25"
|
||||
resultado.push({
|
||||
servicio: nombre,
|
||||
status: 'Activo',
|
||||
fecha_activacion: fechaSolo,
|
||||
});
|
||||
} else {
|
||||
resultado.push({
|
||||
servicio: nombre,
|
||||
status: 'Inactivo',
|
||||
fecha_activacion: "",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return [resultadoPlano]; // importante: frontend espera array
|
||||
|
||||
await mapServicio('Red', servActivo.RedStatus);
|
||||
await mapServicio('Correo', servActivo.CorreoStatus);
|
||||
await mapServicio('Préstamo de equipo PC Puma', servActivo.PrestamosStatus);
|
||||
await mapServicio('Préstamo de equipo en CEDETEC', servActivo.ATStatus);
|
||||
|
||||
|
||||
|
||||
if (resultado.length === 0) {
|
||||
return [{
|
||||
servicio: 'Ninguno',
|
||||
status: 'No hay servicios activos para este usuario',
|
||||
fecha_activacion: null,
|
||||
}];
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
return { resultado, usuario: usuario.nombre };
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
update(id: number, updateUsuarioDto: UpdateUsuarioDto) {
|
||||
return `This action updates a #${id} usuario`;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@Cron('0 0 0 10,25 * *')
|
||||
async tareaMensual() {
|
||||
this.logger.log('Ejecutando consulta mensual de profesores');
|
||||
await this.enviarSolicitud(); // tu función de importación
|
||||
}
|
||||
|
||||
async enviarSolicitud() {
|
||||
const mov = await this.movimientoService.log(
|
||||
'SISTEMA',
|
||||
'LOADING',
|
||||
'Enviando solicitud de consulta masiva de profesores al WebService',
|
||||
'CARGA MASIVA WEB SERVICE'
|
||||
);
|
||||
|
||||
|
||||
interface DatosEntrada {
|
||||
Nombre: string;
|
||||
ApellidoPaterno: string;
|
||||
ApellidoMaterno: string;
|
||||
NumeroTrabajador: string;
|
||||
RFC: string;
|
||||
}
|
||||
|
||||
interface DatosRespuesta {
|
||||
numeroTrabajador: string;
|
||||
nombre: string;
|
||||
apellidoPaterno: string;
|
||||
apellidoMaterno: string;
|
||||
nombreCarrera: string;
|
||||
fechaNacimiento: string;
|
||||
rfc: string;
|
||||
genero: string;
|
||||
correoPersonal: string;
|
||||
nombramiento: string;
|
||||
unidadResponsable: string;
|
||||
curp: string;
|
||||
}
|
||||
|
||||
const apiUrl = process.env.API_URL;
|
||||
if (!apiUrl) {
|
||||
console.error("API_URL no está definida en las variables de entorno");
|
||||
return;
|
||||
}
|
||||
|
||||
const entrada: DatosEntrada = {
|
||||
Nombre: "",
|
||||
ApellidoPaterno: "",
|
||||
ApellidoMaterno: "",
|
||||
NumeroTrabajador: "",
|
||||
RFC: ""
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch(apiUrl, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(entrada)
|
||||
});
|
||||
|
||||
if (response.status === 400) {
|
||||
const errorText = await response.text();
|
||||
console.error("Error 400:", errorText);
|
||||
return;
|
||||
} else if (response.status === 204) {
|
||||
console.log("No se encontraron datos conforme a los criterios de búsqueda");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!response.ok) throw new Error("Error en la petición: " + response.statusText);
|
||||
|
||||
const json: DatosRespuesta[] = await response.json();
|
||||
|
||||
let nuevos = 0;
|
||||
let actualizados = 0;
|
||||
|
||||
let existe = await this.tipoUsuarioRepository.findOne({ where: { tipo_usuario: 'Profesor' } });
|
||||
if (!existe) {
|
||||
const tipoUsuario = this.tipoUsuarioRepository.create({ tipo_usuario: 'Profesor' });
|
||||
existe = await this.tipoUsuarioRepository.save(tipoUsuario);
|
||||
}
|
||||
|
||||
for (const prof of json) {
|
||||
try {
|
||||
if (!prof.rfc || !prof.nombre) {
|
||||
console.warn('Profesor con datos incompletos detectado:', prof);
|
||||
continue;
|
||||
}
|
||||
|
||||
const existente = await this.usuarioRepository.findOne({
|
||||
where: { rfc: prof.rfc },
|
||||
relations: ['genero']
|
||||
});
|
||||
|
||||
if (!existente) {
|
||||
let genero: Genero | null = null;
|
||||
if (prof.genero === 'M' || prof.genero === 'F') {
|
||||
const generoTexto = prof.genero === 'M' ? 'Masculino' : 'Femenino';
|
||||
genero = await this.generoRepository.findOne({ where: { genero: generoTexto } });
|
||||
if (!genero) {
|
||||
genero = await this.generoRepository.create({ genero: generoTexto });
|
||||
await this.generoRepository.save(genero);
|
||||
}
|
||||
}
|
||||
|
||||
let carrera = await this.carreraRepository.findOne({ where: { carrera: prof.nombreCarrera.trim() } })
|
||||
|
||||
if (!carrera) {
|
||||
const nuevaCarrera = await this.carreraRepository.create({ carrera: prof.nombreCarrera.trim(), clave: '' });
|
||||
carrera = await this.carreraRepository.save(nuevaCarrera);
|
||||
}
|
||||
|
||||
|
||||
|
||||
const nuevo = await this.usuarioRepository.create({
|
||||
num_cuenta: prof.numeroTrabajador == '' ? undefined : prof.numeroTrabajador,
|
||||
nombre: prof.nombre,
|
||||
a_paterno: prof.apellidoPaterno,
|
||||
a_materno: prof.apellidoMaterno,
|
||||
rfc: prof.rfc,
|
||||
fecha_nacimiento: prof.fechaNacimiento,
|
||||
genero,
|
||||
|
||||
movimiento: mov
|
||||
});
|
||||
|
||||
const savedUser = await this.usuarioRepository.save(nuevo);
|
||||
|
||||
const servActivo = await this.servActivosRepository.create({
|
||||
ATStatus: 'Inactivo',
|
||||
RedStatus: 'Inactivo',
|
||||
PrestamosStatus: 'Inactivo',
|
||||
CorreoStatus: 'Inactivo',
|
||||
usuario: savedUser,
|
||||
AT: prof.numeroTrabajador !== '',
|
||||
Red: prof.numeroTrabajador !== '',
|
||||
Prestamos: prof.numeroTrabajador !== '',
|
||||
Correo: true
|
||||
});
|
||||
|
||||
await this.servActivosRepository.save(servActivo);
|
||||
|
||||
const userCarrera = await this.carreraUsuario.create({ carrera, usuario: savedUser });
|
||||
const usuarioTipo = await this.usuarioTipoUsuario.create({ tipoUsuario: existe, usuario: savedUser });
|
||||
|
||||
await this.carreraUsuario.save(userCarrera);
|
||||
await this.usuarioTipoUsuario.save(usuarioTipo);
|
||||
|
||||
nuevos++;
|
||||
} else {
|
||||
let cambios = false;
|
||||
|
||||
|
||||
if (existente.nombre !== prof.nombre) {
|
||||
existente.nombre = prof.nombre;
|
||||
const servActivo = await this.servActivosRepository.findOne({ where: { usuario: { id_usuario: existente.id_usuario } } });
|
||||
|
||||
|
||||
if (servActivo) {
|
||||
servActivo.Red = true;
|
||||
servActivo.AT = true;
|
||||
servActivo.Prestamos = true;
|
||||
|
||||
|
||||
servActivo.ATStatus = 'Inactivo';
|
||||
servActivo.PrestamosStatus = 'Inactivo';
|
||||
servActivo.RedStatus = 'Inactivo';
|
||||
await this.servActivosRepository.save(servActivo);
|
||||
} else {
|
||||
console.warn('No se encontró el servicio activo para el usuario:', existente);
|
||||
}
|
||||
cambios = true;
|
||||
}
|
||||
|
||||
if (existente.a_paterno !== prof.apellidoPaterno) {
|
||||
existente.a_paterno = prof.apellidoPaterno;
|
||||
const servActivo = await this.servActivosRepository.findOne({ where: { usuario: { id_usuario: existente.id_usuario } } });
|
||||
|
||||
if (servActivo) {
|
||||
servActivo.Red = true;
|
||||
servActivo.AT = true;
|
||||
servActivo.Prestamos = true;
|
||||
|
||||
|
||||
servActivo.ATStatus = 'Inactivo';
|
||||
servActivo.PrestamosStatus = 'Inactivo';
|
||||
servActivo.RedStatus = 'Inactivo';
|
||||
await this.servActivosRepository.save(servActivo);
|
||||
} else {
|
||||
console.warn('No se encontró el servicio activo para el usuario:', existente);
|
||||
}
|
||||
|
||||
cambios = true;
|
||||
}
|
||||
|
||||
|
||||
if (existente.a_materno !== prof.apellidoMaterno) {
|
||||
|
||||
existente.a_materno = prof.apellidoMaterno;
|
||||
const servActivo = await this.servActivosRepository.findOne({ where: { usuario: { id_usuario: existente.id_usuario } } });
|
||||
|
||||
if (servActivo) {
|
||||
servActivo.Red = true;
|
||||
servActivo.AT = true;
|
||||
servActivo.Prestamos = true;
|
||||
|
||||
|
||||
servActivo.ATStatus = 'Inactivo';
|
||||
servActivo.PrestamosStatus = 'Inactivo';
|
||||
servActivo.RedStatus = 'Inactivo';
|
||||
await this.servActivosRepository.save(servActivo);
|
||||
} else {
|
||||
console.warn('No se encontró el servicio activo para el usuario:', existente);
|
||||
}
|
||||
|
||||
cambios = true;
|
||||
}
|
||||
|
||||
if (existente.rfc !== prof.rfc) {
|
||||
existente.rfc = prof.rfc;
|
||||
const servActivo = await this.servActivosRepository.findOne({ where: { usuario: { id_usuario: existente.id_usuario } } });
|
||||
|
||||
if (servActivo) {
|
||||
servActivo.Red = true;
|
||||
|
||||
servActivo.Prestamos = true;
|
||||
|
||||
|
||||
servActivo.PrestamosStatus = 'Inactivo';
|
||||
servActivo.RedStatus = 'Inactivo';
|
||||
|
||||
await this.servActivosRepository.save(servActivo);
|
||||
} else {
|
||||
console.warn('No se encontró el servicio activo para el usuario:', existente);
|
||||
}
|
||||
cambios = true;
|
||||
}
|
||||
|
||||
if (existente.fecha_nacimiento !== prof.fechaNacimiento) {
|
||||
existente.fecha_nacimiento = prof.fechaNacimiento;
|
||||
const servActivo = await this.servActivosRepository.findOne({ where: { usuario: { id_usuario: existente.id_usuario } } });
|
||||
|
||||
if (servActivo) {
|
||||
|
||||
|
||||
servActivo.Prestamos = true;
|
||||
servActivo.Correo = true;
|
||||
servActivo.PrestamosStatus = 'Inactivo';
|
||||
servActivo.CorreoStatus = 'Inactivo';
|
||||
|
||||
await this.servActivosRepository.save(servActivo);
|
||||
} else {
|
||||
console.warn('No se encontró el servicio activo para el usuario:', existente);
|
||||
}
|
||||
cambios = true;
|
||||
}
|
||||
|
||||
if (prof.numeroTrabajador && existente.num_cuenta !== prof.numeroTrabajador) {
|
||||
existente.num_cuenta = prof.numeroTrabajador;
|
||||
|
||||
|
||||
const servActivo = await this.servActivosRepository.findOne({ where: { usuario: { id_usuario: existente.id_usuario } } });
|
||||
if (servActivo) {
|
||||
servActivo.Red = true;
|
||||
servActivo.AT = true;
|
||||
servActivo.Correo = true;
|
||||
servActivo.Prestamos = true;
|
||||
|
||||
servActivo.CorreoStatus = 'Inactivo';
|
||||
servActivo.ATStatus = 'Inactivo';
|
||||
servActivo.PrestamosStatus = 'Inactivo';
|
||||
servActivo.RedStatus = 'Inactivo';
|
||||
await this.servActivosRepository.save(servActivo);
|
||||
} else {
|
||||
console.warn('No se encontró el servicio activo para el usuario:', existente);
|
||||
}
|
||||
cambios = true;
|
||||
}
|
||||
|
||||
if (cambios) {
|
||||
existente.movimiento = mov;
|
||||
await this.usuarioRepository.save(existente);
|
||||
|
||||
actualizados++;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Progreso -> Nuevos: ${nuevos}, Actualizados: ${actualizados}`);
|
||||
} catch (innerError) {
|
||||
console.error('Error procesando profesor:', prof, innerError);
|
||||
}
|
||||
}
|
||||
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();
|
||||
|
||||
return `Importación finalizada. Nuevos: ${nuevos}, Actualizados: ${actualizados}`;
|
||||
|
||||
} catch (error) {
|
||||
this.logger.error('Error al consultar profesores desde el WebService', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async cargaIndividual(usuario: CreateUsuarioDto, origen: string) {
|
||||
const queryRunner = this.usuarioRepository.manager.connection.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
|
||||
try {
|
||||
const existente = await queryRunner.manager.findOne(Usuario, {
|
||||
where: { num_cuenta: usuario.num_cuenta ?? usuario.usuario },
|
||||
relations: ['genero'],
|
||||
});
|
||||
|
||||
if (existente) {
|
||||
throw new Error('Ya existe este usuario');
|
||||
}
|
||||
|
||||
const mov = await this.movimientoService.logger(queryRunner, origen, 'LOADING', undefined, 'CARGA INDIVIDUAL DE USUARIOS');
|
||||
|
||||
let genero: Genero | null = null;
|
||||
if (usuario.genero === 'M' || usuario.genero === 'F') {
|
||||
const generoTexto = usuario.genero === 'M' ? 'Masculino' : 'Femenino';
|
||||
genero = await queryRunner.manager.findOne(Genero, { where: { genero: generoTexto } });
|
||||
if (!genero) {
|
||||
genero = queryRunner.manager.create(Genero, { genero: generoTexto });
|
||||
await queryRunner.manager.save(genero);
|
||||
}
|
||||
}
|
||||
|
||||
let carrera = await queryRunner.manager.findOne(Carrera, { where: { carrera: usuario.carrera } });
|
||||
if (!carrera) {
|
||||
const nuevaCarrera = queryRunner.manager.create(Carrera, { carrera: usuario.carrera, clave: usuario.clave_carrera });
|
||||
carrera = await queryRunner.manager.save(nuevaCarrera);
|
||||
}
|
||||
|
||||
|
||||
const nuevo = queryRunner.manager.create(Usuario, {
|
||||
num_cuenta: usuario.num_cuenta ?? usuario.usuario,
|
||||
nombre: usuario.nombre,
|
||||
a_paterno: usuario.a_paterno,
|
||||
a_materno: usuario.a_materno,
|
||||
rfc: usuario.rfc ?? null,
|
||||
fecha_nacimiento: usuario.fecha_nacimiento,
|
||||
generacion: usuario.generacion ?? null,
|
||||
genero,
|
||||
movimiento: mov,
|
||||
contraseña: usuario.contraseña ?? null, // Asegúrate de manejar la contraseña adecuadamente
|
||||
});
|
||||
|
||||
const savedUser = await queryRunner.manager.save(nuevo);
|
||||
|
||||
const userCarrera = queryRunner.manager.create(CarreraUsuario, { carrera, usuario: savedUser });
|
||||
|
||||
const FieldMap = [
|
||||
'Diplomado', 'Extra Largo', '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)) {
|
||||
throw new Error(`Tipo de usuario no permitido: ${usuario.tipo_usuario}`);
|
||||
}
|
||||
|
||||
// Verifica si el tipo de usuario ya existe
|
||||
let tipoUsuario = await queryRunner.manager.findOne(TipoUsuario, {
|
||||
where: { tipo_usuario: usuario.tipo_usuario },
|
||||
});
|
||||
|
||||
// Si no existe, lo crea y guarda
|
||||
if (!tipoUsuario) {
|
||||
tipoUsuario = queryRunner.manager.create(TipoUsuario, {
|
||||
tipo_usuario: usuario.tipo_usuario,
|
||||
});
|
||||
tipoUsuario = await queryRunner.manager.save(tipoUsuario);
|
||||
}
|
||||
|
||||
// Luego crea la relación con el usuario ya guardado
|
||||
const usuarioTipo = queryRunner.manager.create(UsuarioTipoUsuario, {
|
||||
tipoUsuario,
|
||||
usuario: savedUser,
|
||||
});
|
||||
await queryRunner.manager.save(usuarioTipo);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
switch (usuario.tipo_usuario.trim()) {
|
||||
|
||||
case 'Diplomado':
|
||||
|
||||
const servActivosDiplomado = this.servActivosRepository.create({
|
||||
Correo: true,
|
||||
usuario: savedUser,
|
||||
RedStatus: 'Inactivo',
|
||||
ATStatus: 'Inactivo',
|
||||
CorreoStatus: 'Inactivo',
|
||||
PrestamosStatus: 'Inactivo',
|
||||
});
|
||||
await queryRunner.manager.save(servActivosDiplomado);
|
||||
|
||||
break;
|
||||
|
||||
case 'Extra Largo':
|
||||
const servActivosExtraLargo = this.servActivosRepository.create({
|
||||
Prestamos: true,
|
||||
Correo: true,
|
||||
usuario: savedUser,
|
||||
RedStatus: 'Inactivo',
|
||||
ATStatus: 'Inactivo',
|
||||
CorreoStatus: 'Inactivo',
|
||||
PrestamosStatus: 'Inactivo',
|
||||
|
||||
});
|
||||
await queryRunner.manager.save(servActivosExtraLargo);
|
||||
break;
|
||||
|
||||
case 'Servicio Social':
|
||||
const servActivosServicio = this.servActivosRepository.create({
|
||||
Red: true,
|
||||
AT: true,
|
||||
Correo: true,
|
||||
usuario: savedUser,
|
||||
RedStatus: 'Inactivo',
|
||||
ATStatus: 'Inactivo',
|
||||
CorreoStatus: 'Inactivo',
|
||||
PrestamosStatus: 'Inactivo',
|
||||
});
|
||||
await queryRunner.manager.save(servActivosServicio);
|
||||
break;
|
||||
|
||||
|
||||
|
||||
case 'Idiomas R (UNAM)':
|
||||
case 'Idiomas Sabatino':
|
||||
const servActivosIdiomas = this.servActivosRepository.create({
|
||||
Red: true,
|
||||
Correo: true,
|
||||
usuario: savedUser,
|
||||
RedStatus: 'Inactivo',
|
||||
ATStatus: 'Inactivo',
|
||||
CorreoStatus: 'Inactivo',
|
||||
PrestamosStatus: 'Inactivo',
|
||||
});
|
||||
await queryRunner.manager.save(servActivosIdiomas);
|
||||
|
||||
break;
|
||||
|
||||
|
||||
|
||||
|
||||
case 'Reinscrito':
|
||||
case 'Posgrado':
|
||||
case 'Intercambio UNAM':
|
||||
case 'Movilidad':
|
||||
case 'Ampliación de Conocimiento':
|
||||
case 'Licenciatura':
|
||||
case 'Profesor':
|
||||
const servActivos = this.servActivosRepository.create({
|
||||
|
||||
Red: true,
|
||||
AT: true,
|
||||
Correo: true,
|
||||
Prestamos: true,
|
||||
usuario: savedUser,
|
||||
RedStatus: 'Inactivo',
|
||||
ATStatus: 'Inactivo',
|
||||
CorreoStatus: 'Inactivo',
|
||||
PrestamosStatus: 'Inactivo',
|
||||
});
|
||||
await queryRunner.manager.save(servActivos);
|
||||
|
||||
break;
|
||||
|
||||
|
||||
case 'Caso especial':
|
||||
case 'Trabajadores':
|
||||
const servActivosTrabajadores = this.servActivosRepository.create({
|
||||
Red: true,
|
||||
usuario: savedUser,
|
||||
RedStatus: 'Inactivo',
|
||||
|
||||
});
|
||||
await queryRunner.manager.save(servActivosTrabajadores);
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
console.log(savedUser)
|
||||
await queryRunner.commitTransaction();
|
||||
|
||||
return { saved: savedUser, movId: mov.id_mov };
|
||||
|
||||
} catch (error) {
|
||||
await queryRunner.rollbackTransaction();
|
||||
throw error;
|
||||
} finally {
|
||||
await queryRunner.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user