first commit
This commit is contained in:
parent
896087a6af
commit
b911d6be61
163 changed files with 16547 additions and 0 deletions
37
.env.example
Normal file
37
.env.example
Normal file
|
|
@ -0,0 +1,37 @@
|
||||||
|
# Servidor
|
||||||
|
PORT=3000
|
||||||
|
|
||||||
|
# PostgreSQL local
|
||||||
|
DB_HOST=localhost
|
||||||
|
DB_PORT=5432
|
||||||
|
DB_USER=postgres
|
||||||
|
DB_PASSWORD=postgres
|
||||||
|
DB_NAME=min_ser
|
||||||
|
DB_SYNCHRONIZE=true
|
||||||
|
DB_LOGGING=false
|
||||||
|
|
||||||
|
# Auth
|
||||||
|
TOKEN_KEY=cambia_esto_en_produccion
|
||||||
|
JWT_EXPIRES_IN=24h
|
||||||
|
HASH_SALT_ROUNDS=10
|
||||||
|
|
||||||
|
# OpenWA Easy API
|
||||||
|
OPENWA_URL=https://tu-servidor-openwa
|
||||||
|
OPENWA_API_KEY=tu_api_key
|
||||||
|
|
||||||
|
# Fallback si configuracion.openwaSessionId está vacío en BD
|
||||||
|
OPENWA_SESSION_ID=
|
||||||
|
|
||||||
|
# Path del envío; {sessionId} se sustituye en runtime
|
||||||
|
OPENWA_SEND_PATH=/api/sessions/{sessionId}/messages/send-text
|
||||||
|
|
||||||
|
# Seed primer Developer (solo si no existe ninguno)
|
||||||
|
SEED_DEVELOPER_COD_PAIS=591
|
||||||
|
SEED_DEVELOPER_WHATSAPP=
|
||||||
|
SEED_DEVELOPER_NOMBRES=Dev
|
||||||
|
SEED_DEVELOPER_APELLIDOS=Bootstrap
|
||||||
|
|
||||||
|
# Firebase Cloud Messaging (push) — opcional
|
||||||
|
FIREBASE_PROJECT_ID=
|
||||||
|
FIREBASE_CLIENT_EMAIL=
|
||||||
|
FIREBASE_PRIVATE_KEY=
|
||||||
60
.gitignore
vendored
Normal file
60
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
# compiled output
|
||||||
|
/dist
|
||||||
|
/node_modules
|
||||||
|
/build
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
|
||||||
|
# Tests
|
||||||
|
/coverage
|
||||||
|
/.nyc_output
|
||||||
|
|
||||||
|
# IDEs and editors
|
||||||
|
/.idea
|
||||||
|
.project
|
||||||
|
.classpath
|
||||||
|
.c9/
|
||||||
|
*.launch
|
||||||
|
.settings/
|
||||||
|
*.sublime-workspace
|
||||||
|
|
||||||
|
# IDE - VSCode
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/settings.json
|
||||||
|
!.vscode/tasks.json
|
||||||
|
!.vscode/launch.json
|
||||||
|
!.vscode/extensions.json
|
||||||
|
|
||||||
|
# dotenv environment variable files
|
||||||
|
.env
|
||||||
|
.env.development.local
|
||||||
|
.env.test.local
|
||||||
|
.env.production.local
|
||||||
|
.env.local
|
||||||
|
|
||||||
|
# uploads (fotos de perfil)
|
||||||
|
/uploads/*
|
||||||
|
!/uploads/.gitignore
|
||||||
|
|
||||||
|
# temp directory
|
||||||
|
.temp
|
||||||
|
.tmp
|
||||||
|
|
||||||
|
# Runtime data
|
||||||
|
pids
|
||||||
|
*.pid
|
||||||
|
*.seed
|
||||||
|
*.pid.lock
|
||||||
|
|
||||||
|
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||||
|
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||||
2
.npmrc
Normal file
2
.npmrc
Normal file
|
|
@ -0,0 +1,2 @@
|
||||||
|
verify-deps-before-run=false
|
||||||
|
ignore-scripts=true
|
||||||
4
.prettierrc
Normal file
4
.prettierrc
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
{
|
||||||
|
"singleQuote": true,
|
||||||
|
"trailingComma": "all"
|
||||||
|
}
|
||||||
32
.vscode/settings.json
vendored
Normal file
32
.vscode/settings.json
vendored
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
{
|
||||||
|
"workbench.colorCustomizations": {
|
||||||
|
"activityBar.activeBackground": "#2f7c47",
|
||||||
|
"activityBar.activeBorder": "#e7e7e7",
|
||||||
|
"activityBar.background": "#2f7c47",
|
||||||
|
"activityBar.foreground": "#e7e7e7",
|
||||||
|
"activityBar.inactiveForeground": "#e7e7e799",
|
||||||
|
"activityBarBadge.background": "#422c74",
|
||||||
|
"activityBarBadge.foreground": "#e7e7e7",
|
||||||
|
"activityBarTop.activeBackground": "#2f7c47",
|
||||||
|
"activityBarTop.activeBorder": "#e7e7e7",
|
||||||
|
"activityBarTop.background": "#2f7c47",
|
||||||
|
"activityBarTop.foreground": "#e7e7e7",
|
||||||
|
"activityBarTop.inactiveForeground": "#e7e7e799",
|
||||||
|
"commandCenter.border": "#e7e7e799",
|
||||||
|
"commandCenter.foreground": "#e7e7e7",
|
||||||
|
"sash.hoverBorder": "#2f7c47",
|
||||||
|
"statusBar.background": "#215732",
|
||||||
|
"statusBar.debuggingBackground": "#215732",
|
||||||
|
"statusBar.debuggingForeground": "#e7e7e7",
|
||||||
|
"statusBar.foreground": "#e7e7e7",
|
||||||
|
"statusBar.inactiveBackground": "#215732",
|
||||||
|
"statusBarItem.hoverBackground": "#2f7c47",
|
||||||
|
"statusBarItem.remoteBackground": "#1b122e",
|
||||||
|
"statusBarItem.remoteForeground": "#e7e7e7",
|
||||||
|
"titleBar.activeBackground": "#215732",
|
||||||
|
"titleBar.activeForeground": "#e7e7e7",
|
||||||
|
"titleBar.inactiveBackground": "#21573299",
|
||||||
|
"titleBar.inactiveForeground": "#e7e7e799"
|
||||||
|
},
|
||||||
|
"peacock.color": "#215732"
|
||||||
|
}
|
||||||
8
nest-cli.json
Normal file
8
nest-cli.json
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/nest-cli",
|
||||||
|
"collection": "@nestjs/schematics",
|
||||||
|
"sourceRoot": "src",
|
||||||
|
"compilerOptions": {
|
||||||
|
"deleteOutDir": true
|
||||||
|
}
|
||||||
|
}
|
||||||
10
oxlint.json
Normal file
10
oxlint.json
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
{
|
||||||
|
"$schema": "https://raw.githubusercontent.com/oxc-project/oxc/main/crates/oxc_linter/src/rules.rs",
|
||||||
|
"rules": {
|
||||||
|
"@typescript-eslint/no-explicit-any": "off",
|
||||||
|
"@typescript-eslint/no-floating-promises": "warn"
|
||||||
|
},
|
||||||
|
"env": {
|
||||||
|
"node": true
|
||||||
|
}
|
||||||
|
}
|
||||||
70
package.json
Normal file
70
package.json
Normal file
|
|
@ -0,0 +1,70 @@
|
||||||
|
{
|
||||||
|
"name": "app-min-ser-nest",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"description": "",
|
||||||
|
"author": "",
|
||||||
|
"private": true,
|
||||||
|
"license": "UNLICENSED",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"build": "nest build",
|
||||||
|
"deploy": "nest deploy",
|
||||||
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
|
"start": "nest start",
|
||||||
|
"start:dev": "nest start --watch",
|
||||||
|
"start:debug": "nest start --debug --watch",
|
||||||
|
"start:prod": "node dist/main",
|
||||||
|
"db:create": "node scripts/create-db.mjs",
|
||||||
|
"lint": "oxlint src/ test/",
|
||||||
|
"test": "vitest run",
|
||||||
|
"test:watch": "vitest",
|
||||||
|
"test:cov": "vitest run --coverage",
|
||||||
|
"test:debug": "vitest --inspect-brk --no-file-parallelism",
|
||||||
|
"test:e2e": "vitest run --config ./vitest.config.e2e.ts"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@nestjs/common": "^12.0.1",
|
||||||
|
"@nestjs/config": "^12.0.1",
|
||||||
|
"@nestjs/core": "^12.0.1",
|
||||||
|
"@nestjs/mapped-types": "^12.0.0",
|
||||||
|
"@nestjs/observe": "^0.1.8",
|
||||||
|
"@nestjs/platform-express": "^12.0.1",
|
||||||
|
"@nestjs/platform-socket.io": "^12.1.2",
|
||||||
|
"@nestjs/swagger": "^12.0.2",
|
||||||
|
"@nestjs/typeorm": "^12.0.2",
|
||||||
|
"@nestjs/websockets": "^12.1.2",
|
||||||
|
"bcrypt": "^6.0.0",
|
||||||
|
"class-transformer": "^0.5.1",
|
||||||
|
"class-validator": "^0.15.1",
|
||||||
|
"dotenv": "^18.0.5",
|
||||||
|
"firebase-admin": "^14.5.0",
|
||||||
|
"jsonwebtoken": "^9.0.3",
|
||||||
|
"multer": "^2.4.0",
|
||||||
|
"pg": "^8.23.1",
|
||||||
|
"reflect-metadata": "^0.2.2",
|
||||||
|
"rxjs": "^7.8.1",
|
||||||
|
"socket.io": "^4.8.4",
|
||||||
|
"typeorm": "^1.1.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@nestjs/cli": "^12.0.0",
|
||||||
|
"@nestjs/mau": "^0.2.6",
|
||||||
|
"@nestjs/schematics": "^12.0.0",
|
||||||
|
"@nestjs/testing": "^12.0.1",
|
||||||
|
"@types/bcrypt": "^6.0.0",
|
||||||
|
"@types/express": "^5.0.0",
|
||||||
|
"@types/jsonwebtoken": "^9.0.10",
|
||||||
|
"@types/multer": "^2.3.0",
|
||||||
|
"@types/node": "^24.0.0",
|
||||||
|
"@types/pg": "^8.23.1",
|
||||||
|
"@types/supertest": "^7.0.0",
|
||||||
|
"@vitest/coverage-v8": "^4.1.2",
|
||||||
|
"oxlint": "^1.58.0",
|
||||||
|
"prettier": "^3.4.2",
|
||||||
|
"source-map-support": "^0.5.21",
|
||||||
|
"supertest": "^7.0.0",
|
||||||
|
"typescript": "^6.0.2",
|
||||||
|
"vite-tsconfig-paths": "^5.1.4",
|
||||||
|
"vitest": "^4.1.2"
|
||||||
|
}
|
||||||
|
}
|
||||||
5552
pnpm-lock.yaml
generated
Normal file
5552
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load diff
8
pnpm-workspace.yaml
Normal file
8
pnpm-workspace.yaml
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
allowBuilds:
|
||||||
|
'@firebase/util': false
|
||||||
|
'@scarf/scarf': false
|
||||||
|
bcrypt: true
|
||||||
|
protobufjs: false
|
||||||
|
|
||||||
|
onlyBuiltDependencies:
|
||||||
|
- bcrypt
|
||||||
43
scripts/create-db.mjs
Normal file
43
scripts/create-db.mjs
Normal file
|
|
@ -0,0 +1,43 @@
|
||||||
|
import { config as loadEnv } from 'dotenv';
|
||||||
|
import { Client } from 'pg';
|
||||||
|
|
||||||
|
loadEnv();
|
||||||
|
|
||||||
|
const host = process.env.DB_HOST ?? 'localhost';
|
||||||
|
const port = Number(process.env.DB_PORT ?? 5432);
|
||||||
|
const user = process.env.DB_USER ?? 'postgres';
|
||||||
|
const password = process.env.DB_PASSWORD ?? 'postgres';
|
||||||
|
const database = process.env.DB_NAME ?? 'min_ser';
|
||||||
|
|
||||||
|
const maintenance = new Client({
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
user,
|
||||||
|
password,
|
||||||
|
database: 'postgres',
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
console.log(`[db] Verificando "${database}" en ${user}@${host}:${port}...`);
|
||||||
|
await maintenance.connect();
|
||||||
|
|
||||||
|
const result = await maintenance.query('SELECT 1 FROM pg_database WHERE datname = $1', [
|
||||||
|
database,
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (result.rowCount && result.rowCount > 0) {
|
||||||
|
console.log(`[db] La base "${database}" ya existe.`);
|
||||||
|
} else {
|
||||||
|
const safeName = database.replace(/"/g, '""');
|
||||||
|
await maintenance.query(`CREATE DATABASE "${safeName}"`);
|
||||||
|
console.log(`[db] Base "${database}" creada correctamente.`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(
|
||||||
|
'[db] Error:',
|
||||||
|
error instanceof Error ? error.message : error,
|
||||||
|
);
|
||||||
|
process.exitCode = 1;
|
||||||
|
} finally {
|
||||||
|
await maintenance.end().catch(() => undefined);
|
||||||
|
}
|
||||||
58
scripts/probe-openwa.mjs
Normal file
58
scripts/probe-openwa.mjs
Normal file
|
|
@ -0,0 +1,58 @@
|
||||||
|
import { readFileSync } from 'fs';
|
||||||
|
|
||||||
|
const env = readFileSync('.env', 'utf8');
|
||||||
|
const get = (k) => {
|
||||||
|
const m = env.match(new RegExp('^' + k + '=(.*)$', 'm'));
|
||||||
|
return m ? m[1].trim() : '';
|
||||||
|
};
|
||||||
|
const base = get('OPENWA_URL');
|
||||||
|
const key = get('OPENWA_API_KEY');
|
||||||
|
const headers = { 'X-API-Key': key, 'Content-Type': 'application/json' };
|
||||||
|
|
||||||
|
const js = await (await fetch(base + '/assets/api-Cyx1hppX.js')).text();
|
||||||
|
console.log('api js len', js.length);
|
||||||
|
const idx = js.toLowerCase().indexOf('send-text');
|
||||||
|
console.log('send-text idx', idx);
|
||||||
|
if (idx >= 0) {
|
||||||
|
console.log('--- context ---');
|
||||||
|
console.log(js.slice(Math.max(0, idx - 400), idx + 600));
|
||||||
|
}
|
||||||
|
|
||||||
|
// also search sendText, send_text, message body fields
|
||||||
|
for (const term of ['sendText', 'send_text', 'chatId', 'text', 'sessionId', 'phone', 'recipient']) {
|
||||||
|
const c = (js.match(new RegExp(term, 'g')) || []).length;
|
||||||
|
console.log(term, c);
|
||||||
|
}
|
||||||
|
|
||||||
|
// try many body shapes against real route (invalid numbers only - 400 vs other)
|
||||||
|
const sessions = await (await fetch(base + '/api/sessions', { headers })).json();
|
||||||
|
const sid = sessions[0].id;
|
||||||
|
const url = `${base}/api/sessions/${sid}/messages/send-text`;
|
||||||
|
|
||||||
|
const shapes = [
|
||||||
|
{ to: '591000000', text: 'x' },
|
||||||
|
{ phone: '591000000', text: 'x' },
|
||||||
|
{ number: '591000000', text: 'x' },
|
||||||
|
{ chatId: '591000000@c.us', text: 'x' },
|
||||||
|
{ chat_id: '591000000@c.us', text: 'x' },
|
||||||
|
{ recipient: '591000000', text: 'x' },
|
||||||
|
{ target: '591000000', text: 'x' },
|
||||||
|
{ body: 'x', to: '591000000' },
|
||||||
|
{ content: 'x', to: '591000000' },
|
||||||
|
{ message: 'x', to: '591000000' },
|
||||||
|
{ text: 'x', number: '591000000', sessionId: sid },
|
||||||
|
{ text: 'x', chatId: '591000000@c.us', sessionId: sid },
|
||||||
|
{ data: { to: '591000000', text: 'x' } },
|
||||||
|
{ payload: { chatId: '591000000@c.us', text: 'x' } },
|
||||||
|
{ to: '59178124224@c.us', text: 'x' }, // self - might work if valid shape
|
||||||
|
{ chatId: '59178124224@c.us', text: 'self-probe-no-send' },
|
||||||
|
{ phone: '59178124224', text: 'x' },
|
||||||
|
{ number: '59178124224', text: 'x' },
|
||||||
|
];
|
||||||
|
|
||||||
|
console.log('--- body shapes (invalid number first) ---');
|
||||||
|
for (const body of shapes) {
|
||||||
|
const res = await fetch(url, { method: 'POST', headers, body: JSON.stringify(body) });
|
||||||
|
const t = await res.text();
|
||||||
|
console.log(JSON.stringify(body).slice(0, 80), '=>', res.status, t.slice(0, 160).replace(/\n/g, ' '));
|
||||||
|
}
|
||||||
12
src/app.controller.ts
Normal file
12
src/app.controller.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
||||||
|
import { Controller, Get } from '@nestjs/common';
|
||||||
|
import { AppService } from './app.service.js';
|
||||||
|
|
||||||
|
@Controller()
|
||||||
|
export class AppController {
|
||||||
|
constructor(private readonly appService: AppService) {}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
getHello(): string {
|
||||||
|
return this.appService.getHello();
|
||||||
|
}
|
||||||
|
}
|
||||||
71
src/app.module.ts
Normal file
71
src/app.module.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { APP_GUARD } from '@nestjs/core';
|
||||||
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { AppController } from './app.controller.js';
|
||||||
|
import { AppService } from './app.service.js';
|
||||||
|
import { AuthGuard } from './common/guards/auth.guard.js';
|
||||||
|
import { TokenService } from './common/services/token.service.js';
|
||||||
|
import { EquipoModule } from './modules/equipo/equipo.module.js';
|
||||||
|
import { TurnoModule } from './modules/turno/turno.module.js';
|
||||||
|
import { ConfiguracionModule } from './modules/configuracion/configuracion.module.js';
|
||||||
|
import { PersonaModule } from './modules/persona/persona.module.js';
|
||||||
|
import { EquipoPersonaModule } from './modules/equipo-persona/equipo-persona.module.js';
|
||||||
|
import { ServicioModule } from './modules/servicio/servicio.module.js';
|
||||||
|
import { ServicioTurnoModule } from './modules/servicio-turno/servicio-turno.module.js';
|
||||||
|
import { ServicioEquipoModule } from './modules/servicio-equipo/servicio-equipo.module.js';
|
||||||
|
import { ReemplazoModule } from './modules/reemplazo/reemplazo.module.js';
|
||||||
|
import { SolicitudApoyoModule } from './modules/solicitud-apoyo/solicitud-apoyo.module.js';
|
||||||
|
import { AsistenciaModule } from './modules/asistencia/asistencia.module.js';
|
||||||
|
import { CodigoOtpModule } from './modules/codigo-otp/codigo-otp.module.js';
|
||||||
|
import { AuthModule } from './modules/auth/auth.module.js';
|
||||||
|
import { DispositivoModule } from './modules/dispositivo/dispositivo.module.js';
|
||||||
|
import { RealtimeModule } from './common/realtime.module.js';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
ConfigModule.forRoot({
|
||||||
|
isGlobal: true,
|
||||||
|
envFilePath: ['.env'],
|
||||||
|
}),
|
||||||
|
TypeOrmModule.forRootAsync({
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: (config: ConfigService) => ({
|
||||||
|
type: 'postgres',
|
||||||
|
host: config.get<string>('DB_HOST', 'localhost'),
|
||||||
|
port: config.get<number>('DB_PORT', 5432),
|
||||||
|
username: config.get<string>('DB_USER', 'postgres'),
|
||||||
|
password: config.get<string>('DB_PASSWORD', 'postgres'),
|
||||||
|
database: config.get<string>('DB_NAME', 'min_ser'),
|
||||||
|
autoLoadEntities: true,
|
||||||
|
synchronize: config.get<string>('DB_SYNCHRONIZE', 'true') === 'true',
|
||||||
|
logging: config.get<string>('DB_LOGGING', 'false') === 'true',
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
AuthModule,
|
||||||
|
EquipoModule,
|
||||||
|
TurnoModule,
|
||||||
|
ConfiguracionModule,
|
||||||
|
PersonaModule,
|
||||||
|
EquipoPersonaModule,
|
||||||
|
ServicioModule,
|
||||||
|
ServicioTurnoModule,
|
||||||
|
ServicioEquipoModule,
|
||||||
|
ReemplazoModule,
|
||||||
|
SolicitudApoyoModule,
|
||||||
|
AsistenciaModule,
|
||||||
|
CodigoOtpModule,
|
||||||
|
DispositivoModule,
|
||||||
|
RealtimeModule,
|
||||||
|
],
|
||||||
|
controllers: [AppController],
|
||||||
|
providers: [
|
||||||
|
AppService,
|
||||||
|
TokenService,
|
||||||
|
{
|
||||||
|
provide: APP_GUARD,
|
||||||
|
useClass: AuthGuard,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
export class AppModule {}
|
||||||
8
src/app.service.ts
Normal file
8
src/app.service.ts
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AppService {
|
||||||
|
getHello(): string {
|
||||||
|
return 'Hello World!';
|
||||||
|
}
|
||||||
|
}
|
||||||
BIN
src/common/class/._find.dto.ts
Executable file
BIN
src/common/class/._find.dto.ts
Executable file
Binary file not shown.
37
src/common/class/find.dto.ts
Executable file
37
src/common/class/find.dto.ts
Executable file
|
|
@ -0,0 +1,37 @@
|
||||||
|
import { IsString, IsNumber, IsIn, IsArray, ValidateNested, IsOptional } from 'class-validator';
|
||||||
|
import { Type } from 'class-transformer';
|
||||||
|
|
||||||
|
// Interfaz para cada condición de búsqueda
|
||||||
|
export class WhereConditionDto {
|
||||||
|
@IsString()
|
||||||
|
attribute: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
value: string; // O el tipo de dato que uses
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(['=', 'like', '>', '<', '>=', '<='])
|
||||||
|
operator?: '=' | 'like' | '>' | '<' | '>=' | '<=';
|
||||||
|
}
|
||||||
|
|
||||||
|
// DTO principal para la solicitud
|
||||||
|
export class FindDto {
|
||||||
|
@IsArray()
|
||||||
|
@Type(() => WhereConditionDto)
|
||||||
|
whereConditions: WhereConditionDto[];
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
orderByAttribute: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsIn(['ASC', 'DESC'])
|
||||||
|
orderByDirection: 'ASC' | 'DESC';
|
||||||
|
|
||||||
|
@IsNumber()
|
||||||
|
limit: number;
|
||||||
|
|
||||||
|
@IsNumber()
|
||||||
|
offset: number; // paginacion
|
||||||
|
|
||||||
|
}
|
||||||
BIN
src/common/decorators/._roles.decorator.ts
Executable file
BIN
src/common/decorators/._roles.decorator.ts
Executable file
Binary file not shown.
5
src/common/decorators/autorizacion.decorator.ts
Normal file
5
src/common/decorators/autorizacion.decorator.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
import { SetMetadata } from '@nestjs/common';
|
||||||
|
|
||||||
|
export const KEY_AUTORIZACION = 'autorizacion';
|
||||||
|
export const Autorizacion = (...autorizaciones: string[]) =>
|
||||||
|
SetMetadata(KEY_AUTORIZACION, autorizaciones);
|
||||||
5
src/common/decorators/public.decorator.ts
Normal file
5
src/common/decorators/public.decorator.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
import { SetMetadata } from '@nestjs/common';
|
||||||
|
|
||||||
|
export const IS_PUBLIC_KEY = 'isPublic';
|
||||||
|
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
|
||||||
|
|
||||||
4
src/common/decorators/roles.decorator.ts
Executable file
4
src/common/decorators/roles.decorator.ts
Executable file
|
|
@ -0,0 +1,4 @@
|
||||||
|
import { SetMetadata } from '@nestjs/common';
|
||||||
|
|
||||||
|
export const KEY_ROLES = 'roles';
|
||||||
|
export const Roles = (...roles: string[]) => SetMetadata(KEY_ROLES, roles);
|
||||||
BIN
src/common/enums/._rol.enum.ts
Executable file
BIN
src/common/enums/._rol.enum.ts
Executable file
Binary file not shown.
37
src/common/enums/estados.enum.ts
Normal file
37
src/common/enums/estados.enum.ts
Normal file
|
|
@ -0,0 +1,37 @@
|
||||||
|
export enum EstadoGeneral {
|
||||||
|
Activo = 'Activo',
|
||||||
|
Inactivo = 'Inactivo',
|
||||||
|
Eliminado = 'Eliminado',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum EstadoMiembro {
|
||||||
|
Activo = 'Activo',
|
||||||
|
Inactivo = 'Inactivo',
|
||||||
|
Suspendido = 'Suspendido',
|
||||||
|
Eliminado = 'Eliminado',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum EstadoServicio {
|
||||||
|
Programado = 'Programado',
|
||||||
|
Publicado = 'Publicado',
|
||||||
|
EnCurso = 'EnCurso',
|
||||||
|
Finalizado = 'Finalizado',
|
||||||
|
Cancelado = 'Cancelado',
|
||||||
|
/** Borrado lógico: solo vía DELETE /servicios/:id, nunca aparece en un find. */
|
||||||
|
Eliminado = 'Eliminado',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum EstadoAsistencia {
|
||||||
|
Pendiente = 'Pendiente',
|
||||||
|
Presente = 'Presente',
|
||||||
|
Atrasado = 'Atrasado',
|
||||||
|
Permiso = 'Permiso',
|
||||||
|
Falta = 'Falta',
|
||||||
|
Eliminado = 'Eliminado',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum EstadoConvocatoria {
|
||||||
|
Abierto = 'Abierto',
|
||||||
|
Cubierto = 'Cubierto',
|
||||||
|
Cancelado = 'Cancelado',
|
||||||
|
}
|
||||||
12
src/common/enums/rol.enum.ts
Executable file
12
src/common/enums/rol.enum.ts
Executable file
|
|
@ -0,0 +1,12 @@
|
||||||
|
export enum Rol {
|
||||||
|
Admin = 'Admin',
|
||||||
|
Lider = 'Líder',
|
||||||
|
Estaca = 'Estaca',
|
||||||
|
Servidor = 'Servidor',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum Autorizacion {
|
||||||
|
Developer = 'Developer',
|
||||||
|
SuperAdmin = 'SuperAdmin',
|
||||||
|
Usuario = 'Usuario',
|
||||||
|
}
|
||||||
18
src/common/enums/tipos.enum.ts
Normal file
18
src/common/enums/tipos.enum.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
export enum TipoTurno {
|
||||||
|
Fijo = 'Fijo',
|
||||||
|
Temporal = 'Temporal',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum TipoAsistencia {
|
||||||
|
Titular = 'Titular',
|
||||||
|
Reemplazo = 'Reemplazo',
|
||||||
|
Apoyo = 'Apoyo',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum MetodoMarcado {
|
||||||
|
QR = 'QR',
|
||||||
|
Manual = 'Manual',
|
||||||
|
PIN = 'PIN',
|
||||||
|
Geolocalizacion = 'Geolocalizacion',
|
||||||
|
Sistema = 'Sistema',
|
||||||
|
}
|
||||||
BIN
src/common/guards/._auth.guard.ts
Executable file
BIN
src/common/guards/._auth.guard.ts
Executable file
Binary file not shown.
79
src/common/guards/auth.guard.ts
Executable file
79
src/common/guards/auth.guard.ts
Executable file
|
|
@ -0,0 +1,79 @@
|
||||||
|
import {
|
||||||
|
CanActivate,
|
||||||
|
ExecutionContext,
|
||||||
|
Injectable,
|
||||||
|
UnauthorizedException,
|
||||||
|
ForbiddenException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { Reflector } from '@nestjs/core';
|
||||||
|
import { TokenService } from '../services/token.service.js';
|
||||||
|
import { KEY_ROLES } from '../decorators/roles.decorator.js';
|
||||||
|
import { KEY_AUTORIZACION } from '../decorators/autorizacion.decorator.js';
|
||||||
|
import { IS_PUBLIC_KEY } from '../decorators/public.decorator.js';
|
||||||
|
import { Autorizacion } from '../enums/rol.enum.js';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AuthGuard implements CanActivate {
|
||||||
|
constructor(
|
||||||
|
private tokenService: TokenService,
|
||||||
|
private reflector: Reflector,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||||
|
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||||
|
context.getHandler(),
|
||||||
|
context.getClass(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (isPublic) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const request = context.switchToHttp().getRequest();
|
||||||
|
const authHeader = request.headers.authorization;
|
||||||
|
|
||||||
|
if (!authHeader) {
|
||||||
|
throw new UnauthorizedException('Token no proporcionado');
|
||||||
|
}
|
||||||
|
|
||||||
|
const [bearer, token] = authHeader.split(' ');
|
||||||
|
|
||||||
|
if (bearer !== 'Bearer' || !token) {
|
||||||
|
throw new UnauthorizedException('Formato de token inválido');
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = this.tokenService.verifyToken(token);
|
||||||
|
if (!payload) {
|
||||||
|
throw new UnauthorizedException('Token inválido o expirado');
|
||||||
|
}
|
||||||
|
|
||||||
|
request.user = payload;
|
||||||
|
|
||||||
|
if (payload.autorizacion === Autorizacion.Developer) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rolesRequeridos = this.reflector.getAllAndOverride<string[]>(KEY_ROLES, [
|
||||||
|
context.getHandler(),
|
||||||
|
context.getClass(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (rolesRequeridos?.length && !rolesRequeridos.includes(payload.rol)) {
|
||||||
|
throw new ForbiddenException('No tienes permisos para esta acción (rol)');
|
||||||
|
}
|
||||||
|
|
||||||
|
const autorizacionesRequeridas = this.reflector.getAllAndOverride<string[]>(
|
||||||
|
KEY_AUTORIZACION,
|
||||||
|
[context.getHandler(), context.getClass()],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (
|
||||||
|
autorizacionesRequeridas?.length &&
|
||||||
|
!autorizacionesRequeridas.includes(payload.autorizacion)
|
||||||
|
) {
|
||||||
|
throw new ForbiddenException('No tienes permisos para esta acción (autorización)');
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
BIN
src/common/interfaces/._api.result.ts
Executable file
BIN
src/common/interfaces/._api.result.ts
Executable file
Binary file not shown.
BIN
src/common/interfaces/._service.result.ts
Executable file
BIN
src/common/interfaces/._service.result.ts
Executable file
Binary file not shown.
25
src/common/interfaces/api.result.ts
Executable file
25
src/common/interfaces/api.result.ts
Executable file
|
|
@ -0,0 +1,25 @@
|
||||||
|
export interface ApiResult {
|
||||||
|
|
||||||
|
title: string;
|
||||||
|
route: string;
|
||||||
|
status: string;
|
||||||
|
code: number;
|
||||||
|
message: string;
|
||||||
|
boolean: boolean;
|
||||||
|
rows: number;
|
||||||
|
data: any[] | null;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
export function defaultApiResult(title: string, route: string): ApiResult {
|
||||||
|
return {
|
||||||
|
title,
|
||||||
|
route,
|
||||||
|
status: "",
|
||||||
|
code: 0,
|
||||||
|
message: "",
|
||||||
|
boolean: false,
|
||||||
|
rows: 0,
|
||||||
|
data: []
|
||||||
|
}
|
||||||
|
}
|
||||||
19
src/common/interfaces/service.result.ts
Executable file
19
src/common/interfaces/service.result.ts
Executable file
|
|
@ -0,0 +1,19 @@
|
||||||
|
export interface ServiceResult {
|
||||||
|
|
||||||
|
boolean: boolean;
|
||||||
|
message: string;
|
||||||
|
number: number;
|
||||||
|
object: any | null;
|
||||||
|
data: any[] | null;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
export function defaultServiceResult (): ServiceResult{
|
||||||
|
return {
|
||||||
|
boolean: false,
|
||||||
|
message: "",
|
||||||
|
number: 0,
|
||||||
|
object: null,
|
||||||
|
data: []
|
||||||
|
}
|
||||||
|
}
|
||||||
21
src/common/realtime.module.ts
Normal file
21
src/common/realtime.module.ts
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { Dispositivo } from '../modules/dispositivo/entities/dispositivo.entity.js';
|
||||||
|
import { DispositivoService } from '../modules/dispositivo/dispositivo.service.js';
|
||||||
|
import { EventsGateway } from '../gateways/events.gateway.js';
|
||||||
|
import { EventsService } from './services/events.service.js';
|
||||||
|
import { PushService } from './services/push.service.js';
|
||||||
|
import { TokenService } from './services/token.service.js';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([Dispositivo])],
|
||||||
|
providers: [
|
||||||
|
EventsGateway,
|
||||||
|
EventsService,
|
||||||
|
PushService,
|
||||||
|
DispositivoService,
|
||||||
|
TokenService,
|
||||||
|
],
|
||||||
|
exports: [EventsService, PushService, EventsGateway],
|
||||||
|
})
|
||||||
|
export class RealtimeModule {}
|
||||||
BIN
src/common/services/._hash.service.ts
Executable file
BIN
src/common/services/._hash.service.ts
Executable file
Binary file not shown.
BIN
src/common/services/._token.service.ts
Executable file
BIN
src/common/services/._token.service.ts
Executable file
Binary file not shown.
56
src/common/services/database-bootstrap.ts
Normal file
56
src/common/services/database-bootstrap.ts
Normal file
|
|
@ -0,0 +1,56 @@
|
||||||
|
import { Client } from 'pg';
|
||||||
|
|
||||||
|
export type DatabaseBootstrapConfig = {
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
user: string;
|
||||||
|
password: string;
|
||||||
|
database: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Crea la base de datos si no existe.
|
||||||
|
* Conecta a la BD de mantenimiento ('postgres') y ejecuta CREATE DATABASE.
|
||||||
|
*/
|
||||||
|
export async function ensureDatabaseExists(config: DatabaseBootstrapConfig): Promise<void> {
|
||||||
|
const maintenance = new Client({
|
||||||
|
host: config.host,
|
||||||
|
port: config.port,
|
||||||
|
user: config.user,
|
||||||
|
password: config.password,
|
||||||
|
database: 'postgres',
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await maintenance.connect();
|
||||||
|
|
||||||
|
const result = await maintenance.query(
|
||||||
|
'SELECT 1 FROM pg_database WHERE datname = $1',
|
||||||
|
[config.database],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.rowCount && result.rowCount > 0) {
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
|
console.log(`[db] La base "${config.database}" ya existe.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// El nombre de BD no admite parámetros en CREATE DATABASE
|
||||||
|
const safeName = config.database.replace(/"/g, '""');
|
||||||
|
await maintenance.query(`CREATE DATABASE "${safeName}"`);
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
|
console.log(`[db] Base "${config.database}" creada correctamente.`);
|
||||||
|
} finally {
|
||||||
|
await maintenance.end().catch(() => undefined);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function databaseConfigFromEnv(): DatabaseBootstrapConfig {
|
||||||
|
return {
|
||||||
|
host: process.env.DB_HOST ?? 'localhost',
|
||||||
|
port: Number(process.env.DB_PORT ?? 5432),
|
||||||
|
user: process.env.DB_USER ?? 'postgres',
|
||||||
|
password: process.env.DB_PASSWORD ?? 'postgres',
|
||||||
|
database: process.env.DB_NAME ?? 'min_ser',
|
||||||
|
};
|
||||||
|
}
|
||||||
52
src/common/services/events.service.ts
Normal file
52
src/common/services/events.service.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { EventsGateway } from '../../gateways/events.gateway.js';
|
||||||
|
import { PushService } from './push.service.js';
|
||||||
|
|
||||||
|
export type AppEvent = {
|
||||||
|
event: string;
|
||||||
|
title: string;
|
||||||
|
body: string;
|
||||||
|
idPersonas: string[];
|
||||||
|
data?: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Emite eventos en vivo por WebSocket y, opcionalmente, push FCM.
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
export class EventsService {
|
||||||
|
private readonly logger = new Logger(EventsService.name);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly eventsGateway: EventsGateway,
|
||||||
|
private readonly pushService: PushService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enviar a personas específicas (WS si están conectadas + push FCM).
|
||||||
|
*/
|
||||||
|
async emitToPersonas(payload: AppEvent): Promise<void> {
|
||||||
|
const { event, title, body, idPersonas, data } = payload;
|
||||||
|
|
||||||
|
for (const idPersona of idPersonas) {
|
||||||
|
this.eventsGateway.sendToPersona(idPersona, event, { title, body, ...data });
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.pushService.sendToPersonas(idPersonas, {
|
||||||
|
title,
|
||||||
|
body,
|
||||||
|
data: { event, ...(data ?? {}) },
|
||||||
|
});
|
||||||
|
|
||||||
|
this.logger.log(
|
||||||
|
`Evento ${event}: ${idPersonas.length} persona(s), FCM ${result.enviados}/${result.tokens}.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Broadcast a todos los conectados (uso interno/admin).
|
||||||
|
*/
|
||||||
|
broadcast(event: string, payload: Record<string, unknown>): void {
|
||||||
|
this.eventsGateway.broadcast(event, payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
14
src/common/services/hash.service.ts
Executable file
14
src/common/services/hash.service.ts
Executable file
|
|
@ -0,0 +1,14 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import bcrypt from 'bcrypt';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class HashService {
|
||||||
|
async hashText(text: string): Promise<string> {
|
||||||
|
const saltRounds = parseInt(process.env.HASH_SALT_ROUNDS || '10', 10);
|
||||||
|
return bcrypt.hash(text, saltRounds);
|
||||||
|
}
|
||||||
|
|
||||||
|
async compareTexts(plainTextText: string, hashedText: string): Promise<boolean> {
|
||||||
|
return bcrypt.compare(plainTextText, hashedText);
|
||||||
|
}
|
||||||
|
}
|
||||||
84
src/common/services/openwa.service.ts
Normal file
84
src/common/services/openwa.service.ts
Normal file
|
|
@ -0,0 +1,84 @@
|
||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { Configuracion } from '../../modules/configuracion/entities/configuracion.entity.js';
|
||||||
|
|
||||||
|
export type OpenwaSessionInfo = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
status: string;
|
||||||
|
phone?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class OpenwaService {
|
||||||
|
private readonly logger = new Logger(OpenwaService.name);
|
||||||
|
|
||||||
|
private get baseUrl(): string {
|
||||||
|
return (process.env.OPENWA_URL || '').replace(/\/$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
private get apiKey(): string {
|
||||||
|
return process.env.OPENWA_API_KEY || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
private headers(): Record<string, string> {
|
||||||
|
// X-API-Key / Bearer funcionan en esta instancia; "apiKey" solo da 401.
|
||||||
|
return {
|
||||||
|
'X-API-Key': this.apiKey,
|
||||||
|
Authorization: `Bearer ${this.apiKey}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private get sendPathTemplate(): string {
|
||||||
|
// {sessionId} se reemplaza por el id o nombre de la sesión
|
||||||
|
return process.env.OPENWA_SEND_PATH || '/api/sessions/{sessionId}/messages/send-text';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SessionId: DB (configuracion.openwaSessionId) → fallback .env OPENWA_SESSION_ID
|
||||||
|
*/
|
||||||
|
resolveSessionId(config?: Configuracion | null): string | null {
|
||||||
|
const fromDb = config?.openwaSessionId?.trim();
|
||||||
|
if (fromDb) {
|
||||||
|
return fromDb;
|
||||||
|
}
|
||||||
|
const fromEnv = process.env.OPENWA_SESSION_ID?.trim();
|
||||||
|
return fromEnv || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async listSessions(): Promise<OpenwaSessionInfo[]> {
|
||||||
|
const res = await fetch(`${this.baseUrl}/api/sessions`, {
|
||||||
|
headers: this.headers(),
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const body = await res.text();
|
||||||
|
throw new Error(`OpenWA sessions HTTP ${res.status}: ${body.slice(0, 200)}`);
|
||||||
|
}
|
||||||
|
return (await res.json()) as OpenwaSessionInfo[];
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendText(chatId: string, text: string, sessionId: string): Promise<void> {
|
||||||
|
const path = this.sendPathTemplate.replace('{sessionId}', encodeURIComponent(sessionId));
|
||||||
|
const url = `${this.baseUrl}${path}`;
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: this.headers(),
|
||||||
|
// Body confirmado en esta Easy API: solo chatId + text
|
||||||
|
body: JSON.stringify({ chatId, text }),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const body = await res.text();
|
||||||
|
throw new Error(`OpenWA sendText HTTP ${res.status} (${url}): ${body.slice(0, 300)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.log(`Mensaje enviado a ${chatId} (session=${sessionId})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Arma el chatId de WhatsApp OpenWA: `{codPais}{whatsapp}@c.us`
|
||||||
|
*/
|
||||||
|
buildChatId(codPais: string, whatsapp: string): string {
|
||||||
|
return `${codPais}${whatsapp}@c.us`;
|
||||||
|
}
|
||||||
|
}
|
||||||
108
src/common/services/push.service.ts
Normal file
108
src/common/services/push.service.ts
Normal file
|
|
@ -0,0 +1,108 @@
|
||||||
|
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||||
|
import { initializeApp, getApps, cert, applicationDefault, App } from 'firebase-admin/app';
|
||||||
|
import { getMessaging, Messaging } from 'firebase-admin/messaging';
|
||||||
|
import { DispositivoService } from '../../modules/dispositivo/dispositivo.service.js';
|
||||||
|
|
||||||
|
export type PushPayload = {
|
||||||
|
title: string;
|
||||||
|
body: string;
|
||||||
|
data?: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PushService implements OnModuleInit {
|
||||||
|
private readonly logger = new Logger(PushService.name);
|
||||||
|
private app: App | null = null;
|
||||||
|
private messaging: Messaging | null = null;
|
||||||
|
|
||||||
|
constructor(private readonly dispositivoService: DispositivoService) {}
|
||||||
|
|
||||||
|
onModuleInit() {
|
||||||
|
this.initFirebase();
|
||||||
|
}
|
||||||
|
|
||||||
|
private initFirebase(): void {
|
||||||
|
const projectId = process.env.FIREBASE_PROJECT_ID;
|
||||||
|
const clientEmail = process.env.FIREBASE_CLIENT_EMAIL;
|
||||||
|
const privateKey = process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n');
|
||||||
|
|
||||||
|
if (!projectId) {
|
||||||
|
this.logger.warn(
|
||||||
|
'FIREBASE_PROJECT_ID no está configurado. Push FCM deshabilitado (solo WebSocket in-app).',
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (getApps().length) {
|
||||||
|
this.app = getApps()[0];
|
||||||
|
} else if (clientEmail && privateKey) {
|
||||||
|
this.app = initializeApp({
|
||||||
|
credential: cert({ projectId, clientEmail, privateKey }),
|
||||||
|
projectId,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Application Default Credentials (gcloud / workload identity)
|
||||||
|
this.app = initializeApp({ projectId });
|
||||||
|
this.logger.log('Firebase inicializado con Application Default Credentials.');
|
||||||
|
}
|
||||||
|
|
||||||
|
this.messaging = getMessaging(this.app);
|
||||||
|
this.logger.log(`Firebase FCM listo (project=${projectId}).`);
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(`No se pudo inicializar Firebase: ${error.message}`);
|
||||||
|
this.app = null;
|
||||||
|
this.messaging = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
get enabled(): boolean {
|
||||||
|
return !!this.messaging;
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendToPersonas(
|
||||||
|
idPersonas: string[],
|
||||||
|
payload: PushPayload,
|
||||||
|
): Promise<{ enviados: number; tokens: number }> {
|
||||||
|
const tokens = await this.dispositivoService.findActiveTokensByPersonas(idPersonas);
|
||||||
|
return this.sendToTokens(tokens, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendToPersona(idPersona: string, payload: PushPayload): Promise<{ enviados: number; tokens: number }> {
|
||||||
|
return this.sendToPersonas([idPersona], payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendToTokens(
|
||||||
|
tokens: string[],
|
||||||
|
payload: PushPayload,
|
||||||
|
): Promise<{ enviados: number; tokens: number }> {
|
||||||
|
if (!this.messaging) {
|
||||||
|
this.logger.warn('Push deshabilitado; se omite envío FCM.');
|
||||||
|
return { enviados: 0, tokens: tokens.length };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tokens.length) {
|
||||||
|
return { enviados: 0, tokens: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await this.messaging.sendEachForMulticast({
|
||||||
|
tokens,
|
||||||
|
notification: {
|
||||||
|
title: payload.title,
|
||||||
|
body: payload.body,
|
||||||
|
},
|
||||||
|
data: payload.data ?? {},
|
||||||
|
android: { priority: 'high' },
|
||||||
|
apns: { payload: { aps: { sound: 'default' } } },
|
||||||
|
});
|
||||||
|
|
||||||
|
const enviados = res.responses.filter((r) => r.success).length;
|
||||||
|
this.logger.log(`FCM: ${enviados}/${tokens.length} enviados.`);
|
||||||
|
return { enviados, tokens: tokens.length };
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(`Error FCM: ${error.message}`);
|
||||||
|
return { enviados: 0, tokens: tokens.length };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
76
src/common/services/seed-developer.ts
Normal file
76
src/common/services/seed-developer.ts
Normal file
|
|
@ -0,0 +1,76 @@
|
||||||
|
import { Logger } from '@nestjs/common';
|
||||||
|
import { Client } from 'pg';
|
||||||
|
import { databaseConfigFromEnv } from './database-bootstrap.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Crea el primer Developer si no existe ninguno con autorizacion='Developer'.
|
||||||
|
* Ejecutar DESDE main.ts después de NestFactory.create (TypeORM ya sincronizó tablas).
|
||||||
|
*/
|
||||||
|
export async function seedFirstDeveloper(): Promise<void> {
|
||||||
|
const logger = new Logger('SeedDeveloper');
|
||||||
|
const db = databaseConfigFromEnv();
|
||||||
|
const client = new Client({
|
||||||
|
host: db.host,
|
||||||
|
port: db.port,
|
||||||
|
user: db.user,
|
||||||
|
password: db.password,
|
||||||
|
database: db.database,
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await client.connect();
|
||||||
|
|
||||||
|
const existing = await client.query(
|
||||||
|
`SELECT 1 FROM persona WHERE autorizacion = 'Developer' AND estado != 'Eliminado' LIMIT 1`,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (existing.rowCount && existing.rowCount > 0) {
|
||||||
|
logger.log('Ya existe al menos un Developer. Seed omitido.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const codPais = process.env.SEED_DEVELOPER_COD_PAIS || '591';
|
||||||
|
const whatsapp = process.env.SEED_DEVELOPER_WHATSAPP || '';
|
||||||
|
const nombres = process.env.SEED_DEVELOPER_NOMBRES || 'Dev';
|
||||||
|
const apellidos = process.env.SEED_DEVELOPER_APELLIDOS || 'Bootstrap';
|
||||||
|
|
||||||
|
if (!whatsapp) {
|
||||||
|
logger.warn(
|
||||||
|
'SEED_DEVELOPER_WHATSAPP vacío en .env. No se creó el Developer. Completá la variable y reiniciá.',
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const byPhone = await client.query(
|
||||||
|
`SELECT "idPersona" FROM persona WHERE "codPais" = $1 AND whatsapp = $2`,
|
||||||
|
[codPais, whatsapp],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (byPhone.rowCount && byPhone.rowCount > 0) {
|
||||||
|
await client.query(
|
||||||
|
`UPDATE persona SET autorizacion = 'Developer', estado = 'Activo', verificado = true
|
||||||
|
WHERE "idPersona" = $1`,
|
||||||
|
[byPhone.rows[0].idPersona],
|
||||||
|
);
|
||||||
|
logger.log(`Persona ${codPais}${whatsapp} promovida a Developer.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await client.query(
|
||||||
|
`INSERT INTO persona (
|
||||||
|
"idPersona", nombres, apellidos, "codPais", whatsapp,
|
||||||
|
rol, autorizacion, verificado, estado
|
||||||
|
) VALUES (
|
||||||
|
gen_random_uuid(), $1, $2, $3, $4,
|
||||||
|
'Admin', 'Developer', true, 'Activo'
|
||||||
|
)`,
|
||||||
|
[nombres, apellidos, codPais, whatsapp],
|
||||||
|
);
|
||||||
|
|
||||||
|
logger.log(`Developer seed creado: ${nombres} ${apellidos} (${codPais}${whatsapp}).`);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`Error en seed Developer: ${error.message}`);
|
||||||
|
} finally {
|
||||||
|
await client.end().catch(() => undefined);
|
||||||
|
}
|
||||||
|
}
|
||||||
22
src/common/services/token.service.ts
Executable file
22
src/common/services/token.service.ts
Executable file
|
|
@ -0,0 +1,22 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import jwt from 'jsonwebtoken';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class TokenService {
|
||||||
|
private secretKey = process.env.TOKEN_KEY || 'secreto_por_defecto';
|
||||||
|
private expiresIn = process.env.JWT_EXPIRES_IN || '24h';
|
||||||
|
|
||||||
|
generateToken(payload: Record<string, unknown>): string {
|
||||||
|
return jwt.sign(payload, this.secretKey, {
|
||||||
|
expiresIn: this.expiresIn as jwt.SignOptions['expiresIn'],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
verifyToken(token: string): any {
|
||||||
|
try {
|
||||||
|
return jwt.verify(token, this.secretKey);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
BIN
src/common/types/._query-builder.types.ts
Executable file
BIN
src/common/types/._query-builder.types.ts
Executable file
Binary file not shown.
5
src/common/types/query-builder.types.ts
Executable file
5
src/common/types/query-builder.types.ts
Executable file
|
|
@ -0,0 +1,5 @@
|
||||||
|
export type WhereCondition = {
|
||||||
|
attribute: string;
|
||||||
|
value: string | number | boolean;
|
||||||
|
operator?: '=' | 'like' | '>' | '<' | '>=' | '<=';
|
||||||
|
};
|
||||||
27
src/common/utils/auth-user.ts
Normal file
27
src/common/utils/auth-user.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
import type { Request } from 'express';
|
||||||
|
|
||||||
|
export type AuthUser = {
|
||||||
|
idPersona: string;
|
||||||
|
rol?: string;
|
||||||
|
autorizacion?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AuthRequest = Request & { user?: AuthUser };
|
||||||
|
|
||||||
|
export function getAuthUser(req: AuthRequest): AuthUser | null {
|
||||||
|
const u = req.user;
|
||||||
|
if (!u?.idPersona) return null;
|
||||||
|
return u;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isDeveloper(user: AuthUser | null): boolean {
|
||||||
|
return user?.autorizacion === 'Developer';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isSuperAdmin(user: AuthUser | null): boolean {
|
||||||
|
return user?.autorizacion === 'SuperAdmin';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isLider(user: AuthUser | null): boolean {
|
||||||
|
return user?.rol === 'Líder';
|
||||||
|
}
|
||||||
130
src/gateways/events.gateway.ts
Normal file
130
src/gateways/events.gateway.ts
Normal file
|
|
@ -0,0 +1,130 @@
|
||||||
|
import { Logger, OnModuleInit } from '@nestjs/common';
|
||||||
|
import {
|
||||||
|
ConnectedSocket,
|
||||||
|
MessageBody,
|
||||||
|
OnGatewayConnection,
|
||||||
|
OnGatewayDisconnect,
|
||||||
|
SubscribeMessage,
|
||||||
|
WebSocketGateway,
|
||||||
|
WebSocketServer,
|
||||||
|
} from '@nestjs/websockets';
|
||||||
|
import { Server, Socket } from 'socket.io';
|
||||||
|
import { TokenService } from '../common/services/token.service.js';
|
||||||
|
|
||||||
|
type AuthPayload = {
|
||||||
|
idPersona?: string;
|
||||||
|
rol?: string;
|
||||||
|
autorizacion?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gateway WebSocket con autenticación JWT.
|
||||||
|
* Flutter: socket_io_client → connect con auth: { token: '<JWT>' }
|
||||||
|
* Namespace: /min-ser
|
||||||
|
*/
|
||||||
|
@WebSocketGateway({
|
||||||
|
namespace: '/min-ser',
|
||||||
|
cors: { origin: '*' },
|
||||||
|
})
|
||||||
|
export class EventsGateway implements OnGatewayConnection, OnGatewayDisconnect, OnModuleInit {
|
||||||
|
private readonly logger = new Logger(EventsGateway.name);
|
||||||
|
private readonly clientsByPersona = new Map<string, Set<string>>();
|
||||||
|
|
||||||
|
@WebSocketServer()
|
||||||
|
server: Server;
|
||||||
|
|
||||||
|
constructor(private readonly tokenService: TokenService) {}
|
||||||
|
|
||||||
|
onModuleInit() {
|
||||||
|
this.logger.log('EventsGateway listo en namespace /min-ser');
|
||||||
|
}
|
||||||
|
|
||||||
|
handleConnection(@ConnectedSocket() client: Socket) {
|
||||||
|
const token =
|
||||||
|
(client.handshake.auth?.token as string | undefined) ||
|
||||||
|
(client.handshake.query?.token as string | undefined);
|
||||||
|
|
||||||
|
const payload = token ? this.tokenService.verifyToken(token) : null;
|
||||||
|
|
||||||
|
if (!payload?.idPersona) {
|
||||||
|
this.logger.warn(`Conexión rechazada (token inválido): ${client.id}`);
|
||||||
|
client.emit('auth:error', { message: 'Token inválido o ausente' });
|
||||||
|
client.disconnect(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auth = payload as AuthPayload;
|
||||||
|
if (!auth.idPersona) {
|
||||||
|
this.logger.warn(`Conexión rechazada (payload sin idPersona): ${client.id}`);
|
||||||
|
client.emit('auth:error', { message: 'Token sin idPersona' });
|
||||||
|
client.disconnect(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
client.data.user = auth;
|
||||||
|
|
||||||
|
let set = this.clientsByPersona.get(auth.idPersona);
|
||||||
|
if (!set) {
|
||||||
|
set = new Set();
|
||||||
|
this.clientsByPersona.set(auth.idPersona, set);
|
||||||
|
}
|
||||||
|
set.add(client.id);
|
||||||
|
|
||||||
|
this.logger.log(
|
||||||
|
`Conectado ${client.id} → persona ${auth.idPersona} (rol=${auth.rol}, auth=${auth.autorizacion})`,
|
||||||
|
);
|
||||||
|
client.emit('auth:ok', {
|
||||||
|
idPersona: auth.idPersona,
|
||||||
|
rol: auth.rol,
|
||||||
|
autorizacion: auth.autorizacion,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
handleDisconnect(@ConnectedSocket() client: Socket) {
|
||||||
|
const user = client.data?.user as AuthPayload | undefined;
|
||||||
|
if (user?.idPersona) {
|
||||||
|
const set = this.clientsByPersona.get(user.idPersona);
|
||||||
|
set?.delete(client.id);
|
||||||
|
if (set && set.size === 0) {
|
||||||
|
this.clientsByPersona.delete(user.idPersona);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.logger.log(`Desconectado ${client.id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SubscribeMessage('ping')
|
||||||
|
handlePing(@ConnectedSocket() client: Socket): { pong: true } {
|
||||||
|
client.emit('pong', { ts: Date.now() });
|
||||||
|
return { pong: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
@SubscribeMessage('subscribe')
|
||||||
|
handleSubscribe(
|
||||||
|
@ConnectedSocket() client: Socket,
|
||||||
|
@MessageBody() body: { sala?: string },
|
||||||
|
): { ok: boolean; sala?: string } {
|
||||||
|
if (body?.sala) {
|
||||||
|
client.join(body.sala);
|
||||||
|
return { ok: true, sala: body.sala };
|
||||||
|
}
|
||||||
|
return { ok: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
sendToPersona(idPersona: string, event: string, payload: Record<string, unknown>): void {
|
||||||
|
const set = this.clientsByPersona.get(idPersona);
|
||||||
|
if (!set?.size) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const clientId of set) {
|
||||||
|
this.server.to(clientId).emit(event, payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
broadcast(event: string, payload: Record<string, unknown>): void {
|
||||||
|
this.server.emit(event, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
isOnline(idPersona: string): boolean {
|
||||||
|
return !!this.clientsByPersona.get(idPersona)?.size;
|
||||||
|
}
|
||||||
|
}
|
||||||
80
src/main.ts
Normal file
80
src/main.ts
Normal file
|
|
@ -0,0 +1,80 @@
|
||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import { ValidationPipe } from '@nestjs/common';
|
||||||
|
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||||
|
import { NestExpressApplication } from '@nestjs/platform-express';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { config as loadEnv } from 'dotenv';
|
||||||
|
import { AppModule } from './app.module.js';
|
||||||
|
import {
|
||||||
|
databaseConfigFromEnv,
|
||||||
|
ensureDatabaseExists,
|
||||||
|
} from './common/services/database-bootstrap.js';
|
||||||
|
import { seedFirstDeveloper } from './common/services/seed-developer.js';
|
||||||
|
|
||||||
|
async function bootstrap() {
|
||||||
|
loadEnv();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await ensureDatabaseExists(databaseConfigFromEnv());
|
||||||
|
} catch (error) {
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
|
console.error(
|
||||||
|
'[db] No se pudo verificar/crear la base de datos. Revisá .env (DB_*).',
|
||||||
|
error instanceof Error ? error.message : error,
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = await NestFactory.create<NestExpressApplication>(AppModule);
|
||||||
|
|
||||||
|
// Seed del primer Developer (idempotente) — requiere tablas ya sincronizadas por TypeORM
|
||||||
|
try {
|
||||||
|
await seedFirstDeveloper();
|
||||||
|
} catch (error) {
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
|
console.error(
|
||||||
|
'[seed] No se pudo crear el Developer inicial.',
|
||||||
|
error instanceof Error ? error.message : error,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
app.setGlobalPrefix('v1', {
|
||||||
|
exclude: ['docs', 'docs-json', 'docs/{*path}'],
|
||||||
|
});
|
||||||
|
|
||||||
|
app.useGlobalPipes(
|
||||||
|
new ValidationPipe({
|
||||||
|
whitelist: true,
|
||||||
|
forbidNonWhitelisted: true,
|
||||||
|
transform: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
app.useStaticAssets(join(process.cwd(), 'uploads'), {
|
||||||
|
prefix: '/uploads/',
|
||||||
|
});
|
||||||
|
|
||||||
|
const config = new DocumentBuilder()
|
||||||
|
.setTitle('min-ser API')
|
||||||
|
.setDescription('API del sistema de ministerio min-ser')
|
||||||
|
.setVersion('1.0')
|
||||||
|
.addBearerAuth()
|
||||||
|
.build();
|
||||||
|
|
||||||
|
const document = SwaggerModule.createDocument(app, config);
|
||||||
|
SwaggerModule.setup('docs', app, document, {
|
||||||
|
swaggerOptions: {
|
||||||
|
persistAuthorization: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const port = process.env.PORT ?? 3000;
|
||||||
|
await app.listen(port, '0.0.0.0');
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
|
console.log(`min-ser API en http://localhost:${port}/docs`);
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
|
console.log(
|
||||||
|
`WebSocket: ws://localhost:${port}/min-ser (auth: { token: JWT } via socket.io)`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await bootstrap();
|
||||||
9
src/modules/asistencia/asistencia.constants.ts
Normal file
9
src/modules/asistencia/asistencia.constants.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
export const ASISTENCIA_FIND_WHITELIST = [
|
||||||
|
'idServicio',
|
||||||
|
'idEquipo',
|
||||||
|
'idPersona',
|
||||||
|
'tipo',
|
||||||
|
'estado',
|
||||||
|
'idReemplazo',
|
||||||
|
'idSolicitudApoyo',
|
||||||
|
];
|
||||||
248
src/modules/asistencia/asistencia.controller.ts
Normal file
248
src/modules/asistencia/asistencia.controller.ts
Normal file
|
|
@ -0,0 +1,248 @@
|
||||||
|
import { Body, Controller, Get, HttpStatus, Param, Patch, Post, Req } from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { AsistenciaService } from './asistencia.service.js';
|
||||||
|
import {
|
||||||
|
AsistenciaDto,
|
||||||
|
MarcarAsistenciaDto,
|
||||||
|
UpdateAsistenciaDto,
|
||||||
|
} from './dto/asistencia.dto.js';
|
||||||
|
import { ApiResult, defaultApiResult } from '../../common/interfaces/api.result.js';
|
||||||
|
import { routeAsistencia } from './asistencia.router.js';
|
||||||
|
import { FindDto } from '../../common/class/find.dto.js';
|
||||||
|
import { Roles } from '../../common/decorators/roles.decorator.js';
|
||||||
|
import { Autorizacion } from '../../common/decorators/autorizacion.decorator.js';
|
||||||
|
import {
|
||||||
|
Rol,
|
||||||
|
Autorizacion as AutorizacionEnum,
|
||||||
|
} from '../../common/enums/rol.enum.js';
|
||||||
|
import { EstadoAsistencia } from '../../common/enums/estados.enum.js';
|
||||||
|
import type { AuthRequest } from '../../common/utils/auth-user.js';
|
||||||
|
import { getAuthUser } from '../../common/utils/auth-user.js';
|
||||||
|
|
||||||
|
@ApiTags('asistencias')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@Controller('asistencias')
|
||||||
|
export class AsistenciaController {
|
||||||
|
constructor(private readonly asistenciaService: AsistenciaService) {}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
@Autorizacion(AutorizacionEnum.SuperAdmin)
|
||||||
|
async create(@Body() asistenciaDto: AsistenciaDto): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeAsistencia.create.title, routeAsistencia.create.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.asistenciaService.create(asistenciaDto);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = [result.object];
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':idAsistencia')
|
||||||
|
async findOne(
|
||||||
|
@Req() req: AuthRequest,
|
||||||
|
@Param('idAsistencia') idAsistencia: string,
|
||||||
|
): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeAsistencia.one.title, routeAsistencia.one.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const user = getAuthUser(req);
|
||||||
|
if (!user) {
|
||||||
|
apiResult.code = HttpStatus.UNAUTHORIZED;
|
||||||
|
apiResult.message = 'Token inválido.';
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.asistenciaService.findOne(idAsistencia, user);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = result.object ? [result.object] : [];
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('find')
|
||||||
|
async find(@Req() req: AuthRequest, @Body() findByDto: FindDto): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeAsistencia.find.title, routeAsistencia.find.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const user = getAuthUser(req);
|
||||||
|
if (!user) {
|
||||||
|
apiResult.code = HttpStatus.UNAUTHORIZED;
|
||||||
|
apiResult.message = 'Token inválido.';
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { orderByDirection, orderByAttribute, whereConditions, limit, offset } = findByDto;
|
||||||
|
|
||||||
|
const result = await this.asistenciaService.find(
|
||||||
|
whereConditions,
|
||||||
|
orderByAttribute,
|
||||||
|
orderByDirection,
|
||||||
|
limit,
|
||||||
|
offset,
|
||||||
|
user,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = result.data;
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch(':idAsistencia')
|
||||||
|
@Roles(Rol.Lider)
|
||||||
|
@Autorizacion(AutorizacionEnum.SuperAdmin)
|
||||||
|
async update(
|
||||||
|
@Req() req: AuthRequest,
|
||||||
|
@Param('idAsistencia') idAsistencia: string,
|
||||||
|
@Body() dto: UpdateAsistenciaDto,
|
||||||
|
): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeAsistencia.update.title, routeAsistencia.update.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const user = getAuthUser(req);
|
||||||
|
if (!user) {
|
||||||
|
apiResult.code = HttpStatus.UNAUTHORIZED;
|
||||||
|
apiResult.message = 'Token inválido.';
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.asistenciaService.update(idAsistencia, dto, user);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('marcar')
|
||||||
|
async marcar(@Req() req: AuthRequest, @Body() dto: MarcarAsistenciaDto): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeAsistencia.marcar.title, routeAsistencia.marcar.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const user = getAuthUser(req);
|
||||||
|
if (!user) {
|
||||||
|
apiResult.code = HttpStatus.UNAUTHORIZED;
|
||||||
|
apiResult.message = 'Token inválido.';
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.asistenciaService.marcar(dto, user);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = result.object ? [result.object] : [];
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post(':idAsistencia/estado')
|
||||||
|
@Roles(Rol.Lider)
|
||||||
|
async setEstado(
|
||||||
|
@Req() req: AuthRequest,
|
||||||
|
@Param('idAsistencia') idAsistencia: string,
|
||||||
|
@Body() body: { estado: EstadoAsistencia; observacion?: string },
|
||||||
|
): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(
|
||||||
|
routeAsistencia.setEstado.title,
|
||||||
|
routeAsistencia.setEstado.route,
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const user = getAuthUser(req);
|
||||||
|
if (!user) {
|
||||||
|
apiResult.code = HttpStatus.UNAUTHORIZED;
|
||||||
|
apiResult.message = 'Token inválido.';
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.asistenciaService.setEstadoPermisoFalta(
|
||||||
|
idAsistencia,
|
||||||
|
body.estado as EstadoAsistencia.Permiso | EstadoAsistencia.Falta,
|
||||||
|
body.observacion,
|
||||||
|
user,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
}
|
||||||
31
src/modules/asistencia/asistencia.module.ts
Normal file
31
src/modules/asistencia/asistencia.module.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { Asistencia } from './entities/asistencia.entity.js';
|
||||||
|
import { EquipoPersona } from '../equipo-persona/entities/equipo-persona.entity.js';
|
||||||
|
import { Reemplazo } from '../reemplazo/entities/reemplazo.entity.js';
|
||||||
|
import { Servicio } from '../servicio/entities/servicio.entity.js';
|
||||||
|
import { ServicioEquipo } from '../servicio-equipo/entities/servicio-equipo.entity.js';
|
||||||
|
import { ServicioTurno } from '../servicio-turno/entities/servicio-turno.entity.js';
|
||||||
|
import { Turno } from '../turno/entities/turno.entity.js';
|
||||||
|
import { Configuracion } from '../configuracion/entities/configuracion.entity.js';
|
||||||
|
import { AsistenciaService } from './asistencia.service.js';
|
||||||
|
import { AsistenciaController } from './asistencia.controller.js';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
TypeOrmModule.forFeature([
|
||||||
|
Asistencia,
|
||||||
|
EquipoPersona,
|
||||||
|
Reemplazo,
|
||||||
|
Servicio,
|
||||||
|
ServicioEquipo,
|
||||||
|
ServicioTurno,
|
||||||
|
Turno,
|
||||||
|
Configuracion,
|
||||||
|
]),
|
||||||
|
],
|
||||||
|
exports: [AsistenciaService, TypeOrmModule],
|
||||||
|
controllers: [AsistenciaController],
|
||||||
|
providers: [AsistenciaService],
|
||||||
|
})
|
||||||
|
export class AsistenciaModule {}
|
||||||
26
src/modules/asistencia/asistencia.router.ts
Normal file
26
src/modules/asistencia/asistencia.router.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
export const routeAsistencia = {
|
||||||
|
create: {
|
||||||
|
route: '[POST].../v1/asistencias',
|
||||||
|
title: 'Create Asistencia',
|
||||||
|
},
|
||||||
|
one: {
|
||||||
|
route: '[GET].../v1/asistencias/:idAsistencia',
|
||||||
|
title: 'Find One Asistencia',
|
||||||
|
},
|
||||||
|
find: {
|
||||||
|
route: '[POST].../v1/asistencias/find',
|
||||||
|
title: 'Find Asistencia',
|
||||||
|
},
|
||||||
|
update: {
|
||||||
|
route: '[PATCH].../v1/asistencias/:idAsistencia',
|
||||||
|
title: 'Update Asistencia',
|
||||||
|
},
|
||||||
|
marcar: {
|
||||||
|
route: '[POST].../v1/asistencias/marcar',
|
||||||
|
title: 'Marcar Asistencia',
|
||||||
|
},
|
||||||
|
setEstado: {
|
||||||
|
route: '[POST].../v1/asistencias/:idAsistencia/estado',
|
||||||
|
title: 'Set Estado Asistencia (Permiso/Falta)',
|
||||||
|
},
|
||||||
|
};
|
||||||
542
src/modules/asistencia/asistencia.service.ts
Normal file
542
src/modules/asistencia/asistencia.service.ts
Normal file
|
|
@ -0,0 +1,542 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { In, Repository } from 'typeorm';
|
||||||
|
import { Asistencia } from './entities/asistencia.entity.js';
|
||||||
|
import { EquipoPersona } from '../equipo-persona/entities/equipo-persona.entity.js';
|
||||||
|
import { Reemplazo } from '../reemplazo/entities/reemplazo.entity.js';
|
||||||
|
import { Servicio } from '../servicio/entities/servicio.entity.js';
|
||||||
|
import { ServicioEquipo } from '../servicio-equipo/entities/servicio-equipo.entity.js';
|
||||||
|
import { ServicioTurno } from '../servicio-turno/entities/servicio-turno.entity.js';
|
||||||
|
import { Turno } from '../turno/entities/turno.entity.js';
|
||||||
|
import { Configuracion } from '../configuracion/entities/configuracion.entity.js';
|
||||||
|
import {
|
||||||
|
AsistenciaDto,
|
||||||
|
MarcarAsistenciaDto,
|
||||||
|
UpdateAsistenciaDto,
|
||||||
|
} from './dto/asistencia.dto.js';
|
||||||
|
import {
|
||||||
|
defaultServiceResult,
|
||||||
|
ServiceResult,
|
||||||
|
} from '../../common/interfaces/service.result.js';
|
||||||
|
import { WhereCondition } from '../../common/types/query-builder.types.js';
|
||||||
|
import {
|
||||||
|
EstadoAsistencia,
|
||||||
|
EstadoMiembro,
|
||||||
|
EstadoServicio,
|
||||||
|
} from '../../common/enums/estados.enum.js';
|
||||||
|
import {
|
||||||
|
MetodoMarcado,
|
||||||
|
TipoAsistencia,
|
||||||
|
} from '../../common/enums/tipos.enum.js';
|
||||||
|
import { Rol } from '../../common/enums/rol.enum.js';
|
||||||
|
import { ASISTENCIA_FIND_WHITELIST } from './asistencia.constants.js';
|
||||||
|
import {
|
||||||
|
AuthUser,
|
||||||
|
isDeveloper,
|
||||||
|
isSuperAdmin,
|
||||||
|
} from '../../common/utils/auth-user.js';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AsistenciaService {
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(Asistencia)
|
||||||
|
private asistenciaRepository: Repository<Asistencia>,
|
||||||
|
@InjectRepository(EquipoPersona)
|
||||||
|
private equipoPersonaRepository: Repository<EquipoPersona>,
|
||||||
|
@InjectRepository(Reemplazo)
|
||||||
|
private reemplazoRepository: Repository<Reemplazo>,
|
||||||
|
@InjectRepository(Servicio)
|
||||||
|
private servicioRepository: Repository<Servicio>,
|
||||||
|
@InjectRepository(ServicioEquipo)
|
||||||
|
private servicioEquipoRepository: Repository<ServicioEquipo>,
|
||||||
|
@InjectRepository(ServicioTurno)
|
||||||
|
private servicioTurnoRepository: Repository<ServicioTurno>,
|
||||||
|
@InjectRepository(Turno)
|
||||||
|
private turnoRepository: Repository<Turno>,
|
||||||
|
@InjectRepository(Configuracion)
|
||||||
|
private configuracionRepository: Repository<Configuracion>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async create(asistenciaDto: AsistenciaDto): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const entity = this.asistenciaRepository.create({
|
||||||
|
...asistenciaDto,
|
||||||
|
tipo: asistenciaDto.tipo ?? TipoAsistencia.Titular,
|
||||||
|
estado: asistenciaDto.estado ?? EstadoAsistencia.Pendiente,
|
||||||
|
});
|
||||||
|
const result = await this.asistenciaRepository.save(entity);
|
||||||
|
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message = 'Asistencia creada correctamente.';
|
||||||
|
serviceResult.number = 1;
|
||||||
|
serviceResult.object = result;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Backfill para una membresía nueva o reactivada: crea Titular/Pendiente
|
||||||
|
* en los servicios del equipo que ya están Publicado o EnCurso y aún no
|
||||||
|
* tienen fila de la persona (idempotente, igual que publicar()).
|
||||||
|
*/
|
||||||
|
async backfillPorMembresia(
|
||||||
|
idEquipo: string,
|
||||||
|
idPersona: string,
|
||||||
|
): Promise<number> {
|
||||||
|
const convocatorias = await this.servicioEquipoRepository.findBy({
|
||||||
|
idEquipo,
|
||||||
|
});
|
||||||
|
if (!convocatorias.length) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const servicios = await this.servicioRepository.find({
|
||||||
|
where: {
|
||||||
|
idServicio: In(convocatorias.map((c) => c.idServicio)),
|
||||||
|
estado: In([EstadoServicio.Publicado, EstadoServicio.EnCurso]),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
let creadas = 0;
|
||||||
|
for (const servicio of servicios) {
|
||||||
|
const existe = await this.asistenciaRepository.findOneBy({
|
||||||
|
idServicio: servicio.idServicio,
|
||||||
|
idPersona,
|
||||||
|
});
|
||||||
|
if (existe) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
await this.asistenciaRepository.insert({
|
||||||
|
idServicio: servicio.idServicio,
|
||||||
|
idEquipo,
|
||||||
|
idPersona,
|
||||||
|
tipo: TipoAsistencia.Titular,
|
||||||
|
estado: EstadoAsistencia.Pendiente,
|
||||||
|
});
|
||||||
|
creadas++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return creadas;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findOne(idAsistencia: string, user: AuthUser): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const result = await this.asistenciaRepository.findOneBy({ idAsistencia });
|
||||||
|
if (!result) {
|
||||||
|
serviceResult.message = 'No existe la asistencia.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ok = await this.puedeVer(user, result);
|
||||||
|
if (!ok) {
|
||||||
|
serviceResult.message = 'No tiene permiso para ver esta asistencia.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message = 'Existe una asistencia.';
|
||||||
|
serviceResult.number = 1;
|
||||||
|
serviceResult.object = result;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async find(
|
||||||
|
whereConditions: WhereCondition[],
|
||||||
|
orderByAttribute: string,
|
||||||
|
orderByDirection: 'ASC' | 'DESC',
|
||||||
|
limit: number,
|
||||||
|
offset: number,
|
||||||
|
user: AuthUser,
|
||||||
|
): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
try {
|
||||||
|
let query = this.asistenciaRepository.createQueryBuilder('asistencia');
|
||||||
|
|
||||||
|
whereConditions.forEach((condition, index) => {
|
||||||
|
const { attribute, value, operator = '=' } = condition;
|
||||||
|
|
||||||
|
if (!ASISTENCIA_FIND_WHITELIST.includes(attribute)) {
|
||||||
|
throw new Error(`Atributo no permitido: ${attribute}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const paramKey = `param${index}`;
|
||||||
|
const param = {
|
||||||
|
[paramKey]: operator === 'like' ? `%${value}%` : value,
|
||||||
|
};
|
||||||
|
const whereMethod = index === 0 ? 'where' : 'andWhere';
|
||||||
|
|
||||||
|
query = query[whereMethod](
|
||||||
|
`asistencia.${attribute} ${operator} :${paramKey}`,
|
||||||
|
param,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (user.rol === Rol.Servidor) {
|
||||||
|
query = query.andWhere('asistencia."idPersona" = :id', {
|
||||||
|
id: user.idPersona,
|
||||||
|
});
|
||||||
|
} else if (user.rol === Rol.Lider || user.rol === Rol.Estaca) {
|
||||||
|
const misEquipos = await this.equipoPersonaRepository
|
||||||
|
.createQueryBuilder('ep')
|
||||||
|
.select('ep."idEquipo"')
|
||||||
|
.where('ep."idPersona" = :id', { id: user.idPersona })
|
||||||
|
.andWhere('ep.estado = :e', { e: EstadoMiembro.Activo })
|
||||||
|
.getRawMany();
|
||||||
|
const ids = misEquipos.map((r: { idEquipo: string }) => r.idEquipo);
|
||||||
|
if (!ids.length) {
|
||||||
|
query = query.andWhere('1 = 0');
|
||||||
|
} else {
|
||||||
|
query = query.andWhere('asistencia."idEquipo" IN (:...ids)', { ids });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ASISTENCIA_FIND_WHITELIST.includes(orderByAttribute)) {
|
||||||
|
throw new Error(`Atributo de orden no permitido: ${orderByAttribute}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
query = query.orderBy(`asistencia.${orderByAttribute}`, orderByDirection);
|
||||||
|
|
||||||
|
const totalRegistros = await query.getCount();
|
||||||
|
const skip = (offset - 1) * limit;
|
||||||
|
query = query.skip(skip).take(limit);
|
||||||
|
|
||||||
|
const result = await query.getMany();
|
||||||
|
serviceResult.boolean = result.length > 0;
|
||||||
|
serviceResult.message = `${result.length} asistencia(s) encontrada(s).`;
|
||||||
|
serviceResult.number = totalRegistros;
|
||||||
|
serviceResult.data = result;
|
||||||
|
} catch (error) {
|
||||||
|
serviceResult.boolean = false;
|
||||||
|
serviceResult.message = `Error en el servicio: ${error.message}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(
|
||||||
|
idAsistencia: string,
|
||||||
|
dto: UpdateAsistenciaDto,
|
||||||
|
user: AuthUser,
|
||||||
|
): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const asistencia = await this.asistenciaRepository.findOneBy({
|
||||||
|
idAsistencia,
|
||||||
|
});
|
||||||
|
if (!asistencia) {
|
||||||
|
serviceResult.message = 'No se encontró la asistencia.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Solo SuperAdmin/Dev o Líder del equipo de la fila
|
||||||
|
const puede =
|
||||||
|
isDeveloper(user) ||
|
||||||
|
isSuperAdmin(user) ||
|
||||||
|
(await this.esLiderDeLaFila(user, asistencia));
|
||||||
|
if (!puede) {
|
||||||
|
serviceResult.message = 'No tiene permiso para editar esta asistencia.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Evitar editar campos de marcado libre; el service de marcar es el camino
|
||||||
|
const clean: Partial<Asistencia> = {};
|
||||||
|
if (dto.tipo !== undefined) clean.tipo = dto.tipo;
|
||||||
|
if (dto.observacion !== undefined) clean.observacion = dto.observacion;
|
||||||
|
if (dto.estado !== undefined) clean.estado = dto.estado;
|
||||||
|
|
||||||
|
if (Object.keys(clean).length === 0) {
|
||||||
|
serviceResult.message = 'No hay campos permitidos para actualizar.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.asistenciaRepository.update(idAsistencia, clean);
|
||||||
|
|
||||||
|
serviceResult.boolean = result.affected === 1;
|
||||||
|
serviceResult.message = 'Asistencia actualizada correctamente.';
|
||||||
|
serviceResult.number = result.affected || 0;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Marcar ingreso/salida con permisos por tipo de fila.
|
||||||
|
*/
|
||||||
|
async marcar(
|
||||||
|
dto: MarcarAsistenciaDto,
|
||||||
|
user: AuthUser,
|
||||||
|
): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const asistencia = await this.asistenciaRepository.findOneBy({
|
||||||
|
idAsistencia: dto.idAsistencia,
|
||||||
|
});
|
||||||
|
if (!asistencia) {
|
||||||
|
serviceResult.message = 'No existe la asistencia.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const puede = await this.puedeMarcar(user, asistencia);
|
||||||
|
if (!puede) {
|
||||||
|
serviceResult.message = 'No tiene permiso para marcar esta asistencia.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const servicio = await this.servicioRepository.findOneBy({
|
||||||
|
idServicio: asistencia.idServicio,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (dto.metodo === MetodoMarcado.Geolocalizacion) {
|
||||||
|
if (!dto.coords) {
|
||||||
|
serviceResult.message = 'Geolocalizacion requiere coords.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
const fueraDeRadio = await this.radioExcedido(dto.coords);
|
||||||
|
if (fueraDeRadio) {
|
||||||
|
serviceResult.message = fueraDeRadio;
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dto.metodo === MetodoMarcado.PIN || dto.metodo === MetodoMarcado.QR) {
|
||||||
|
const pin = dto.pin?.trim();
|
||||||
|
if (!pin) {
|
||||||
|
serviceResult.message = `Marcado ${dto.metodo} requiere pin.`;
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
if (!servicio?.pinMarcado || servicio.pinMarcado !== pin) {
|
||||||
|
serviceResult.message = 'PIN incorrecto.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dto.accion === 'ingreso') {
|
||||||
|
if (asistencia.fecIngreso) {
|
||||||
|
serviceResult.message = 'Ingreso ya registrado.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Atraso automático: después de la hora del primer turno (sin tolerancia).
|
||||||
|
await this.asistenciaRepository.update(dto.idAsistencia, {
|
||||||
|
fecIngreso: () => 'now()',
|
||||||
|
metodoIngreso: dto.metodo,
|
||||||
|
marcadoIngresoPor: user.idPersona,
|
||||||
|
estado: await this.estadoMarcado(servicio),
|
||||||
|
observacion: dto.observacion ?? asistencia.observacion,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
if (!asistencia.fecIngreso) {
|
||||||
|
serviceResult.message = 'Debe registrar el ingreso antes de la salida.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
if (asistencia.fecSalida) {
|
||||||
|
serviceResult.message = 'Salida ya registrada.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.asistenciaRepository.update(dto.idAsistencia, {
|
||||||
|
fecSalida: () => 'now()',
|
||||||
|
metodoSalida: dto.metodo,
|
||||||
|
marcadoSalidaPor: user.idPersona,
|
||||||
|
observacion: dto.observacion ?? asistencia.observacion,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await this.asistenciaRepository.findOneBy({
|
||||||
|
idAsistencia: dto.idAsistencia,
|
||||||
|
});
|
||||||
|
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message =
|
||||||
|
dto.accion === 'ingreso'
|
||||||
|
? `Ingreso registrado: ${updated?.estado}.`
|
||||||
|
: 'Salida registrada correctamente.';
|
||||||
|
serviceResult.number = 1;
|
||||||
|
serviceResult.object = updated;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mensaje si coords cae fuera del radio `configuracion.distancia` del punto
|
||||||
|
* de marcado. Si no hay fila de configuración, no valida.
|
||||||
|
*/
|
||||||
|
private async radioExcedido(coords: {
|
||||||
|
lat: number;
|
||||||
|
lng: number;
|
||||||
|
}): Promise<string | null> {
|
||||||
|
const config = await this.configuracionRepository.findOneBy({});
|
||||||
|
if (!config || !(config.distancia > 0)) return null;
|
||||||
|
|
||||||
|
const metros = this.distanciaMetros(
|
||||||
|
coords.lat,
|
||||||
|
coords.lng,
|
||||||
|
config.lat,
|
||||||
|
config.lng,
|
||||||
|
);
|
||||||
|
if (metros <= config.distancia) return null;
|
||||||
|
|
||||||
|
return `Está a ${Math.round(metros)} m del punto de marcado (radio ${Math.round(config.distancia)} m).`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Distancia en metros entre dos puntos (Haversine). */
|
||||||
|
private distanciaMetros(
|
||||||
|
lat1: number,
|
||||||
|
lng1: number,
|
||||||
|
lat2: number,
|
||||||
|
lng2: number,
|
||||||
|
): number {
|
||||||
|
const toRad = (v: number) => (v * Math.PI) / 180;
|
||||||
|
const dLat = toRad(lat2 - lat1);
|
||||||
|
const dLng = toRad(lng2 - lng1);
|
||||||
|
const a =
|
||||||
|
Math.sin(dLat / 2) ** 2 +
|
||||||
|
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLng / 2) ** 2;
|
||||||
|
return 2 * 6371000 * Math.asin(Math.sqrt(a));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Estado al ingresar: `Atrasado` si ya pasó la hora de inicio del turno más
|
||||||
|
* temprano del servicio (sin tolerancia); si no, `Presente`. Sin turnos o
|
||||||
|
* sin hora parseable, queda `Presente`.
|
||||||
|
*/
|
||||||
|
private async estadoMarcado(
|
||||||
|
servicio?: Servicio | null,
|
||||||
|
): Promise<EstadoAsistencia> {
|
||||||
|
if (!servicio?.fecha) return EstadoAsistencia.Presente;
|
||||||
|
|
||||||
|
const st = await this.servicioTurnoRepository.findOne({
|
||||||
|
where: { idServicio: servicio.idServicio },
|
||||||
|
order: { sec: 'ASC' },
|
||||||
|
});
|
||||||
|
if (!st) return EstadoAsistencia.Presente;
|
||||||
|
|
||||||
|
const turno = await this.turnoRepository.findOneBy({ idTurno: st.idTurno });
|
||||||
|
if (!turno?.horaInicio) return EstadoAsistencia.Presente;
|
||||||
|
|
||||||
|
const hora =
|
||||||
|
turno.horaInicio.length === 5
|
||||||
|
? `${turno.horaInicio}:00`
|
||||||
|
: turno.horaInicio;
|
||||||
|
const inicio = new Date(`${servicio.fecha}T${hora}`);
|
||||||
|
if (Number.isNaN(inicio.getTime())) return EstadoAsistencia.Presente;
|
||||||
|
|
||||||
|
return Date.now() > inicio.getTime()
|
||||||
|
? EstadoAsistencia.Atrasado
|
||||||
|
: EstadoAsistencia.Presente;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Permiso/Falta: solo Líder del equipo de la fila (matriz K).
|
||||||
|
*/
|
||||||
|
async setEstadoPermisoFalta(
|
||||||
|
idAsistencia: string,
|
||||||
|
estado: EstadoAsistencia.Permiso | EstadoAsistencia.Falta,
|
||||||
|
observacion: string | undefined,
|
||||||
|
user: AuthUser,
|
||||||
|
): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
if (
|
||||||
|
estado !== EstadoAsistencia.Permiso &&
|
||||||
|
estado !== EstadoAsistencia.Falta
|
||||||
|
) {
|
||||||
|
serviceResult.message = "Solo se puede asignar 'Permiso' o 'Falta'.";
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const asistencia = await this.asistenciaRepository.findOneBy({
|
||||||
|
idAsistencia,
|
||||||
|
});
|
||||||
|
if (!asistencia) {
|
||||||
|
serviceResult.message = 'No se encontró la asistencia.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const esLider =
|
||||||
|
user.rol === Rol.Lider && (await this.esLiderDeLaFila(user, asistencia));
|
||||||
|
const dev = isDeveloper(user);
|
||||||
|
if (!esLider && !dev) {
|
||||||
|
serviceResult.message =
|
||||||
|
'Solo el Líder del equipo (o Developer) puede asignar Permiso/Falta.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (asistencia.estado === EstadoAsistencia.Eliminado) {
|
||||||
|
serviceResult.message =
|
||||||
|
'No se puede asignar estado a una asistencia eliminada.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.asistenciaRepository.update(idAsistencia, {
|
||||||
|
estado,
|
||||||
|
observacion: observacion ?? asistencia.observacion,
|
||||||
|
});
|
||||||
|
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message = `Asistencia asignada a '${estado}'.`;
|
||||||
|
serviceResult.number = 1;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async puedeMarcar(user: AuthUser, a: Asistencia): Promise<boolean> {
|
||||||
|
if (isDeveloper(user)) return true;
|
||||||
|
if (isSuperAdmin(user)) return true;
|
||||||
|
|
||||||
|
if (user.rol === Rol.Admin) return false;
|
||||||
|
|
||||||
|
if (user.rol === Rol.Lider || user.rol === Rol.Estaca) {
|
||||||
|
return this.esLiderDeLaFila(user, a);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Servidor / otros: solo filas propias según tipo
|
||||||
|
if (a.idPersona === user.idPersona) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reemplazo: si hay reemplazo vinculado y el solicitante es el reemplazo
|
||||||
|
if (a.idReemplazo) {
|
||||||
|
const r = await this.reemplazoRepository.findOneBy({
|
||||||
|
idReemplazo: a.idReemplazo,
|
||||||
|
});
|
||||||
|
if (r?.idPersonaReemplazo === user.idPersona) return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async esLiderDeLaFila(
|
||||||
|
user: AuthUser,
|
||||||
|
a: Asistencia,
|
||||||
|
): Promise<boolean> {
|
||||||
|
if (isDeveloper(user)) return true;
|
||||||
|
if (user.rol !== Rol.Lider && user.rol !== Rol.Estaca) return false;
|
||||||
|
|
||||||
|
const m = await this.equipoPersonaRepository.findOneBy({
|
||||||
|
idPersona: user.idPersona,
|
||||||
|
idEquipo: a.idEquipo,
|
||||||
|
estado: EstadoMiembro.Activo,
|
||||||
|
});
|
||||||
|
return !!m;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async puedeVer(user: AuthUser, a: Asistencia): Promise<boolean> {
|
||||||
|
if (isDeveloper(user) || isSuperAdmin(user) || user.rol === Rol.Admin)
|
||||||
|
return true;
|
||||||
|
if (a.idPersona === user.idPersona) return true;
|
||||||
|
if (user.rol === Rol.Lider || user.rol === Rol.Estaca) {
|
||||||
|
return this.esLiderDeLaFila(user, a);
|
||||||
|
}
|
||||||
|
if (a.idReemplazo) {
|
||||||
|
const r = await this.reemplazoRepository.findOneBy({
|
||||||
|
idReemplazo: a.idReemplazo,
|
||||||
|
});
|
||||||
|
if (r?.idPersonaReemplazo === user.idPersona) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
165
src/modules/asistencia/dto/asistencia.dto.ts
Normal file
165
src/modules/asistencia/dto/asistencia.dto.ts
Normal file
|
|
@ -0,0 +1,165 @@
|
||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import {
|
||||||
|
IsDateString,
|
||||||
|
IsEnum,
|
||||||
|
IsIn,
|
||||||
|
IsNotEmpty,
|
||||||
|
IsNumber,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
ValidateNested,
|
||||||
|
} from 'class-validator';
|
||||||
|
import { Type } from 'class-transformer';
|
||||||
|
import { MetodoMarcado, TipoAsistencia } from '../../../common/enums/tipos.enum.js';
|
||||||
|
import { EstadoAsistencia } from '../../../common/enums/estados.enum.js';
|
||||||
|
|
||||||
|
export class AsistenciaDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
idServicio: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
idEquipo: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
idPersona: string;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: TipoAsistencia, required: false })
|
||||||
|
@IsEnum(TipoAsistencia)
|
||||||
|
@IsOptional()
|
||||||
|
tipo?: TipoAsistencia;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
idReemplazo?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
idSolicitudApoyo?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsDateString()
|
||||||
|
@IsOptional()
|
||||||
|
fecIngreso?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
marcadoIngresoPor?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: MetodoMarcado, required: false })
|
||||||
|
@IsEnum(MetodoMarcado)
|
||||||
|
@IsOptional()
|
||||||
|
metodoIngreso?: MetodoMarcado;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsDateString()
|
||||||
|
@IsOptional()
|
||||||
|
fecSalida?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
marcadoSalidaPor?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: MetodoMarcado, required: false })
|
||||||
|
@IsEnum(MetodoMarcado)
|
||||||
|
@IsOptional()
|
||||||
|
metodoSalida?: MetodoMarcado;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: EstadoAsistencia, required: false })
|
||||||
|
@IsEnum(EstadoAsistencia)
|
||||||
|
@IsOptional()
|
||||||
|
estado?: EstadoAsistencia;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
observacion?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UpdateAsistenciaDto {
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsEnum(TipoAsistencia)
|
||||||
|
@IsOptional()
|
||||||
|
tipo?: TipoAsistencia;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsEnum(EstadoAsistencia)
|
||||||
|
@IsOptional()
|
||||||
|
estado?: EstadoAsistencia;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
observacion?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsDateString()
|
||||||
|
@IsOptional()
|
||||||
|
fecIngreso?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsDateString()
|
||||||
|
@IsOptional()
|
||||||
|
fecSalida?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: MetodoMarcado, required: false })
|
||||||
|
@IsEnum(MetodoMarcado)
|
||||||
|
@IsOptional()
|
||||||
|
metodoIngreso?: MetodoMarcado;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: MetodoMarcado, required: false })
|
||||||
|
@IsEnum(MetodoMarcado)
|
||||||
|
@IsOptional()
|
||||||
|
metodoSalida?: MetodoMarcado;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CoordsDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsNumber()
|
||||||
|
lat: number;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsNumber()
|
||||||
|
lng: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class MarcarAsistenciaDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
idAsistencia: string;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: ['ingreso', 'salida'] })
|
||||||
|
@IsIn(['ingreso', 'salida'])
|
||||||
|
accion: 'ingreso' | 'salida';
|
||||||
|
|
||||||
|
@ApiProperty({ enum: MetodoMarcado })
|
||||||
|
@IsEnum(MetodoMarcado)
|
||||||
|
metodo: MetodoMarcado;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@ValidateNested()
|
||||||
|
@Type(() => CoordsDto)
|
||||||
|
@IsOptional()
|
||||||
|
coords?: CoordsDto;
|
||||||
|
|
||||||
|
/** PIN del servicio (tecleado en método PIN o escaneado en método QR). */
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
pin?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
observacion?: string;
|
||||||
|
}
|
||||||
63
src/modules/asistencia/entities/asistencia.entity.ts
Normal file
63
src/modules/asistencia/entities/asistencia.entity.ts
Normal file
|
|
@ -0,0 +1,63 @@
|
||||||
|
import { Entity, PrimaryGeneratedColumn, Column, Unique } from 'typeorm';
|
||||||
|
import { TipoAsistencia, MetodoMarcado } from '../../../common/enums/tipos.enum.js';
|
||||||
|
import { EstadoAsistencia } from '../../../common/enums/estados.enum.js';
|
||||||
|
|
||||||
|
@Entity('asistencia')
|
||||||
|
@Unique(['idServicio', 'idPersona'])
|
||||||
|
export class Asistencia {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
idAsistencia: string;
|
||||||
|
|
||||||
|
@Column({ type: 'uuid' })
|
||||||
|
idServicio: string;
|
||||||
|
|
||||||
|
@Column({ type: 'uuid' })
|
||||||
|
idEquipo: string;
|
||||||
|
|
||||||
|
@Column({ type: 'uuid' })
|
||||||
|
idPersona: string;
|
||||||
|
|
||||||
|
@Column({
|
||||||
|
type: 'varchar',
|
||||||
|
})
|
||||||
|
tipo: TipoAsistencia;
|
||||||
|
|
||||||
|
@Column({ type: 'uuid', nullable: true })
|
||||||
|
idReemplazo?: string | null;
|
||||||
|
|
||||||
|
@Column({ type: 'uuid', nullable: true })
|
||||||
|
idSolicitudApoyo?: string | null;
|
||||||
|
|
||||||
|
@Column({ type: 'timestamptz', nullable: true })
|
||||||
|
fecIngreso?: Date | null;
|
||||||
|
|
||||||
|
@Column({ type: 'uuid', nullable: true })
|
||||||
|
marcadoIngresoPor?: string | null;
|
||||||
|
|
||||||
|
@Column({
|
||||||
|
type: 'varchar',
|
||||||
|
nullable: true,
|
||||||
|
})
|
||||||
|
metodoIngreso?: MetodoMarcado | null;
|
||||||
|
|
||||||
|
@Column({ type: 'timestamptz', nullable: true })
|
||||||
|
fecSalida?: Date | null;
|
||||||
|
|
||||||
|
@Column({ type: 'uuid', nullable: true })
|
||||||
|
marcadoSalidaPor?: string | null;
|
||||||
|
|
||||||
|
@Column({
|
||||||
|
type: 'varchar',
|
||||||
|
nullable: true,
|
||||||
|
})
|
||||||
|
metodoSalida?: MetodoMarcado | null;
|
||||||
|
|
||||||
|
@Column({
|
||||||
|
type: 'varchar',
|
||||||
|
default: EstadoAsistencia.Pendiente,
|
||||||
|
})
|
||||||
|
estado: EstadoAsistencia;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', nullable: true })
|
||||||
|
observacion?: string | null;
|
||||||
|
}
|
||||||
201
src/modules/auth/auth.controller.ts
Normal file
201
src/modules/auth/auth.controller.ts
Normal file
|
|
@ -0,0 +1,201 @@
|
||||||
|
import { Body, Controller, Get, HttpStatus, Patch, Post, Req } from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||||
|
import type { Request } from 'express';
|
||||||
|
import { AuthService } from './auth.service.js';
|
||||||
|
import { EnviarOtpDto, LoginDto, UpdatePerfilDto } from './dto/auth.dto.js';
|
||||||
|
import { ApiResult, defaultApiResult } from '../../common/interfaces/api.result.js';
|
||||||
|
import { routeAuth } from './auth.router.js';
|
||||||
|
import { Public } from '../../common/decorators/public.decorator.js';
|
||||||
|
|
||||||
|
type AuthRequest = Request & {
|
||||||
|
user?: { idPersona?: string; rol?: string; autorizacion?: string };
|
||||||
|
};
|
||||||
|
|
||||||
|
@ApiTags('auth')
|
||||||
|
@Controller('auth')
|
||||||
|
export class AuthController {
|
||||||
|
constructor(private readonly authService: AuthService) {}
|
||||||
|
|
||||||
|
@Public()
|
||||||
|
@Post('otp/enviar')
|
||||||
|
async enviarOtp(@Body() dto: EnviarOtpDto): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeAuth.enviarOtp.title, routeAuth.enviarOtp.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.authService.enviarOtp(dto, false);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = result.object ? [result.object] : [];
|
||||||
|
console.log(result)
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Public()
|
||||||
|
@Post('otp/reenviar')
|
||||||
|
async reenviarOtp(@Body() dto: EnviarOtpDto): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeAuth.reenviarOtp.title, routeAuth.reenviarOtp.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.authService.enviarOtp(dto, true);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = result.object ? [result.object] : [];
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Public()
|
||||||
|
@Post('login')
|
||||||
|
async login(@Body() dto: LoginDto): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeAuth.login.title, routeAuth.login.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.authService.login(dto);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = result.object ? [result.object] : [];
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@Post('refrescar')
|
||||||
|
async refrescar(@Req() req: AuthRequest): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeAuth.refrescar.title, routeAuth.refrescar.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const idPersona = req.user?.idPersona;
|
||||||
|
if (!idPersona) {
|
||||||
|
apiResult.code = HttpStatus.UNAUTHORIZED;
|
||||||
|
apiResult.message = 'Token inválido.';
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.authService.refrescar(idPersona);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = result.object ? [result.object] : [];
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@Get('perfil')
|
||||||
|
async getPerfil(@Req() req: AuthRequest): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeAuth.perfil.title, routeAuth.perfil.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const idPersona = req.user?.idPersona;
|
||||||
|
if (!idPersona) {
|
||||||
|
apiResult.code = HttpStatus.UNAUTHORIZED;
|
||||||
|
apiResult.message = 'Token inválido.';
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.authService.getPerfil(idPersona);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = result.object ? [result.object] : [];
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@Patch('perfil')
|
||||||
|
async updatePerfil(@Req() req: AuthRequest, @Body() dto: UpdatePerfilDto): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeAuth.updatePerfil.title, routeAuth.updatePerfil.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const idPersona = req.user?.idPersona;
|
||||||
|
if (!idPersona) {
|
||||||
|
apiResult.code = HttpStatus.UNAUTHORIZED;
|
||||||
|
apiResult.message = 'Token inválido.';
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.authService.updatePerfil(idPersona, dto);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
}
|
||||||
18
src/modules/auth/auth.module.ts
Normal file
18
src/modules/auth/auth.module.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { AuthController } from './auth.controller.js';
|
||||||
|
import { AuthService } from './auth.service.js';
|
||||||
|
import { Persona } from '../persona/entities/persona.entity.js';
|
||||||
|
import { CodigoOtp } from '../codigo-otp/entities/codigo-otp.entity.js';
|
||||||
|
import { Configuracion } from '../configuracion/entities/configuracion.entity.js';
|
||||||
|
import { HashService } from '../../common/services/hash.service.js';
|
||||||
|
import { TokenService } from '../../common/services/token.service.js';
|
||||||
|
import { OpenwaService } from '../../common/services/openwa.service.js';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([Persona, CodigoOtp, Configuracion])],
|
||||||
|
controllers: [AuthController],
|
||||||
|
providers: [AuthService, HashService, TokenService, OpenwaService],
|
||||||
|
exports: [TokenService],
|
||||||
|
})
|
||||||
|
export class AuthModule {}
|
||||||
26
src/modules/auth/auth.router.ts
Normal file
26
src/modules/auth/auth.router.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
export const routeAuth = {
|
||||||
|
enviarOtp: {
|
||||||
|
route: '[POST].../v1/auth/otp/enviar',
|
||||||
|
title: 'Enviar OTP',
|
||||||
|
},
|
||||||
|
reenviarOtp: {
|
||||||
|
route: '[POST].../v1/auth/otp/reenviar',
|
||||||
|
title: 'Reenviar OTP',
|
||||||
|
},
|
||||||
|
login: {
|
||||||
|
route: '[POST].../v1/auth/login',
|
||||||
|
title: 'Login',
|
||||||
|
},
|
||||||
|
refrescar: {
|
||||||
|
route: '[POST].../v1/auth/refrescar',
|
||||||
|
title: 'Refrescar token',
|
||||||
|
},
|
||||||
|
perfil: {
|
||||||
|
route: '[GET].../v1/auth/perfil',
|
||||||
|
title: 'Get Perfil',
|
||||||
|
},
|
||||||
|
updatePerfil: {
|
||||||
|
route: '[PATCH].../v1/auth/perfil',
|
||||||
|
title: 'Update Perfil',
|
||||||
|
},
|
||||||
|
};
|
||||||
353
src/modules/auth/auth.service.ts
Normal file
353
src/modules/auth/auth.service.ts
Normal file
|
|
@ -0,0 +1,353 @@
|
||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { Persona } from '../persona/entities/persona.entity.js';
|
||||||
|
import { CodigoOtp } from '../codigo-otp/entities/codigo-otp.entity.js';
|
||||||
|
import { Configuracion } from '../configuracion/entities/configuracion.entity.js';
|
||||||
|
import { HashService } from '../../common/services/hash.service.js';
|
||||||
|
import { TokenService } from '../../common/services/token.service.js';
|
||||||
|
import { OpenwaService } from '../../common/services/openwa.service.js';
|
||||||
|
import { defaultServiceResult, ServiceResult } from '../../common/interfaces/service.result.js';
|
||||||
|
import { EstadoGeneral } from '../../common/enums/estados.enum.js';
|
||||||
|
import { EnviarOtpDto, LoginDto, UpdatePerfilDto } from './dto/auth.dto.js';
|
||||||
|
|
||||||
|
const OTP_EXPIRATION_MINUTES = 2;
|
||||||
|
const OTP_MAX_INTENTS = 3;
|
||||||
|
|
||||||
|
/** Cache en memoria del OTP vigente (para reenviar el MISMO código). */
|
||||||
|
type OtpCacheEntry = {
|
||||||
|
codigo: string;
|
||||||
|
expiraEn: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AuthService {
|
||||||
|
private readonly logger = new Logger(AuthService.name);
|
||||||
|
private readonly otpCache = new Map<string, OtpCacheEntry>();
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(Persona)
|
||||||
|
private personaRepository: Repository<Persona>,
|
||||||
|
@InjectRepository(CodigoOtp)
|
||||||
|
private codigoOtpRepository: Repository<CodigoOtp>,
|
||||||
|
@InjectRepository(Configuracion)
|
||||||
|
private configuracionRepository: Repository<Configuracion>,
|
||||||
|
private hashService: HashService,
|
||||||
|
private tokenService: TokenService,
|
||||||
|
private openwaService: OpenwaService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async enviarOtp(dto: EnviarOtpDto, isResend = false): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const persona = await this.personaRepository.findOneBy({
|
||||||
|
codPais: dto.codPais,
|
||||||
|
whatsapp: dto.whatsapp,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!persona) {
|
||||||
|
serviceResult.message =
|
||||||
|
'No se encontró una cuenta con ese número. Contacte a su líder para el pre-registro.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (persona.estado !== EstadoGeneral.Activo) {
|
||||||
|
serviceResult.message =
|
||||||
|
'La cuenta no está activa. Contacte a su líder o administrador.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Invalidar OTPs ya caducados
|
||||||
|
await this.codigoOtpRepository
|
||||||
|
.createQueryBuilder()
|
||||||
|
.update(CodigoOtp)
|
||||||
|
.set({ usado: true })
|
||||||
|
.where('"idPersona" = :idPersona', { idPersona: persona.idPersona })
|
||||||
|
.andWhere('usado = :usado', { usado: false })
|
||||||
|
.andWhere('"fecExpiracion" < now()')
|
||||||
|
.execute();
|
||||||
|
|
||||||
|
// ¿Existe OTP vigente (sin usar y sin caducar)?
|
||||||
|
const activo = await this.codigoOtpRepository
|
||||||
|
.createQueryBuilder('otp')
|
||||||
|
.where('otp."idPersona" = :idPersona', { idPersona: persona.idPersona })
|
||||||
|
.andWhere('otp.usado = :usado', { usado: false })
|
||||||
|
.andWhere('otp."fecExpiracion" > now()')
|
||||||
|
.orderBy('otp."fecCreacion"', 'DESC')
|
||||||
|
.getOne();
|
||||||
|
|
||||||
|
if (activo) {
|
||||||
|
const cache = this.otpCache.get(persona.idPersona);
|
||||||
|
const cacheVigente = !!cache && cache.expiraEn > Date.now();
|
||||||
|
|
||||||
|
// Reenviar: si tenemos el código en memoria, manda EL MISMO (no crea otro)
|
||||||
|
if (isResend && cacheVigente) {
|
||||||
|
try {
|
||||||
|
await this.sendOtpViaOpenwa(persona, cache.codigo);
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(`Error OpenWA: ${error.message}`);
|
||||||
|
serviceResult.message = `No se pudo reenviar el código: ${error.message}`;
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message = 'Código reenviado por WhatsApp (el mismo código anterior).';
|
||||||
|
serviceResult.number = 1;
|
||||||
|
// Solo en dev: idPersona + código. En producción no se expone nada.
|
||||||
|
serviceResult.object =
|
||||||
|
process.env.NODE_ENV !== 'production'
|
||||||
|
? { idPersona: persona.idPersona, codigoDebug: cache.codigo }
|
||||||
|
: null;
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ya hay código vigente → NO crear otro
|
||||||
|
const expira = new Date(activo.fecExpiracion);
|
||||||
|
const hhmm = `${String(expira.getHours()).padStart(2, '0')}:${String(
|
||||||
|
expira.getMinutes(),
|
||||||
|
).padStart(2, '0')}`;
|
||||||
|
serviceResult.message = `Ya existe un código activo válido hasta las ${hhmm}. Úselo o espere a que expire para solicitar uno nuevo.`;
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sin código vigente → crear uno nuevo
|
||||||
|
const codigo = this.generateOtpCode();
|
||||||
|
const codigoHash = await this.hashService.hashText(codigo);
|
||||||
|
const fecCreacion = new Date();
|
||||||
|
const fecExpiracion = new Date(fecCreacion.getTime() + OTP_EXPIRATION_MINUTES * 60_000);
|
||||||
|
|
||||||
|
await this.codigoOtpRepository.manager.transaction(async (manager) => {
|
||||||
|
await manager
|
||||||
|
.createQueryBuilder()
|
||||||
|
.update(CodigoOtp)
|
||||||
|
.set({ usado: true })
|
||||||
|
.where('"idPersona" = :idPersona', { idPersona: persona.idPersona })
|
||||||
|
.andWhere('usado = :usado', { usado: false })
|
||||||
|
.execute();
|
||||||
|
|
||||||
|
await manager.save(CodigoOtp, {
|
||||||
|
idPersona: persona.idPersona,
|
||||||
|
codigoHash,
|
||||||
|
intentosFallidos: 0,
|
||||||
|
fecCreacion,
|
||||||
|
fecExpiracion,
|
||||||
|
usado: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
this.otpCache.set(persona.idPersona, {
|
||||||
|
codigo,
|
||||||
|
expiraEn: fecExpiracion.getTime(),
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.sendOtpViaOpenwa(persona, codigo);
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(`Error OpenWA: ${error.message}`);
|
||||||
|
serviceResult.message = `No se pudo enviar el código por WhatsApp: ${error.message}`;
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message = 'Código enviado por WhatsApp.';
|
||||||
|
serviceResult.number = 1;
|
||||||
|
// Solo en dev: idPersona + código. En producción no se expone nada.
|
||||||
|
serviceResult.object =
|
||||||
|
process.env.NODE_ENV !== 'production'
|
||||||
|
? { idPersona: persona.idPersona, codigoDebug: codigo }
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async login(dto: LoginDto): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const persona = await this.personaRepository.findOneBy({
|
||||||
|
codPais: dto.codPais,
|
||||||
|
whatsapp: dto.whatsapp,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!persona) {
|
||||||
|
serviceResult.message = 'Credenciales inválidas.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (persona.estado !== EstadoGeneral.Activo) {
|
||||||
|
serviceResult.message = 'La cuenta no está activa.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const otp = await this.codigoOtpRepository
|
||||||
|
.createQueryBuilder('otp')
|
||||||
|
.where('otp."idPersona" = :idPersona', { idPersona: persona.idPersona })
|
||||||
|
.andWhere('otp.usado = :usado', { usado: false })
|
||||||
|
.andWhere('otp."fecExpiracion" > now()')
|
||||||
|
.orderBy('otp."fecCreacion"', 'DESC')
|
||||||
|
.getOne();
|
||||||
|
|
||||||
|
if (!otp) {
|
||||||
|
serviceResult.message = 'No hay un código activo. Solicite uno nuevo.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (otp.intentosFallidos >= OTP_MAX_INTENTS) {
|
||||||
|
await this.codigoOtpRepository.update(otp.idOtp, { usado: true });
|
||||||
|
this.otpCache.delete(persona.idPersona);
|
||||||
|
serviceResult.message = 'Código bloqueado por seguridad. Solicite uno nuevo.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const match = await this.hashService.compareTexts(dto.codigo, otp.codigoHash);
|
||||||
|
|
||||||
|
if (!match) {
|
||||||
|
const intentos = otp.intentosFallidos + 1;
|
||||||
|
const payload: Partial<CodigoOtp> =
|
||||||
|
intentos >= OTP_MAX_INTENTS
|
||||||
|
? { intentosFallidos: intentos, usado: true }
|
||||||
|
: { intentosFallidos: intentos };
|
||||||
|
await this.codigoOtpRepository.update(otp.idOtp, payload);
|
||||||
|
if (intentos >= OTP_MAX_INTENTS) {
|
||||||
|
this.otpCache.delete(persona.idPersona);
|
||||||
|
}
|
||||||
|
serviceResult.message = `Código incorrecto. ${Math.max(
|
||||||
|
0,
|
||||||
|
OTP_MAX_INTENTS - intentos,
|
||||||
|
)} intento(s) restante(s).`;
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.codigoOtpRepository.update(otp.idOtp, { usado: true });
|
||||||
|
this.otpCache.delete(persona.idPersona);
|
||||||
|
|
||||||
|
const updates: Partial<Persona> = { ultConexion: new Date() };
|
||||||
|
if (!persona.verificado) {
|
||||||
|
updates.verificado = true;
|
||||||
|
}
|
||||||
|
await this.personaRepository.update(persona.idPersona, updates);
|
||||||
|
|
||||||
|
const token = this.tokenService.generateToken({
|
||||||
|
idPersona: persona.idPersona,
|
||||||
|
rol: persona.rol,
|
||||||
|
autorizacion: persona.autorizacion,
|
||||||
|
});
|
||||||
|
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message = 'Sesión iniciada correctamente.';
|
||||||
|
serviceResult.number = 1;
|
||||||
|
serviceResult.object = {
|
||||||
|
token,
|
||||||
|
persona: {
|
||||||
|
idPersona: persona.idPersona,
|
||||||
|
nombres: persona.nombres,
|
||||||
|
apellidos: persona.apellidos,
|
||||||
|
rol: persona.rol,
|
||||||
|
autorizacion: persona.autorizacion,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Emite un JWT nuevo con `rol`/`autorizacion` leídos de la DB.
|
||||||
|
* El usuario NO cierra sesión: solo se renuevan los permisos del token
|
||||||
|
* cuando cambiaron en la base (flujo de refresh de la Fase 2).
|
||||||
|
*/
|
||||||
|
async refrescar(idPersona: string): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const persona = await this.personaRepository.findOneBy({ idPersona });
|
||||||
|
|
||||||
|
if (!persona) {
|
||||||
|
serviceResult.message = 'No existe la persona.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (persona.estado !== EstadoGeneral.Activo) {
|
||||||
|
serviceResult.message = 'La cuenta no está activa.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = this.tokenService.generateToken({
|
||||||
|
idPersona: persona.idPersona,
|
||||||
|
rol: persona.rol,
|
||||||
|
autorizacion: persona.autorizacion,
|
||||||
|
});
|
||||||
|
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message = 'Sesión renovada.';
|
||||||
|
serviceResult.number = 1;
|
||||||
|
serviceResult.object = {
|
||||||
|
token,
|
||||||
|
rol: persona.rol,
|
||||||
|
autorizacion: persona.autorizacion,
|
||||||
|
};
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPerfil(idPersona: string): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const persona = await this.personaRepository.findOneBy({ idPersona });
|
||||||
|
|
||||||
|
if (!persona) {
|
||||||
|
serviceResult.message = 'No existe la persona.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message = 'Perfil obtenido.';
|
||||||
|
serviceResult.number = 1;
|
||||||
|
serviceResult.object = persona;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async updatePerfil(idPersona: string, dto: UpdatePerfilDto): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const clean: Partial<Persona> = {};
|
||||||
|
if (dto.nombres !== undefined) clean.nombres = dto.nombres;
|
||||||
|
if (dto.apellidos !== undefined) clean.apellidos = dto.apellidos;
|
||||||
|
if (dto.photoUrl !== undefined) clean.photoUrl = dto.photoUrl;
|
||||||
|
if (dto.fecNac !== undefined) clean.fecNac = dto.fecNac;
|
||||||
|
if (dto.ci !== undefined) clean.ci = dto.ci;
|
||||||
|
if (dto.complemento !== undefined) clean.complemento = dto.complemento;
|
||||||
|
|
||||||
|
if (Object.keys(clean).length === 0) {
|
||||||
|
serviceResult.message = 'No hay campos para actualizar.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.personaRepository.update(idPersona, clean);
|
||||||
|
|
||||||
|
serviceResult.boolean = result.affected === 1;
|
||||||
|
serviceResult.message =
|
||||||
|
result.affected === 1
|
||||||
|
? 'Perfil actualizado correctamente.'
|
||||||
|
: 'No se encontró la persona.';
|
||||||
|
serviceResult.number = result.affected || 0;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
private generateOtpCode(): string {
|
||||||
|
return String(Math.floor(1000 + Math.random() * 9000));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async sendOtpViaOpenwa(persona: Persona, codigo: string): Promise<void> {
|
||||||
|
const config = await this.configuracionRepository.findOneBy({});
|
||||||
|
const sessionId = this.openwaService.resolveSessionId(config);
|
||||||
|
|
||||||
|
if (!sessionId) {
|
||||||
|
throw new Error(
|
||||||
|
'No hay sessionId de OpenWA (configuracion.openwaSessionId ni OPENWA_SESSION_ID).',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const chatId = this.openwaService.buildChatId(persona.codPais, persona.whatsapp);
|
||||||
|
const text = `*Tu código de acceso es:* ${codigo}.\n🏛️ *_Ministerio Ser Ekklesia_*\n\n🔐 \n⏳ *Caduca en ${OTP_EXPIRATION_MINUTES} minutos.*\n\n🙏 No compartas este código con nadie.`;
|
||||||
|
await this.openwaService.sendText(chatId, text, sessionId);
|
||||||
|
}
|
||||||
|
}
|
||||||
57
src/modules/auth/dto/auth.dto.ts
Normal file
57
src/modules/auth/dto/auth.dto.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsNotEmpty, IsString } from 'class-validator';
|
||||||
|
|
||||||
|
export class EnviarOtpDto {
|
||||||
|
@ApiProperty({ example: '591' })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
codPais: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '63051500' })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
whatsapp: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class LoginDto {
|
||||||
|
@ApiProperty({ example: '591' })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
codPais: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '63051500' })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
whatsapp: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '4821' })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
codigo: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UpdatePerfilDto {
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsString()
|
||||||
|
nombres?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsString()
|
||||||
|
apellidos?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsString()
|
||||||
|
photoUrl?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsString()
|
||||||
|
fecNac?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsString()
|
||||||
|
ci?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsString()
|
||||||
|
complemento?: string;
|
||||||
|
}
|
||||||
1
src/modules/codigo-otp/codigo-otp.constants.ts
Normal file
1
src/modules/codigo-otp/codigo-otp.constants.ts
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
export const CODIGO_OTP_FIND_WHITELIST = ['idPersona', 'usado', 'intentosFallidos'];
|
||||||
77
src/modules/codigo-otp/codigo-otp.controller.ts
Normal file
77
src/modules/codigo-otp/codigo-otp.controller.ts
Normal file
|
|
@ -0,0 +1,77 @@
|
||||||
|
import { Body, Controller, Get, HttpStatus, Param, Post } from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { CodigoOtpService } from './codigo-otp.service.js';
|
||||||
|
import { ApiResult, defaultApiResult } from '../../common/interfaces/api.result.js';
|
||||||
|
import { routeCodigoOtp } from './codigo-otp.router.js';
|
||||||
|
import { FindDto } from '../../common/class/find.dto.js';
|
||||||
|
import { Autorizacion } from '../../common/decorators/autorizacion.decorator.js';
|
||||||
|
import { Autorizacion as AutorizacionEnum } from '../../common/enums/rol.enum.js';
|
||||||
|
|
||||||
|
@ApiTags('codigos-otp')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@Controller('codigos-otp')
|
||||||
|
export class CodigoOtpController {
|
||||||
|
constructor(private readonly codigoOtpService: CodigoOtpService) {}
|
||||||
|
|
||||||
|
@Get(':idOtp')
|
||||||
|
@Autorizacion(AutorizacionEnum.Developer)
|
||||||
|
async findOne(@Param('idOtp') idOtp: string): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeCodigoOtp.one.title, routeCodigoOtp.one.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.codigoOtpService.findOne(idOtp);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = [result.object];
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('find')
|
||||||
|
@Autorizacion(AutorizacionEnum.Developer)
|
||||||
|
async find(@Body() findByDto: FindDto): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeCodigoOtp.find.title, routeCodigoOtp.find.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { orderByDirection, orderByAttribute, whereConditions, limit, offset } = findByDto;
|
||||||
|
|
||||||
|
const result = await this.codigoOtpService.find(
|
||||||
|
whereConditions,
|
||||||
|
orderByAttribute,
|
||||||
|
orderByDirection,
|
||||||
|
limit,
|
||||||
|
offset,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = result.data;
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
}
|
||||||
13
src/modules/codigo-otp/codigo-otp.module.ts
Normal file
13
src/modules/codigo-otp/codigo-otp.module.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { CodigoOtp } from './entities/codigo-otp.entity.js';
|
||||||
|
import { CodigoOtpService } from './codigo-otp.service.js';
|
||||||
|
import { CodigoOtpController } from './codigo-otp.controller.js';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([CodigoOtp])],
|
||||||
|
exports: [TypeOrmModule],
|
||||||
|
controllers: [CodigoOtpController],
|
||||||
|
providers: [CodigoOtpService],
|
||||||
|
})
|
||||||
|
export class CodigoOtpModule {}
|
||||||
10
src/modules/codigo-otp/codigo-otp.router.ts
Normal file
10
src/modules/codigo-otp/codigo-otp.router.ts
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
export const routeCodigoOtp = {
|
||||||
|
one: {
|
||||||
|
route: '[GET].../v1/codigos-otp/:idOtp',
|
||||||
|
title: 'Find One Codigo OTP',
|
||||||
|
},
|
||||||
|
find: {
|
||||||
|
route: '[POST].../v1/codigos-otp/find',
|
||||||
|
title: 'Find Codigo OTP',
|
||||||
|
},
|
||||||
|
};
|
||||||
88
src/modules/codigo-otp/codigo-otp.service.ts
Normal file
88
src/modules/codigo-otp/codigo-otp.service.ts
Normal file
|
|
@ -0,0 +1,88 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { CodigoOtp } from './entities/codigo-otp.entity.js';
|
||||||
|
import { defaultServiceResult, ServiceResult } from '../../common/interfaces/service.result.js';
|
||||||
|
import { WhereCondition } from '../../common/types/query-builder.types.js';
|
||||||
|
import { CODIGO_OTP_FIND_WHITELIST } from './codigo-otp.constants.js';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class CodigoOtpService {
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(CodigoOtp)
|
||||||
|
private codigoOtpRepository: Repository<CodigoOtp>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async findOne(idOtp: string): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const result = await this.codigoOtpRepository.findOneBy({ idOtp });
|
||||||
|
|
||||||
|
if (result) {
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message = 'Existe un código OTP.';
|
||||||
|
serviceResult.number = 1;
|
||||||
|
serviceResult.object = result;
|
||||||
|
} else {
|
||||||
|
serviceResult.message = 'No existe el código OTP.';
|
||||||
|
}
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async find(
|
||||||
|
whereConditions: WhereCondition[],
|
||||||
|
orderByAttribute: string,
|
||||||
|
orderByDirection: 'ASC' | 'DESC',
|
||||||
|
limit: number,
|
||||||
|
offset: number,
|
||||||
|
): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
try {
|
||||||
|
let query = this.codigoOtpRepository.createQueryBuilder('codigo_otp');
|
||||||
|
|
||||||
|
whereConditions.forEach((condition, index) => {
|
||||||
|
const { attribute, value, operator = '=' } = condition;
|
||||||
|
|
||||||
|
if (!CODIGO_OTP_FIND_WHITELIST.includes(attribute)) {
|
||||||
|
throw new Error(`Atributo no permitido: ${attribute}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const paramKey = `param${index}`;
|
||||||
|
const param = {
|
||||||
|
[paramKey]: operator === 'like' ? `%${value}%` : value,
|
||||||
|
};
|
||||||
|
const whereMethod = index === 0 ? 'where' : 'andWhere';
|
||||||
|
|
||||||
|
query = query[whereMethod](
|
||||||
|
`codigo_otp.${attribute} ${operator} :${paramKey}`,
|
||||||
|
param,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
const orderAttr = CODIGO_OTP_FIND_WHITELIST.includes(orderByAttribute)
|
||||||
|
? orderByAttribute
|
||||||
|
: 'fecCreacion';
|
||||||
|
query = query.orderBy(`codigo_otp.${orderAttr}`, orderByDirection);
|
||||||
|
|
||||||
|
const totalRegistros = await query.getCount();
|
||||||
|
const skip = (offset - 1) * limit;
|
||||||
|
|
||||||
|
query = query.skip(skip).take(limit);
|
||||||
|
|
||||||
|
const result = await query.getMany();
|
||||||
|
const count = result.length;
|
||||||
|
|
||||||
|
serviceResult.boolean = count > 0;
|
||||||
|
serviceResult.message = `${count} código(s) OTP encontrado(s).`;
|
||||||
|
serviceResult.number = totalRegistros;
|
||||||
|
serviceResult.data = result;
|
||||||
|
} catch (error) {
|
||||||
|
serviceResult.boolean = false;
|
||||||
|
serviceResult.message = `Error en el servicio: ${error.message}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
}
|
||||||
25
src/modules/codigo-otp/entities/codigo-otp.entity.ts
Normal file
25
src/modules/codigo-otp/entities/codigo-otp.entity.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
|
||||||
|
|
||||||
|
@Entity('codigo_otp')
|
||||||
|
export class CodigoOtp {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
idOtp: string;
|
||||||
|
|
||||||
|
@Column({ type: 'uuid' })
|
||||||
|
idPersona: string;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
codigoHash: string;
|
||||||
|
|
||||||
|
@Column({ default: 0 })
|
||||||
|
intentosFallidos: number;
|
||||||
|
|
||||||
|
@Column({ type: 'timestamptz', default: () => 'now()' })
|
||||||
|
fecCreacion: Date;
|
||||||
|
|
||||||
|
@Column({ type: 'timestamptz' })
|
||||||
|
fecExpiracion: Date;
|
||||||
|
|
||||||
|
@Column({ default: false })
|
||||||
|
usado: boolean;
|
||||||
|
}
|
||||||
95
src/modules/configuracion/configuracion.controller.ts
Normal file
95
src/modules/configuracion/configuracion.controller.ts
Normal file
|
|
@ -0,0 +1,95 @@
|
||||||
|
import { Body, Controller, Get, HttpStatus, Patch, Post } from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { ConfiguracionService } from './configuracion.service.js';
|
||||||
|
import { ConfiguracionDto } from './dto/configuracion.dto.js';
|
||||||
|
import { UpdateConfiguracionDto } from './dto/update-configuracion.dto.js';
|
||||||
|
import { ApiResult, defaultApiResult } from '../../common/interfaces/api.result.js';
|
||||||
|
import { routeConfiguracion } from './configuracion.router.js';
|
||||||
|
import { Autorizacion } from '../../common/decorators/autorizacion.decorator.js';
|
||||||
|
import { Autorizacion as AutorizacionEnum } from '../../common/enums/rol.enum.js';
|
||||||
|
|
||||||
|
@ApiTags('configuracion')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@Controller('configuracion')
|
||||||
|
export class ConfiguracionController {
|
||||||
|
constructor(private readonly configuracionService: ConfiguracionService) {}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
async findUnique(): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeConfiguracion.get.title, routeConfiguracion.get.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.configuracionService.findUnique();
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = [result.object];
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
@Autorizacion(AutorizacionEnum.SuperAdmin)
|
||||||
|
async create(@Body() configuracionDto: ConfiguracionDto): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeConfiguracion.create.title, routeConfiguracion.create.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.configuracionService.create(configuracionDto);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = [result.object];
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch()
|
||||||
|
@Autorizacion(AutorizacionEnum.SuperAdmin)
|
||||||
|
async update(@Body() updateConfiguracionDto: UpdateConfiguracionDto): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeConfiguracion.update.title, routeConfiguracion.update.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.configuracionService.update(updateConfiguracionDto);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
}
|
||||||
13
src/modules/configuracion/configuracion.module.ts
Normal file
13
src/modules/configuracion/configuracion.module.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { Configuracion } from './entities/configuracion.entity.js';
|
||||||
|
import { ConfiguracionService } from './configuracion.service.js';
|
||||||
|
import { ConfiguracionController } from './configuracion.controller.js';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([Configuracion])],
|
||||||
|
exports: [TypeOrmModule],
|
||||||
|
controllers: [ConfiguracionController],
|
||||||
|
providers: [ConfiguracionService],
|
||||||
|
})
|
||||||
|
export class ConfiguracionModule {}
|
||||||
14
src/modules/configuracion/configuracion.router.ts
Normal file
14
src/modules/configuracion/configuracion.router.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
export const routeConfiguracion = {
|
||||||
|
get: {
|
||||||
|
route: '[GET].../v1/configuracion',
|
||||||
|
title: 'Find Configuracion',
|
||||||
|
},
|
||||||
|
create: {
|
||||||
|
route: '[POST].../v1/configuracion',
|
||||||
|
title: 'Create Configuracion',
|
||||||
|
},
|
||||||
|
update: {
|
||||||
|
route: '[PATCH].../v1/configuracion',
|
||||||
|
title: 'Update Configuracion',
|
||||||
|
},
|
||||||
|
};
|
||||||
111
src/modules/configuracion/configuracion.service.ts
Normal file
111
src/modules/configuracion/configuracion.service.ts
Normal file
|
|
@ -0,0 +1,111 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { Configuracion } from './entities/configuracion.entity.js';
|
||||||
|
import { ConfiguracionDto } from './dto/configuracion.dto.js';
|
||||||
|
import { UpdateConfiguracionDto } from './dto/update-configuracion.dto.js';
|
||||||
|
import { defaultServiceResult, ServiceResult } from '../../common/interfaces/service.result.js';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ConfiguracionService {
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(Configuracion)
|
||||||
|
private configuracionRepository: Repository<Configuracion>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async findUnique(): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const result = await this.configuracionRepository.findOneBy({});
|
||||||
|
|
||||||
|
if (result) {
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message = 'Existe una configuración.';
|
||||||
|
serviceResult.number = 1;
|
||||||
|
serviceResult.object = result;
|
||||||
|
} else {
|
||||||
|
serviceResult.message = 'No existe la configuración.';
|
||||||
|
}
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Singleton: solo se crea si no existe ninguna fila.
|
||||||
|
*/
|
||||||
|
async create(configuracionDto: ConfiguracionDto): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const exists = await this.configuracionRepository.findOneBy({});
|
||||||
|
|
||||||
|
if (exists) {
|
||||||
|
serviceResult.message = 'Ya existe una configuración. Use PATCH para actualizarla.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (configuracionDto.distancia <= 0) {
|
||||||
|
serviceResult.message = 'La distancia debe ser mayor a 0.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const entity = this.configuracionRepository.create({
|
||||||
|
lat: configuracionDto.lat,
|
||||||
|
lng: configuracionDto.lng,
|
||||||
|
distancia: configuracionDto.distancia,
|
||||||
|
openwaSessionId: configuracionDto.openwaSessionId ?? null,
|
||||||
|
});
|
||||||
|
const result = await this.configuracionRepository.save(entity);
|
||||||
|
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message = 'Configuración creada correctamente.';
|
||||||
|
serviceResult.number = 1;
|
||||||
|
serviceResult.object = result;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(updateConfiguracionDto: UpdateConfiguracionDto): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const exists = await this.configuracionRepository.findOneBy({});
|
||||||
|
|
||||||
|
if (!exists) {
|
||||||
|
serviceResult.message = 'No existe la configuración. Cree la alta inicial primero.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
updateConfiguracionDto.distancia !== undefined &&
|
||||||
|
updateConfiguracionDto.distancia <= 0
|
||||||
|
) {
|
||||||
|
serviceResult.message = 'La distancia debe ser mayor a 0.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const clean: Partial<Configuracion> = {};
|
||||||
|
if (updateConfiguracionDto.lat !== undefined) clean.lat = updateConfiguracionDto.lat;
|
||||||
|
if (updateConfiguracionDto.lng !== undefined) clean.lng = updateConfiguracionDto.lng;
|
||||||
|
if (updateConfiguracionDto.distancia !== undefined) {
|
||||||
|
clean.distancia = updateConfiguracionDto.distancia;
|
||||||
|
}
|
||||||
|
if (updateConfiguracionDto.openwaSessionId !== undefined) {
|
||||||
|
clean.openwaSessionId = updateConfiguracionDto.openwaSessionId;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Object.keys(clean).length === 0) {
|
||||||
|
serviceResult.message = 'No hay campos para actualizar.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.configuracionRepository.update(exists.idConfig, clean);
|
||||||
|
|
||||||
|
serviceResult.boolean = result.affected === 1;
|
||||||
|
serviceResult.message =
|
||||||
|
result.affected === 1
|
||||||
|
? 'Configuración actualizada correctamente.'
|
||||||
|
: 'No se encontró la configuración.';
|
||||||
|
serviceResult.number = result.affected || 0;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
}
|
||||||
24
src/modules/configuracion/dto/configuracion.dto.ts
Normal file
24
src/modules/configuracion/dto/configuracion.dto.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsNotEmpty, IsNumber, IsOptional, IsString } from 'class-validator';
|
||||||
|
|
||||||
|
export class ConfiguracionDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsNumber()
|
||||||
|
@IsNotEmpty()
|
||||||
|
lat: number;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsNumber()
|
||||||
|
@IsNotEmpty()
|
||||||
|
lng: number;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsNumber()
|
||||||
|
@IsNotEmpty()
|
||||||
|
distancia: number;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false, description: 'SessionId de OpenWA' })
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
openwaSessionId?: string;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,4 @@
|
||||||
|
import { PartialType } from '@nestjs/mapped-types';
|
||||||
|
import { ConfiguracionDto } from './configuracion.dto.js';
|
||||||
|
|
||||||
|
export class UpdateConfiguracionDto extends PartialType(ConfiguracionDto) {}
|
||||||
20
src/modules/configuracion/entities/configuracion.entity.ts
Normal file
20
src/modules/configuracion/entities/configuracion.entity.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
|
||||||
|
|
||||||
|
@Entity('configuracion')
|
||||||
|
export class Configuracion {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
idConfig: string;
|
||||||
|
|
||||||
|
@Column('double precision')
|
||||||
|
lat: number;
|
||||||
|
|
||||||
|
@Column('double precision')
|
||||||
|
lng: number;
|
||||||
|
|
||||||
|
@Column('double precision')
|
||||||
|
distancia: number;
|
||||||
|
|
||||||
|
/** SessionId de OpenWA (Easy API). Si es null se usa OPENWA_SESSION_ID de .env */
|
||||||
|
@Column({ type: 'varchar', nullable: true })
|
||||||
|
openwaSessionId?: string | null;
|
||||||
|
}
|
||||||
1
src/modules/dispositivo/dispositivo.constants.ts
Normal file
1
src/modules/dispositivo/dispositivo.constants.ts
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
export const DISPOSITIVO_FIND_WHITELIST = ['idPersona', 'plataforma', 'activo'];
|
||||||
166
src/modules/dispositivo/dispositivo.controller.ts
Normal file
166
src/modules/dispositivo/dispositivo.controller.ts
Normal file
|
|
@ -0,0 +1,166 @@
|
||||||
|
import { Body, Controller, Delete, Get, HttpStatus, Param, Patch, Post, Req } from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||||
|
import type { Request } from 'express';
|
||||||
|
import { DispositivoService } from './dispositivo.service.js';
|
||||||
|
import { DispositivoDto, UpdateDispositivoDto } from './dto/dispositivo.dto.js';
|
||||||
|
import { ApiResult, defaultApiResult } from '../../common/interfaces/api.result.js';
|
||||||
|
import { routeDispositivo } from './dispositivo.router.js';
|
||||||
|
import { FindDto } from '../../common/class/find.dto.js';
|
||||||
|
|
||||||
|
type AuthRequest = Request & {
|
||||||
|
user?: { idPersona?: string };
|
||||||
|
};
|
||||||
|
|
||||||
|
@ApiTags('dispositivos')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@Controller('dispositivos')
|
||||||
|
export class DispositivoController {
|
||||||
|
constructor(private readonly dispositivoService: DispositivoService) {}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
async register(@Req() req: AuthRequest, @Body() dto: DispositivoDto): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeDispositivo.create.title, routeDispositivo.create.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const idPersona = req.user?.idPersona;
|
||||||
|
if (!idPersona) {
|
||||||
|
apiResult.code = HttpStatus.UNAUTHORIZED;
|
||||||
|
apiResult.message = 'Token inválido.';
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.dispositivoService.register(idPersona, dto);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = result.object ? [result.object] : [];
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':idDispositivo')
|
||||||
|
async findOne(@Req() req: AuthRequest, @Param('idDispositivo') idDispositivo: string): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeDispositivo.one.title, routeDispositivo.one.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.dispositivoService.findOne(idDispositivo, req.user);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = result.object ? [result.object] : [];
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('find')
|
||||||
|
async find(@Body() findByDto: FindDto): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeDispositivo.find.title, routeDispositivo.find.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { orderByDirection, orderByAttribute, whereConditions, limit, offset } = findByDto;
|
||||||
|
|
||||||
|
const result = await this.dispositivoService.find(
|
||||||
|
whereConditions,
|
||||||
|
orderByAttribute,
|
||||||
|
orderByDirection,
|
||||||
|
limit,
|
||||||
|
offset,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = result.data;
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch(':idDispositivo')
|
||||||
|
async update(
|
||||||
|
@Req() req: AuthRequest,
|
||||||
|
@Param('idDispositivo') idDispositivo: string,
|
||||||
|
@Body() dto: UpdateDispositivoDto,
|
||||||
|
): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeDispositivo.update.title, routeDispositivo.update.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.dispositivoService.update(idDispositivo, dto, req.user);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete(':idDispositivo')
|
||||||
|
async remove(@Req() req: AuthRequest, @Param('idDispositivo') idDispositivo: string): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeDispositivo.remove.title, routeDispositivo.remove.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.dispositivoService.remove(idDispositivo, req.user);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
}
|
||||||
13
src/modules/dispositivo/dispositivo.module.ts
Normal file
13
src/modules/dispositivo/dispositivo.module.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { Dispositivo } from './entities/dispositivo.entity.js';
|
||||||
|
import { DispositivoService } from './dispositivo.service.js';
|
||||||
|
import { DispositivoController } from './dispositivo.controller.js';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([Dispositivo])],
|
||||||
|
exports: [DispositivoService],
|
||||||
|
controllers: [DispositivoController],
|
||||||
|
providers: [DispositivoService],
|
||||||
|
})
|
||||||
|
export class DispositivoModule {}
|
||||||
22
src/modules/dispositivo/dispositivo.router.ts
Normal file
22
src/modules/dispositivo/dispositivo.router.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
export const routeDispositivo = {
|
||||||
|
create: {
|
||||||
|
route: '[POST].../v1/dispositivos',
|
||||||
|
title: 'Register Dispositivo (FCM token)',
|
||||||
|
},
|
||||||
|
find: {
|
||||||
|
route: '[POST].../v1/dispositivos/find',
|
||||||
|
title: 'Find Dispositivos',
|
||||||
|
},
|
||||||
|
one: {
|
||||||
|
route: '[GET].../v1/dispositivos/:idDispositivo',
|
||||||
|
title: 'Find One Dispositivo',
|
||||||
|
},
|
||||||
|
update: {
|
||||||
|
route: '[PATCH].../v1/dispositivos/:idDispositivo',
|
||||||
|
title: 'Update Dispositivo',
|
||||||
|
},
|
||||||
|
remove: {
|
||||||
|
route: '[DELETE].../v1/dispositivos/:idDispositivo',
|
||||||
|
title: 'Remove Dispositivo',
|
||||||
|
},
|
||||||
|
};
|
||||||
212
src/modules/dispositivo/dispositivo.service.ts
Normal file
212
src/modules/dispositivo/dispositivo.service.ts
Normal file
|
|
@ -0,0 +1,212 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { Dispositivo } from './entities/dispositivo.entity.js';
|
||||||
|
import { DispositivoDto, UpdateDispositivoDto } from './dto/dispositivo.dto.js';
|
||||||
|
import { defaultServiceResult, ServiceResult } from '../../common/interfaces/service.result.js';
|
||||||
|
import { WhereCondition } from '../../common/types/query-builder.types.js';
|
||||||
|
import { DISPOSITIVO_FIND_WHITELIST } from './dispositivo.constants.js';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class DispositivoService {
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(Dispositivo)
|
||||||
|
private dispositivoRepository: Repository<Dispositivo>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registra o actualiza el token FCM de la persona logueada.
|
||||||
|
* Si el token ya existe para esa persona, se reactiva/actualiza.
|
||||||
|
*/
|
||||||
|
async register(idPersona: string, dto: DispositivoDto): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const existing = await this.dispositivoRepository.findOneBy({
|
||||||
|
idPersona,
|
||||||
|
token: dto.token,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
const result = await this.dispositivoRepository.update(existing.idDispositivo, {
|
||||||
|
activo: dto.activo ?? true,
|
||||||
|
plataforma: dto.plataforma ?? existing.plataforma,
|
||||||
|
ultimaConexion: new Date(),
|
||||||
|
});
|
||||||
|
serviceResult.boolean = result.affected === 1;
|
||||||
|
serviceResult.message = 'Dispositivo actualizado.';
|
||||||
|
serviceResult.number = result.affected || 0;
|
||||||
|
const updated = await this.dispositivoRepository.findOneBy({
|
||||||
|
idDispositivo: existing.idDispositivo,
|
||||||
|
});
|
||||||
|
serviceResult.object = updated;
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const entity = this.dispositivoRepository.create({
|
||||||
|
idPersona,
|
||||||
|
token: dto.token,
|
||||||
|
plataforma: dto.plataforma ?? 'android',
|
||||||
|
activo: dto.activo ?? true,
|
||||||
|
ultimaConexion: new Date(),
|
||||||
|
});
|
||||||
|
const result = await this.dispositivoRepository.save(entity);
|
||||||
|
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message = 'Dispositivo registrado correctamente.';
|
||||||
|
serviceResult.number = 1;
|
||||||
|
serviceResult.object = result;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findOne(idDispositivo: string, user?: { idPersona?: string; autorizacion?: string }): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const result = await this.dispositivoRepository.findOneBy({ idDispositivo });
|
||||||
|
|
||||||
|
if (!result) {
|
||||||
|
serviceResult.message = 'No existe el dispositivo.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (user && user.autorizacion !== 'Developer' && result.idPersona !== user.idPersona) {
|
||||||
|
serviceResult.message = 'No tiene permiso sobre este dispositivo.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message = 'Existe el dispositivo.';
|
||||||
|
serviceResult.number = 1;
|
||||||
|
serviceResult.object = result;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async find(
|
||||||
|
whereConditions: WhereCondition[],
|
||||||
|
orderByAttribute: string,
|
||||||
|
orderByDirection: 'ASC' | 'DESC',
|
||||||
|
limit: number,
|
||||||
|
offset: number,
|
||||||
|
): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
try {
|
||||||
|
let query = this.dispositivoRepository.createQueryBuilder('dispositivo');
|
||||||
|
|
||||||
|
whereConditions.forEach((condition, index) => {
|
||||||
|
const { attribute, value, operator = '=' } = condition;
|
||||||
|
|
||||||
|
if (!DISPOSITIVO_FIND_WHITELIST.includes(attribute)) {
|
||||||
|
throw new Error(`Atributo no permitido: ${attribute}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const paramKey = `param${index}`;
|
||||||
|
const param = {
|
||||||
|
[paramKey]: operator === 'like' ? `%${value}%` : value,
|
||||||
|
};
|
||||||
|
const whereMethod = index === 0 ? 'where' : 'andWhere';
|
||||||
|
|
||||||
|
query = query[whereMethod](
|
||||||
|
`dispositivo.${attribute} ${operator} :${paramKey}`,
|
||||||
|
param,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
const orderAttr = DISPOSITIVO_FIND_WHITELIST.includes(orderByAttribute)
|
||||||
|
? orderByAttribute
|
||||||
|
: 'ultimaConexion';
|
||||||
|
query = query.orderBy(`dispositivo.${orderAttr}`, orderByDirection);
|
||||||
|
|
||||||
|
const totalRegistros = await query.getCount();
|
||||||
|
const skip = (offset - 1) * limit;
|
||||||
|
query = query.skip(skip).take(limit);
|
||||||
|
|
||||||
|
const result = await query.getMany();
|
||||||
|
serviceResult.boolean = result.length > 0;
|
||||||
|
serviceResult.message = `${result.length} dispositivo(s) encontrado(s).`;
|
||||||
|
serviceResult.number = totalRegistros;
|
||||||
|
serviceResult.data = result;
|
||||||
|
} catch (error) {
|
||||||
|
serviceResult.boolean = false;
|
||||||
|
serviceResult.message = `Error en el servicio: ${error.message}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(
|
||||||
|
idDispositivo: string,
|
||||||
|
dto: UpdateDispositivoDto,
|
||||||
|
user?: { idPersona?: string; autorizacion?: string },
|
||||||
|
): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const existente = await this.dispositivoRepository.findOneBy({ idDispositivo });
|
||||||
|
if (!existente) {
|
||||||
|
serviceResult.message = 'No se encontró el dispositivo.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
if (user && user.autorizacion !== 'Developer' && existente.idPersona !== user.idPersona) {
|
||||||
|
serviceResult.message = 'No tiene permiso sobre este dispositivo.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.dispositivoRepository.update(idDispositivo, dto);
|
||||||
|
|
||||||
|
serviceResult.boolean = result.affected === 1;
|
||||||
|
serviceResult.message =
|
||||||
|
result.affected === 1
|
||||||
|
? 'Dispositivo actualizado correctamente.'
|
||||||
|
: 'No se encontró el dispositivo.';
|
||||||
|
serviceResult.number = result.affected || 0;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(
|
||||||
|
idDispositivo: string,
|
||||||
|
user?: { idPersona?: string; autorizacion?: string },
|
||||||
|
): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const existente = await this.dispositivoRepository.findOneBy({ idDispositivo });
|
||||||
|
if (!existente) {
|
||||||
|
serviceResult.message = 'No se encontró el dispositivo.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
if (user && user.autorizacion !== 'Developer' && existente.idPersona !== user.idPersona) {
|
||||||
|
serviceResult.message = 'No tiene permiso sobre este dispositivo.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.dispositivoRepository.update(idDispositivo, { activo: false });
|
||||||
|
|
||||||
|
serviceResult.boolean = result.affected === 1;
|
||||||
|
serviceResult.message =
|
||||||
|
result.affected === 1
|
||||||
|
? 'Dispositivo desactivado correctamente.'
|
||||||
|
: 'No se encontró el dispositivo.';
|
||||||
|
serviceResult.number = result.affected || 0;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findActiveTokensByPersona(idPersona: string): Promise<string[]> {
|
||||||
|
const rows = await this.dispositivoRepository.findBy({
|
||||||
|
idPersona,
|
||||||
|
activo: true,
|
||||||
|
});
|
||||||
|
return rows.map((r) => r.token);
|
||||||
|
}
|
||||||
|
|
||||||
|
async findActiveTokensByPersonas(ids: string[]): Promise<string[]> {
|
||||||
|
if (!ids.length) return [];
|
||||||
|
const rows = await this.dispositivoRepository
|
||||||
|
.createQueryBuilder('d')
|
||||||
|
.where('d."idPersona" IN (:...ids)', { ids })
|
||||||
|
.andWhere('d.activo = :activo', { activo: true })
|
||||||
|
.getMany();
|
||||||
|
return rows.map((r) => r.token);
|
||||||
|
}
|
||||||
|
}
|
||||||
31
src/modules/dispositivo/dto/dispositivo.dto.ts
Normal file
31
src/modules/dispositivo/dto/dispositivo.dto.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsBoolean, IsIn, IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||||
|
|
||||||
|
export class DispositivoDto {
|
||||||
|
@ApiProperty({ description: 'Token FCM del dispositivo' })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
token: string;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: ['android', 'ios'], default: 'android' })
|
||||||
|
@IsIn(['android', 'ios'])
|
||||||
|
@IsOptional()
|
||||||
|
plataforma?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false, default: true })
|
||||||
|
@IsBoolean()
|
||||||
|
@IsOptional()
|
||||||
|
activo?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UpdateDispositivoDto {
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsBoolean()
|
||||||
|
@IsOptional()
|
||||||
|
activo?: boolean;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
plataforma?: string;
|
||||||
|
}
|
||||||
23
src/modules/dispositivo/entities/dispositivo.entity.ts
Normal file
23
src/modules/dispositivo/entities/dispositivo.entity.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
||||||
|
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
|
||||||
|
|
||||||
|
@Entity('dispositivo')
|
||||||
|
export class Dispositivo {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
idDispositivo: string;
|
||||||
|
|
||||||
|
@Column({ type: 'uuid' })
|
||||||
|
idPersona: string;
|
||||||
|
|
||||||
|
/** Token FCM del dispositivo */
|
||||||
|
@Column()
|
||||||
|
token: string;
|
||||||
|
|
||||||
|
@Column({ default: 'android' })
|
||||||
|
plataforma: string;
|
||||||
|
|
||||||
|
@Column({ default: true })
|
||||||
|
activo: boolean;
|
||||||
|
|
||||||
|
@Column({ type: 'timestamptz', default: () => 'now()' })
|
||||||
|
ultimaConexion?: Date;
|
||||||
|
}
|
||||||
14
src/modules/equipo-persona/dto/cambiar-equipo-persona.dto.ts
Normal file
14
src/modules/equipo-persona/dto/cambiar-equipo-persona.dto.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsNotEmpty, IsString } from 'class-validator';
|
||||||
|
|
||||||
|
export class CambiarEquipoPersonaDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
idPersona: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
idEquipoNuevo: string;
|
||||||
|
}
|
||||||
20
src/modules/equipo-persona/dto/equipo-persona.dto.ts
Normal file
20
src/modules/equipo-persona/dto/equipo-persona.dto.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsEnum, IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||||
|
import { EstadoMiembro } from '../../../common/enums/estados.enum.js';
|
||||||
|
|
||||||
|
export class EquipoPersonaDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
idPersona: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
idEquipo: string;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: EstadoMiembro, default: EstadoMiembro.Activo, required: false })
|
||||||
|
@IsEnum(EstadoMiembro)
|
||||||
|
@IsOptional()
|
||||||
|
estado?: EstadoMiembro = EstadoMiembro.Activo;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,4 @@
|
||||||
|
import { PartialType } from '@nestjs/mapped-types';
|
||||||
|
import { EquipoPersonaDto } from './equipo-persona.dto.js';
|
||||||
|
|
||||||
|
export class UpdateEquipoPersonaDto extends PartialType(EquipoPersonaDto) {}
|
||||||
20
src/modules/equipo-persona/entities/equipo-persona.entity.ts
Normal file
20
src/modules/equipo-persona/entities/equipo-persona.entity.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
|
||||||
|
import { EstadoMiembro } from '../../../common/enums/estados.enum.js';
|
||||||
|
|
||||||
|
@Entity('equipo_persona')
|
||||||
|
export class EquipoPersona {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
idEquipoPersona: string;
|
||||||
|
|
||||||
|
@Column({ type: 'uuid' })
|
||||||
|
idPersona: string;
|
||||||
|
|
||||||
|
@Column({ type: 'uuid' })
|
||||||
|
idEquipo: string;
|
||||||
|
|
||||||
|
@Column({
|
||||||
|
type: 'varchar',
|
||||||
|
default: EstadoMiembro.Activo,
|
||||||
|
})
|
||||||
|
estado: EstadoMiembro;
|
||||||
|
}
|
||||||
1
src/modules/equipo-persona/equipo-persona.constants.ts
Normal file
1
src/modules/equipo-persona/equipo-persona.constants.ts
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
export const EQUIPO_PERSONA_FIND_WHITELIST = ['idPersona', 'idEquipo', 'estado'];
|
||||||
298
src/modules/equipo-persona/equipo-persona.controller.ts
Normal file
298
src/modules/equipo-persona/equipo-persona.controller.ts
Normal file
|
|
@ -0,0 +1,298 @@
|
||||||
|
import { Body, Controller, Delete, Get, HttpStatus, Param, Patch, Post, Req } from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { EquipoPersonaService } from './equipo-persona.service.js';
|
||||||
|
import { EquipoPersonaDto } from './dto/equipo-persona.dto.js';
|
||||||
|
import { UpdateEquipoPersonaDto } from './dto/update-equipo-persona.dto.js';
|
||||||
|
import { CambiarEquipoPersonaDto } from './dto/cambiar-equipo-persona.dto.js';
|
||||||
|
import { ApiResult, defaultApiResult } from '../../common/interfaces/api.result.js';
|
||||||
|
import { routeEquipoPersona } from './equipo-persona.router.js';
|
||||||
|
import { FindDto } from '../../common/class/find.dto.js';
|
||||||
|
import { Roles } from '../../common/decorators/roles.decorator.js';
|
||||||
|
import { Rol } from '../../common/enums/rol.enum.js';
|
||||||
|
import type { AuthRequest } from '../../common/utils/auth-user.js';
|
||||||
|
import { getAuthUser } from '../../common/utils/auth-user.js';
|
||||||
|
|
||||||
|
@ApiTags('equipos-personas')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@Controller('equipos-personas')
|
||||||
|
export class EquipoPersonaController {
|
||||||
|
constructor(private readonly equipoPersonaService: EquipoPersonaService) {}
|
||||||
|
|
||||||
|
@Post('/multiple')
|
||||||
|
@Roles(Rol.Lider)
|
||||||
|
async createMultiple(
|
||||||
|
@Req() req: AuthRequest,
|
||||||
|
@Body() array: EquipoPersonaDto[],
|
||||||
|
): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(
|
||||||
|
routeEquipoPersona.multiple.title,
|
||||||
|
routeEquipoPersona.multiple.route,
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const user = getAuthUser(req);
|
||||||
|
if (!user) {
|
||||||
|
apiResult.code = HttpStatus.UNAUTHORIZED;
|
||||||
|
apiResult.message = 'Token inválido.';
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.equipoPersonaService.createMultiple(array);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Permiso en el service: Líder de ese equipo, SuperAdmin o Developer
|
||||||
|
// (el guard @Roles no admite OR con SuperAdmin).
|
||||||
|
@Post()
|
||||||
|
async create(
|
||||||
|
@Req() req: AuthRequest,
|
||||||
|
@Body() equipoPersonaDto: EquipoPersonaDto,
|
||||||
|
): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(
|
||||||
|
routeEquipoPersona.create.title,
|
||||||
|
routeEquipoPersona.create.route,
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const user = getAuthUser(req);
|
||||||
|
if (!user) {
|
||||||
|
apiResult.code = HttpStatus.UNAUTHORIZED;
|
||||||
|
apiResult.message = 'Token inválido.';
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.equipoPersonaService.create(equipoPersonaDto, user);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = [result.object];
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':idEquipoPersona')
|
||||||
|
async findOne(
|
||||||
|
@Param('idEquipoPersona') idEquipoPersona: string,
|
||||||
|
): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(
|
||||||
|
routeEquipoPersona.one.title,
|
||||||
|
routeEquipoPersona.one.route,
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.equipoPersonaService.findOne(idEquipoPersona);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = [result.object];
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('find')
|
||||||
|
async find(@Req() req: AuthRequest, @Body() findByDto: FindDto): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(
|
||||||
|
routeEquipoPersona.find.title,
|
||||||
|
routeEquipoPersona.find.route,
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const user = getAuthUser(req);
|
||||||
|
if (!user) {
|
||||||
|
apiResult.code = HttpStatus.UNAUTHORIZED;
|
||||||
|
apiResult.message = 'Token inválido.';
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { orderByDirection, orderByAttribute, whereConditions, limit, offset } = findByDto;
|
||||||
|
|
||||||
|
const result = await this.equipoPersonaService.find(
|
||||||
|
whereConditions,
|
||||||
|
orderByAttribute,
|
||||||
|
orderByDirection,
|
||||||
|
limit,
|
||||||
|
offset,
|
||||||
|
user,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = result.data;
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Permiso en el service (puedeGestionarEquipo): Líder / SuperAdmin / Dev.
|
||||||
|
@Patch(':idEquipoPersona')
|
||||||
|
async update(
|
||||||
|
@Req() req: AuthRequest,
|
||||||
|
@Param('idEquipoPersona') idEquipoPersona: string,
|
||||||
|
@Body() updateEquipoPersonaDto: UpdateEquipoPersonaDto,
|
||||||
|
): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(
|
||||||
|
routeEquipoPersona.update.title,
|
||||||
|
routeEquipoPersona.update.route,
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const user = getAuthUser(req);
|
||||||
|
if (!user) {
|
||||||
|
apiResult.code = HttpStatus.UNAUTHORIZED;
|
||||||
|
apiResult.message = 'Token inválido.';
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.equipoPersonaService.update(
|
||||||
|
idEquipoPersona,
|
||||||
|
updateEquipoPersonaDto,
|
||||||
|
user,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Permiso en el service (puedeGestionarEquipo): Líder / SuperAdmin / Dev.
|
||||||
|
@Delete(':idEquipoPersona')
|
||||||
|
async remove(
|
||||||
|
@Req() req: AuthRequest,
|
||||||
|
@Param('idEquipoPersona') idEquipoPersona: string,
|
||||||
|
): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(
|
||||||
|
routeEquipoPersona.remove.title,
|
||||||
|
routeEquipoPersona.remove.route,
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const user = getAuthUser(req);
|
||||||
|
if (!user) {
|
||||||
|
apiResult.code = HttpStatus.UNAUTHORIZED;
|
||||||
|
apiResult.message = 'Token inválido.';
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.equipoPersonaService.remove(idEquipoPersona, user);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Permiso en el service: Líder del equipo DESTINO, SuperAdmin o Dev.
|
||||||
|
@Post('cambiar')
|
||||||
|
async cambiar(
|
||||||
|
@Req() req: AuthRequest,
|
||||||
|
@Body() cambiarEquipoPersonaDto: CambiarEquipoPersonaDto,
|
||||||
|
): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(
|
||||||
|
routeEquipoPersona.cambiar.title,
|
||||||
|
routeEquipoPersona.cambiar.route,
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const user = getAuthUser(req);
|
||||||
|
if (!user) {
|
||||||
|
apiResult.code = HttpStatus.UNAUTHORIZED;
|
||||||
|
apiResult.message = 'Token inválido.';
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.equipoPersonaService.cambiar(cambiarEquipoPersonaDto, user);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
}
|
||||||
19
src/modules/equipo-persona/equipo-persona.module.ts
Normal file
19
src/modules/equipo-persona/equipo-persona.module.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { EquipoPersona } from './entities/equipo-persona.entity.js';
|
||||||
|
import { Persona } from '../persona/entities/persona.entity.js';
|
||||||
|
import { Equipo } from '../equipo/entities/equipo.entity.js';
|
||||||
|
import { EquipoPersonaService } from './equipo-persona.service.js';
|
||||||
|
import { EquipoPersonaController } from './equipo-persona.controller.js';
|
||||||
|
import { AsistenciaModule } from '../asistencia/asistencia.module.js';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
TypeOrmModule.forFeature([EquipoPersona, Persona, Equipo]),
|
||||||
|
AsistenciaModule,
|
||||||
|
],
|
||||||
|
exports: [EquipoPersonaService, TypeOrmModule],
|
||||||
|
controllers: [EquipoPersonaController],
|
||||||
|
providers: [EquipoPersonaService],
|
||||||
|
})
|
||||||
|
export class EquipoPersonaModule {}
|
||||||
30
src/modules/equipo-persona/equipo-persona.router.ts
Normal file
30
src/modules/equipo-persona/equipo-persona.router.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
export const routeEquipoPersona = {
|
||||||
|
multiple: {
|
||||||
|
route: '[POST].../v1/equipos-personas/multiple',
|
||||||
|
title: 'Create Multiple EquipoPersona',
|
||||||
|
},
|
||||||
|
create: {
|
||||||
|
route: '[POST].../v1/equipos-personas',
|
||||||
|
title: 'Create EquipoPersona',
|
||||||
|
},
|
||||||
|
one: {
|
||||||
|
route: '[GET].../v1/equipos-personas/:idEquipoPersona',
|
||||||
|
title: 'Find One EquipoPersona',
|
||||||
|
},
|
||||||
|
find: {
|
||||||
|
route: '[POST].../v1/equipos-personas/find',
|
||||||
|
title: 'Find EquipoPersona',
|
||||||
|
},
|
||||||
|
update: {
|
||||||
|
route: '[PATCH].../v1/equipos-personas/:idEquipoPersona',
|
||||||
|
title: 'Update EquipoPersona',
|
||||||
|
},
|
||||||
|
remove: {
|
||||||
|
route: '[DELETE].../v1/equipos-personas/:idEquipoPersona',
|
||||||
|
title: 'Remove EquipoPersona',
|
||||||
|
},
|
||||||
|
cambiar: {
|
||||||
|
route: '[POST].../v1/equipos-personas/cambiar',
|
||||||
|
title: 'Cambiar Equipo Persona',
|
||||||
|
},
|
||||||
|
};
|
||||||
466
src/modules/equipo-persona/equipo-persona.service.ts
Normal file
466
src/modules/equipo-persona/equipo-persona.service.ts
Normal file
|
|
@ -0,0 +1,466 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { EquipoPersona } from './entities/equipo-persona.entity.js';
|
||||||
|
import { EquipoPersonaDto } from './dto/equipo-persona.dto.js';
|
||||||
|
import { UpdateEquipoPersonaDto } from './dto/update-equipo-persona.dto.js';
|
||||||
|
import { CambiarEquipoPersonaDto } from './dto/cambiar-equipo-persona.dto.js';
|
||||||
|
import {
|
||||||
|
defaultServiceResult,
|
||||||
|
ServiceResult,
|
||||||
|
} from '../../common/interfaces/service.result.js';
|
||||||
|
import { WhereCondition } from '../../common/types/query-builder.types.js';
|
||||||
|
import {
|
||||||
|
EstadoGeneral,
|
||||||
|
EstadoMiembro,
|
||||||
|
} from '../../common/enums/estados.enum.js';
|
||||||
|
import { Rol } from '../../common/enums/rol.enum.js';
|
||||||
|
import { EQUIPO_PERSONA_FIND_WHITELIST } from './equipo-persona.constants.js';
|
||||||
|
import {
|
||||||
|
AuthUser,
|
||||||
|
isDeveloper,
|
||||||
|
isSuperAdmin,
|
||||||
|
} from '../../common/utils/auth-user.js';
|
||||||
|
import { Persona } from '../persona/entities/persona.entity.js';
|
||||||
|
import { Equipo } from '../equipo/entities/equipo.entity.js';
|
||||||
|
import { AsistenciaService } from '../asistencia/asistencia.service.js';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class EquipoPersonaService {
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(EquipoPersona)
|
||||||
|
private equipoPersonaRepository: Repository<EquipoPersona>,
|
||||||
|
@InjectRepository(Persona)
|
||||||
|
private personaRepository: Repository<Persona>,
|
||||||
|
@InjectRepository(Equipo)
|
||||||
|
private equipoRepository: Repository<Equipo>,
|
||||||
|
private asistenciaService: AsistenciaService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async createMultiple(array: EquipoPersonaDto[]): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
for (const item of array) {
|
||||||
|
const check = await this.validarAlta(item.idPersona, item.idEquipo);
|
||||||
|
if (!check.ok) {
|
||||||
|
serviceResult.message = check.message;
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.equipoPersonaRepository
|
||||||
|
.createQueryBuilder()
|
||||||
|
.insert()
|
||||||
|
.into(EquipoPersona)
|
||||||
|
.values(
|
||||||
|
array.map((a) => ({
|
||||||
|
...a,
|
||||||
|
estado: a.estado ?? EstadoMiembro.Activo,
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
.execute();
|
||||||
|
|
||||||
|
// En PostgreSQL el driver expone rowCount (affectedRows es de MySQL).
|
||||||
|
const rows =
|
||||||
|
result.raw?.rowCount ??
|
||||||
|
result.raw?.affectedRows ??
|
||||||
|
result.identifiers.length;
|
||||||
|
|
||||||
|
serviceResult.boolean = rows > 0;
|
||||||
|
serviceResult.message =
|
||||||
|
rows > 0
|
||||||
|
? `${rows} membresía(s) agregada(s).`
|
||||||
|
: 'No se han agregado membresías.';
|
||||||
|
serviceResult.number = rows;
|
||||||
|
|
||||||
|
if (rows > 0) {
|
||||||
|
for (const item of array) {
|
||||||
|
if ((item.estado ?? EstadoMiembro.Activo) === EstadoMiembro.Activo) {
|
||||||
|
await this.asistenciaService.backfillPorMembresia(
|
||||||
|
item.idEquipo,
|
||||||
|
item.idPersona,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(
|
||||||
|
equipoPersonaDto: EquipoPersonaDto,
|
||||||
|
user: AuthUser,
|
||||||
|
): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const puede = await this.puedeGestionarEquipo(
|
||||||
|
user,
|
||||||
|
equipoPersonaDto.idEquipo,
|
||||||
|
);
|
||||||
|
if (!puede) {
|
||||||
|
serviceResult.message =
|
||||||
|
'No tiene permiso para agregar miembros a ese equipo.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const check = await this.validarAlta(
|
||||||
|
equipoPersonaDto.idPersona,
|
||||||
|
equipoPersonaDto.idEquipo,
|
||||||
|
);
|
||||||
|
if (!check.ok) {
|
||||||
|
serviceResult.message = check.message;
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const entity = this.equipoPersonaRepository.create({
|
||||||
|
...equipoPersonaDto,
|
||||||
|
estado: equipoPersonaDto.estado ?? EstadoMiembro.Activo,
|
||||||
|
});
|
||||||
|
const result = await this.equipoPersonaRepository.save(entity);
|
||||||
|
|
||||||
|
if (result.estado === EstadoMiembro.Activo) {
|
||||||
|
await this.asistenciaService.backfillPorMembresia(
|
||||||
|
result.idEquipo,
|
||||||
|
result.idPersona,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message = 'Membresía agregada correctamente.';
|
||||||
|
serviceResult.number = 1;
|
||||||
|
serviceResult.object = result;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findOne(idEquipoPersona: string): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const result = await this.equipoPersonaRepository.findOneBy({
|
||||||
|
idEquipoPersona,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result) {
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message = 'Existe una membresía.';
|
||||||
|
serviceResult.number = 1;
|
||||||
|
serviceResult.object = result;
|
||||||
|
} else {
|
||||||
|
serviceResult.message = 'No existe la membresía.';
|
||||||
|
}
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async find(
|
||||||
|
whereConditions: WhereCondition[],
|
||||||
|
orderByAttribute: string,
|
||||||
|
orderByDirection: 'ASC' | 'DESC',
|
||||||
|
limit: number,
|
||||||
|
offset: number,
|
||||||
|
user: AuthUser,
|
||||||
|
): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
try {
|
||||||
|
let query =
|
||||||
|
this.equipoPersonaRepository.createQueryBuilder('equipoPersona');
|
||||||
|
|
||||||
|
whereConditions.forEach((condition, index) => {
|
||||||
|
const { attribute, value, operator = '=' } = condition;
|
||||||
|
|
||||||
|
if (!EQUIPO_PERSONA_FIND_WHITELIST.includes(attribute)) {
|
||||||
|
throw new Error(`Atributo no permitido: ${attribute}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const paramKey = `param${index}`;
|
||||||
|
const param = {
|
||||||
|
[paramKey]: operator === 'like' ? `%${value}%` : value,
|
||||||
|
};
|
||||||
|
const whereMethod = index === 0 ? 'where' : 'andWhere';
|
||||||
|
|
||||||
|
query = query[whereMethod](
|
||||||
|
`equipoPersona.${attribute} ${operator} :${paramKey}`,
|
||||||
|
param,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Developer ve todo (mismo bypass que ServicioService.aplicarScoping);
|
||||||
|
// el resto aplica el scoping de su rol (0.5.2). El Servidor ve su(s)
|
||||||
|
// equipo(s) activo(s) igual que Líder/Estaca — solo ids/estado, sin PII.
|
||||||
|
if (isDeveloper(user)) {
|
||||||
|
// sin scoping
|
||||||
|
} else if (
|
||||||
|
user.rol === Rol.Lider ||
|
||||||
|
user.rol === Rol.Estaca ||
|
||||||
|
user.rol === Rol.Servidor
|
||||||
|
) {
|
||||||
|
const misEquipos = await this.equiposActivosDe(user.idPersona);
|
||||||
|
if (!misEquipos.length) {
|
||||||
|
query = query.andWhere('1 = 0');
|
||||||
|
} else {
|
||||||
|
query = query.andWhere('equipoPersona.idEquipo IN (:...ids)', {
|
||||||
|
ids: misEquipos,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!EQUIPO_PERSONA_FIND_WHITELIST.includes(orderByAttribute)) {
|
||||||
|
throw new Error(`Atributo de orden no permitido: ${orderByAttribute}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
query = query.orderBy(
|
||||||
|
`equipoPersona.${orderByAttribute}`,
|
||||||
|
orderByDirection,
|
||||||
|
);
|
||||||
|
|
||||||
|
const totalRegistros = await query.getCount();
|
||||||
|
const skip = (offset - 1) * limit;
|
||||||
|
query = query.skip(skip).take(limit);
|
||||||
|
|
||||||
|
const result = await query.getMany();
|
||||||
|
serviceResult.boolean = result.length > 0;
|
||||||
|
serviceResult.message = `${result.length} membresía(s) encontrada(s).`;
|
||||||
|
serviceResult.number = totalRegistros;
|
||||||
|
serviceResult.data = result;
|
||||||
|
} catch (error) {
|
||||||
|
serviceResult.boolean = false;
|
||||||
|
serviceResult.message = `Error en el servicio: ${error.message}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(
|
||||||
|
idEquipoPersona: string,
|
||||||
|
dto: UpdateEquipoPersonaDto,
|
||||||
|
user: AuthUser,
|
||||||
|
): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const membresia = await this.equipoPersonaRepository.findOneBy({
|
||||||
|
idEquipoPersona,
|
||||||
|
});
|
||||||
|
if (!membresia) {
|
||||||
|
serviceResult.message = 'No se encontró la membresía.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const puede = await this.puedeGestionarEquipo(user, membresia.idEquipo);
|
||||||
|
if (!puede) {
|
||||||
|
serviceResult.message = 'No tiene permiso para modificar esta membresía.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.equipoPersonaRepository.update(
|
||||||
|
idEquipoPersona,
|
||||||
|
dto,
|
||||||
|
);
|
||||||
|
|
||||||
|
const estadoFinal = dto.estado ?? membresia.estado;
|
||||||
|
const equipoFinal = dto.idEquipo ?? membresia.idEquipo;
|
||||||
|
const transicionaNuevoConvocado =
|
||||||
|
estadoFinal === EstadoMiembro.Activo &&
|
||||||
|
(membresia.estado !== EstadoMiembro.Activo ||
|
||||||
|
equipoFinal !== membresia.idEquipo);
|
||||||
|
if (result.affected === 1 && transicionaNuevoConvocado) {
|
||||||
|
await this.asistenciaService.backfillPorMembresia(
|
||||||
|
equipoFinal,
|
||||||
|
membresia.idPersona,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
serviceResult.boolean = result.affected === 1;
|
||||||
|
serviceResult.message =
|
||||||
|
result.affected === 1
|
||||||
|
? 'Membresía actualizada correctamente.'
|
||||||
|
: 'No se encontró la membresía.';
|
||||||
|
serviceResult.number = result.affected || 0;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(
|
||||||
|
idEquipoPersona: string,
|
||||||
|
user: AuthUser,
|
||||||
|
): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const membresia = await this.equipoPersonaRepository.findOneBy({
|
||||||
|
idEquipoPersona,
|
||||||
|
});
|
||||||
|
if (!membresia) {
|
||||||
|
serviceResult.message = 'No se encontró la membresía.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const puede = await this.puedeGestionarEquipo(user, membresia.idEquipo);
|
||||||
|
if (!puede) {
|
||||||
|
serviceResult.message = 'No tiene permiso para eliminar esta membresía.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.equipoPersonaRepository.update(idEquipoPersona, {
|
||||||
|
estado: EstadoMiembro.Eliminado,
|
||||||
|
});
|
||||||
|
|
||||||
|
serviceResult.boolean = result.affected === 1;
|
||||||
|
serviceResult.message =
|
||||||
|
result.affected === 1
|
||||||
|
? 'Membresía eliminada correctamente.'
|
||||||
|
: 'No se encontró la membresía.';
|
||||||
|
serviceResult.number = result.affected || 0;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cambio de equipo (matriz D + F9):
|
||||||
|
* - Solo Líder del equipo DESTINO o Developer.
|
||||||
|
* - 409 si ya está activo en ese mismo equipo.
|
||||||
|
* - Máximo 1 equipo activo a la vez.
|
||||||
|
*/
|
||||||
|
async cambiar(
|
||||||
|
dto: CambiarEquipoPersonaDto,
|
||||||
|
user: AuthUser,
|
||||||
|
): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const { idPersona, idEquipoNuevo } = dto;
|
||||||
|
|
||||||
|
const equipoNuevo = await this.equipoRepository.findOneBy({
|
||||||
|
idEquipo: idEquipoNuevo,
|
||||||
|
});
|
||||||
|
if (!equipoNuevo || equipoNuevo.estado === EstadoGeneral.Eliminado) {
|
||||||
|
serviceResult.message = 'El equipo destino no existe o está eliminado.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const puedeDestino = await this.puedeGestionarEquipo(user, idEquipoNuevo);
|
||||||
|
if (!puedeDestino) {
|
||||||
|
serviceResult.message =
|
||||||
|
'Solo el Líder del equipo DESTINO (o Developer) puede cambiar de equipo.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const persona = await this.personaRepository.findOneBy({ idPersona });
|
||||||
|
if (!persona || persona.estado !== EstadoGeneral.Activo) {
|
||||||
|
serviceResult.message = 'La persona no existe o no está activa.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (persona.rol === Rol.Admin) {
|
||||||
|
serviceResult.message = 'El rol Admin no se asigna a equipos.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const actual = await this.equipoPersonaRepository.findOne({
|
||||||
|
where: {
|
||||||
|
idPersona,
|
||||||
|
estado: EstadoMiembro.Activo,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (actual && actual.idEquipo === idEquipoNuevo) {
|
||||||
|
serviceResult.message = 'La persona ya pertenece a ese equipo.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (actual) {
|
||||||
|
await this.equipoPersonaRepository.update(actual.idEquipoPersona, {
|
||||||
|
estado: EstadoMiembro.Eliminado,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.equipoPersonaRepository.save(
|
||||||
|
this.equipoPersonaRepository.create({
|
||||||
|
idPersona,
|
||||||
|
idEquipo: idEquipoNuevo,
|
||||||
|
estado: EstadoMiembro.Activo,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.asistenciaService.backfillPorMembresia(idEquipoNuevo, idPersona);
|
||||||
|
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message = 'Cambio de equipo registrado.';
|
||||||
|
serviceResult.number = 1;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async validarAlta(
|
||||||
|
idPersona: string,
|
||||||
|
idEquipo: string,
|
||||||
|
): Promise<{ ok: boolean; message: string }> {
|
||||||
|
const persona = await this.personaRepository.findOneBy({ idPersona });
|
||||||
|
if (!persona) {
|
||||||
|
return { ok: false, message: `No existe la persona ${idPersona}.` };
|
||||||
|
}
|
||||||
|
if (persona.estado === EstadoGeneral.Eliminado) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
message: 'La persona está eliminada; el Developer debe desbloquearla.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (persona.rol === Rol.Admin) {
|
||||||
|
return { ok: false, message: 'El rol Admin no se asigna a equipos.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const equipo = await this.equipoRepository.findOneBy({ idEquipo });
|
||||||
|
if (!equipo || equipo.estado === EstadoGeneral.Eliminado) {
|
||||||
|
return { ok: false, message: 'El equipo no existe o está eliminado.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Regla (Fase 5c): solo se da de alta a quien **no tiene equipo**;
|
||||||
|
// si ya tuvo, su membresía debe quedar en 'Eliminado' antes de
|
||||||
|
// asignarla a otro (Activo/Inactivo/Suspendido cuentan como vigentes).
|
||||||
|
const vigente = await this.equipoPersonaRepository.findOne({
|
||||||
|
where: [
|
||||||
|
{ idPersona, estado: EstadoMiembro.Activo },
|
||||||
|
{ idPersona, estado: EstadoMiembro.Inactivo },
|
||||||
|
{ idPersona, estado: EstadoMiembro.Suspendido },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
if (vigente) {
|
||||||
|
if (vigente.idEquipo === idEquipo) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
message: `La persona ya es miembro de este equipo (estado ${vigente.estado}).`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
message:
|
||||||
|
'La persona ya pertenece a otro equipo; su membresía debe quedar en Eliminado para ser asignada a otro.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ok: true, message: 'OK' };
|
||||||
|
}
|
||||||
|
|
||||||
|
private async puedeGestionarEquipo(
|
||||||
|
user: AuthUser,
|
||||||
|
idEquipo: string,
|
||||||
|
): Promise<boolean> {
|
||||||
|
if (isDeveloper(user)) return true;
|
||||||
|
// SuperAdmin gestiona membresías desde Personas (Fase 5c).
|
||||||
|
if (isSuperAdmin(user)) return true;
|
||||||
|
if (user.rol !== Rol.Lider) return false;
|
||||||
|
|
||||||
|
const membresia = await this.equipoPersonaRepository.findOneBy({
|
||||||
|
idPersona: user.idPersona,
|
||||||
|
idEquipo,
|
||||||
|
estado: EstadoMiembro.Activo,
|
||||||
|
});
|
||||||
|
return !!membresia;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async equiposActivosDe(idPersona: string): Promise<string[]> {
|
||||||
|
const rows = await this.equipoPersonaRepository.findBy({
|
||||||
|
idPersona,
|
||||||
|
estado: EstadoMiembro.Activo,
|
||||||
|
});
|
||||||
|
return rows.map((r) => r.idEquipo);
|
||||||
|
}
|
||||||
|
}
|
||||||
15
src/modules/equipo/dto/equipo.dto.ts
Normal file
15
src/modules/equipo/dto/equipo.dto.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsEnum, IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||||
|
import { EstadoGeneral } from '../../../common/enums/estados.enum.js';
|
||||||
|
|
||||||
|
export class EquipoDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
nombreEquipo: string;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: EstadoGeneral, required: false })
|
||||||
|
@IsEnum(EstadoGeneral)
|
||||||
|
@IsOptional()
|
||||||
|
estado?: EstadoGeneral;
|
||||||
|
}
|
||||||
4
src/modules/equipo/dto/update-equipo.dto.ts
Normal file
4
src/modules/equipo/dto/update-equipo.dto.ts
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
import { PartialType } from '@nestjs/mapped-types';
|
||||||
|
import { EquipoDto } from './equipo.dto.js';
|
||||||
|
|
||||||
|
export class UpdateEquipoDto extends PartialType(EquipoDto) {}
|
||||||
17
src/modules/equipo/entities/equipo.entity.ts
Normal file
17
src/modules/equipo/entities/equipo.entity.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
|
||||||
|
import { EstadoGeneral } from '../../../common/enums/estados.enum.js';
|
||||||
|
|
||||||
|
@Entity('equipo')
|
||||||
|
export class Equipo {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
idEquipo: string;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
nombreEquipo: string;
|
||||||
|
|
||||||
|
@Column({
|
||||||
|
type: 'varchar',
|
||||||
|
default: EstadoGeneral.Activo,
|
||||||
|
})
|
||||||
|
estado: EstadoGeneral;
|
||||||
|
}
|
||||||
1
src/modules/equipo/equipo.constants.ts
Normal file
1
src/modules/equipo/equipo.constants.ts
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
export const EQUIPO_FIND_WHITELIST = ['nombreEquipo', 'estado'];
|
||||||
185
src/modules/equipo/equipo.controller.ts
Normal file
185
src/modules/equipo/equipo.controller.ts
Normal file
|
|
@ -0,0 +1,185 @@
|
||||||
|
import { Body, Controller, Delete, Get, HttpStatus, Param, Patch, Post } from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { EquipoService } from './equipo.service.js';
|
||||||
|
import { EquipoDto } from './dto/equipo.dto.js';
|
||||||
|
import { UpdateEquipoDto } from './dto/update-equipo.dto.js';
|
||||||
|
import { ApiResult, defaultApiResult } from '../../common/interfaces/api.result.js';
|
||||||
|
import { routeEquipo } from './equipo.router.js';
|
||||||
|
import { FindDto } from '../../common/class/find.dto.js';
|
||||||
|
import { Autorizacion } from '../../common/decorators/autorizacion.decorator.js';
|
||||||
|
import { Autorizacion as AutorizacionEnum } from '../../common/enums/rol.enum.js';
|
||||||
|
|
||||||
|
@ApiTags('equipos')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@Controller('equipos')
|
||||||
|
export class EquipoController {
|
||||||
|
constructor(private readonly equipoService: EquipoService) {}
|
||||||
|
|
||||||
|
@Post('/multiple')
|
||||||
|
@Autorizacion(AutorizacionEnum.SuperAdmin)
|
||||||
|
async createMultiple(@Body() array: EquipoDto[]): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeEquipo.multiple.title, routeEquipo.multiple.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.equipoService.createMultiple(array);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
@Autorizacion(AutorizacionEnum.SuperAdmin)
|
||||||
|
async create(@Body() equipoDto: EquipoDto): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeEquipo.create.title, routeEquipo.create.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.equipoService.create(equipoDto);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = [result.object];
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':idEquipo')
|
||||||
|
async findOne(@Param('idEquipo') idEquipo: string): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeEquipo.one.title, routeEquipo.one.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.equipoService.findOne(idEquipo);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = [result.object];
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('find')
|
||||||
|
async find(@Body() findByDto: FindDto): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeEquipo.find.title, routeEquipo.find.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { orderByDirection, orderByAttribute, whereConditions, limit, offset } = findByDto;
|
||||||
|
|
||||||
|
const result = await this.equipoService.find(
|
||||||
|
whereConditions,
|
||||||
|
orderByAttribute,
|
||||||
|
orderByDirection,
|
||||||
|
limit,
|
||||||
|
offset,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
apiResult.data = result.data;
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch(':idEquipo')
|
||||||
|
@Autorizacion(AutorizacionEnum.SuperAdmin)
|
||||||
|
async update(
|
||||||
|
@Param('idEquipo') idEquipo: string,
|
||||||
|
@Body() updateEquipoDto: UpdateEquipoDto,
|
||||||
|
): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeEquipo.update.title, routeEquipo.update.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.equipoService.update(idEquipo, updateEquipoDto);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete(':idEquipo')
|
||||||
|
@Autorizacion(AutorizacionEnum.SuperAdmin)
|
||||||
|
async remove(@Param('idEquipo') idEquipo: string): Promise<ApiResult> {
|
||||||
|
const apiResult = defaultApiResult(routeEquipo.remove.title, routeEquipo.remove.route);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.equipoService.remove(idEquipo);
|
||||||
|
|
||||||
|
if (result.boolean) {
|
||||||
|
apiResult.status = 'correct';
|
||||||
|
apiResult.code = HttpStatus.OK;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
apiResult.boolean = true;
|
||||||
|
apiResult.rows = result.number;
|
||||||
|
} else {
|
||||||
|
apiResult.code = HttpStatus.BAD_REQUEST;
|
||||||
|
apiResult.message = result.message;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
apiResult.message = error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiResult;
|
||||||
|
}
|
||||||
|
}
|
||||||
14
src/modules/equipo/equipo.module.ts
Normal file
14
src/modules/equipo/equipo.module.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { Equipo } from './entities/equipo.entity.js';
|
||||||
|
import { EquipoPersona } from '../equipo-persona/entities/equipo-persona.entity.js';
|
||||||
|
import { EquipoService } from './equipo.service.js';
|
||||||
|
import { EquipoController } from './equipo.controller.js';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([Equipo, EquipoPersona])],
|
||||||
|
exports: [TypeOrmModule],
|
||||||
|
controllers: [EquipoController],
|
||||||
|
providers: [EquipoService],
|
||||||
|
})
|
||||||
|
export class EquipoModule {}
|
||||||
26
src/modules/equipo/equipo.router.ts
Normal file
26
src/modules/equipo/equipo.router.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
export const routeEquipo = {
|
||||||
|
multiple: {
|
||||||
|
route: '[POST].../v1/equipos/multiple',
|
||||||
|
title: 'Create Multiple Equipo',
|
||||||
|
},
|
||||||
|
create: {
|
||||||
|
route: '[POST].../v1/equipos',
|
||||||
|
title: 'Create Equipo',
|
||||||
|
},
|
||||||
|
one: {
|
||||||
|
route: '[GET].../v1/equipos/:idEquipo',
|
||||||
|
title: 'Find One Equipo',
|
||||||
|
},
|
||||||
|
find: {
|
||||||
|
route: '[POST].../v1/equipos/find',
|
||||||
|
title: 'Find Equipo',
|
||||||
|
},
|
||||||
|
update: {
|
||||||
|
route: '[PATCH].../v1/equipos/:idEquipo',
|
||||||
|
title: 'Update Equipo',
|
||||||
|
},
|
||||||
|
remove: {
|
||||||
|
route: '[DELETE].../v1/equipos/:idEquipo',
|
||||||
|
title: 'Remove Equipo',
|
||||||
|
},
|
||||||
|
};
|
||||||
217
src/modules/equipo/equipo.service.ts
Normal file
217
src/modules/equipo/equipo.service.ts
Normal file
|
|
@ -0,0 +1,217 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { Equipo } from './entities/equipo.entity.js';
|
||||||
|
import { EquipoPersona } from '../equipo-persona/entities/equipo-persona.entity.js';
|
||||||
|
import { EquipoDto } from './dto/equipo.dto.js';
|
||||||
|
import { UpdateEquipoDto } from './dto/update-equipo.dto.js';
|
||||||
|
import { defaultServiceResult, ServiceResult } from '../../common/interfaces/service.result.js';
|
||||||
|
import { WhereCondition } from '../../common/types/query-builder.types.js';
|
||||||
|
import { EstadoGeneral, EstadoMiembro } from '../../common/enums/estados.enum.js';
|
||||||
|
import { EQUIPO_FIND_WHITELIST } from './equipo.constants.js';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class EquipoService {
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(Equipo)
|
||||||
|
private equipoRepository: Repository<Equipo>,
|
||||||
|
@InjectRepository(EquipoPersona)
|
||||||
|
private equipoPersonaRepository: Repository<EquipoPersona>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async createMultiple(array: EquipoDto[]): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const values = array.map((e) => ({
|
||||||
|
...e,
|
||||||
|
estado: e.estado ?? EstadoGeneral.Activo,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const result = await this.equipoRepository
|
||||||
|
.createQueryBuilder()
|
||||||
|
.insert()
|
||||||
|
.into(Equipo)
|
||||||
|
.values(values)
|
||||||
|
.execute();
|
||||||
|
|
||||||
|
const rows = result.raw.affectedRows ?? 0;
|
||||||
|
|
||||||
|
serviceResult.boolean = rows > 0;
|
||||||
|
serviceResult.message =
|
||||||
|
rows > 0 ? `${rows} equipo(s) agregado(s).` : 'No se han agregado equipos.';
|
||||||
|
serviceResult.number = rows;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(equipoDto: EquipoDto): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const existente = await this.equipoRepository.findOneBy({
|
||||||
|
nombreEquipo: equipoDto.nombreEquipo,
|
||||||
|
estado: EstadoGeneral.Activo,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (existente) {
|
||||||
|
serviceResult.message = 'Ya existe un equipo activo con ese nombre.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const entity = this.equipoRepository.create({
|
||||||
|
...equipoDto,
|
||||||
|
estado: equipoDto.estado ?? EstadoGeneral.Activo,
|
||||||
|
});
|
||||||
|
const result = await this.equipoRepository.save(entity);
|
||||||
|
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message = 'Equipo agregado correctamente.';
|
||||||
|
serviceResult.number = 1;
|
||||||
|
serviceResult.object = result;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findOne(idEquipo: string): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const result = await this.equipoRepository.findOneBy({ idEquipo });
|
||||||
|
|
||||||
|
if (result) {
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message = 'Existe un equipo.';
|
||||||
|
serviceResult.number = 1;
|
||||||
|
serviceResult.object = result;
|
||||||
|
} else {
|
||||||
|
serviceResult.message = 'No existe el equipo.';
|
||||||
|
}
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async find(
|
||||||
|
whereConditions: WhereCondition[],
|
||||||
|
orderByAttribute: string,
|
||||||
|
orderByDirection: 'ASC' | 'DESC',
|
||||||
|
limit: number,
|
||||||
|
offset: number,
|
||||||
|
): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
try {
|
||||||
|
let query = this.equipoRepository.createQueryBuilder('equipo');
|
||||||
|
|
||||||
|
whereConditions.forEach((condition, index) => {
|
||||||
|
const { attribute, value, operator = '=' } = condition;
|
||||||
|
|
||||||
|
if (!EQUIPO_FIND_WHITELIST.includes(attribute)) {
|
||||||
|
throw new Error(`Atributo no permitido: ${attribute}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const paramKey = `param${index}`;
|
||||||
|
const param = {
|
||||||
|
[paramKey]: operator === 'like' ? `%${value}%` : value,
|
||||||
|
};
|
||||||
|
const whereMethod = index === 0 ? 'where' : 'andWhere';
|
||||||
|
|
||||||
|
query = query[whereMethod](
|
||||||
|
`equipo.${attribute} ${operator} :${paramKey}`,
|
||||||
|
param,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!EQUIPO_FIND_WHITELIST.includes(orderByAttribute)) {
|
||||||
|
throw new Error(`Atributo de orden no permitido: ${orderByAttribute}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
query = query.orderBy(`equipo.${orderByAttribute}`, orderByDirection);
|
||||||
|
|
||||||
|
const totalRegistros = await query.getCount();
|
||||||
|
const skip = (offset - 1) * limit;
|
||||||
|
|
||||||
|
query = query.skip(skip).take(limit);
|
||||||
|
|
||||||
|
const result = await query.getMany();
|
||||||
|
const count = result.length;
|
||||||
|
|
||||||
|
serviceResult.boolean = count > 0;
|
||||||
|
serviceResult.message = `${count} equipo(s) encontrado(s).`;
|
||||||
|
serviceResult.number = totalRegistros;
|
||||||
|
serviceResult.data = result;
|
||||||
|
} catch (error) {
|
||||||
|
serviceResult.boolean = false;
|
||||||
|
serviceResult.message = `Error en el servicio: ${error.message}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(idEquipo: string, updateEquipoDto: UpdateEquipoDto): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const existente = await this.equipoRepository.findOneBy({ idEquipo });
|
||||||
|
if (!existente) {
|
||||||
|
serviceResult.message = 'No se encontró el equipo.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
updateEquipoDto.nombreEquipo &&
|
||||||
|
updateEquipoDto.nombreEquipo !== existente.nombreEquipo
|
||||||
|
) {
|
||||||
|
const duplicado = await this.equipoRepository.findOneBy({
|
||||||
|
nombreEquipo: updateEquipoDto.nombreEquipo,
|
||||||
|
estado: EstadoGeneral.Activo,
|
||||||
|
});
|
||||||
|
if (duplicado && duplicado.idEquipo !== idEquipo) {
|
||||||
|
serviceResult.message = 'Ya existe otro equipo activo con ese nombre.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.equipoRepository.update(idEquipo, updateEquipoDto);
|
||||||
|
|
||||||
|
serviceResult.boolean = result.affected === 1;
|
||||||
|
serviceResult.message =
|
||||||
|
result.affected === 1 ? 'Equipo actualizado correctamente.' : 'No se encontró el equipo.';
|
||||||
|
serviceResult.number = result.affected || 0;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Borrado lógico del equipo + miembros → 'Eliminado' (regla Q2.5).
|
||||||
|
*/
|
||||||
|
async remove(idEquipo: string): Promise<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
|
const existente = await this.equipoRepository.findOneBy({ idEquipo });
|
||||||
|
if (!existente) {
|
||||||
|
serviceResult.message = 'No se encontró el equipo.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (existente.estado === EstadoGeneral.Eliminado) {
|
||||||
|
serviceResult.message = 'El equipo ya está eliminado.';
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.equipoRepository.manager.transaction(async (manager) => {
|
||||||
|
await manager.update(Equipo, idEquipo, { estado: EstadoGeneral.Eliminado });
|
||||||
|
|
||||||
|
await manager
|
||||||
|
.createQueryBuilder()
|
||||||
|
.update(EquipoPersona)
|
||||||
|
.set({ estado: EstadoMiembro.Eliminado })
|
||||||
|
.where('"idEquipo" = :idEquipo', { idEquipo })
|
||||||
|
.andWhere('estado != :eliminado', { eliminado: EstadoMiembro.Eliminado })
|
||||||
|
.execute();
|
||||||
|
});
|
||||||
|
|
||||||
|
serviceResult.boolean = true;
|
||||||
|
serviceResult.message =
|
||||||
|
'Equipo eliminado correctamente (miembros pasan a Eliminado).';
|
||||||
|
serviceResult.number = 1;
|
||||||
|
|
||||||
|
return serviceResult;
|
||||||
|
}
|
||||||
|
}
|
||||||
66
src/modules/persona/dto/persona.dto.ts
Normal file
66
src/modules/persona/dto/persona.dto.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsBoolean, IsEnum, IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||||
|
import { Rol, Autorizacion } from '../../../common/enums/rol.enum.js';
|
||||||
|
import { EstadoGeneral } from '../../../common/enums/estados.enum.js';
|
||||||
|
|
||||||
|
export class PersonaDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
nombres: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
apellidos: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
whatsapp: string;
|
||||||
|
|
||||||
|
@ApiProperty({ default: '591', required: false })
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
codPais?: string = '591';
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
photoUrl?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: Rol })
|
||||||
|
@IsEnum(Rol)
|
||||||
|
@IsNotEmpty()
|
||||||
|
rol: Rol;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: Autorizacion, default: Autorizacion.Usuario, required: false })
|
||||||
|
@IsEnum(Autorizacion)
|
||||||
|
@IsOptional()
|
||||||
|
autorizacion?: Autorizacion = Autorizacion.Usuario;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
fecNac?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
ci?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
complemento?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ default: false, required: false })
|
||||||
|
@IsBoolean()
|
||||||
|
@IsOptional()
|
||||||
|
verificado?: boolean = false;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: EstadoGeneral, default: EstadoGeneral.Activo, required: false })
|
||||||
|
@IsEnum(EstadoGeneral)
|
||||||
|
@IsOptional()
|
||||||
|
estado?: EstadoGeneral = EstadoGeneral.Activo;
|
||||||
|
}
|
||||||
56
src/modules/persona/dto/preregistro-lote.dto.ts
Normal file
56
src/modules/persona/dto/preregistro-lote.dto.ts
Normal file
|
|
@ -0,0 +1,56 @@
|
||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { Type } from 'class-transformer';
|
||||||
|
import {
|
||||||
|
ArrayNotEmpty,
|
||||||
|
IsArray,
|
||||||
|
IsEnum,
|
||||||
|
IsIn,
|
||||||
|
IsNotEmpty,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
ValidateNested,
|
||||||
|
} from 'class-validator';
|
||||||
|
import { Rol } from '../../../common/enums/rol.enum.js';
|
||||||
|
|
||||||
|
export class PreRegistroPersonaItemDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
nombres: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
apellidos: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '78124224' })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
whatsapp: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
enum: [Rol.Lider, Rol.Estaca, Rol.Servidor],
|
||||||
|
description: 'Líder, Estaca o Servidor (no Admin)',
|
||||||
|
})
|
||||||
|
@IsIn([Rol.Lider, Rol.Estaca, Rol.Servidor])
|
||||||
|
rol: Rol;
|
||||||
|
|
||||||
|
@ApiProperty({ default: '591', required: false })
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
codPais?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class PreRegistroLoteDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
idEquipo: string;
|
||||||
|
|
||||||
|
@ApiProperty({ type: [PreRegistroPersonaItemDto] })
|
||||||
|
@IsArray()
|
||||||
|
@ArrayNotEmpty()
|
||||||
|
@ValidateNested({ each: true })
|
||||||
|
@Type(() => PreRegistroPersonaItemDto)
|
||||||
|
personas: PreRegistroPersonaItemDto[];
|
||||||
|
}
|
||||||
18
src/modules/persona/dto/update-autorizacion-persona.dto.ts
Normal file
18
src/modules/persona/dto/update-autorizacion-persona.dto.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsEnum, IsNotEmpty } from 'class-validator';
|
||||||
|
import { Autorizacion } from '../../../common/enums/rol.enum.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cambio de autorización (eje oculto de permisos).
|
||||||
|
* Solo Developer (ruta con @Autorizacion('Developer') + validación en service)
|
||||||
|
* y nunca sobre la propia persona.
|
||||||
|
*/
|
||||||
|
export class UpdateAutorizacionPersonaDto {
|
||||||
|
@ApiProperty({
|
||||||
|
enum: [Autorizacion.Usuario, Autorizacion.SuperAdmin, Autorizacion.Developer],
|
||||||
|
description: 'Usuario / SuperAdmin / Developer',
|
||||||
|
})
|
||||||
|
@IsEnum(Autorizacion)
|
||||||
|
@IsNotEmpty()
|
||||||
|
autorizacion: Autorizacion;
|
||||||
|
}
|
||||||
9
src/modules/persona/dto/update-persona.dto.ts
Normal file
9
src/modules/persona/dto/update-persona.dto.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
import { PartialType } from '@nestjs/mapped-types';
|
||||||
|
import { PersonaDto } from './persona.dto.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update de perfil: solo campos de perfil.
|
||||||
|
* No incluye whatsapp, codPais, rol, autorizacion (se validan en el service
|
||||||
|
* y el rol se cambia por endpoint aparte).
|
||||||
|
*/
|
||||||
|
export class UpdatePersonaDto extends PartialType(PersonaDto) {}
|
||||||
13
src/modules/persona/dto/update-rol-persona.dto.ts
Normal file
13
src/modules/persona/dto/update-rol-persona.dto.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsEnum, IsIn, IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||||
|
import { Rol } from '../../../common/enums/rol.enum.js';
|
||||||
|
|
||||||
|
export class UpdateRolPersonaDto {
|
||||||
|
@ApiProperty({
|
||||||
|
enum: [Rol.Lider, Rol.Estaca, Rol.Servidor],
|
||||||
|
description: 'Admin solo puede asignar Líder; Líder solo Estaca/Servidor',
|
||||||
|
})
|
||||||
|
@IsIn([Rol.Lider, Rol.Estaca, Rol.Servidor])
|
||||||
|
@IsNotEmpty()
|
||||||
|
rol: Rol;
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue