diff --git a/Dockerfile b/Dockerfile index fe6847f..078981e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -27,6 +27,8 @@ ENV NODE_ENV=production WORKDIR /app COPY --from=prod-deps /app/node_modules ./node_modules COPY --from=build /app/dist ./dist +# logos de los reportes PDF (se resuelven con process.cwd() + /assets) +COPY assets ./assets # package.json se copia porque dist/*.js son ESM ("type": "module") COPY package.json ./ RUN mkdir -p uploads && chown -R node:node /app diff --git a/assets/logo-ekklesia.png b/assets/logo-ekklesia.png new file mode 100644 index 0000000..4aca7cb Binary files /dev/null and b/assets/logo-ekklesia.png differ diff --git a/assets/logo-ser.png b/assets/logo-ser.png new file mode 100644 index 0000000..7f93f90 Binary files /dev/null and b/assets/logo-ser.png differ diff --git a/package.json b/package.json index 33ab383..af48649 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,7 @@ "firebase-admin": "^14.5.0", "jsonwebtoken": "^9.0.3", "multer": "^2.4.0", + "pdfkit": "^0.20.2", "pg": "^8.23.1", "reflect-metadata": "^0.2.2", "rxjs": "^7.8.1", @@ -56,6 +57,7 @@ "@types/jsonwebtoken": "^9.0.10", "@types/multer": "^2.3.0", "@types/node": "^24.0.0", + "@types/pdfkit": "^0.17.6", "@types/pg": "^8.23.1", "@types/supertest": "^7.0.0", "@vitest/coverage-v8": "^4.1.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3c6334e..7c98d57 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -59,6 +59,9 @@ importers: multer: specifier: ^2.4.0 version: 2.4.0 + pdfkit: + specifier: ^0.20.2 + version: 0.20.2 pg: specifier: ^8.23.1 version: 8.23.1 @@ -102,6 +105,9 @@ importers: '@types/node': specifier: ^24.0.0 version: 24.19.0 + '@types/pdfkit': + specifier: ^0.17.6 + version: 0.17.6 '@types/pg': specifier: ^8.23.1 version: 8.23.1 @@ -606,6 +612,10 @@ packages: '@nestjs/platform-socket.io': optional: true + '@noble/ciphers@1.3.0': + resolution: {integrity: sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==} + engines: {node: ^14.21.3 || >=16} + '@noble/hashes@1.8.0': resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==} engines: {node: ^14.21.3 || >=16} @@ -891,6 +901,9 @@ packages: '@standard-schema/spec@1.1.0': resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + '@swc/helpers@0.5.23': + resolution: {integrity: sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==} + '@tokenizer/inflate@0.4.1': resolution: {integrity: sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==} engines: {node: '>=18'} @@ -946,6 +959,9 @@ packages: '@types/node@24.19.0': resolution: {integrity: sha512-zY+5tKxXdhGh1PYI0ac+7juvEu4OI6vWtVVoj5i2m42jxAY1U+zHGt6QCyOFwykdP62sM3MJ9stoYYUw5aCWew==} + '@types/pdfkit@0.17.6': + resolution: {integrity: sha512-tIwzxk2uWKp0Cq9JIluQXJid77lYhF52EsIOwhsMF4iWLA6YneoBR1xVKYYdAysHuepUB0OX4tdwMiUDdGKmig==} + '@types/pg@8.23.1': resolution: {integrity: sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==} @@ -1097,6 +1113,10 @@ packages: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} engines: {node: 18 || 20 || >=22} + base64-js@0.0.8: + resolution: {integrity: sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==} + engines: {node: '>= 0.4'} + base64-js@1.5.1: resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} @@ -1125,6 +1145,9 @@ packages: resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==} engines: {node: 20 || >=22} + brotli@1.3.3: + resolution: {integrity: sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==} + buffer-equal-constant-time@1.0.1: resolution: {integrity: sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==} @@ -1226,6 +1249,10 @@ packages: resolution: {integrity: sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==} engines: {node: '>=0.8'} + clone@2.1.2: + resolution: {integrity: sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==} + engines: {node: '>=0.8'} + color-convert@2.0.1: resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} engines: {node: '>=7.0.0'} @@ -1328,6 +1355,9 @@ packages: dezalgo@1.0.4: resolution: {integrity: sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig==} + dfa@1.2.0: + resolution: {integrity: sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==} + dotenv-expand@13.0.0: resolution: {integrity: sha512-aBfBS8eYIeXmpHI9ThIlA7/WLq+SLt18iXUZhb52rW89QLKQFoIpPG1bPeewoPZsTyjSSO3T7234FBVUM1V2rA==} engines: {node: '>=12'} @@ -1495,6 +1525,9 @@ packages: resolution: {integrity: sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==} engines: {node: ^12.20 || >= 14.13} + fflate@0.8.3: + resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==} + figures@3.2.0: resolution: {integrity: sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==} engines: {node: '>=8'} @@ -1511,6 +1544,9 @@ packages: resolution: {integrity: sha512-DElmgmaH9aPXu2dWXGQiDoan33UfTnbfAAKaue4fwEZxmpdaNrTk5DmuFn+vVDki2KZ6TiaC0IHRWcEzcDxB3Q==} engines: {node: '>=22'} + fontkit@2.0.4: + resolution: {integrity: sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==} + foreground-child@3.3.1: resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==} engines: {node: '>=14'} @@ -1867,6 +1903,9 @@ packages: limiter@1.1.5: resolution: {integrity: sha512-FWWMIEOxz3GwUI4Ts/IvgVy6LPvoMPgjMdQ185nN6psJyBJ4yOpzqm695/h5umdLJg2vW3GR5iG11MAkR2AzJA==} + linebreak@1.1.0: + resolution: {integrity: sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==} + load-esm@1.0.3: resolution: {integrity: sha512-v5xlu8eHD1+6r8EHTg6hfmO97LN8ugKtiXcy5e6oN72iD2r6u0RPfLl6fxM+7Wnh2ZRq15o0russMst44WauPA==} engines: {node: '>=13.2.0'} @@ -2128,6 +2167,9 @@ packages: package-json-from-dist@1.0.1: resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==} + pako@0.2.9: + resolution: {integrity: sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==} + parseurl@1.3.3: resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==} engines: {node: '>= 0.8'} @@ -2150,6 +2192,9 @@ packages: pathe@2.0.3: resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + pdfkit@0.20.2: + resolution: {integrity: sha512-Q/w03ICAQyXfHNfTsg1udp0ADerdBN0s7a6XSPL7J7Ro6ABnafoBOCDBstIO9U02mvzHEV8HrvFIw5iV5ejIRA==} + pg-cloudflare@1.4.1: resolution: {integrity: sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==} @@ -2195,6 +2240,9 @@ packages: resolution: {integrity: sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==} engines: {node: '>=4'} + png-js@2.0.0: + resolution: {integrity: sha512-GdzJuUMc6ZSpxFJWVxtOH1bzYHym+TOnveqUjb+VJIbZWbZzyiRGFiKhbiielfpYbgMlhHVhsJ0FTazfuRFkMA==} + postcss@8.5.28: resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==} engines: {node: ^10 || ^12 || >=14} @@ -2275,6 +2323,9 @@ packages: resolution: {integrity: sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==} engines: {node: '>=18'} + restructure@3.0.2: + resolution: {integrity: sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==} + retry-request@8.0.4: resolution: {integrity: sha512-pI6/7eabUYkZxamkOq0g0uMxKLLGnjzhefY+vL8bVXag5rto4OU2YBTPytWLuHH7aEKD6fn7kJycQfid0Mwnkw==} engines: {node: '>=18'} @@ -2496,6 +2547,9 @@ packages: through@2.3.8: resolution: {integrity: sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==} + tiny-inflate@1.0.3: + resolution: {integrity: sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==} + tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} @@ -2632,6 +2686,12 @@ packages: resolution: {integrity: sha512-yLSH4py7oFH3oG/9K+XWrz1pSi3dfUrWEnInbxMfArOfc1+33BlGPQtLsOYwvdMy11AwUBetYuaRxSPqgkq+8g==} engines: {node: '>=4'} + unicode-properties@1.4.1: + resolution: {integrity: sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==} + + unicode-trie@2.0.0: + resolution: {integrity: sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==} + unpipe@1.0.0: resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==} engines: {node: '>= 0.8'} @@ -3319,6 +3379,8 @@ snapshots: optionalDependencies: '@nestjs/platform-socket.io': 12.1.2(@nestjs/common@12.1.2(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2)(supports-color@7.2.0))(@nestjs/websockets@12.1.2)(rxjs@7.8.2)(supports-color@7.2.0) + '@noble/ciphers@1.3.0': {} + '@noble/hashes@1.8.0': {} '@nodable/entities@3.1.0': @@ -3479,6 +3541,10 @@ snapshots: '@standard-schema/spec@1.1.0': {} + '@swc/helpers@0.5.23': + dependencies: + tslib: 2.8.1 + '@tokenizer/inflate@0.4.1(supports-color@7.2.0)': dependencies: debug: 4.4.3(supports-color@7.2.0) @@ -3548,6 +3614,10 @@ snapshots: dependencies: undici-types: 7.24.6 + '@types/pdfkit@0.17.6': + dependencies: + '@types/node': 24.19.0 + '@types/pg@8.23.1': dependencies: '@types/node': 24.19.0 @@ -3715,6 +3785,8 @@ snapshots: balanced-match@4.0.4: {} + base64-js@0.0.8: {} + base64-js@1.5.1: {} base64id@2.0.0: {} @@ -3755,6 +3827,10 @@ snapshots: dependencies: balanced-match: 4.0.4 + brotli@1.3.3: + dependencies: + base64-js: 1.5.1 + buffer-equal-constant-time@1.0.1: {} buffer-from@1.1.2: {} @@ -3848,6 +3924,8 @@ snapshots: clone@1.0.4: {} + clone@2.1.2: {} + color-convert@2.0.1: dependencies: color-name: 1.1.4 @@ -3922,6 +4000,8 @@ snapshots: asap: 2.0.6 wrappy: 1.0.2 + dfa@1.2.0: {} + dotenv-expand@13.0.0: dependencies: dotenv: 17.4.2 @@ -4113,6 +4193,8 @@ snapshots: node-domexception: 1.0.0 web-streams-polyfill: 3.3.3 + fflate@0.8.3: {} + figures@3.2.0: dependencies: escape-string-regexp: 1.0.5 @@ -4155,6 +4237,18 @@ snapshots: - encoding - supports-color + fontkit@2.0.4: + dependencies: + '@swc/helpers': 0.5.23 + brotli: 1.3.3 + clone: 2.1.2 + dfa: 1.2.0 + fast-deep-equal: 3.1.3 + restructure: 3.0.2 + tiny-inflate: 1.0.3 + unicode-properties: 1.4.1 + unicode-trie: 2.0.0 + foreground-child@3.3.1: dependencies: cross-spawn: 7.0.6 @@ -4603,6 +4697,11 @@ snapshots: limiter@1.1.5: {} + linebreak@1.1.0: + dependencies: + base64-js: 0.0.8 + unicode-trie: 2.0.0 + load-esm@1.0.3: {} lodash.camelcase@4.3.0: @@ -4842,6 +4941,8 @@ snapshots: package-json-from-dist@1.0.1: optional: true + pako@0.2.9: {} + parseurl@1.3.3: {} path-expression-matcher@1.6.2: @@ -4860,6 +4961,15 @@ snapshots: pathe@2.0.3: {} + pdfkit@0.20.2: + dependencies: + '@noble/ciphers': 1.3.0 + '@noble/hashes': 1.8.0 + fflate: 0.8.3 + fontkit: 2.0.4 + linebreak: 1.1.0 + png-js: 2.0.0 + pg-cloudflare@1.4.1: optional: true @@ -4901,6 +5011,10 @@ snapshots: pluralize@8.0.0: {} + png-js@2.0.0: + dependencies: + fflate: 0.8.3 + postcss@8.5.28: dependencies: nanoid: 3.3.19 @@ -4988,6 +5102,8 @@ snapshots: onetime: 7.0.0 signal-exit: 4.1.0 + restructure@3.0.2: {} + retry-request@8.0.4(supports-color@7.2.0): dependencies: extend: 3.0.2 @@ -5306,6 +5422,8 @@ snapshots: through@2.3.8: {} + tiny-inflate@1.0.3: {} + tinybench@2.9.0: {} tinyexec@1.3.1: {} @@ -5389,6 +5507,16 @@ snapshots: unicode-emoji-modifier-base@1.0.0: {} + unicode-properties@1.4.1: + dependencies: + base64-js: 1.5.1 + unicode-trie: 2.0.0 + + unicode-trie@2.0.0: + dependencies: + pako: 0.2.9 + tiny-inflate: 1.0.3 + unpipe@1.0.0: {} util-deprecate@1.0.2: {} diff --git a/src/app.module.ts b/src/app.module.ts index 5112055..dba1f5a 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -20,6 +20,8 @@ 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 { MantenimientoModule } from './modules/mantenimiento/mantenimiento.module.js'; +import { ReportesModule } from './modules/reportes/reportes.module.js'; import { RealtimeModule } from './common/realtime.module.js'; @Module({ @@ -56,6 +58,8 @@ import { RealtimeModule } from './common/realtime.module.js'; AsistenciaModule, CodigoOtpModule, DispositivoModule, + MantenimientoModule, + ReportesModule, RealtimeModule, ], controllers: [AppController], diff --git a/src/common/class/find.dto.ts b/src/common/class/find.dto.ts index 7accf36..907705a 100755 --- a/src/common/class/find.dto.ts +++ b/src/common/class/find.dto.ts @@ -1,4 +1,11 @@ -import { IsString, IsNumber, IsIn, IsArray, ValidateNested, IsOptional } from 'class-validator'; +import { + IsString, + IsNumber, + IsIn, + IsArray, + ValidateNested, + IsOptional, +} from 'class-validator'; import { Type } from 'class-transformer'; // Interfaz para cada condición de búsqueda @@ -11,8 +18,8 @@ export class WhereConditionDto { @IsString() @IsOptional() - @IsIn(['=', 'like', '>', '<', '>=', '<=']) - operator?: '=' | 'like' | '>' | '<' | '>=' | '<='; + @IsIn(['=', 'like', '>', '<', '>=', '<=', 'in']) + operator?: '=' | 'like' | '>' | '<' | '>=' | '<=' | 'in'; } // DTO principal para la solicitud @@ -33,5 +40,4 @@ export class FindDto { @IsNumber() offset: number; // paginacion - -} \ No newline at end of file +} diff --git a/src/common/enums/estados.enum.ts b/src/common/enums/estados.enum.ts index c388ceb..b20fd73 100644 --- a/src/common/enums/estados.enum.ts +++ b/src/common/enums/estados.enum.ts @@ -2,6 +2,11 @@ export enum EstadoGeneral { Activo = 'Activo', Inactivo = 'Inactivo', Eliminado = 'Eliminado', + /** Marca por inactividad (solo rol Servidor): sin ingreso en 3 meses. + * No es un bloqueo: la persona sigue pudiendo entrar y marcar (al + * hacerlo vuelve a Activo automáticamente). La pone el reporte de + * Asistencia por servicio (tanda Reportes). */ + Inhabilitado = 'Inhabilitado', } export enum EstadoMiembro { diff --git a/src/common/enums/tipos.enum.ts b/src/common/enums/tipos.enum.ts index 197cbd5..3cf649f 100644 --- a/src/common/enums/tipos.enum.ts +++ b/src/common/enums/tipos.enum.ts @@ -15,4 +15,5 @@ export enum MetodoMarcado { PIN = 'PIN', Geolocalizacion = 'Geolocalizacion', Sistema = 'Sistema', + Lider = 'Líder' } diff --git a/src/common/types/query-builder.types.ts b/src/common/types/query-builder.types.ts index ddb6c9f..3d5750d 100755 --- a/src/common/types/query-builder.types.ts +++ b/src/common/types/query-builder.types.ts @@ -1,5 +1,6 @@ export type WhereCondition = { attribute: string; value: string | number | boolean; - operator?: '=' | 'like' | '>' | '<' | '>=' | '<='; -}; \ No newline at end of file + // 'in': `value` es una lista CSV (ej. `'Publicado,EnCurso'`). + operator?: '=' | 'like' | '>' | '<' | '>=' | '<=' | 'in'; +}; diff --git a/src/modules/asistencia/asistencia.module.ts b/src/modules/asistencia/asistencia.module.ts index 204c13f..e8c25a8 100644 --- a/src/modules/asistencia/asistencia.module.ts +++ b/src/modules/asistencia/asistencia.module.ts @@ -8,6 +8,7 @@ import { ServicioEquipo } from '../servicio-equipo/entities/servicio-equipo.enti 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 { Persona } from '../persona/entities/persona.entity.js'; import { AsistenciaService } from './asistencia.service.js'; import { AsistenciaController } from './asistencia.controller.js'; @@ -22,6 +23,7 @@ import { AsistenciaController } from './asistencia.controller.js'; ServicioTurno, Turno, Configuracion, + Persona, ]), ], exports: [AsistenciaService, TypeOrmModule], diff --git a/src/modules/asistencia/asistencia.service.ts b/src/modules/asistencia/asistencia.service.ts index 9e26486..9f5ba89 100644 --- a/src/modules/asistencia/asistencia.service.ts +++ b/src/modules/asistencia/asistencia.service.ts @@ -9,6 +9,7 @@ import { ServicioEquipo } from '../servicio-equipo/entities/servicio-equipo.enti 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 { Persona } from '../persona/entities/persona.entity.js'; import { AsistenciaDto, MarcarAsistenciaDto, @@ -21,6 +22,7 @@ import { import { WhereCondition } from '../../common/types/query-builder.types.js'; import { EstadoAsistencia, + EstadoGeneral, EstadoMiembro, EstadoServicio, } from '../../common/enums/estados.enum.js'; @@ -55,6 +57,8 @@ export class AsistenciaService { private turnoRepository: Repository, @InjectRepository(Configuracion) private configuracionRepository: Repository, + @InjectRepository(Persona) + private personaRepository: Repository, ) {} async create(asistenciaDto: AsistenciaDto): Promise { @@ -343,6 +347,10 @@ export class AsistenciaService { estado: await this.estadoMarcado(servicio), observacion: dto.observacion ?? asistencia.observacion, }); + + // Tanda Reportes: un servidor `Inhabilitado` que vuelve a marcar + // ingreso se rehabilita solo (vuelve a Activo). + await this.rehabilitarSiInhabilitado(asistencia.idPersona); } else { if (!asistencia.fecIngreso) { serviceResult.message = 'Debe registrar el ingreso antes de la salida.'; @@ -376,6 +384,19 @@ export class AsistenciaService { return serviceResult; } + /** + * Auto-rehabilitación (tanda Reportes): si la persona estaba + * `Inhabilitado` y acaba de registrar ingreso, vuelve a `Activo`. + * No es un bloqueo: la marca por inactividad se limpia al marcar. + */ + private async rehabilitarSiInhabilitado(idPersona: string): Promise { + const persona = await this.personaRepository.findOneBy({ idPersona }); + if (!persona || persona.estado !== EstadoGeneral.Inhabilitado) return; + await this.personaRepository.update(idPersona, { + estado: EstadoGeneral.Activo, + }); + } + /** * Mensaje si coords cae fuera del radio `configuracion.distancia` del punto * de marcado. Si no hay fila de configuración, no valida. diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts index a1aebde..3d57a60 100644 --- a/src/modules/auth/auth.service.ts +++ b/src/modules/auth/auth.service.ts @@ -7,7 +7,10 @@ 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 { + 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'; @@ -51,7 +54,10 @@ export class AuthService { return serviceResult; } - if (persona.estado !== EstadoGeneral.Activo) { + if ( + persona.estado !== EstadoGeneral.Activo && + persona.estado !== EstadoGeneral.Inhabilitado + ) { serviceResult.message = 'La cuenta no está activa. Contacte a su líder o administrador.'; return serviceResult; @@ -90,7 +96,8 @@ export class AuthService { return serviceResult; } serviceResult.boolean = true; - serviceResult.message = 'Código reenviado por WhatsApp (el mismo código anterior).'; + 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 = @@ -113,7 +120,9 @@ export class AuthService { 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); + const fecExpiracion = new Date( + fecCreacion.getTime() + OTP_EXPIRATION_MINUTES * 60_000, + ); await this.codigoOtpRepository.manager.transaction(async (manager) => { await manager @@ -172,7 +181,10 @@ export class AuthService { return serviceResult; } - if (persona.estado !== EstadoGeneral.Activo) { + if ( + persona.estado !== EstadoGeneral.Activo && + persona.estado !== EstadoGeneral.Inhabilitado + ) { serviceResult.message = 'La cuenta no está activa.'; return serviceResult; } @@ -193,11 +205,15 @@ export class AuthService { 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.'; + serviceResult.message = + 'Código bloqueado por seguridad. Solicite uno nuevo.'; return serviceResult; } - const match = await this.hashService.compareTexts(dto.codigo, otp.codigoHash); + const match = await this.hashService.compareTexts( + dto.codigo, + otp.codigoHash, + ); if (!match) { const intentos = otp.intentosFallidos + 1; @@ -263,7 +279,10 @@ export class AuthService { return serviceResult; } - if (persona.estado !== EstadoGeneral.Activo) { + if ( + persona.estado !== EstadoGeneral.Activo && + persona.estado !== EstadoGeneral.Inhabilitado + ) { serviceResult.message = 'La cuenta no está activa.'; return serviceResult; } @@ -304,7 +323,10 @@ export class AuthService { return serviceResult; } - async updatePerfil(idPersona: string, dto: UpdatePerfilDto): Promise { + async updatePerfil( + idPersona: string, + dto: UpdatePerfilDto, + ): Promise { const serviceResult = defaultServiceResult(); const clean: Partial = {}; @@ -336,7 +358,10 @@ export class AuthService { return String(Math.floor(1000 + Math.random() * 9000)); } - private async sendOtpViaOpenwa(persona: Persona, codigo: string): Promise { + private async sendOtpViaOpenwa( + persona: Persona, + codigo: string, + ): Promise { const config = await this.configuracionRepository.findOneBy({}); const sessionId = this.openwaService.resolveSessionId(config); @@ -346,7 +371,10 @@ export class AuthService { ); } - const chatId = this.openwaService.buildChatId(persona.codPais, persona.whatsapp); + 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); } diff --git a/src/modules/mantenimiento/dto/purga.dto.ts b/src/modules/mantenimiento/dto/purga.dto.ts new file mode 100644 index 0000000..2db8b8c --- /dev/null +++ b/src/modules/mantenimiento/dto/purga.dto.ts @@ -0,0 +1,48 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { + ArrayNotEmpty, + IsArray, + IsBoolean, + IsIn, + IsOptional, + IsString, +} from 'class-validator'; + +/// Categorías de la purga física (solo Developer, PlanFlutter §7.10). +export const PURGA_CATEGORIAS = [ + 'equipos', + 'servicios', + 'turnos', + 'personas', +] as const; +export type PurgaCategoria = (typeof PURGA_CATEGORIAS)[number]; + +export class PurgaDto { + @ApiProperty({ + type: [String], + enum: PURGA_CATEGORIAS, + example: ['equipos'], + description: 'Categorías a purgar (borrado físico total por categoría).', + }) + @IsArray() + @ArrayNotEmpty() + @IsIn([...PURGA_CATEGORIAS], { each: true }) + categorias: PurgaCategoria[]; + + @ApiProperty({ + required: false, + default: false, + description: 'true = solo cuenta filas (no borra nada).', + }) + @IsOptional() + @IsBoolean() + dryRun?: boolean; + + @ApiProperty({ + required: false, + description: 'Debe ser exactamente "ELIMINAR" cuando dryRun=false.', + }) + @IsOptional() + @IsString() + confirmacion?: string; +} diff --git a/src/modules/mantenimiento/mantenimiento.controller.ts b/src/modules/mantenimiento/mantenimiento.controller.ts new file mode 100644 index 0000000..e1fd0a0 --- /dev/null +++ b/src/modules/mantenimiento/mantenimiento.controller.ts @@ -0,0 +1,62 @@ +import { Body, Controller, HttpStatus, Post } from '@nestjs/common'; +import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'; +import { Autorizacion } from '../../common/decorators/autorizacion.decorator.js'; +import { Autorizacion as AutorizacionEnum } from '../../common/enums/rol.enum.js'; +import { + ApiResult, + defaultApiResult, +} from '../../common/interfaces/api.result.js'; +import { PurgaDto } from './dto/purga.dto.js'; +import { MantenimientoService } from './mantenimiento.service.js'; +import { routeMantenimiento } from './mantenimiento.router.js'; + +@ApiTags('mantenimiento') +@ApiBearerAuth() +@Controller('mantenimiento') +export class MantenimientoController { + constructor(private readonly mantenimientoService: MantenimientoService) {} + + /// Borrado físico total por categoría: dryRun cuenta; ejecutar exige + /// `confirmacion === 'ELIMINAR'`. + @Post('purga') + @Autorizacion(AutorizacionEnum.Developer) + async purgar(@Body() purgaDto: PurgaDto): Promise { + const apiResult = defaultApiResult( + routeMantenimiento.purga.title, + routeMantenimiento.purga.route, + ); + + try { + const dryRun = purgaDto.dryRun === true; + + if (!dryRun && purgaDto.confirmacion !== 'ELIMINAR') { + apiResult.code = HttpStatus.BAD_REQUEST; + apiResult.message = + 'Confirmación incorrecta: escribí ELIMINAR para borrar.'; + return apiResult; + } + + const result = await this.mantenimientoService.purgar( + purgaDto.categorias, + dryRun, + ); + + 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; + } +} diff --git a/src/modules/mantenimiento/mantenimiento.module.ts b/src/modules/mantenimiento/mantenimiento.module.ts new file mode 100644 index 0000000..1c71cda --- /dev/null +++ b/src/modules/mantenimiento/mantenimiento.module.ts @@ -0,0 +1,38 @@ +import { Module } from '@nestjs/common'; +import { TypeOrmModule } from '@nestjs/typeorm'; +import { Asistencia } from '../asistencia/entities/asistencia.entity.js'; +import { CodigoOtp } from '../codigo-otp/entities/codigo-otp.entity.js'; +import { Dispositivo } from '../dispositivo/entities/dispositivo.entity.js'; +import { EquipoPersona } from '../equipo-persona/entities/equipo-persona.entity.js'; +import { Equipo } from '../equipo/entities/equipo.entity.js'; +import { Persona } from '../persona/entities/persona.entity.js'; +import { Reemplazo } from '../reemplazo/entities/reemplazo.entity.js'; +import { ServicioEquipo } from '../servicio-equipo/entities/servicio-equipo.entity.js'; +import { ServicioTurno } from '../servicio-turno/entities/servicio-turno.entity.js'; +import { Servicio } from '../servicio/entities/servicio.entity.js'; +import { SolicitudApoyo } from '../solicitud-apoyo/entities/solicitud-apoyo.entity.js'; +import { Turno } from '../turno/entities/turno.entity.js'; +import { MantenimientoController } from './mantenimiento.controller.js'; +import { MantenimientoService } from './mantenimiento.service.js'; + +@Module({ + imports: [ + TypeOrmModule.forFeature([ + Asistencia, + Reemplazo, + SolicitudApoyo, + EquipoPersona, + CodigoOtp, + Dispositivo, + ServicioEquipo, + ServicioTurno, + Equipo, + Servicio, + Turno, + Persona, + ]), + ], + controllers: [MantenimientoController], + providers: [MantenimientoService], +}) +export class MantenimientoModule {} diff --git a/src/modules/mantenimiento/mantenimiento.router.ts b/src/modules/mantenimiento/mantenimiento.router.ts new file mode 100644 index 0000000..c64a6a7 --- /dev/null +++ b/src/modules/mantenimiento/mantenimiento.router.ts @@ -0,0 +1,6 @@ +export const routeMantenimiento = { + purga: { + route: '[POST].../v1/mantenimiento/purga', + title: 'Purga de datos (Developer)', + }, +}; diff --git a/src/modules/mantenimiento/mantenimiento.service.ts b/src/modules/mantenimiento/mantenimiento.service.ts new file mode 100644 index 0000000..73ed0f8 --- /dev/null +++ b/src/modules/mantenimiento/mantenimiento.service.ts @@ -0,0 +1,197 @@ +import { Injectable } from '@nestjs/common'; +import { InjectRepository } from '@nestjs/typeorm'; +import { Repository } from 'typeorm'; +import { Asistencia } from '../asistencia/entities/asistencia.entity.js'; +import { CodigoOtp } from '../codigo-otp/entities/codigo-otp.entity.js'; +import { Dispositivo } from '../dispositivo/entities/dispositivo.entity.js'; +import { EquipoPersona } from '../equipo-persona/entities/equipo-persona.entity.js'; +import { Equipo } from '../equipo/entities/equipo.entity.js'; +import { Persona } from '../persona/entities/persona.entity.js'; +import { Reemplazo } from '../reemplazo/entities/reemplazo.entity.js'; +import { ServicioEquipo } from '../servicio-equipo/entities/servicio-equipo.entity.js'; +import { ServicioTurno } from '../servicio-turno/entities/servicio-turno.entity.js'; +import { Servicio } from '../servicio/entities/servicio.entity.js'; +import { SolicitudApoyo } from '../solicitud-apoyo/entities/solicitud-apoyo.entity.js'; +import { Turno } from '../turno/entities/turno.entity.js'; +import { + defaultServiceResult, + ServiceResult, +} from '../../common/interfaces/service.result.js'; +import { PurgaCategoria } from './dto/purga.dto.js'; + +interface TablaPurga { + nombre: string; + repo: Repository; + /// Fragmento WHERE por categoría (columnas camelCase → entrecomilladas). + fragmentos: Partial>; +} + +/** + * Purga física total por categoría (endpoint solo Developer). + * + * La DB no tiene FKs (entities de columnas planas + synchronize): el orden + * "hijos primero" vive acá y está fijado por el orden de `tablas()`. Los + * `*Por`/audit de filas que sobreviven pueden quedar apuntando a personas + * borradas (solo auditoría; no se resuelven nombres en la UI). + */ +@Injectable() +export class MantenimientoService { + constructor( + @InjectRepository(Asistencia) + private asistenciaRepo: Repository, + @InjectRepository(Reemplazo) private reemplazoRepo: Repository, + @InjectRepository(SolicitudApoyo) + private solicitudApoyoRepo: Repository, + @InjectRepository(EquipoPersona) + private equipoPersonaRepo: Repository, + @InjectRepository(CodigoOtp) private codigoOtpRepo: Repository, + @InjectRepository(Dispositivo) + private dispositivoRepo: Repository, + @InjectRepository(ServicioEquipo) + private servicioEquipoRepo: Repository, + @InjectRepository(ServicioTurno) + private servicioTurnoRepo: Repository, + @InjectRepository(Equipo) private equipoRepo: Repository, + @InjectRepository(Servicio) private servicioRepo: Repository, + @InjectRepository(Turno) private turnoRepo: Repository, + @InjectRepository(Persona) private personaRepo: Repository, + ) {} + + /// Orden = orden de borrado (hijos primero). `1 = 1` = tabla completa. + private tablas(): TablaPurga[] { + return [ + { + nombre: 'asistencia', + repo: this.asistenciaRepo, + fragmentos: { + equipos: '"idEquipo" IS NOT NULL', + servicios: '"idServicio" IS NOT NULL', + personas: '"idPersona" IS NOT NULL', + }, + }, + { + nombre: 'reemplazo', + repo: this.reemplazoRepo, + fragmentos: { + equipos: '"idEquipo" IS NOT NULL', + servicios: '"idServicio" IS NOT NULL', + personas: + '("idPersonaTitular" IS NOT NULL OR "idPersonaReemplazo" IS NOT NULL)', + }, + }, + { + nombre: 'solicitud_apoyo', + repo: this.solicitudApoyoRepo, + fragmentos: { + equipos: '"idEquipo" IS NOT NULL', + servicios: '"idServicio" IS NOT NULL', + }, + }, + { + nombre: 'equipo_persona', + repo: this.equipoPersonaRepo, + fragmentos: { + equipos: '"idEquipo" IS NOT NULL', + personas: '"idPersona" IS NOT NULL', + }, + }, + { + nombre: 'codigo_otp', + repo: this.codigoOtpRepo, + fragmentos: { personas: '"idPersona" IS NOT NULL' }, + }, + { + nombre: 'dispositivo', + repo: this.dispositivoRepo, + fragmentos: { personas: '"idPersona" IS NOT NULL' }, + }, + { + nombre: 'servicio_equipo', + repo: this.servicioEquipoRepo, + fragmentos: { + equipos: '"idEquipo" IS NOT NULL', + servicios: '"idServicio" IS NOT NULL', + }, + }, + { + nombre: 'servicio_turno', + repo: this.servicioTurnoRepo, + fragmentos: { + servicios: '"idServicio" IS NOT NULL', + turnos: '"idTurno" IS NOT NULL', + }, + }, + { + nombre: 'equipo', + repo: this.equipoRepo, + fragmentos: { equipos: '1 = 1' }, + }, + { + nombre: 'servicio', + repo: this.servicioRepo, + fragmentos: { servicios: '1 = 1' }, + }, + { + nombre: 'turno', + repo: this.turnoRepo, + fragmentos: { turnos: '1 = 1' }, + }, + { + nombre: 'persona', + repo: this.personaRepo, + fragmentos: { personas: '1 = 1' }, + }, + ]; + } + + private whereDe( + tabla: TablaPurga, + categorias: PurgaCategoria[], + ): string | null { + const partes = categorias + .map((categoria) => tabla.fragmentos[categoria]) + .filter((fragmento): fragmento is string => Boolean(fragmento)); + + if (partes.length === 0) return null; + return partes.length === 1 ? partes[0] : `(${partes.join(' OR ')})`; + } + + /** + * Cuenta (dryRun) o borra las filas que impactan las categorías. + * `object` = `{ dryRun, filas: { tabla: n, ... } }` (todas las tablas con + * fragmento para la selección; la UI filtra las que son 0). + */ + async purgar( + categorias: PurgaCategoria[], + dryRun: boolean, + ): Promise { + const serviceResult = defaultServiceResult(); + const filas: Record = {}; + + for (const tabla of this.tablas()) { + const where = this.whereDe(tabla, categorias); + if (!where) continue; + + const conteo = await tabla.repo + .createQueryBuilder('t') + .where(where) + .getCount(); + filas[tabla.nombre] = conteo; + + if (!dryRun && conteo > 0) { + await tabla.repo.createQueryBuilder().delete().where(where).execute(); + } + } + + const total = Object.values(filas).reduce((suma, n) => suma + n, 0); + + serviceResult.boolean = true; + serviceResult.message = dryRun + ? `Previsualización: ${total} fila(s) se eliminarían.` + : `Borrado físico completado: ${total} fila(s) eliminadas.`; + serviceResult.number = total; + serviceResult.object = { dryRun, filas }; + + return serviceResult; + } +} diff --git a/src/modules/reportes/dto/reporte.dto.ts b/src/modules/reportes/dto/reporte.dto.ts new file mode 100644 index 0000000..028aa1b --- /dev/null +++ b/src/modules/reportes/dto/reporte.dto.ts @@ -0,0 +1,25 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsIn, IsObject, IsOptional } from 'class-validator'; + +/** Tipos de reporte exportables a PDF. */ +export const TIPOS_REPORTE = [ + 'asistencia-servicio', + 'asistencia-persona', + 'resumen-equipo', + 'faltas-permisos', + 'atrasos', +] as const; + +export type TipoReporte = (typeof TIPOS_REPORTE)[number]; + +export class ReportePdfDto { + @ApiProperty({ enum: TIPOS_REPORTE }) + @IsIn(TIPOS_REPORTE) + tipo: TipoReporte; + + /** Mismos parámetros que el GET del reporte (idServicio / desde / hasta…). */ + @ApiProperty({ required: false }) + @IsObject() + @IsOptional() + parametros?: Record; +} diff --git a/src/modules/reportes/entities/reporte.entity.ts b/src/modules/reportes/entities/reporte.entity.ts new file mode 100644 index 0000000..095a4f6 --- /dev/null +++ b/src/modules/reportes/entities/reporte.entity.ts @@ -0,0 +1,24 @@ +import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; + +/** Historial de PDFs exportados desde Reportes (link en `rutaArchivo`). */ +@Entity('reporte') +export class Reporte { + @PrimaryGeneratedColumn('uuid') + idReporte: string; + + @Column({ type: 'varchar' }) + tipo: string; + + @Column({ type: 'jsonb', nullable: true }) + parametros?: Record | null; + + /** Ruta relativa del archivo físico bajo `uploads/` (se sirve estático). */ + @Column({ type: 'varchar' }) + rutaArchivo: string; + + @Column({ type: 'uuid' }) + generadoPor: string; + + @Column({ type: 'timestamptz', default: () => 'now()' }) + generadoEn: Date; +} diff --git a/src/modules/reportes/reportes.controller.ts b/src/modules/reportes/reportes.controller.ts new file mode 100644 index 0000000..1852f36 --- /dev/null +++ b/src/modules/reportes/reportes.controller.ts @@ -0,0 +1,210 @@ +import { + Body, + Controller, + Get, + HttpStatus, + Post, + Query, + Req, +} from '@nestjs/common'; +import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'; +import { Autorizacion } from '../../common/decorators/autorizacion.decorator.js'; +import { Autorizacion as AutorizacionEnum } from '../../common/enums/rol.enum.js'; +import { + ApiResult, + defaultApiResult, +} from '../../common/interfaces/api.result.js'; +import type { AuthRequest } from '../../common/utils/auth-user.js'; +import { getAuthUser } from '../../common/utils/auth-user.js'; +import { ReportePdfDto } from './dto/reporte.dto.js'; +import { ReportesService } from './reportes.service.js'; +import { routeReportes } from './reportes.router.js'; + +@ApiTags('reportes') +@ApiBearerAuth() +@Controller('reportes') +// Developer pasa por bypass de AuthGuard; SuperAdmin y Usuario (Líder) entran +// por aquí y el service exige rol Líder a los que no son globales. +@Autorizacion(AutorizacionEnum.SuperAdmin, AutorizacionEnum.Usuario) +export class ReportesController { + constructor(private readonly reportesService: ReportesService) {} + + @Get('asistencia-servicio') + async asistenciaServicio( + @Req() req: AuthRequest, + @Query('idServicio') idServicio?: string, + @Query('idEquipo') idEquipo?: string, + ): Promise { + const apiResult = defaultApiResult( + routeReportes.asistenciaServicio.title, + routeReportes.asistenciaServicio.route, + ); + try { + const r = await this.reportesService.asistenciaPorServicio( + idServicio, + getAuthUser(req), + idEquipo, + ); + apiResult.status = 'correct'; + apiResult.code = HttpStatus.OK; + apiResult.message = r.message; + apiResult.boolean = true; + apiResult.rows = r.number; + apiResult.data = [r.object]; + } catch (error) { + apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR; + apiResult.message = error.message; + } + return apiResult; + } + + @Get('asistencia-persona') + async asistenciaPersona( + @Req() req: AuthRequest, + @Query('desde') desde?: string, + @Query('hasta') hasta?: string, + @Query('idEquipo') idEquipo?: string, + @Query('idPersona') idPersona?: string, + ): Promise { + const apiResult = defaultApiResult( + routeReportes.asistenciaPersona.title, + routeReportes.asistenciaPersona.route, + ); + try { + const r = await this.reportesService.asistenciaPorPersona( + desde, + hasta, + getAuthUser(req), + idEquipo, + idPersona, + ); + apiResult.status = 'correct'; + apiResult.code = HttpStatus.OK; + apiResult.message = r.message; + apiResult.boolean = true; + apiResult.rows = r.number; + apiResult.data = [r.object]; + } catch (error) { + apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR; + apiResult.message = error.message; + } + return apiResult; + } + + @Get('resumen-equipo') + async resumenEquipo( + @Req() req: AuthRequest, + @Query('desde') desde?: string, + @Query('hasta') hasta?: string, + ): Promise { + const apiResult = defaultApiResult( + routeReportes.resumenEquipo.title, + routeReportes.resumenEquipo.route, + ); + try { + const r = await this.reportesService.resumenPorEquipo( + desde, + hasta, + getAuthUser(req), + ); + apiResult.status = 'correct'; + apiResult.code = HttpStatus.OK; + apiResult.message = r.message; + apiResult.boolean = true; + apiResult.rows = r.number; + apiResult.data = [r.object]; + } catch (error) { + apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR; + apiResult.message = error.message; + } + return apiResult; + } + + @Get('faltas-permisos') + async faltasPermisos( + @Req() req: AuthRequest, + @Query('desde') desde?: string, + @Query('hasta') hasta?: string, + @Query('idEquipo') idEquipo?: string, + ): Promise { + const apiResult = defaultApiResult( + routeReportes.faltasPermisos.title, + routeReportes.faltasPermisos.route, + ); + try { + const r = await this.reportesService.faltasPermisos( + desde, + hasta, + getAuthUser(req), + idEquipo, + ); + apiResult.status = 'correct'; + apiResult.code = HttpStatus.OK; + apiResult.message = r.message; + apiResult.boolean = true; + apiResult.rows = r.number; + apiResult.data = [r.object]; + } catch (error) { + apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR; + apiResult.message = error.message; + } + return apiResult; + } + + @Get('atrasos') + async atrasos( + @Req() req: AuthRequest, + @Query('desde') desde?: string, + @Query('hasta') hasta?: string, + ): Promise { + const apiResult = defaultApiResult( + routeReportes.atrasos.title, + routeReportes.atrasos.route, + ); + try { + const r = await this.reportesService.atrasos( + desde, + hasta, + getAuthUser(req), + ); + apiResult.status = 'correct'; + apiResult.code = HttpStatus.OK; + apiResult.message = r.message; + apiResult.boolean = true; + apiResult.rows = r.number; + apiResult.data = [r.object]; + } catch (error) { + apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR; + apiResult.message = error.message; + } + return apiResult; + } + + @Post('pdf') + async exportarPdf( + @Req() req: AuthRequest, + @Body() reporteDto: ReportePdfDto, + ): Promise { + const apiResult = defaultApiResult( + routeReportes.pdf.title, + routeReportes.pdf.route, + ); + try { + const r = await this.reportesService.generarPdf( + reporteDto.tipo, + reporteDto.parametros, + getAuthUser(req), + ); + apiResult.status = 'correct'; + apiResult.code = HttpStatus.OK; + apiResult.message = r.message; + apiResult.boolean = true; + apiResult.rows = r.number; + apiResult.data = [r.object]; + } catch (error) { + apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR; + apiResult.message = error.message; + } + return apiResult; + } +} diff --git a/src/modules/reportes/reportes.module.ts b/src/modules/reportes/reportes.module.ts new file mode 100644 index 0000000..56fc895 --- /dev/null +++ b/src/modules/reportes/reportes.module.ts @@ -0,0 +1,13 @@ +import { Module } from '@nestjs/common'; +import { TypeOrmModule } from '@nestjs/typeorm'; +import { Persona } from '../persona/entities/persona.entity.js'; +import { Reporte } from './entities/reporte.entity.js'; +import { ReportesController } from './reportes.controller.js'; +import { ReportesService } from './reportes.service.js'; + +@Module({ + imports: [TypeOrmModule.forFeature([Persona, Reporte])], + controllers: [ReportesController], + providers: [ReportesService], +}) +export class ReportesModule {} diff --git a/src/modules/reportes/reportes.router.ts b/src/modules/reportes/reportes.router.ts new file mode 100644 index 0000000..4983ac8 --- /dev/null +++ b/src/modules/reportes/reportes.router.ts @@ -0,0 +1,26 @@ +export const routeReportes = { + asistenciaServicio: { + route: '[GET].../v1/reportes/asistencia-servicio', + title: 'Reporte de asistencia por servicio', + }, + asistenciaPersona: { + route: '[GET].../v1/reportes/asistencia-persona', + title: 'Reporte de asistencia por persona', + }, + resumenEquipo: { + route: '[GET].../v1/reportes/resumen-equipo', + title: 'Reporte resumen por equipo', + }, + faltasPermisos: { + route: '[GET].../v1/reportes/faltas-permisos', + title: 'Reporte de faltas y permisos', + }, + atrasos: { + route: '[GET].../v1/reportes/atrasos', + title: 'Reporte de atrasos', + }, + pdf: { + route: '[POST].../v1/reportes/pdf', + title: 'Exportar reporte a PDF', + }, +}; diff --git a/src/modules/reportes/reportes.service.ts b/src/modules/reportes/reportes.service.ts new file mode 100644 index 0000000..44bbdae --- /dev/null +++ b/src/modules/reportes/reportes.service.ts @@ -0,0 +1,993 @@ +import { + BadRequestException, + ForbiddenException, + Injectable, +} from '@nestjs/common'; +import { InjectRepository } from '@nestjs/typeorm'; +import { randomUUID } from 'node:crypto'; +import { existsSync, mkdirSync, createWriteStream } from 'node:fs'; +import { join } from 'node:path'; +import PDFDocument from 'pdfkit'; +import { Repository } from 'typeorm'; +import { + EstadoAsistencia, + EstadoGeneral, + EstadoMiembro, + EstadoServicio, +} from '../../common/enums/estados.enum.js'; +import { Autorizacion, Rol } from '../../common/enums/rol.enum.js'; +import { + AuthUser, + isDeveloper, + isSuperAdmin, +} from '../../common/utils/auth-user.js'; +import { + defaultServiceResult, + ServiceResult, +} from '../../common/interfaces/service.result.js'; +import { Persona } from '../persona/entities/persona.entity.js'; +import { Reporte } from './entities/reporte.entity.js'; +import { TipoReporte } from './dto/reporte.dto.js'; + +/** Fila cruda de los reportes (JSON para el front, base de las tablas PDF). */ +type Fila = Record; + +interface Col { + header: string; + width: number; + get: (fila: Fila) => string; +} + +interface EncabezadoControl { + /** Nombre(s) del equipo (convención: uno por servicio). */ + equipo: string; + /** Nombre del servicio (REUNIÓN). */ + reunion: string; + /** Fecha larga: "25 de Oct. de 2026". */ + fecha: string; +} + +interface DatosReporte { + titulo: string; + columnas: Col[]; + filas: Fila[]; + /** Solo el reporte por servicio: servidores marcados en esta corrida. */ + inhabilitados?: Fila[]; + /** Solo asistencia-servicio: encabezado "CONTROL DE ASISTENCIA" (Letter). */ + control?: EncabezadoControl; +} + +const ESTADOS_REALIZADO = [ + EstadoServicio.Publicado, + EstadoServicio.EnCurso, + EstadoServicio.Finalizado, +]; + +const MESES_CORTOS = [ + 'Ene.', + 'Feb.', + 'Mar.', + 'Abr.', + 'May.', + 'Jun.', + 'Jul.', + 'Ago.', + 'Sep.', + 'Oct.', + 'Nov.', + 'Dic.', +]; + +@Injectable() +export class ReportesService { + constructor( + @InjectRepository(Persona) + private readonly personaRepository: Repository, + @InjectRepository(Reporte) + private readonly reporteRepository: Repository, + ) {} + + // ---------------------------------------------------------------- acceso + + /** Developer (bypass) y SuperAdmin ven todo; solo el Líder ve reportes. */ + private validarAcceso(user: AuthUser | null): void { + if (isDeveloper(user) || isSuperAdmin(user)) return; + if (user?.rol !== Rol.Lider) { + throw new ForbiddenException( + 'Solo Developer, SuperAdmin o Líder pueden generar reportes.', + ); + } + } + + /** `null` = sin scoping (Developer/SuperAdmin); si no, equipos activos del líder. */ + private async equiposScope(user: AuthUser | null): Promise { + if (isDeveloper(user) || isSuperAdmin(user)) return null; + const rows: { idEquipo: string }[] = + await this.personaRepository.manager.query( + `SELECT "idEquipo" FROM equipo_persona + WHERE "idPersona" = $1 AND estado = $2`, + [user?.idPersona, EstadoMiembro.Activo], + ); + return rows.map((r) => r.idEquipo); + } + + private validarRango(desde?: string, hasta?: string): void { + const iso = /^\d{4}-\d{2}-\d{2}$/; + if (!desde || !iso.test(desde) || !hasta || !iso.test(hasta)) { + throw new BadRequestException( + 'Rango de fechas inválido: usá el formato YYYY-MM-DD (desde y hasta).', + ); + } + if (desde > hasta) { + throw new BadRequestException( + 'El rango de fechas es inválido (desde > hasta).', + ); + } + } + + // ------------------------------------------------------------ reportes + + async asistenciaPorServicio( + idServicio: string | undefined, + user: AuthUser | null, + idEquipo?: string, + ): Promise { + this.validarAcceso(user); + if (!idServicio) { + throw new BadRequestException('Falta el parámetro idServicio.'); + } + + const manager = this.personaRepository.manager; + const servicioRows: Fila[] = await manager.query( + `SELECT "idServicio", nombre, + to_char(fecha, 'YYYY-MM-DD') AS fecha, + estado + FROM servicio + WHERE "idServicio" = $1 AND estado <> $2`, + [idServicio, EstadoServicio.Eliminado], + ); + if (!servicioRows.length) { + throw new BadRequestException('No existe el servicio.'); + } + + // Convocados con su nombre (para el selector de equipo del front). + const convocados: Fila[] = await manager.query( + `SELECT se."idEquipo", e."nombreEquipo" + FROM servicio_equipo se + JOIN equipo e ON e."idEquipo" = se."idEquipo" + WHERE se."idServicio" = $1 + ORDER BY e."nombreEquipo"`, + [idServicio], + ); + + // Scoping Líder: solo sus equipos (membresía Activa ∩ convocados). + let equipos: string[] | null = await this.equiposScope(user); + if (equipos !== null) { + const set = new Set(equipos); + equipos = convocados + .map((c) => c.idEquipo as string) + .filter((id) => set.has(id)); + if (!equipos.length) { + throw new ForbiddenException( + 'Solo el líder de un equipo convocado del servicio puede ver el reporte.', + ); + } + } + + // Selector de equipo (un equipo o "Todos"): si viene idEquipo debe ser + // uno de los convocados (y del scoping del líder). + const convocadoSet = new Set(convocados.map((c) => c.idEquipo as string)); + if (idEquipo) { + if (!convocadoSet.has(idEquipo)) { + throw new BadRequestException( + 'El equipo no está convocado en el servicio.', + ); + } + if (equipos !== null && !equipos.includes(idEquipo)) { + throw new ForbiddenException('No podés ver reportes de ese equipo.'); + } + } + + // Título del reporte: un equipo → "Equipo X - Reporte"; Todos → + // "Ministerio Ser - Reporte". + const nombreEquipoSel = idEquipo + ? (convocados.find((c) => c.idEquipo === idEquipo) + ?.nombreEquipo as string) + : null; + const titulo = nombreEquipoSel + ? `${nombreEquipoSel} - Reporte` + : 'Ministerio Ser - Reporte'; + + const turnos: Fila[] = await manager.query( + `SELECT t.nombre, + t.tipo, + t."horaInicio", + t."horaFin", + st.sec + FROM servicio_turno st + JOIN turno t ON t."idTurno" = st."idTurno" + WHERE st."idServicio" = $1 + ORDER BY st.sec`, + [idServicio], + ); + + const paramsFilas: unknown[] = [idServicio]; + let whereFilas = 'a."idServicio" = $1'; + if (idEquipo) { + paramsFilas.push(idEquipo); + whereFilas += ' AND a."idEquipo" = $2'; + } else if (equipos !== null) { + paramsFilas.push(`{${equipos.join(',')}}`); + whereFilas += ' AND a."idEquipo" = ANY($2::uuid[])'; + } + + const filas: Fila[] = await manager.query( + `SELECT a."idAsistencia", + p."idPersona", + p.nombres, + p.apellidos, + p.nombres || ' ' || p.apellidos AS persona, + p.rol, + p.estado AS "estadoPersona", + e."nombreEquipo" AS equipo, + a.estado, + a."fecIngreso" IS NOT NULL AS "tieneIngreso", + to_char(a."fecIngreso", 'HH24:MI DD-MM-YYYY') AS ingreso, + to_char(a."fecSalida", 'HH24:MI DD-MM-YYYY') AS salida, + a.observacion + FROM asistencia a + JOIN persona p ON p."idPersona" = a."idPersona" + JOIN equipo e ON e."idEquipo" = a."idEquipo" + WHERE ${whereFilas} + ORDER BY e."nombreEquipo", p.apellidos, p.nombres`, + paramsFilas, + ); + + // Subrutina de la tanda: servidores activos sin ingreso en 3 meses + // calendario → Inhabilitado (solo al generar este reporte). No es un + // bloqueo: la persona sigue pudiendo entrar y marcar (rehabilita sola). + const inhabilitados = await this.evaluarInhabilitados(); + + // `equiposVisibles` acota el selector del front al scoping del líder. + const equiposVisibles = + equipos === null + ? convocados + : convocados.filter((c) => equipos!.includes(c.idEquipo as string)); + + return this.ok( + titulo, + filas, + { + ...servicioRows[0], + titulo, + equipos: equiposVisibles, + turnos, + filas, + }, + inhabilitados, + ); + } + + async asistenciaPorPersona( + desde: string | undefined, + hasta: string | undefined, + user: AuthUser | null, + idEquipo?: string, + idPersona?: string, + ): Promise { + this.validarAcceso(user); + this.validarRango(desde, hasta); + const scope = await this.equiposScope(user); + + const filtros: string[] = [ + 's.estado = ANY($1)', + 's.fecha >= $2::date', + 's.fecha <= $3::date', + ]; + const params: unknown[] = [ + `{${ESTADOS_REALIZADO.join(',')}}`, + desde, + hasta, + ]; + if (scope !== null) { + filtros.push('a."idEquipo" = ANY($4::uuid[])'); + params.push(`{${scope.join(',')}}`); + } + if (idEquipo) { + params.push(idEquipo); + filtros.push(`a."idEquipo" = $${params.length}`); + } + if (idPersona) { + params.push(idPersona); + filtros.push(`a."idPersona" = $${params.length}`); + } + + const filas: Fila[] = await this.personaRepository.manager.query( + `SELECT p."idPersona", + p.nombres || ' ' || p.apellidos AS persona, + p.rol, + p.estado AS "estadoPersona", + COUNT(*)::int AS convocados, + COUNT(*) FILTER (WHERE a.estado IN ('Presente','Atrasado'))::int AS ingresados, + COUNT(*) FILTER (WHERE a.estado = 'Presente')::int AS presentes, + COUNT(*) FILTER (WHERE a.estado = 'Atrasado')::int AS atrasados, + COUNT(*) FILTER (WHERE a.estado = 'Permiso')::int AS permisos, + COUNT(*) FILTER (WHERE a.estado = 'Falta')::int AS faltas, + COUNT(*) FILTER (WHERE a.estado = 'Pendiente')::int AS pendientes + FROM asistencia a + JOIN persona p ON p."idPersona" = a."idPersona" + JOIN servicio s ON s."idServicio" = a."idServicio" + WHERE ${filtros.join(' AND ')} + GROUP BY p."idPersona", p.nombres, p.apellidos, p.rol, p.estado + ORDER BY (COUNT(*) FILTER (WHERE a.estado IN ('Presente','Atrasado'))::float + / NULLIF(COUNT(*), 0)) DESC, persona`, + params, + ); + + return this.ok('Reporte de asistencia por persona.', filas, { + desde, + hasta, + idEquipo, + idPersona, + }); + } + + async resumenPorEquipo( + desde: string | undefined, + hasta: string | undefined, + user: AuthUser | null, + ): Promise { + this.validarAcceso(user); + this.validarRango(desde, hasta); + const scope = await this.equiposScope(user); + + const filtros: string[] = [ + 's.estado = ANY($1)', + 's.fecha >= $2::date', + 's.fecha <= $3::date', + ]; + const params: unknown[] = [ + `{${ESTADOS_REALIZADO.join(',')}}`, + desde, + hasta, + ]; + if (scope !== null) { + filtros.push('a."idEquipo" = ANY($4::uuid[])'); + params.push(`{${scope.join(',')}}`); + } + + const filas: Fila[] = await this.personaRepository.manager.query( + `SELECT e."idEquipo", + e."nombreEquipo" AS equipo, + COUNT(*)::int AS convocados, + COUNT(*) FILTER (WHERE a.estado IN ('Presente','Atrasado'))::int AS ingresados, + COUNT(*) FILTER (WHERE a.estado = 'Atrasado')::int AS atrasados, + COUNT(*) FILTER (WHERE a.estado = 'Permiso')::int AS permisos, + COUNT(*) FILTER (WHERE a.estado = 'Falta')::int AS faltas, + COUNT(*) FILTER (WHERE a.estado = 'Pendiente')::int AS pendientes + FROM asistencia a + JOIN equipo e ON e."idEquipo" = a."idEquipo" + JOIN servicio s ON s."idServicio" = a."idServicio" + WHERE ${filtros.join(' AND ')} + GROUP BY e."idEquipo", e."nombreEquipo" + ORDER BY (COUNT(*) FILTER (WHERE a.estado IN ('Presente','Atrasado'))::float + / NULLIF(COUNT(*), 0)) DESC, e."nombreEquipo"`, + params, + ); + + return this.ok('Reporte resumen por equipo.', filas, { desde, hasta }); + } + + async faltasPermisos( + desde: string | undefined, + hasta: string | undefined, + user: AuthUser | null, + idEquipo?: string, + ): Promise { + this.validarAcceso(user); + this.validarRango(desde, hasta); + const scope = await this.equiposScope(user); + + const filtros: string[] = [ + `a.estado IN ('Falta','Permiso')`, + 's.estado = ANY($1)', + 's.fecha >= $2::date', + 's.fecha <= $3::date', + ]; + const params: unknown[] = [ + `{${ESTADOS_REALIZADO.join(',')}}`, + desde, + hasta, + ]; + if (scope !== null) { + filtros.push('a."idEquipo" = ANY($4::uuid[])'); + params.push(`{${scope.join(',')}}`); + } + if (idEquipo) { + filtros.push(`a."idEquipo" = $${params.length + 1}`); + params.push(idEquipo); + } + + const filas: Fila[] = await this.personaRepository.manager.query( + `SELECT to_char(s.fecha, 'YYYY-MM-DD') AS fecha, + s.nombre AS servicio, + p.nombres || ' ' || p.apellidos AS persona, + e."nombreEquipo" AS equipo, + a.estado, + COALESCE(a.observacion, '') AS observacion + FROM asistencia a + JOIN persona p ON p."idPersona" = a."idPersona" + JOIN equipo e ON e."idEquipo" = a."idEquipo" + JOIN servicio s ON s."idServicio" = a."idServicio" + WHERE ${filtros.join(' AND ')} + ORDER BY s.fecha DESC, e."nombreEquipo", p.apellidos`, + params, + ); + + return this.ok('Reporte de faltas y permisos.', filas, { + desde, + hasta, + idEquipo, + }); + } + + async atrasos( + desde: string | undefined, + hasta: string | undefined, + user: AuthUser | null, + ): Promise { + this.validarAcceso(user); + this.validarRango(desde, hasta); + const scope = await this.equiposScope(user); + + const filtros: string[] = [ + 's.estado = ANY($1)', + 's.fecha >= $2::date', + 's.fecha <= $3::date', + ]; + const params: unknown[] = [ + `{${ESTADOS_REALIZADO.join(',')}}`, + desde, + hasta, + ]; + if (scope !== null) { + filtros.push('a."idEquipo" = ANY($4::uuid[])'); + params.push(`{${scope.join(',')}}`); + } + + const filas: Fila[] = await this.personaRepository.manager.query( + `SELECT p."idPersona", + p.nombres || ' ' || p.apellidos AS persona, + string_agg(DISTINCT e."nombreEquipo", ', ' ORDER BY e."nombreEquipo") AS equipo, + COUNT(*) FILTER (WHERE a.estado = 'Atrasado')::int AS atrasados, + COUNT(*)::int AS convocados + FROM asistencia a + JOIN persona p ON p."idPersona" = a."idPersona" + JOIN equipo e ON e."idEquipo" = a."idEquipo" + JOIN servicio s ON s."idServicio" = a."idServicio" + WHERE ${filtros.join(' AND ')} + GROUP BY p."idPersona", p.nombres, p.apellidos + HAVING COUNT(*) FILTER (WHERE a.estado = 'Atrasado') > 0 + ORDER BY atrasados DESC, persona`, + params, + ); + + return this.ok('Reporte de atrasos.', filas, { desde, hasta }); + } + + // ------------------------------------------------------- inhabilitados + + /** + * Servidores con membresía activa, `estado = Activo` y **cero ingresos** + * (Presente/Atrasado con `fecIngreso`) en los últimos 3 meses calendario + * → pasan a `Inhabilitado`. Devuelve los marcados en esta corrida. + */ + private async evaluarInhabilitados(): Promise { + const manager = this.personaRepository.manager; + const candidatos: Fila[] = await manager.query( + `SELECT p."idPersona", + p.nombres || ' ' || p.apellidos AS persona, + p.whatsapp + FROM persona p + WHERE p.rol = $1 + AND p.estado = $2 + AND p.autorizacion = $6 + AND EXISTS ( + SELECT 1 FROM equipo_persona ep + WHERE ep."idPersona" = p."idPersona" + AND ep.estado = $3 + ) + AND NOT EXISTS ( + SELECT 1 FROM asistencia a + WHERE a."idPersona" = p."idPersona" + AND a."fecIngreso" IS NOT NULL + AND a.estado IN ($4, $5) + AND a."fecIngreso" >= now() - interval '3 months' + )`, + [ + Rol.Servidor, + EstadoGeneral.Activo, + EstadoMiembro.Activo, + EstadoAsistencia.Presente, + EstadoAsistencia.Atrasado, + Autorizacion.Usuario, + ], + ); + if (!candidatos.length) return []; + + const ids = candidatos.map((c) => c.idPersona as string); + await manager.query( + `UPDATE persona SET estado = $1 WHERE "idPersona" = ANY($2::uuid[])`, + [EstadoGeneral.Inhabilitado, `{${ids.join(',')}}`], + ); + return candidatos; + } + + // ---------------------------------------------------------------- PDF + + /** Exporta el reporte a PDF en `uploads/reportes/` y registra el link. */ + async generarPdf( + tipo: TipoReporte, + parametros: Record | undefined, + user: AuthUser | null, + ): Promise { + this.validarAcceso(user); + + const p = parametros ?? {}; + let datos: DatosReporte; + switch (tipo) { + case 'asistencia-servicio': + datos = await this.datosAsistenciaServicio( + p.idServicio as string, + user, + p.idEquipo as string | undefined, + ); + break; + case 'asistencia-persona': + datos = this.extraer( + tipo, + await this.asistenciaPorPersona( + p.desde as string, + p.hasta as string, + user, + p.idEquipo as string | undefined, + p.idPersona as string | undefined, + ), + ); + break; + case 'resumen-equipo': + datos = this.extraer( + tipo, + await this.resumenPorEquipo( + p.desde as string, + p.hasta as string, + user, + ), + ); + break; + case 'faltas-permisos': + datos = this.extraer( + tipo, + await this.faltasPermisos( + p.desde as string, + p.hasta as string, + user, + p.idEquipo as string | undefined, + ), + ); + break; + case 'atrasos': + datos = this.extraer( + tipo, + await this.atrasos(p.desde as string, p.hasta as string, user), + ); + break; + default: + throw new ForbiddenException('Tipo de reporte inválido.'); + } + + const idPersona = (user?.idPersona ?? '') as string; + const generadoPor = await this.personaRepository.findOneBy({ + idPersona, + }); + const nombreGenerado = generadoPor + ? `${generadoPor.nombres} ${generadoPor.apellidos}` + : 'Sistema'; + + const dir = join(process.cwd(), 'uploads', 'reportes'); + mkdirSync(dir, { recursive: true }); + const archivo = `${new Date().toISOString().slice(0, 10)}-${tipo}-${randomUUID()}.pdf`; + const rutaRel = `uploads/reportes/${archivo}`; + const url = `/uploads/reportes/${archivo}`; + + await this.renderPdf(dir, archivo, datos, nombreGenerado); + + const fila = await this.reporteRepository.save({ + tipo, + parametros: p, + rutaArchivo: rutaRel, + generadoPor: idPersona, + }); + + const serviceResult = defaultServiceResult(); + serviceResult.boolean = true; + serviceResult.message = 'PDF generado correctamente.'; + serviceResult.number = 1; + serviceResult.object = { + idReporte: fila.idReporte, + url, + titulo: datos.titulo, + filas: datos.filas.length, + }; + return serviceResult; + } + + /** Convierte el ServiceResult de un GET en los datos para renderizar. */ + private extraer(tipo: TipoReporte, result: ServiceResult): DatosReporte { + return { + titulo: result.message, + columnas: this.columnasDe(tipo), + filas: result.data ?? [], + }; + } + + private ok( + message: string, + filas: Fila[], + objeto: Record, + inhabilitados?: Fila[], + ): ServiceResult { + const serviceResult = defaultServiceResult(); + serviceResult.boolean = true; + serviceResult.message = message; + serviceResult.number = filas.length; + serviceResult.data = filas; + serviceResult.object = { + ...objeto, + titulo: message, + filas, + inhabilitados: inhabilitados ?? [], + }; + return serviceResult; + } + + // El método de datos por servicio se separa para poder reutilizarlo en el + // PDF con su side-effect de inhabilitados incluido. + private async datosAsistenciaServicio( + idServicio: string | undefined, + user: AuthUser | null, + idEquipo?: string, + ): Promise { + const result = await this.asistenciaPorServicio(idServicio, user, idEquipo); + const objeto = result.object as { + nombre?: string; + fecha?: string; + equipos?: { nombreEquipo?: string }[]; + }; + // Numeración para la columna "N" del CONTROL DE ASISTENCIA. + const filas = (result.data ?? []).map((f, i) => ({ ...f, n: i + 1 })); + // EQUIPO del encabezado: el de las filas (con idEquipo filtrado ya vienen + // solo de ese equipo); sin filas, los equipos visibles (convocados). + const porFilas = [ + ...new Set( + filas + .map((f) => (f.equipo == null ? '' : String(f.equipo))) + .filter((v) => v !== ''), + ), + ]; + const nombres = + porFilas.length > 0 + ? porFilas + : (objeto.equipos ?? []).map((e) => e.nombreEquipo ?? ''); + return { + // `result.message` ya es el título calculado ("Equipo X - Reporte" o + // "Ministerio Ser - Reporte"); se le agrega el detalle del servicio. + titulo: + `${result.message} — ${objeto.nombre ?? ''} (${objeto.fecha ?? ''})`.trim(), + columnas: this.columnasDe('asistencia-servicio'), + filas, + control: { + equipo: nombres.filter(Boolean).join(' · ') || '—', + reunion: objeto.nombre ?? '', + fecha: this.fechaTexto(objeto.fecha), + }, + }; + } + + /** "2026-10-21" → "21 de Oct. de 2026" (encabezado del reporte Letter). */ + private fechaTexto(iso?: string): string { + const partes = (iso ?? '').split('-'); + if (partes.length !== 3) return '—'; + const [anio, mes, dia] = partes; + const mesTxt = MESES_CORTOS[Number(mes) - 1]; + if (!mesTxt) return '—'; + return `${Number(dia)} de ${mesTxt} de ${anio}`; + } + + /** Definición de columnas de cada reporte para la tabla del PDF. */ + private columnasDe(tipo: TipoReporte | string): Col[] { + const str = (v: unknown) => (v == null ? '' : String(v)); + const hora = (v: unknown) => str(v) || '—'; + const pct = (ing: unknown, conv: unknown) => + Number(conv) > 0 + ? `${((Number(ing) * 100) / Number(conv)).toFixed(1)}%` + : '—'; + + switch (tipo) { + // CONTROL DE ASISTENCIA (Letter): N | NOMBRES | APELLIDOS | INGRESO | + // SALIDA | ASISTENCIA (estado de la asistencia, texto de la DB) | + // ESTADO (persona.estado en mayúsculas). Suma 532pt = Letter - márgenes. + case 'asistencia-servicio': + return [ + { header: 'N', width: 26, get: (f) => str(f.n) }, + { header: 'NOMBRES', width: 92, get: (f) => str(f.nombres) }, + { header: 'APELLIDOS', width: 92, get: (f) => str(f.apellidos) }, + { header: 'INGRESO', width: 96, get: (f) => hora(f.ingreso) }, + { header: 'SALIDA', width: 96, get: (f) => hora(f.salida) }, + { header: 'ASISTENCIA', width: 66, get: (f) => str(f.estado) }, + { + header: 'ESTADO', + width: 64, + get: (f) => str(f.estadoPersona).toUpperCase(), + }, + ]; + case 'asistencia-persona': + return [ + { header: 'Persona', width: 150, get: (f) => str(f.persona) }, + { header: 'Conv.', width: 45, get: (f) => str(f.convocados) }, + { header: 'Ing.', width: 45, get: (f) => str(f.ingresados) }, + { header: 'Atraso', width: 50, get: (f) => str(f.atrasados) }, + { header: 'Permiso', width: 55, get: (f) => str(f.permisos) }, + { header: 'Falta', width: 45, get: (f) => str(f.faltas) }, + { header: 'Pend.', width: 50, get: (f) => str(f.pendientes) }, + { + header: '% asist.', + width: 60, + get: (f) => pct(f.ingresados, f.convocados), + }, + ]; + case 'resumen-equipo': + return [ + { header: 'Equipo', width: 150, get: (f) => str(f.equipo) }, + { header: 'Conv.', width: 50, get: (f) => str(f.convocados) }, + { header: 'Ing.', width: 50, get: (f) => str(f.ingresados) }, + { header: 'Atraso', width: 55, get: (f) => str(f.atrasados) }, + { header: 'Permiso', width: 60, get: (f) => str(f.permisos) }, + { header: 'Falta', width: 50, get: (f) => str(f.faltas) }, + { + header: '% asist.', + width: 70, + get: (f) => pct(f.ingresados, f.convocados), + }, + ]; + case 'faltas-permisos': + return [ + { header: 'Fecha', width: 70, get: (f) => str(f.fecha) }, + { header: 'Servicio', width: 120, get: (f) => str(f.servicio) }, + { header: 'Persona', width: 140, get: (f) => str(f.persona) }, + { header: 'Equipo', width: 90, get: (f) => str(f.equipo) }, + { header: 'Estado', width: 60, get: (f) => str(f.estado) }, + { header: 'Observación', width: 90, get: (f) => str(f.observacion) }, + ]; + case 'atrasos': + return [ + { header: 'Persona', width: 150, get: (f) => str(f.persona) }, + { header: 'Equipo', width: 130, get: (f) => str(f.equipo) }, + { header: 'Atrasos', width: 60, get: (f) => str(f.atrasados) }, + { header: 'Conv.', width: 50, get: (f) => str(f.convocados) }, + { + header: '% atraso', + width: 70, + get: (f) => pct(f.atrasados, f.convocados), + }, + ]; + default: + return [{ header: 'Datos', width: 300, get: (f) => JSON.stringify(f) }]; + } + } + + /** Escribe el PDF (pdfkit) y resuelve al terminar el stream. */ + private renderPdf( + dir: string, + archivo: string, + datos: DatosReporte, + generadoPor: string, + ): Promise { + return new Promise((resolve, reject) => { + const doc = new PDFDocument({ + margin: 40, + // Los 5 reportes van en tamaño Carta (tanda 2026-10-22). + size: 'LETTER', + bufferPages: true, + }); + const stream = createWriteStream(join(dir, archivo)); + stream.on('finish', () => resolve()); + stream.on('error', reject); + doc.pipe(stream); + + const cols = datos.columnas; + const left = doc.page.margins.left; + const usable = doc.page.width - left - doc.page.margins.right; + let y: number; + + if (datos.control) { + // --- CONTROL DE ASISTENCIA (Letter): logos + título + campos. --- + y = doc.page.margins.top; + const hLogo = 34; + const rutaSer = join(process.cwd(), 'assets', 'logo-ser.png'); + const rutaEk = join(process.cwd(), 'assets', 'logo-ekklesia.png'); + if (existsSync(rutaSer)) { + doc.image(rutaSer, left, y, { height: hLogo }); + } + if (existsSync(rutaEk)) { + // logo-ekklesia.png mide 1920×600 (relación 3.2): alineado a la + // derecha del área útil. + const wEk = Math.round(hLogo * (1920 / 600)); + doc.image(rutaEk, left + usable - wEk, y, { height: hLogo }); + } + doc + .font('Helvetica-Bold') + .fontSize(16) + .fillColor('#000000') + .text('CONTROL DE ASISTENCIA', left, y + 9, { + width: usable, + align: 'center', + }); + + // Campos: EQUIPO (izq.) · REUNIÓN (centro) · FECHA (der.); la + // etiqueta va en negrita y el valor se trunca con "…" si no cabe. + const yCampos = y + hLogo + 10; + const campo = ( + x: number, + w: number, + alin: 'left' | 'center' | 'right', + etiqueta: string, + valor: string, + ): void => { + doc.font('Helvetica-Bold').fontSize(10); + const lw = doc.widthOfString(`${etiqueta}: `); + doc.font('Helvetica'); + let v = valor || '—'; + while (v.length > 1 && lw + doc.widthOfString(`${v}…`) > w) { + v = v.slice(0, -1); + } + if (lw + doc.widthOfString(v) > w) v = '…'; + const xTxt = + alin === 'left' + ? x + : alin === 'right' + ? x + w - (lw + doc.widthOfString(v)) + : x + (w - (lw + doc.widthOfString(v))) / 2; + doc.font('Helvetica-Bold').text(`${etiqueta}: `, xTxt, yCampos, { + lineBreak: false, + }); + doc.font('Helvetica').text(v, xTxt + lw, yCampos, { + lineBreak: false, + }); + }; + const tercio = Math.floor(usable / 3); + campo(left, tercio, 'left', 'EQUIPO', datos.control.equipo); + campo( + left + tercio, + tercio, + 'center', + 'REUNIÓN', + datos.control.reunion, + ); + campo( + left + 2 * tercio, + usable - 2 * tercio, + 'right', + 'FECHA', + datos.control.fecha, + ); + + doc + .moveTo(left, yCampos + 16) + .lineTo(left + usable, yCampos + 16) + .strokeColor('#999999') + .lineWidth(0.75) + .stroke(); + y = yCampos + 24; + doc.font('Helvetica').fontSize(9).fillColor('#000000'); + } else { + // Los otros 4 reportes: solo el título dinámico (sin "Generado por" + // ni "Filtros"; el pie se dibuja al final de cada página). + doc.font('Helvetica').fontSize(14).text(datos.titulo, { + align: 'center', + }); + doc.moveDown(1); + y = doc.y; + } + + const rowHeight = 16; + + const dibujarHeader = () => { + doc.font('Helvetica-Bold').fontSize(9); + let x = left; + doc + .rect( + left, + y, + cols.reduce((a, c) => a + c.width, 0), + rowHeight, + ) + .fill('#e8eef7'); + doc.fillColor('#000000'); + for (const c of cols) { + doc.text(c.header, x + 3, y + 4, { + width: c.width - 6, + ellipsis: true, + }); + x += c.width; + } + y += rowHeight; + doc.font('Helvetica').fontSize(9); + }; + + dibujarHeader(); + for (const fila of datos.filas) { + if (y > doc.page.height - doc.page.margins.bottom - rowHeight) { + doc.addPage(); + y = doc.page.margins.top; + dibujarHeader(); + } + let x = left; + for (const c of cols) { + doc.text(c.get(fila), x + 3, y + 4, { + width: c.width - 6, + height: rowHeight - 4, + ellipsis: true, + lineBreak: false, + }); + x += c.width; + } + doc + .moveTo(left, y + rowHeight) + .lineTo(left + cols.reduce((a, c) => a + c.width, 0), y + rowHeight) + .strokeColor('#dddddd') + .lineWidth(0.5) + .stroke(); + y += rowHeight; + } + + if (!datos.filas.length) { + doc + .moveDown(1) + .text( + datos.control + ? 'Sin asistencias registradas.' + : '(sin filas para el rango/filtros elegidos)', + { align: 'center' }, + ); + } + + // Pie de cada página: quién lo generó, fecha/hora y "Página X de Y". + // bufferedPageRange() ya incluye todas las páginas (también la actual); + // el y debe quedar dentro del área útil (height - 50), porque si excede + // maxY() pdfkit agrega una página nueva en vez de dibujar el pie. + const rango = doc.bufferedPageRange(); + const total = rango.count; + const generado = `Generado por: ${generadoPor} · ${new Date().toLocaleString('es-BO', { timeZone: 'America/La_Paz' })}`; + for (let i = rango.start; i < rango.start + rango.count; i++) { + doc.switchToPage(i); + doc + .fontSize(8) + .fillColor('#777777') + .text( + `${generado} · Página ${i - rango.start + 1} de ${total}`, + doc.page.margins.left, + doc.page.height - 50, + { + width: + doc.page.width - doc.page.margins.left - doc.page.margins.right, + align: 'center', + }, + ); + doc.fillColor('#000000'); + } + + doc.end(); + }); + } +} diff --git a/src/modules/servicio/servicio.service.ts b/src/modules/servicio/servicio.service.ts index 3bca816..111a6b6 100644 --- a/src/modules/servicio/servicio.service.ts +++ b/src/modules/servicio/servicio.service.ts @@ -175,6 +175,25 @@ export class ServicioService { throw new Error(`Atributo no permitido: ${attribute}`); } + // `in`: value es una lista CSV (`'Publicado,EnCurso,…'`) resuelta + // como IN con parámetros (tanda 2026-10-22 — Próximos servicios). + if (operator === 'in') { + const valores = String(value) + .split(',') + .map((v) => v.trim()) + .filter((v) => v.length > 0); + if (!valores.length) { + throw new Error('Valor de in inválido.'); + } + const whereMethod = index === 0 ? 'where' : 'andWhere'; + query = query[whereMethod]( + `servicio.${attribute} IN (:...${paramKey})`, + { [paramKey]: valores }, + ); + index++; + continue; + } + const param = { [paramKey]: operator === 'like' ? `%${value}%` : value, }; @@ -221,9 +240,10 @@ export class ServicioService { } /** - * Adjunta a cada fila del find sus turnos (con nombre) y equipos (con - * nombre) en 4 queries por página: dos `IN` de filas de unión y dos `IN` - * de catálogo. Así el card de la lista pinta grupos y turnos sin N+1. + * Adjunta a cada fila del find sus turnos (con `nombre` y `horaInicio` + * del catálogo) y equipos (con nombre) en 4 queries por página: dos `IN` + * de filas de unión y dos `IN` de catálogo. Así el card de la lista + * pinta grupos, turnos y la hora de ingreso sin N+1. */ private async enriquecer(servicios: Servicio[]): Promise { if (!servicios.length) return servicios; @@ -247,6 +267,7 @@ export class ServicioService { : []; const nombreTurno = new Map(turnos.map((t) => [t.idTurno, t.nombre])); + const horaTurno = new Map(turnos.map((t) => [t.idTurno, t.horaInicio])); const nombreEquipo = new Map( equipos.map((e) => [e.idEquipo, e.nombreEquipo]), ); @@ -256,7 +277,11 @@ export class ServicioService { turnos: filasTurno .filter((t) => t.idServicio === servicio.idServicio) .sort((a, b) => a.sec - b.sec) - .map((t) => ({ ...t, nombre: nombreTurno.get(t.idTurno) ?? '' })), + .map((t) => ({ + ...t, + nombre: nombreTurno.get(t.idTurno) ?? '', + horaInicio: horaTurno.get(t.idTurno) ?? null, + })), equipos: filasEquipo .filter((e) => e.idServicio === servicio.idServicio) .map((e) => ({ @@ -426,16 +451,22 @@ export class ServicioService { let mensaje = `Servicio actualizado a '${destino}'.`; if (destino === EstadoServicio.Finalizado) { + // Método de salida (tanda 2026-10-22): la autorización manda. + // Líder del equipo convocado → 'Líder'; SuperAdmin/Dev → 'Sistema'. + // marcadoSalidaPor siempre registra quién autorizó el cierre. + const metodoSalida = esGlobal + ? MetodoMarcado.Sistema + : MetodoMarcado.Lider; + // Cierre de salidas: solo de quienes ingresaron y aún no salen. - // Líder → solo sus equipos convocados (marcadoSalidaPor = su id); - // SuperAdmin/Dev → todos los equipos (null, como hasta ahora). + // Líder → solo sus equipos convocados; SuperAdmin/Dev → todos. let qb = this.asistenciaRepository .createQueryBuilder() .update(Asistencia) .set({ fecSalida: () => 'now()', - metodoSalida: MetodoMarcado.Sistema, - marcadoSalidaPor: esGlobal ? null : user.idPersona, + metodoSalida, + marcadoSalidaPor: user.idPersona, }) .where('"idServicio" = :idServicio', { idServicio }) .andWhere('"fecIngreso" IS NOT NULL') @@ -448,37 +479,52 @@ export class ServicioService { const cerradas = await qb.execute(); const n = cerradas.affected ?? 0; - // Sin ingreso registrado → Falta con observación (tanda 2026-10-17): - // solo filas aún 'Pendiente' (respeta Permiso/Falta manuales y - // Eliminado); mismo scoping por equipo que el cierre de salidas. - let qbFalta = this.asistenciaRepository - .createQueryBuilder() - .update(Asistencia) - .set({ - estado: EstadoAsistencia.Falta, - observacion: - 'Cierre automático: sin ingreso al finalizar el servicio.', - }) - .where('"idServicio" = :idServicio', { idServicio }) - .andWhere('"fecIngreso" IS NULL') - .andWhere('"estado" = :estadoPendiente', { - estadoPendiente: EstadoAsistencia.Pendiente, - }); + // Re-evaluación de estado al finalizar (tanda 2026-10-22), en este + // orden de prioridad: + // 1) persona no Activa → Eliminado (aunque haya marcado o Permiso). + // 2) Permiso (manual) → se respeta, no se toca. + // 3) sin ingreso → Falta, sin observación automática (la observación + // es solo para justificar Permiso/Falta manuales). + // 4) con ingreso → Presente/Atrasado según fecIngreso vs inicio del + // turno más temprano, sin tolerancia (igual que marcar()). + // Un Eliminado existente no se re-abre. + const umbral = await this.umbralInicio(servicio); + const params: unknown[] = [idServicio]; + let alcance = ''; if (!esGlobal) { - qbFalta = qbFalta.andWhere('"idEquipo" IN (:...idsEquipos)', { - idsEquipos: equiposPropios, - }); + params.push(equiposPropios); + alcance = 'AND a."idEquipo" = ANY($2::uuid[])'; } - const faltas = await qbFalta.execute(); - const m = faltas.affected ?? 0; + params.push(umbral); + const iUmbral = params.length; + const resp = (await this.asistenciaRepository.query( + `UPDATE asistencia a + SET estado = CASE WHEN p.estado <> 'Activo' THEN 'Eliminado' + WHEN a.estado = 'Permiso' THEN 'Permiso' + WHEN a."fecIngreso" IS NULL THEN 'Falta' + WHEN $${iUmbral}::timestamptz IS NOT NULL + AND a."fecIngreso" > $${iUmbral}::timestamptz + THEN 'Atrasado' + ELSE 'Presente' + END + FROM persona p + WHERE p."idPersona" = a."idPersona" + AND a."idServicio" = $1 + AND a.estado <> 'Eliminado' + ${alcance}`, + params, + )) as unknown; + // pg entrega [rows, rowCount] para UPDATE (QueryRunner sin structured). + const m = + Array.isArray(resp) && typeof resp[1] === 'number' ? resp[1] : 0; const detalle = n > 0 && m > 0 - ? `Se cerró la salida de ${n} integrante(s) y se marcaron ${m} falta(s) por sin ingreso` + ? `Se cerró la salida de ${n} integrante(s) y se re-evaluó ${m} estado(s)` : n > 0 ? `Se cerró la salida de ${n} integrante(s)` : m > 0 - ? `Se marcaron ${m} falta(s) por sin ingreso` + ? `Se re-evaluó ${m} estado(s)` : ''; mensaje = !detalle ? 'Servicio finalizado.' @@ -494,6 +540,28 @@ export class ServicioService { return serviceResult; } + /** + * Inicio del turno más temprano (primer turno por `sec`) del servicio como + * fecha-hora; `null` si no hay fecha o turno con hora parseable. Es el mismo + * umbral que usa `estadoMarcado()` al marcar ingreso (sin tolerancia). + */ + private async umbralInicio(servicio: Servicio): Promise { + if (!servicio.fecha) return null; + const st = await this.servicioTurnoRepository.findOne({ + where: { idServicio: servicio.idServicio }, + order: { sec: 'ASC' }, + }); + if (!st) return null; + const turno = await this.turnoRepository.findOneBy({ idTurno: st.idTurno }); + if (!turno?.horaInicio) return null; + const hora = + turno.horaInicio.length === 5 + ? `${turno.horaInicio}:00` + : turno.horaInicio; + const inicio = new Date(`${servicio.fecha}T${hora}`); + return Number.isNaN(inicio.getTime()) ? null : inicio; + } + /** * DELETE = borrado lógico (`estado = Eliminado`) de **cualquier estado** * (decisión del usuario 2026-10-10: antes solo borradores). Aplica los