Merge branch 'Lino' of https://github.com/IO420/api-nexus into Axel

This commit is contained in:
2025-09-17 14:35:31 -06:00
32 changed files with 523 additions and 266 deletions
+18
View File
@@ -0,0 +1,18 @@
import { IsInt, IsNotEmpty, Min } from "class-validator";
export class chargePrintDto {
@IsInt()
@IsNotEmpty()
@Min(1)
monto:number
@IsInt()
@Min(1)
@IsNotEmpty()
numero_hojas: number;
@IsInt()
@IsNotEmpty()
id_cuenta: number;
}
+12
View File
@@ -0,0 +1,12 @@
import { Body, Controller, Post } from "@nestjs/common";
import { OperationsService } from "./operations.services";
@Controller('operations')
export class OperationsController{
constructor(private readonly operationsService:OperationsService){}
@Post()
async Login(@Body() data) {
return this.operationsService.chargePrint(data,data.userid);
}
}
+15
View File
@@ -0,0 +1,15 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Student } from 'src/alumno/entities/student.entity';
import { DetalleServicio } from 'src/detalle_servicio/entities/detalle_servicio.entity';
import { OperationsController } from './operations.controller';
import { OperationsService } from './operations.services';
@Module({
imports: [
TypeOrmModule.forFeature([Student, DetalleServicio]), // entidades que usarán las transacciones
],
controllers: [OperationsController],
providers: [OperationsService],
})
export class OperationsModule {}
+54
View File
@@ -0,0 +1,54 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import { StudentService } from 'src/alumno/student.service';
import { DetalleServicioService } from 'src/detalle_servicio/detalle_servicio.service';
import { DataSource } from 'typeorm';
import { chargePrintDto } from './dto/operations.dto';
import { CreateDetalleServicioDto } from 'src/detalle_servicio/dto/create-detalle_servicio.dto';
@Injectable()
export class OperationsService {
constructor(
private readonly dataSource: DataSource,
private readonly studentService: StudentService,
private readonly detalleServicioService: DetalleServicioService,
) {}
async chargePrint(data: chargePrintDto, userId: number) {
const { monto, id_cuenta } = data;
const queryRunner = this.dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const credit = await this.studentService.GetCredit(id_cuenta);
if (credit < monto) {
throw new BadRequestException('Crédito insuficiente');
}
const detalleData: CreateDetalleServicioDto = {
...data,
id_servicio: 1,
id_usuario: userId,
fecha_operacion: new Date(),
};
await this.detalleServicioService.Create(detalleData, queryRunner.manager);
await this.studentService.UpdateCredit(
id_cuenta,
monto,
queryRunner.manager,
);
await queryRunner.commitTransaction();
return { message: 'correct' };
} catch (error) {
await queryRunner.rollbackTransaction();
return { message: 'error', error: error.message };
} finally {
await queryRunner.release();
}
}
}
+3 -2
View File
@@ -1,5 +1,5 @@
import { Type } from 'class-transformer';
import { IsDate, IsNotEmpty, IsNumber, IsString } from 'class-validator';
import { IsEmail, IsNotEmpty, IsNumber, IsString } from 'class-validator';
export class CreateStudentDto {
@IsNotEmpty()
@@ -17,6 +17,7 @@ export class CreateStudentDto {
@IsNumber()
id_carrera: number;
@IsEmail()
@IsString()
correo: string;
}
+1 -1
View File
@@ -26,7 +26,7 @@ export class Student {
scale: 2,
default: 0.0,
})
credito: string;
credito: number;
@Column({
name: 'fecha_actualizacion_credito',
+1 -14
View File
@@ -3,13 +3,10 @@ import {
Get,
Post,
Body,
Patch,
Param,
Delete,
} from '@nestjs/common';
import { StudentService } from './student.service';
import { CreateStudentDto } from './dto/create-student.dto';
import { UpdateStudentDto } from './dto/update-student.dto';
import { Student } from './entities/student.entity';
@Controller('student')
@@ -27,17 +24,7 @@ export class StudentController {
}
@Get(':id')
findOne(@Param('id') id: string) {
findOne(@Param('id') id: number) {
return this.studentService.findOne(+id);
}
@Patch(':id')
update(@Param('id') id: string, @Body() updateStudentDto: UpdateStudentDto) {
return this.studentService.update(+id, updateStudentDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.studentService.remove(+id);
}
}
+16 -5
View File
@@ -2,7 +2,7 @@ import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateStudentDto } from './dto/create-student.dto';
import { UpdateStudentDto } from './dto/update-student.dto';
import { Student } from './entities/student.entity';
import { Repository } from 'typeorm';
import { EntityManager, Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
@Injectable()
@@ -32,11 +32,22 @@ export class StudentService {
return student;
}
update(id: number, updateStudentDto: UpdateStudentDto) {
return `This action updates a #${id} student`;
async GetCredit(id_cuenta: number): Promise<Student['credito']> {
const student = await this.findOne(id_cuenta);
return student.credito;
}
remove(id: number) {
return `This action removes a #${id} student`;
async UpdateCredit(
id_cuenta: number,
credit: number,
manager: EntityManager,
) {
const repo = manager.getRepository(Student);
return await repo
.createQueryBuilder()
.update()
.set({ credito: () => `credito - ${credit}` })
.where({ id_cuenta })
.execute();
}
}
+7 -3
View File
@@ -5,11 +5,14 @@ import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { StudentModule } from './alumno/student.module';
import { UserModule } from './user/user.module';
import { User } from './user/entities/user.entity';
import { Perfil, User } from './user/entities/user.entity';
import { DetalleServicioModule } from './detalle_servicio/detalle_servicio.module';
import { PeriodoModule } from './periodo/periodo.module';
import { ServicioModule } from './servicio/servicio.module';
import { Student } from './alumno/entities/student.entity';
import { DetalleServicio } from './detalle_servicio/entities/detalle_servicio.entity';
import { Periodo } from './periodo/entities/periodo.entity';
import { Servicio } from './servicio/entities/servicio.entity';
@Module({
imports: [
@@ -26,11 +29,12 @@ import { Student } from './alumno/entities/student.entity';
username: configService.get<string>('DB_USER'),
password: configService.get<string>('DB_PASSWORD'),
database: configService.get<string>('DB_NAME'),
entities: [User, Student],
synchronize: false,
entities: [User,Student,DetalleServicio,Periodo,Servicio,Perfil],
synchronize: false,//Never change to true in production!
}),
}),
UserModule,
StudentModule,
DetalleServicioModule,
PeriodoModule,
ServicioModule,
@@ -1,20 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { DetalleServicioController } from './detalle_servicio.controller';
import { DetalleServicioService } from './detalle_servicio.service';
describe('DetalleServicioController', () => {
let controller: DetalleServicioController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [DetalleServicioController],
providers: [DetalleServicioService],
}).compile();
controller = module.get<DetalleServicioController>(DetalleServicioController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
@@ -1,34 +1,9 @@
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { Controller } from '@nestjs/common';
import { DetalleServicioService } from './detalle_servicio.service';
import { CreateDetalleServicioDto } from './dto/create-detalle_servicio.dto';
import { UpdateDetalleServicioDto } from './dto/update-detalle_servicio.dto';
@Controller('detalle-servicio')
export class DetalleServicioController {
constructor(private readonly detalleServicioService: DetalleServicioService) {}
@Post()
create(@Body() createDetalleServicioDto: CreateDetalleServicioDto) {
return this.detalleServicioService.create(createDetalleServicioDto);
}
@Get()
findAll() {
return this.detalleServicioService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.detalleServicioService.findOne(+id);
}
@Patch(':id')
update(@Param('id') id: string, @Body() updateDetalleServicioDto: UpdateDetalleServicioDto) {
return this.detalleServicioService.update(+id, updateDetalleServicioDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.detalleServicioService.remove(+id);
}
}
@@ -1,18 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { DetalleServicioService } from './detalle_servicio.service';
describe('DetalleServicioService', () => {
let service: DetalleServicioService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [DetalleServicioService],
}).compile();
service = module.get<DetalleServicioService>(DetalleServicioService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
@@ -1,26 +1,13 @@
import { Injectable } from '@nestjs/common';
import { DetalleServicio } from './entities/detalle_servicio.entity';
import { EntityManager } from 'typeorm';
import { CreateDetalleServicioDto } from './dto/create-detalle_servicio.dto';
import { UpdateDetalleServicioDto } from './dto/update-detalle_servicio.dto';
@Injectable()
export class DetalleServicioService {
create(createDetalleServicioDto: CreateDetalleServicioDto) {
return 'This action adds a new detalleServicio';
}
findAll() {
return `This action returns all detalleServicio`;
}
findOne(id: number) {
return `This action returns a #${id} detalleServicio`;
}
update(id: number, updateDetalleServicioDto: UpdateDetalleServicioDto) {
return `This action updates a #${id} detalleServicio`;
}
remove(id: number) {
return `This action removes a #${id} detalleServicio`;
async Create(data: CreateDetalleServicioDto, manager: EntityManager) {
const repo = manager.getRepository(DetalleServicio);
const details = repo.create(data);
return await repo.save(details);
}
}
@@ -1,9 +1,15 @@
import { Type } from 'class-transformer';
import { IsDate, IsInt, IsNotEmpty, IsOptional, Min } from 'class-validator';
import { IsDate, IsIn, IsInt, IsNotEmpty, IsOptional, Min } from 'class-validator';
export class CreateDetalleServicioDto {
@IsInt()
@Min(0)
@IsNotEmpty()
@Min(1)
monto:number
@IsInt()
@Min(1)
@IsNotEmpty()
numero_hojas: number;
@@ -23,8 +29,4 @@ export class CreateDetalleServicioDto {
@IsInt()
@IsNotEmpty()
id_usuario: number;
@IsOptional()
@IsInt()
id_periodo?: number;
}
@@ -1,9 +0,0 @@
export class DetalleServicioDto {
id_detalle_servicio: number;
numero_hojas: number;
fecha_operacion: Date;
id_cuenta: number;
id_servicio: number;
id_usuario: number;
id_periodo: number | null;
}
@@ -15,7 +15,7 @@ export class DetalleServicio {
scale: 2,
nullable: false,
})
monto: string;
monto: number;
@Column({ name: 'numero_hojas', type: 'int', nullable: false, default: 0 })
numero_hojas: number;
@@ -39,13 +39,4 @@ export class DetalleServicio {
@Column({ name: 'id_perido', type: 'int', default: null })
id_periodo: number;
}
/* `id_detalle_servicio` int(11) NOT NULL AUTO_INCREMENT,
`monto` decimal(10,2) NOT NULL,
`numero_hojas` int(11) NOT NULL DEFAULT 0,
`fecha_operacion` timestamp NOT NULL DEFAULT current_timestamp(),
`id_cuenta` int(9) unsigned zerofill NOT NULL,
`id_servicio` int(11) NOT NULL,
`id_usuario` int(11) NOT NULL,
`id_periodo` int(11) DEFAULT NULL,*/
}
+10 -1
View File
@@ -1,11 +1,20 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
app.useGlobalPipes(new ValidationPipe());
app.enableCors();
app.enableCors(
{
origin: configService.get<string>('Front_URL'),
}
);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
-20
View File
@@ -1,20 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PeriodoController } from './periodo.controller';
import { PeriodoService } from './periodo.service';
describe('PeriodoController', () => {
let controller: PeriodoController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [PeriodoController],
providers: [PeriodoService],
}).compile();
controller = module.get<PeriodoController>(PeriodoController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
-18
View File
@@ -1,18 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PeriodoService } from './periodo.service';
describe('PeriodoService', () => {
let service: PeriodoService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [PeriodoService],
}).compile();
service = module.get<PeriodoService>(PeriodoService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
-20
View File
@@ -1,20 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ServicioController } from './servicio.controller';
import { ServicioService } from './servicio.service';
describe('ServicioController', () => {
let controller: ServicioController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [ServicioController],
providers: [ServicioService],
}).compile();
controller = module.get<ServicioController>(ServicioController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
+1
View File
@@ -32,3 +32,4 @@ export class ServicioController {
return this.servicioService.remove(+id);
}
}
//IO
-18
View File
@@ -1,18 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ServicioService } from './servicio.service';
describe('ServicioService', () => {
let service: ServicioService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ServicioService],
}).compile();
service = module.get<ServicioService>(ServicioService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
+50 -31
View File
@@ -1,35 +1,54 @@
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
import {
Column,
Entity,
JoinColumn,
ManyToOne,
OneToMany,
PrimaryGeneratedColumn,
} from 'typeorm';
@Entity({name:'usuario'})
export class User {
@Entity({ name: 'perfil' })
export class Perfil {
@PrimaryGeneratedColumn({ name: 'id_perfil', type: 'int' })
id_perfil: number;
@PrimaryGeneratedColumn({name:'id_usuario',type: 'int'})
id_usuario:number;
@Column({ name: 'perfil', type: 'varchar', length: 45, nullable: false })
perfil: string;
@Column({name:'nombre',type:'varchar'})
nombre:string
@Column({name:'apellido_paterno',type:'varchar'})
apellido_paterno:string
@Column({name:'apellido_materno',type:'varchar'})
apellido_materno:string
@Column({name:'usuario',type:'varchar'})
usuario:string
@Column({name:'password',type:'varchar',length:45, nullable:false})
password:string
@Column({name:'activo',type:'tinyint',nullable:false, default:1})
activo: number
@Column({name:'descripcion',type:'varchar',length:50,default:null})
description:boolean
@Column({name:'fecha_registro',type:'varchar'})
fecha_registro:string
@Column({name:'id_perfil',})
id_perfil:number
@OneToMany(() => User, (user) => user.perfil)
usuarios: User[];
}
@Entity({ name: 'usuario' })
export class User {
@PrimaryGeneratedColumn({ name: 'id_usuario', type: 'int' })
id_usuario: number;
@Column({ name: 'nombre', type: 'varchar' })
nombre: string;
@Column({ name: 'apellido_paterno', type: 'varchar' })
apellido_paterno: string;
@Column({ name: 'apellido_materno', type: 'varchar' })
apellido_materno: string;
@Column({ name: 'usuario', type: 'varchar' })
usuario: string;
@Column({ name: 'password', type: 'varchar', length: 45, nullable: false })
password: string;
@Column({ name: 'activo', type: 'tinyint', nullable: false, default: 1 })
activo: number;
@Column({ name: 'descripcion', type: 'varchar', length: 50, default: null })
description: boolean;
@Column({ name: 'fecha_registro', type: 'varchar' })
fecha_registro: string;
@ManyToOne(() => Perfil, (perfil) => perfil.usuarios, { eager: true })
@JoinColumn({ name: 'id_perfil' })
perfil: Perfil;
}
+20
View File
@@ -0,0 +1,20 @@
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { UserService } from './user.service';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private configService: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: configService.get('JWT_SECRET')!,
});
}
async validate(payload: any) {
return { userId: payload.id, username: payload.usuario };
}
}
+20 -5
View File
@@ -1,15 +1,30 @@
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import {
Controller,
Get,
Post,
Body,
UseGuards,
Request,
Res,
} from '@nestjs/common';
import type { Response } from 'express';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { AuthGuard } from '@nestjs/passport';
@Controller('user')
export class UserController {
constructor(private readonly userService: UserService) {}
@Post()
Login(@Body() user: CreateUserDto) {
return this.userService.Login(user);
async Login(@Body() data: CreateUserDto, @Res() res: Response) {
return this.userService.Login(data, res);
}
@UseGuards(AuthGuard('jwt'))
@Get('/validate-token')
getProfile(@Request() req) {
return req.user;
}
}
//IO
+20 -4
View File
@@ -3,13 +3,29 @@ import { UserService } from './user.service';
import { UserController } from './user.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { JwtStrategy } from './jwt.strategy';
@Module({
imports:[
TypeOrmModule.forFeature([User])
imports: [
TypeOrmModule.forFeature([User]),
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.registerAsync({
inject: [ConfigService],
useFactory: async (configService: ConfigService) => {
return {
global: true,
secret: configService.get('JWT_SECRET'),
signOptions: { expiresIn: '1h' },
};
},
}),
],
controllers: [UserController],
providers: [UserService],
providers: [UserService,JwtStrategy],
exports: [UserService],
})
export class UserModule {}
export class UserModule { }
+22 -9
View File
@@ -1,38 +1,51 @@
import { Injectable, Logger, NotFoundException, UnauthorizedException } from '@nestjs/common';
import { Injectable, NotFoundException } from '@nestjs/common';
import { Response } from 'express';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { Repository } from 'typeorm';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private userRepository: Repository<User>,
private readonly userRepository: Repository<User>,
private jwtService: JwtService
) { }
async findOneByNameandPassword(data:CreateUserDto): Promise<User> {
async findOneByNameandPassword(data: CreateUserDto): Promise<User> {
const { usuario, password } = data
const user = await this.userRepository.findOne({
where: { usuario,password }
where: { usuario, password }
})
if (!user) {
throw new NotFoundException(
`El usuario ${usuario} no fue encontrado`,
`El usuario o la contraseña es incorrecta`,
);
}
return user;
}
async Login(data: CreateUserDto) {
async Login(data: CreateUserDto, res: Response) {
const user = await this.findOneByNameandPassword(data);
return user
const payload = { id: user.id_usuario, usuario: user.usuario };
const token = await this.jwtService.signAsync(payload);
res.cookie('token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production', // en dev desactívalo
sameSite: 'strict',
path: '/',
});
return res.json({ message: 'Inicio de sesión exitoso' });
}
}