new structure whit other database

This commit is contained in:
2025-10-23 08:35:55 -06:00
parent ec1dd723d2
commit f66de9458b
65 changed files with 123 additions and 80 deletions
@@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AbonoTicketController } from './abono-ticket.controller';
import { AbonoTicketService } from './abono-ticket.service';
describe('AbonoTicketController', () => {
let controller: AbonoTicketController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AbonoTicketController],
providers: [AbonoTicketService],
}).compile();
controller = module.get<AbonoTicketController>(AbonoTicketController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
@@ -0,0 +1,18 @@
import { Controller, Get, Post, Body } from '@nestjs/common';
import { AbonoTicketService } from './abono-ticket.service';
import { CreateAbonoTicketDto } from './dto/create-abono-ticket.dto';
@Controller('abono-ticket')
export class AbonoTicketController {
constructor(private readonly abonoTicketService: AbonoTicketService) {}
@Post()
create(@Body() createAbonoTicketDto: CreateAbonoTicketDto) {
return this.abonoTicketService.create(createAbonoTicketDto);
}
@Get()
all() {
return this.abonoTicketService.find();
}
}
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { AbonoTicketService } from './abono-ticket.service';
import { AbonoTicketController } from './abono-ticket.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AbonoTicket } from '../../../database/Monedero/entities/abono-ticket.entity';
@Module({
imports: [TypeOrmModule.forFeature([AbonoTicket], 'dbMonedero')],
controllers: [AbonoTicketController],
providers: [AbonoTicketService],
exports: [AbonoTicketService],
})
export class AbonoTicketModule {}
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AbonoTicketService } from './abono-ticket.service';
describe('AbonoTicketService', () => {
let service: AbonoTicketService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AbonoTicketService],
}).compile();
service = module.get<AbonoTicketService>(AbonoTicketService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
@@ -0,0 +1,34 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateAbonoTicketDto } from './dto/create-abono-ticket.dto';
import { AbonoTicket } from '../../../database/Monedero/entities/abono-ticket.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Transaccion } from 'src/database/Monedero/entities/transaccion.entity';
@Injectable()
export class AbonoTicketService {
constructor(
@InjectRepository(AbonoTicket, 'dbMonedero')
private readonly abonoTicketRepository: Repository<AbonoTicket>,
) {}
async find() {
return await this.abonoTicketRepository.find();
}
async findByTransaccion(transaccion: Transaccion): Promise<AbonoTicket> {
const abonoTicket = await this.abonoTicketRepository.findOne({
where: { transaccion },
});
if (!abonoTicket) {
throw new NotFoundException('abonoTicket not found');
}
return abonoTicket;
}
async create(createAbonoTicketDto: CreateAbonoTicketDto) {
const create = this.abonoTicketRepository.create(createAbonoTicketDto);
await this.abonoTicketRepository.save(create);
return 'success';
}
}
@@ -0,0 +1 @@
export class CreateAbonoTicketDto {}
@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreateAbonoTicketDto } from './create-abono-ticket.dto';
export class UpdateAbonoTicketDto extends PartialType(CreateAbonoTicketDto) {}
@@ -0,0 +1 @@
export class CreateKioscoDto {}
@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreateKioscoDto } from './create-kiosco.dto';
export class UpdateKioscoDto extends PartialType(CreateKioscoDto) {}
@@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { KioscoController } from './kiosco.controller';
import { KioscoService } from './kiosco.service';
describe('KioscoController', () => {
let controller: KioscoController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [KioscoController],
providers: [KioscoService],
}).compile();
controller = module.get<KioscoController>(KioscoController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
@@ -0,0 +1,22 @@
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
} from '@nestjs/common';
import { KioscoService } from './kiosco.service';
import { CreateKioscoDto } from './dto/create-kiosco.dto';
import { UpdateKioscoDto } from './dto/update-kiosco.dto';
@Controller('kiosco')
export class KioscoController {
constructor(private readonly kioscoService: KioscoService) {}
@Get()
findAll() {
return this.kioscoService.findAll();
}
}
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { KioscoService } from './kiosco.service';
import { KioscoController } from './kiosco.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Kiosco } from 'src/database/Monedero/entities/kiosco.entity';
@Module({
imports: [TypeOrmModule.forFeature([Kiosco], 'dbMonedero')],
controllers: [KioscoController],
providers: [KioscoService],
exports: [KioscoService],
})
export class KioscoModule {}
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { KioscoService } from './kiosco.service';
describe('KioscoService', () => {
let service: KioscoService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [KioscoService],
}).compile();
service = module.get<KioscoService>(KioscoService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
@@ -0,0 +1,27 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateKioscoDto } from './dto/create-kiosco.dto';
import { UpdateKioscoDto } from './dto/update-kiosco.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Kiosco } from 'src/database/Monedero/entities/kiosco.entity';
@Injectable()
export class KioscoService {
constructor(
@InjectRepository(Kiosco, 'dbMonedero')
private readonly KioscoRepository: Repository<Kiosco>,
) {}
findAll() {
return this.KioscoRepository.find();
}
async findById(idKiosco: number): Promise<Kiosco> {
const kiosco = await this.KioscoRepository.findOne({ where: { idKiosco } });
if (!kiosco) {
throw new NotFoundException('kiosco not found');
}
return kiosco;
}
}
@@ -0,0 +1 @@
export class CreateNombreTransaccionDto {}
@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreateNombreTransaccionDto } from './create-nombre-transaccion.dto';
export class UpdateNombreTransaccionDto extends PartialType(CreateNombreTransaccionDto) {}
@@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { NombreTransaccionController } from './nombre-transaccion.controller';
import { NombreTransaccionService } from './nombre-transaccion.service';
describe('NombreTransaccionController', () => {
let controller: NombreTransaccionController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [NombreTransaccionController],
providers: [NombreTransaccionService],
}).compile();
controller = module.get<NombreTransaccionController>(NombreTransaccionController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
@@ -0,0 +1,14 @@
import { Controller, Get } from '@nestjs/common';
import { NombreTransaccionService } from './nombre-transaccion.service';
@Controller('nombre-transaccion')
export class NombreTransaccionController {
constructor(
private readonly nombreTransaccionService: NombreTransaccionService,
) {}
@Get()
findAll() {
return this.nombreTransaccionService.findAll();
}
}
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { NombreTransaccionService } from './nombre-transaccion.service';
import { NombreTransaccionController } from './nombre-transaccion.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { NombreTransaccion } from 'src/database/Monedero/entities/nombre-transaccion.entity';
@Module({
imports: [TypeOrmModule.forFeature([NombreTransaccion], 'dbMonedero')],
controllers: [NombreTransaccionController],
providers: [NombreTransaccionService],
exports: [NombreTransaccionService],
})
export class NombreTransaccionModule {}
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { NombreTransaccionService } from './nombre-transaccion.service';
describe('NombreTransaccionService', () => {
let service: NombreTransaccionService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [NombreTransaccionService],
}).compile();
service = module.get<NombreTransaccionService>(NombreTransaccionService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
@@ -0,0 +1,40 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { NombreTransaccion } from 'src/database/Monedero/entities/nombre-transaccion.entity';
import { Repository } from 'typeorm';
@Injectable()
export class NombreTransaccionService {
constructor(
@InjectRepository(NombreTransaccion, 'dbMonedero')
private readonly nombreTransaccionRepository: Repository<NombreTransaccion>,
) {}
findAll() {
return this.nombreTransaccionRepository.find();
}
async findById(idNombreTransaccion: number): Promise<NombreTransaccion> {
const nameTransaccion = await this.nombreTransaccionRepository.findOne({
where: { idNombreTransaccion },
});
if (!nameTransaccion) {
throw new NotFoundException('name transaction not found');
}
return nameTransaccion;
}
async findByName(nombreTransaccion: string): Promise<NombreTransaccion> {
const transaccion = await this.nombreTransaccionRepository.findOne({
where: { nombreTransaccion },
});
if (!transaccion) {
throw new NotFoundException('transaction not found');
}
return transaccion;
}
}
@@ -0,0 +1,18 @@
import { IsBoolean, IsDateString, IsNumber } from 'class-validator';
export class CreatePagoKioscoDto {
@IsNumber()
idTransaccion: number;
@IsNumber()
monto: number;
@IsDateString()
fecha: string;
@IsNumber()
idKiosco: number;
@IsBoolean()
pagoPatronatoCreado: boolean;
}
@@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PagoKioscoController } from './pago-kiosco.controller';
import { PagoKioscoService } from './pago-kiosco.service';
describe('PagoKioscoController', () => {
let controller: PagoKioscoController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [PagoKioscoController],
providers: [PagoKioscoService],
}).compile();
controller = module.get<PagoKioscoController>(PagoKioscoController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
@@ -0,0 +1,26 @@
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
} from '@nestjs/common';
import { PagoKioscoService } from './pago-kiosco.service';
import { CreatePagoKioscoDto } from './dto/create-pago-kiosco.dto';
@Controller('pago-kiosco')
export class PagoKioscoController {
constructor(private readonly pagoKioscoService: PagoKioscoService) {}
@Post()
create(@Body() createPagoKioscoDto: CreatePagoKioscoDto) {
return this.pagoKioscoService.create(createPagoKioscoDto);
}
@Get()
all() {
return this.pagoKioscoService.all();
}
}
@@ -0,0 +1,19 @@
import { Module } from '@nestjs/common';
import { PagoKioscoService } from './pago-kiosco.service';
import { PagoKioscoController } from './pago-kiosco.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { KioscoModule } from 'src/modules/Monedero/kiosco/kiosco.module';
import { TransaccionModule } from 'src/modules/Monedero/transaccion/transaccion.module';
import { PagoKiosco } from 'src/database/Monedero/entities/pago-kiosco.entity';
@Module({
imports: [
TypeOrmModule.forFeature([PagoKiosco], 'dbMonedero'),
KioscoModule,
TransaccionModule,
],
controllers: [PagoKioscoController],
providers: [PagoKioscoService],
exports: [PagoKioscoService],
})
export class PagoKioscoModule {}
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PagoKioscoService } from './pago-kiosco.service';
describe('PagoKioscoService', () => {
let service: PagoKioscoService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [PagoKioscoService],
}).compile();
service = module.get<PagoKioscoService>(PagoKioscoService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
@@ -0,0 +1,39 @@
import { Injectable } from '@nestjs/common';
import { CreatePagoKioscoDto } from './dto/create-pago-kiosco.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { KioscoService } from 'src/modules/Monedero/kiosco/kiosco.service';
import { TransaccionService } from 'src/modules/Monedero/transaccion/transaccion.service';
import { PagoKiosco } from 'src/database/Monedero/entities/pago-kiosco.entity';
@Injectable()
export class PagoKioscoService {
constructor(
@InjectRepository(PagoKiosco, 'dbMonedero')
private readonly pagoKioscoRepository: Repository<PagoKiosco>,
private readonly kioscoService: KioscoService,
private readonly transaccionService: TransaccionService,
) {}
async all() {
return this.pagoKioscoRepository.find();
}
async create(createPagoKiosco: CreatePagoKioscoDto) {
const { idKiosco, idTransaccion, ...rest } = createPagoKiosco;
const kiosco = this.kioscoService.findById(idKiosco);
const transaccion = this.transaccionService.findById(idTransaccion);
const data = {
...rest,
kiosco: await kiosco,
transaccion: await transaccion,
};
const create = this.pagoKioscoRepository.create(data);
await this.pagoKioscoRepository.save(create);
return await this.pagoKioscoRepository.save(create);
}
}
@@ -0,0 +1 @@
export class CreatePagoPatronatoDto {}
@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreatePagoPatronatoDto } from './create-pago-patronato.dto';
export class UpdatePagoPatronatoDto extends PartialType(CreatePagoPatronatoDto) {}
@@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PagoPatronatoController } from './pago-patronato.controller';
import { PagoPatronatoService } from './pago-patronato.service';
describe('PagoPatronatoController', () => {
let controller: PagoPatronatoController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [PagoPatronatoController],
providers: [PagoPatronatoService],
}).compile();
controller = module.get<PagoPatronatoController>(PagoPatronatoController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
@@ -0,0 +1,20 @@
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
} from '@nestjs/common';
import { PagoPatronatoService } from './pago-patronato.service';
@Controller('pago-patronato')
export class PagoPatronatoController {
constructor(private readonly pagoPatronatoService: PagoPatronatoService) {}
@Get()
findAll() {
return this.pagoPatronatoService.findAll();
}
}
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { PagoPatronatoService } from './pago-patronato.service';
import { PagoPatronatoController } from './pago-patronato.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { PagoPatronato } from '../../../database/Monedero/entities/pago-patronato.entity';
@Module({
imports: [TypeOrmModule.forFeature([PagoPatronato], 'dbMonedero')],
controllers: [PagoPatronatoController],
providers: [PagoPatronatoService],
exports: [PagoPatronatoService],
})
export class PagoPatronatoModule {}
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PagoPatronatoService } from './pago-patronato.service';
describe('PagoPatronatoService', () => {
let service: PagoPatronatoService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [PagoPatronatoService],
}).compile();
service = module.get<PagoPatronatoService>(PagoPatronatoService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
@@ -0,0 +1,22 @@
import { Injectable } from '@nestjs/common';
import { CreatePagoPatronatoDto } from './dto/create-pago-patronato.dto';
import { UpdatePagoPatronatoDto } from './dto/update-pago-patronato.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { PagoPatronato } from '../../../database/Monedero/entities/pago-patronato.entity';
import { Repository } from 'typeorm';
@Injectable()
export class PagoPatronatoService {
constructor(
@InjectRepository(PagoPatronato, 'dbMonedero')
private readonly pagoPatronatoRepository: Repository<PagoPatronato>,
) {}
findAll() {
return this.pagoPatronatoRepository.find();
}
findById(idPagoPatronato: number) {
return this.pagoPatronatoRepository.findOne({ where: { idPagoPatronato } });
}
}
@@ -0,0 +1 @@
export class CreatePersonaDto {}
@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreatePersonaDto } from './create-persona.dto';
export class UpdatePersonaDto extends PartialType(CreatePersonaDto) {}
@@ -0,0 +1,16 @@
import {
Injectable,
ExecutionContext,
UnauthorizedException,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class GoogleAuthGuard extends AuthGuard('google') {
handleRequest(err, user, info, context: ExecutionContext) {
if (err || !user) {
throw err || new UnauthorizedException(); // deja que el controller maneje el redirect
}
return user;
}
}
@@ -0,0 +1,61 @@
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { Strategy, VerifyCallback } from 'passport-google-oauth20';
import { ConfigService } from '@nestjs/config';
import { PersonaService } from './persona.service';
@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
constructor(
private readonly personaService: PersonaService,
private readonly config: ConfigService,
) {
const clientID = config.get<string>('GOOGLE_CLIENT_ID');
const clientSecret = config.get<string>('GOOGLE_CLIENT_SECRET');
const callbackURL = config.get<string>('GOOGLE_CALLBACK_URL');
if (!clientID || !clientSecret || !callbackURL) {
throw new Error(
'Las variables de entorno de Google OAuth no están definidas',
);
}
super({
clientID,
clientSecret,
callbackURL,
scope: ['email', 'profile'],
passReqToCallback: true,
});
}
authorizationParams() {
return {
prompt: 'select_account',
};
}
async validate(
req: any,
accessToken: string,
refreshToken: string,
profile: any,
done: VerifyCallback,
): Promise<any> {
try {
const email = profile.emails?.[0]?.value || '';
const nombre = profile.name?.givenName || '';
const apellido = profile.name?.familyName || '';
const user = await this.personaService.validateOrCreateGoogleUser({
email,
nombre,
apellido,
});
done(null, user);
} catch (error) {
done(error, false);
}
}
}
+16
View File
@@ -0,0 +1,16 @@
import {
ExecutionContext,
Injectable,
ForbiddenException,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
handleRequest(err: any, user: any, info: any, context: ExecutionContext) {
if (err || !user) {
throw new ForbiddenException('Access denied: token inválido o ausente');
}
return user;
}
}
@@ -0,0 +1,32 @@
import { Injectable, ForbiddenException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
export interface JwtPayload {
idPersona: string;
user: string;
userType: string;
}
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private configService: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: configService.get<string>('JWT_SECRET')!,
});
}
async validate(payload: JwtPayload) {
if (!payload || !payload.idPersona || !payload.user || !payload.userType) {
throw new ForbiddenException('Token inválido o corrupto');
}
return {
idPersona: payload.idPersona,
user: payload.user,
userType: payload.userType,
};
}
}
+10
View File
@@ -0,0 +1,10 @@
export default function passwordRand(length: number): string {
const characters =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let pass = '';
for (let i = 0; i < length; i++) {
pass += characters.charAt(Math.floor(Math.random() * characters.length));
}
return pass;
}
@@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PersonaController } from './persona.controller';
import { PersonaService } from './persona.service';
describe('PersonaController', () => {
let controller: PersonaController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [PersonaController],
providers: [PersonaService],
}).compile();
controller = module.get<PersonaController>(PersonaController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
@@ -0,0 +1,68 @@
import { Controller, Get, UseGuards, Req, Res } from '@nestjs/common';
import type { Response } from 'express';
import { PersonaService } from './persona.service';
import { GoogleAuthGuard } from './google-auth.guard';
import { JwtAuthGuard } from './jwt.guard';
@Controller('persona')
export class PersonaController {
constructor(private readonly personaService: PersonaService) {}
@Get()
getAll() {
return this.personaService.findAll();
}
@Get('google')
@UseGuards(GoogleAuthGuard)
async googleLogin() {}
@Get('google/callback')
@UseGuards(GoogleAuthGuard)
async googleCallback(@Req() req, @Res() res: Response) {
const persona = req.user;
if (!persona) {
return res.redirect(`${process.env.FRONTEND_URL}?error=oauth_failed`);
}
const jwt = await this.personaService.generateJwt(persona);
return res.redirect(
`${process.env.FRONTEND_URL}/oauth-callback?token=${jwt.access_token}`,
);
}
@UseGuards(JwtAuthGuard)
@Get('me')
async getMe(@Req() req) {
const idPersona = req.user.idPersona;
const persona = await this.personaService.findById(idPersona);
return {
error: false,
msj: `Bienvenido ${persona.nombre} ${persona.apellidoP} ${persona.apellidoM}`,
data: {
userId: persona.idPersona,
nombre: persona.nombre,
apellidoP: persona.apellidoP,
apellidoM: persona.apellidoM,
saldo: persona.cantidadCuenta,
carreraAds: persona.carreraAds,
numeroCuenta: persona.numeroIdentificar,
tipoUsuario: persona.tipoUsuario,
primerLogin: persona.primerLogin,
cambioPassword: persona.cambioPasswordReq,
},
};
}
@UseGuards(JwtAuthGuard)
@Get('saldo')
async saldo(@Req() req) {
const idPersona = req.user.idPersona;
return this.personaService.saldo(idPersona);
}
}
//IO
@@ -0,0 +1,32 @@
import { Module } from '@nestjs/common';
import { PersonaService } from './persona.service';
import { PersonaController } from './persona.controller';
import { PassportModule } from '@nestjs/passport';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { JwtModule } from '@nestjs/jwt';
import { GoogleStrategy } from './google.strategy';
import { JwtStrategy } from './jwt.strategy';
import { Persona } from 'src/database/Monedero/entities/persona.entity';
@Module({
imports: [
TypeOrmModule.forFeature([Persona], 'dbMonedero'),
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => {
return {
global: true,
secret: configService.get<string>('JWT_SECRET'),
signOptions: { expiresIn: '1h' },
};
},
}),
],
controllers: [PersonaController],
providers: [PersonaService, GoogleStrategy, JwtStrategy],
exports: [PersonaService],
})
export class PersonaModule {}
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PersonaService } from './persona.service';
describe('PersonaService', () => {
let service: PersonaService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [PersonaService],
}).compile();
service = module.get<PersonaService>(PersonaService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
@@ -0,0 +1,118 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Persona } from 'src/database/Monedero/entities/persona.entity';
@Injectable()
export class PersonaService {
constructor(
@InjectRepository(Persona, 'dbMonedero')
private readonly personaRepository: Repository<Persona>,
private readonly jwtService: JwtService,
) {}
async findAll() {
return this.personaRepository.find();
}
async findByEmail(correo: string): Promise<Persona | null> {
const user = await this.personaRepository.findOne({
where: { correo },
});
console.log('service', user);
return user;
}
async create(data: Partial<Persona>): Promise<Persona> {
const persona = this.personaRepository.create(data);
return this.personaRepository.save(persona);
}
async findById(idPersona: number): Promise<Persona> {
const user = await this.personaRepository.findOne({ where: { idPersona } });
if (!user) {
throw new NotFoundException('user not found');
}
return user;
}
async generateJwt(user: Persona) {
const payload = {
userType: 'usuario',
user: 'alumno',
idPersona: user.idPersona,
};
return {
access_token: this.jwtService.sign(payload),
};
}
async validateOrCreateGoogleUser(data: {
email: string;
nombre: string;
apellido: string;
}) {
let persona = await this.findByEmail(data.email);
if (!persona) {
const apellidoArray = data.apellido.split(' ');
const apellidoP = apellidoArray[0] || '';
const apellidoM = apellidoArray[1] || '';
let realName;
const numeroIdentificar = data.email.split('@')[0];
let tipo;
if (numeroIdentificar.length === 9) {
tipo = 'Alumno';
realName = apellidoArray.slice(2).join(' ') || '';
} else {
tipo = 'Academico';
realName = data.nombre;
}
persona = await this.create({
nombre: realName || '',
apellidoP: apellidoP || '',
apellidoM: apellidoM || '',
password: '',
fechaPasswordTem: new Date(),
correo: data.email,
carreraAds: '',
cantidadCuenta: 0,
usuario: numeroIdentificar,
numeroIdentificar: numeroIdentificar || '',
tipoUsuario: tipo,
correoEnviado: false,
fechaRegistro: new Date(),
cambioPasswordReq: true,
primerLogin: false,
});
}
return persona;
}
async saldo(idPersona: number) {
const persona = await this.personaRepository.findOne({
where: { idPersona },
select: { cantidadCuenta: true },
});
return persona?.cantidadCuenta;
}
async updateSaldo(idPersona: number, monto: number) {
const persona = await this.findById(idPersona);
const newSaldo = (persona.cantidadCuenta || 0) + monto;
await this.personaRepository.update(idPersona, {
cantidadCuenta: newSaldo,
});
return newSaldo;
}
}
//IO
@@ -0,0 +1,19 @@
import { IsInt, IsNotEmpty, IsDateString, IsNumber } from 'class-validator';
export class CreateTransaccionDto {
@IsInt()
@IsNotEmpty()
nombreTransaccion: string;
@IsInt()
@IsNotEmpty()
idPersona: number;
@IsDateString()
@IsNotEmpty()
fecha: string;
@IsNumber()
@IsNotEmpty()
tipoTransaccion: number;
}
@@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { TransaccionController } from './transaccion.controller';
import { TransaccionService } from './transaccion.service';
describe('TransaccionController', () => {
let controller: TransaccionController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [TransaccionController],
providers: [TransaccionService],
}).compile();
controller = module.get<TransaccionController>(TransaccionController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
@@ -0,0 +1,26 @@
import { Controller, Get, Post, Body } from '@nestjs/common';
import { TransaccionService } from './transaccion.service';
import { CreateTransaccionDto } from './dto/create-transaccion.dto';
@Controller('transaccion')
export class TransaccionController {
constructor(private readonly transaccionService: TransaccionService) {}
@Get()
all() {
return this.transaccionService.all();
}
@Post('abonoKiosco')
abonoKiosco(@Body() createTransaccionDto: CreateTransaccionDto) {
const { ...rest } = createTransaccionDto;
const data = {
...rest,
fecha: new Date().toString(),
tipoTransaccion: 2,
};
return this.transaccionService.create(data);
}
}
//IO
@@ -0,0 +1,19 @@
import { Module } from '@nestjs/common';
import { TransaccionService } from './transaccion.service';
import { TransaccionController } from './transaccion.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { NombreTransaccionModule } from 'src/modules/Monedero/nombre-transaccion/nombre-transaccion.module';
import { PersonaModule } from 'src/modules/Monedero/persona/persona.module';
import { Transaccion } from 'src/database/Monedero/entities/transaccion.entity';
@Module({
imports: [
TypeOrmModule.forFeature([Transaccion], 'dbMonedero'),
NombreTransaccionModule,
PersonaModule,
],
controllers: [TransaccionController],
providers: [TransaccionService],
exports: [TransaccionService],
})
export class TransaccionModule {}
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { TransaccionService } from './transaccion.service';
describe('TransaccionService', () => {
let service: TransaccionService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [TransaccionService],
}).compile();
service = module.get<TransaccionService>(TransaccionService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
@@ -0,0 +1,52 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateTransaccionDto } from './dto/create-transaccion.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Transaccion } from '../../../database/Monedero/entities/transaccion.entity';
import { Repository } from 'typeorm';
import { NombreTransaccionService } from 'src/modules/Monedero/nombre-transaccion/nombre-transaccion.service';
import { PersonaService } from 'src/modules/Monedero/persona/persona.service';
@Injectable()
export class TransaccionService {
constructor(
@InjectRepository(Transaccion, 'dbMonedero')
private readonly transaccionRepository: Repository<Transaccion>,
private readonly nombreTransaccionService: NombreTransaccionService,
private readonly personaService: PersonaService,
) {}
async all() {
return await this.transaccionRepository.find();
}
async findById(idTransaccion: number): Promise<Transaccion> {
const transaccion = await this.transaccionRepository.findOne({
where: { idTransaccion },
});
if (!transaccion) {
throw new NotFoundException('transaccion not found');
}
return transaccion;
}
async create(createTransaccion: CreateTransaccionDto): Promise<Transaccion> {
const { nombreTransaccion, idPersona, ...rest } = createTransaccion;
const Transaccion =
this.nombreTransaccionService.findByName(nombreTransaccion);
const persona = this.personaService.findById(idPersona);
const data = {
nombreTransaccion: await Transaccion,
persona: await persona,
...rest,
};
const create = this.transaccionRepository.create(data);
return await this.transaccionRepository.save(create);
}
}
//IO