5to Commit
This commit is contained in:
parent
df8b1a11be
commit
6d107d4397
25 changed files with 1959 additions and 49 deletions
|
|
@ -27,6 +27,8 @@ ENV NODE_ENV=production
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY --from=prod-deps /app/node_modules ./node_modules
|
COPY --from=prod-deps /app/node_modules ./node_modules
|
||||||
COPY --from=build /app/dist ./dist
|
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")
|
# package.json se copia porque dist/*.js son ESM ("type": "module")
|
||||||
COPY package.json ./
|
COPY package.json ./
|
||||||
RUN mkdir -p uploads && chown -R node:node /app
|
RUN mkdir -p uploads && chown -R node:node /app
|
||||||
|
|
|
||||||
BIN
assets/logo-ekklesia.png
Normal file
BIN
assets/logo-ekklesia.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 93 KiB |
BIN
assets/logo-ser.png
Normal file
BIN
assets/logo-ser.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 169 KiB |
|
|
@ -40,6 +40,7 @@
|
||||||
"firebase-admin": "^14.5.0",
|
"firebase-admin": "^14.5.0",
|
||||||
"jsonwebtoken": "^9.0.3",
|
"jsonwebtoken": "^9.0.3",
|
||||||
"multer": "^2.4.0",
|
"multer": "^2.4.0",
|
||||||
|
"pdfkit": "^0.20.2",
|
||||||
"pg": "^8.23.1",
|
"pg": "^8.23.1",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
"rxjs": "^7.8.1",
|
"rxjs": "^7.8.1",
|
||||||
|
|
@ -56,6 +57,7 @@
|
||||||
"@types/jsonwebtoken": "^9.0.10",
|
"@types/jsonwebtoken": "^9.0.10",
|
||||||
"@types/multer": "^2.3.0",
|
"@types/multer": "^2.3.0",
|
||||||
"@types/node": "^24.0.0",
|
"@types/node": "^24.0.0",
|
||||||
|
"@types/pdfkit": "^0.17.6",
|
||||||
"@types/pg": "^8.23.1",
|
"@types/pg": "^8.23.1",
|
||||||
"@types/supertest": "^7.0.0",
|
"@types/supertest": "^7.0.0",
|
||||||
"@vitest/coverage-v8": "^4.1.2",
|
"@vitest/coverage-v8": "^4.1.2",
|
||||||
|
|
|
||||||
128
pnpm-lock.yaml
generated
128
pnpm-lock.yaml
generated
|
|
@ -59,6 +59,9 @@ importers:
|
||||||
multer:
|
multer:
|
||||||
specifier: ^2.4.0
|
specifier: ^2.4.0
|
||||||
version: 2.4.0
|
version: 2.4.0
|
||||||
|
pdfkit:
|
||||||
|
specifier: ^0.20.2
|
||||||
|
version: 0.20.2
|
||||||
pg:
|
pg:
|
||||||
specifier: ^8.23.1
|
specifier: ^8.23.1
|
||||||
version: 8.23.1
|
version: 8.23.1
|
||||||
|
|
@ -102,6 +105,9 @@ importers:
|
||||||
'@types/node':
|
'@types/node':
|
||||||
specifier: ^24.0.0
|
specifier: ^24.0.0
|
||||||
version: 24.19.0
|
version: 24.19.0
|
||||||
|
'@types/pdfkit':
|
||||||
|
specifier: ^0.17.6
|
||||||
|
version: 0.17.6
|
||||||
'@types/pg':
|
'@types/pg':
|
||||||
specifier: ^8.23.1
|
specifier: ^8.23.1
|
||||||
version: 8.23.1
|
version: 8.23.1
|
||||||
|
|
@ -606,6 +612,10 @@ packages:
|
||||||
'@nestjs/platform-socket.io':
|
'@nestjs/platform-socket.io':
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
|
'@noble/ciphers@1.3.0':
|
||||||
|
resolution: {integrity: sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==}
|
||||||
|
engines: {node: ^14.21.3 || >=16}
|
||||||
|
|
||||||
'@noble/hashes@1.8.0':
|
'@noble/hashes@1.8.0':
|
||||||
resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==}
|
resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==}
|
||||||
engines: {node: ^14.21.3 || >=16}
|
engines: {node: ^14.21.3 || >=16}
|
||||||
|
|
@ -891,6 +901,9 @@ packages:
|
||||||
'@standard-schema/spec@1.1.0':
|
'@standard-schema/spec@1.1.0':
|
||||||
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
|
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':
|
'@tokenizer/inflate@0.4.1':
|
||||||
resolution: {integrity: sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==}
|
resolution: {integrity: sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
|
|
@ -946,6 +959,9 @@ packages:
|
||||||
'@types/node@24.19.0':
|
'@types/node@24.19.0':
|
||||||
resolution: {integrity: sha512-zY+5tKxXdhGh1PYI0ac+7juvEu4OI6vWtVVoj5i2m42jxAY1U+zHGt6QCyOFwykdP62sM3MJ9stoYYUw5aCWew==}
|
resolution: {integrity: sha512-zY+5tKxXdhGh1PYI0ac+7juvEu4OI6vWtVVoj5i2m42jxAY1U+zHGt6QCyOFwykdP62sM3MJ9stoYYUw5aCWew==}
|
||||||
|
|
||||||
|
'@types/pdfkit@0.17.6':
|
||||||
|
resolution: {integrity: sha512-tIwzxk2uWKp0Cq9JIluQXJid77lYhF52EsIOwhsMF4iWLA6YneoBR1xVKYYdAysHuepUB0OX4tdwMiUDdGKmig==}
|
||||||
|
|
||||||
'@types/pg@8.23.1':
|
'@types/pg@8.23.1':
|
||||||
resolution: {integrity: sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==}
|
resolution: {integrity: sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==}
|
||||||
|
|
||||||
|
|
@ -1097,6 +1113,10 @@ packages:
|
||||||
resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}
|
resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}
|
||||||
engines: {node: 18 || 20 || >=22}
|
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:
|
base64-js@1.5.1:
|
||||||
resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}
|
resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}
|
||||||
|
|
||||||
|
|
@ -1125,6 +1145,9 @@ packages:
|
||||||
resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==}
|
resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==}
|
||||||
engines: {node: 20 || >=22}
|
engines: {node: 20 || >=22}
|
||||||
|
|
||||||
|
brotli@1.3.3:
|
||||||
|
resolution: {integrity: sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==}
|
||||||
|
|
||||||
buffer-equal-constant-time@1.0.1:
|
buffer-equal-constant-time@1.0.1:
|
||||||
resolution: {integrity: sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==}
|
resolution: {integrity: sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==}
|
||||||
|
|
||||||
|
|
@ -1226,6 +1249,10 @@ packages:
|
||||||
resolution: {integrity: sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==}
|
resolution: {integrity: sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==}
|
||||||
engines: {node: '>=0.8'}
|
engines: {node: '>=0.8'}
|
||||||
|
|
||||||
|
clone@2.1.2:
|
||||||
|
resolution: {integrity: sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==}
|
||||||
|
engines: {node: '>=0.8'}
|
||||||
|
|
||||||
color-convert@2.0.1:
|
color-convert@2.0.1:
|
||||||
resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==}
|
resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==}
|
||||||
engines: {node: '>=7.0.0'}
|
engines: {node: '>=7.0.0'}
|
||||||
|
|
@ -1328,6 +1355,9 @@ packages:
|
||||||
dezalgo@1.0.4:
|
dezalgo@1.0.4:
|
||||||
resolution: {integrity: sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig==}
|
resolution: {integrity: sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig==}
|
||||||
|
|
||||||
|
dfa@1.2.0:
|
||||||
|
resolution: {integrity: sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==}
|
||||||
|
|
||||||
dotenv-expand@13.0.0:
|
dotenv-expand@13.0.0:
|
||||||
resolution: {integrity: sha512-aBfBS8eYIeXmpHI9ThIlA7/WLq+SLt18iXUZhb52rW89QLKQFoIpPG1bPeewoPZsTyjSSO3T7234FBVUM1V2rA==}
|
resolution: {integrity: sha512-aBfBS8eYIeXmpHI9ThIlA7/WLq+SLt18iXUZhb52rW89QLKQFoIpPG1bPeewoPZsTyjSSO3T7234FBVUM1V2rA==}
|
||||||
engines: {node: '>=12'}
|
engines: {node: '>=12'}
|
||||||
|
|
@ -1495,6 +1525,9 @@ packages:
|
||||||
resolution: {integrity: sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==}
|
resolution: {integrity: sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==}
|
||||||
engines: {node: ^12.20 || >= 14.13}
|
engines: {node: ^12.20 || >= 14.13}
|
||||||
|
|
||||||
|
fflate@0.8.3:
|
||||||
|
resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==}
|
||||||
|
|
||||||
figures@3.2.0:
|
figures@3.2.0:
|
||||||
resolution: {integrity: sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==}
|
resolution: {integrity: sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==}
|
||||||
engines: {node: '>=8'}
|
engines: {node: '>=8'}
|
||||||
|
|
@ -1511,6 +1544,9 @@ packages:
|
||||||
resolution: {integrity: sha512-DElmgmaH9aPXu2dWXGQiDoan33UfTnbfAAKaue4fwEZxmpdaNrTk5DmuFn+vVDki2KZ6TiaC0IHRWcEzcDxB3Q==}
|
resolution: {integrity: sha512-DElmgmaH9aPXu2dWXGQiDoan33UfTnbfAAKaue4fwEZxmpdaNrTk5DmuFn+vVDki2KZ6TiaC0IHRWcEzcDxB3Q==}
|
||||||
engines: {node: '>=22'}
|
engines: {node: '>=22'}
|
||||||
|
|
||||||
|
fontkit@2.0.4:
|
||||||
|
resolution: {integrity: sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==}
|
||||||
|
|
||||||
foreground-child@3.3.1:
|
foreground-child@3.3.1:
|
||||||
resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==}
|
resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==}
|
||||||
engines: {node: '>=14'}
|
engines: {node: '>=14'}
|
||||||
|
|
@ -1867,6 +1903,9 @@ packages:
|
||||||
limiter@1.1.5:
|
limiter@1.1.5:
|
||||||
resolution: {integrity: sha512-FWWMIEOxz3GwUI4Ts/IvgVy6LPvoMPgjMdQ185nN6psJyBJ4yOpzqm695/h5umdLJg2vW3GR5iG11MAkR2AzJA==}
|
resolution: {integrity: sha512-FWWMIEOxz3GwUI4Ts/IvgVy6LPvoMPgjMdQ185nN6psJyBJ4yOpzqm695/h5umdLJg2vW3GR5iG11MAkR2AzJA==}
|
||||||
|
|
||||||
|
linebreak@1.1.0:
|
||||||
|
resolution: {integrity: sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==}
|
||||||
|
|
||||||
load-esm@1.0.3:
|
load-esm@1.0.3:
|
||||||
resolution: {integrity: sha512-v5xlu8eHD1+6r8EHTg6hfmO97LN8ugKtiXcy5e6oN72iD2r6u0RPfLl6fxM+7Wnh2ZRq15o0russMst44WauPA==}
|
resolution: {integrity: sha512-v5xlu8eHD1+6r8EHTg6hfmO97LN8ugKtiXcy5e6oN72iD2r6u0RPfLl6fxM+7Wnh2ZRq15o0russMst44WauPA==}
|
||||||
engines: {node: '>=13.2.0'}
|
engines: {node: '>=13.2.0'}
|
||||||
|
|
@ -2128,6 +2167,9 @@ packages:
|
||||||
package-json-from-dist@1.0.1:
|
package-json-from-dist@1.0.1:
|
||||||
resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==}
|
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:
|
parseurl@1.3.3:
|
||||||
resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==}
|
resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==}
|
||||||
engines: {node: '>= 0.8'}
|
engines: {node: '>= 0.8'}
|
||||||
|
|
@ -2150,6 +2192,9 @@ packages:
|
||||||
pathe@2.0.3:
|
pathe@2.0.3:
|
||||||
resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
|
resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
|
||||||
|
|
||||||
|
pdfkit@0.20.2:
|
||||||
|
resolution: {integrity: sha512-Q/w03ICAQyXfHNfTsg1udp0ADerdBN0s7a6XSPL7J7Ro6ABnafoBOCDBstIO9U02mvzHEV8HrvFIw5iV5ejIRA==}
|
||||||
|
|
||||||
pg-cloudflare@1.4.1:
|
pg-cloudflare@1.4.1:
|
||||||
resolution: {integrity: sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==}
|
resolution: {integrity: sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==}
|
||||||
|
|
||||||
|
|
@ -2195,6 +2240,9 @@ packages:
|
||||||
resolution: {integrity: sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==}
|
resolution: {integrity: sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==}
|
||||||
engines: {node: '>=4'}
|
engines: {node: '>=4'}
|
||||||
|
|
||||||
|
png-js@2.0.0:
|
||||||
|
resolution: {integrity: sha512-GdzJuUMc6ZSpxFJWVxtOH1bzYHym+TOnveqUjb+VJIbZWbZzyiRGFiKhbiielfpYbgMlhHVhsJ0FTazfuRFkMA==}
|
||||||
|
|
||||||
postcss@8.5.28:
|
postcss@8.5.28:
|
||||||
resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==}
|
resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==}
|
||||||
engines: {node: ^10 || ^12 || >=14}
|
engines: {node: ^10 || ^12 || >=14}
|
||||||
|
|
@ -2275,6 +2323,9 @@ packages:
|
||||||
resolution: {integrity: sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==}
|
resolution: {integrity: sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
|
restructure@3.0.2:
|
||||||
|
resolution: {integrity: sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==}
|
||||||
|
|
||||||
retry-request@8.0.4:
|
retry-request@8.0.4:
|
||||||
resolution: {integrity: sha512-pI6/7eabUYkZxamkOq0g0uMxKLLGnjzhefY+vL8bVXag5rto4OU2YBTPytWLuHH7aEKD6fn7kJycQfid0Mwnkw==}
|
resolution: {integrity: sha512-pI6/7eabUYkZxamkOq0g0uMxKLLGnjzhefY+vL8bVXag5rto4OU2YBTPytWLuHH7aEKD6fn7kJycQfid0Mwnkw==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
|
|
@ -2496,6 +2547,9 @@ packages:
|
||||||
through@2.3.8:
|
through@2.3.8:
|
||||||
resolution: {integrity: sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==}
|
resolution: {integrity: sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==}
|
||||||
|
|
||||||
|
tiny-inflate@1.0.3:
|
||||||
|
resolution: {integrity: sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==}
|
||||||
|
|
||||||
tinybench@2.9.0:
|
tinybench@2.9.0:
|
||||||
resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
|
resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
|
||||||
|
|
||||||
|
|
@ -2632,6 +2686,12 @@ packages:
|
||||||
resolution: {integrity: sha512-yLSH4py7oFH3oG/9K+XWrz1pSi3dfUrWEnInbxMfArOfc1+33BlGPQtLsOYwvdMy11AwUBetYuaRxSPqgkq+8g==}
|
resolution: {integrity: sha512-yLSH4py7oFH3oG/9K+XWrz1pSi3dfUrWEnInbxMfArOfc1+33BlGPQtLsOYwvdMy11AwUBetYuaRxSPqgkq+8g==}
|
||||||
engines: {node: '>=4'}
|
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:
|
unpipe@1.0.0:
|
||||||
resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==}
|
resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==}
|
||||||
engines: {node: '>= 0.8'}
|
engines: {node: '>= 0.8'}
|
||||||
|
|
@ -3319,6 +3379,8 @@ snapshots:
|
||||||
optionalDependencies:
|
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)
|
'@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': {}
|
'@noble/hashes@1.8.0': {}
|
||||||
|
|
||||||
'@nodable/entities@3.1.0':
|
'@nodable/entities@3.1.0':
|
||||||
|
|
@ -3479,6 +3541,10 @@ snapshots:
|
||||||
|
|
||||||
'@standard-schema/spec@1.1.0': {}
|
'@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)':
|
'@tokenizer/inflate@0.4.1(supports-color@7.2.0)':
|
||||||
dependencies:
|
dependencies:
|
||||||
debug: 4.4.3(supports-color@7.2.0)
|
debug: 4.4.3(supports-color@7.2.0)
|
||||||
|
|
@ -3548,6 +3614,10 @@ snapshots:
|
||||||
dependencies:
|
dependencies:
|
||||||
undici-types: 7.24.6
|
undici-types: 7.24.6
|
||||||
|
|
||||||
|
'@types/pdfkit@0.17.6':
|
||||||
|
dependencies:
|
||||||
|
'@types/node': 24.19.0
|
||||||
|
|
||||||
'@types/pg@8.23.1':
|
'@types/pg@8.23.1':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/node': 24.19.0
|
'@types/node': 24.19.0
|
||||||
|
|
@ -3715,6 +3785,8 @@ snapshots:
|
||||||
|
|
||||||
balanced-match@4.0.4: {}
|
balanced-match@4.0.4: {}
|
||||||
|
|
||||||
|
base64-js@0.0.8: {}
|
||||||
|
|
||||||
base64-js@1.5.1: {}
|
base64-js@1.5.1: {}
|
||||||
|
|
||||||
base64id@2.0.0: {}
|
base64id@2.0.0: {}
|
||||||
|
|
@ -3755,6 +3827,10 @@ snapshots:
|
||||||
dependencies:
|
dependencies:
|
||||||
balanced-match: 4.0.4
|
balanced-match: 4.0.4
|
||||||
|
|
||||||
|
brotli@1.3.3:
|
||||||
|
dependencies:
|
||||||
|
base64-js: 1.5.1
|
||||||
|
|
||||||
buffer-equal-constant-time@1.0.1: {}
|
buffer-equal-constant-time@1.0.1: {}
|
||||||
|
|
||||||
buffer-from@1.1.2: {}
|
buffer-from@1.1.2: {}
|
||||||
|
|
@ -3848,6 +3924,8 @@ snapshots:
|
||||||
|
|
||||||
clone@1.0.4: {}
|
clone@1.0.4: {}
|
||||||
|
|
||||||
|
clone@2.1.2: {}
|
||||||
|
|
||||||
color-convert@2.0.1:
|
color-convert@2.0.1:
|
||||||
dependencies:
|
dependencies:
|
||||||
color-name: 1.1.4
|
color-name: 1.1.4
|
||||||
|
|
@ -3922,6 +4000,8 @@ snapshots:
|
||||||
asap: 2.0.6
|
asap: 2.0.6
|
||||||
wrappy: 1.0.2
|
wrappy: 1.0.2
|
||||||
|
|
||||||
|
dfa@1.2.0: {}
|
||||||
|
|
||||||
dotenv-expand@13.0.0:
|
dotenv-expand@13.0.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
dotenv: 17.4.2
|
dotenv: 17.4.2
|
||||||
|
|
@ -4113,6 +4193,8 @@ snapshots:
|
||||||
node-domexception: 1.0.0
|
node-domexception: 1.0.0
|
||||||
web-streams-polyfill: 3.3.3
|
web-streams-polyfill: 3.3.3
|
||||||
|
|
||||||
|
fflate@0.8.3: {}
|
||||||
|
|
||||||
figures@3.2.0:
|
figures@3.2.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
escape-string-regexp: 1.0.5
|
escape-string-regexp: 1.0.5
|
||||||
|
|
@ -4155,6 +4237,18 @@ snapshots:
|
||||||
- encoding
|
- encoding
|
||||||
- supports-color
|
- 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:
|
foreground-child@3.3.1:
|
||||||
dependencies:
|
dependencies:
|
||||||
cross-spawn: 7.0.6
|
cross-spawn: 7.0.6
|
||||||
|
|
@ -4603,6 +4697,11 @@ snapshots:
|
||||||
|
|
||||||
limiter@1.1.5: {}
|
limiter@1.1.5: {}
|
||||||
|
|
||||||
|
linebreak@1.1.0:
|
||||||
|
dependencies:
|
||||||
|
base64-js: 0.0.8
|
||||||
|
unicode-trie: 2.0.0
|
||||||
|
|
||||||
load-esm@1.0.3: {}
|
load-esm@1.0.3: {}
|
||||||
|
|
||||||
lodash.camelcase@4.3.0:
|
lodash.camelcase@4.3.0:
|
||||||
|
|
@ -4842,6 +4941,8 @@ snapshots:
|
||||||
package-json-from-dist@1.0.1:
|
package-json-from-dist@1.0.1:
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
|
pako@0.2.9: {}
|
||||||
|
|
||||||
parseurl@1.3.3: {}
|
parseurl@1.3.3: {}
|
||||||
|
|
||||||
path-expression-matcher@1.6.2:
|
path-expression-matcher@1.6.2:
|
||||||
|
|
@ -4860,6 +4961,15 @@ snapshots:
|
||||||
|
|
||||||
pathe@2.0.3: {}
|
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:
|
pg-cloudflare@1.4.1:
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
|
|
@ -4901,6 +5011,10 @@ snapshots:
|
||||||
|
|
||||||
pluralize@8.0.0: {}
|
pluralize@8.0.0: {}
|
||||||
|
|
||||||
|
png-js@2.0.0:
|
||||||
|
dependencies:
|
||||||
|
fflate: 0.8.3
|
||||||
|
|
||||||
postcss@8.5.28:
|
postcss@8.5.28:
|
||||||
dependencies:
|
dependencies:
|
||||||
nanoid: 3.3.19
|
nanoid: 3.3.19
|
||||||
|
|
@ -4988,6 +5102,8 @@ snapshots:
|
||||||
onetime: 7.0.0
|
onetime: 7.0.0
|
||||||
signal-exit: 4.1.0
|
signal-exit: 4.1.0
|
||||||
|
|
||||||
|
restructure@3.0.2: {}
|
||||||
|
|
||||||
retry-request@8.0.4(supports-color@7.2.0):
|
retry-request@8.0.4(supports-color@7.2.0):
|
||||||
dependencies:
|
dependencies:
|
||||||
extend: 3.0.2
|
extend: 3.0.2
|
||||||
|
|
@ -5306,6 +5422,8 @@ snapshots:
|
||||||
|
|
||||||
through@2.3.8: {}
|
through@2.3.8: {}
|
||||||
|
|
||||||
|
tiny-inflate@1.0.3: {}
|
||||||
|
|
||||||
tinybench@2.9.0: {}
|
tinybench@2.9.0: {}
|
||||||
|
|
||||||
tinyexec@1.3.1: {}
|
tinyexec@1.3.1: {}
|
||||||
|
|
@ -5389,6 +5507,16 @@ snapshots:
|
||||||
|
|
||||||
unicode-emoji-modifier-base@1.0.0: {}
|
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: {}
|
unpipe@1.0.0: {}
|
||||||
|
|
||||||
util-deprecate@1.0.2: {}
|
util-deprecate@1.0.2: {}
|
||||||
|
|
|
||||||
|
|
@ -20,6 +20,8 @@ import { AsistenciaModule } from './modules/asistencia/asistencia.module.js';
|
||||||
import { CodigoOtpModule } from './modules/codigo-otp/codigo-otp.module.js';
|
import { CodigoOtpModule } from './modules/codigo-otp/codigo-otp.module.js';
|
||||||
import { AuthModule } from './modules/auth/auth.module.js';
|
import { AuthModule } from './modules/auth/auth.module.js';
|
||||||
import { DispositivoModule } from './modules/dispositivo/dispositivo.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';
|
import { RealtimeModule } from './common/realtime.module.js';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
|
|
@ -56,6 +58,8 @@ import { RealtimeModule } from './common/realtime.module.js';
|
||||||
AsistenciaModule,
|
AsistenciaModule,
|
||||||
CodigoOtpModule,
|
CodigoOtpModule,
|
||||||
DispositivoModule,
|
DispositivoModule,
|
||||||
|
MantenimientoModule,
|
||||||
|
ReportesModule,
|
||||||
RealtimeModule,
|
RealtimeModule,
|
||||||
],
|
],
|
||||||
controllers: [AppController],
|
controllers: [AppController],
|
||||||
|
|
|
||||||
|
|
@ -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';
|
import { Type } from 'class-transformer';
|
||||||
|
|
||||||
// Interfaz para cada condición de búsqueda
|
// Interfaz para cada condición de búsqueda
|
||||||
|
|
@ -11,8 +18,8 @@ export class WhereConditionDto {
|
||||||
|
|
||||||
@IsString()
|
@IsString()
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsIn(['=', 'like', '>', '<', '>=', '<='])
|
@IsIn(['=', 'like', '>', '<', '>=', '<=', 'in'])
|
||||||
operator?: '=' | 'like' | '>' | '<' | '>=' | '<=';
|
operator?: '=' | 'like' | '>' | '<' | '>=' | '<=' | 'in';
|
||||||
}
|
}
|
||||||
|
|
||||||
// DTO principal para la solicitud
|
// DTO principal para la solicitud
|
||||||
|
|
@ -33,5 +40,4 @@ export class FindDto {
|
||||||
|
|
||||||
@IsNumber()
|
@IsNumber()
|
||||||
offset: number; // paginacion
|
offset: number; // paginacion
|
||||||
|
}
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,11 @@ export enum EstadoGeneral {
|
||||||
Activo = 'Activo',
|
Activo = 'Activo',
|
||||||
Inactivo = 'Inactivo',
|
Inactivo = 'Inactivo',
|
||||||
Eliminado = 'Eliminado',
|
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 {
|
export enum EstadoMiembro {
|
||||||
|
|
|
||||||
|
|
@ -15,4 +15,5 @@ export enum MetodoMarcado {
|
||||||
PIN = 'PIN',
|
PIN = 'PIN',
|
||||||
Geolocalizacion = 'Geolocalizacion',
|
Geolocalizacion = 'Geolocalizacion',
|
||||||
Sistema = 'Sistema',
|
Sistema = 'Sistema',
|
||||||
|
Lider = 'Líder'
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
export type WhereCondition = {
|
export type WhereCondition = {
|
||||||
attribute: string;
|
attribute: string;
|
||||||
value: string | number | boolean;
|
value: string | number | boolean;
|
||||||
operator?: '=' | 'like' | '>' | '<' | '>=' | '<=';
|
// 'in': `value` es una lista CSV (ej. `'Publicado,EnCurso'`).
|
||||||
};
|
operator?: '=' | 'like' | '>' | '<' | '>=' | '<=' | 'in';
|
||||||
|
};
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ import { ServicioEquipo } from '../servicio-equipo/entities/servicio-equipo.enti
|
||||||
import { ServicioTurno } from '../servicio-turno/entities/servicio-turno.entity.js';
|
import { ServicioTurno } from '../servicio-turno/entities/servicio-turno.entity.js';
|
||||||
import { Turno } from '../turno/entities/turno.entity.js';
|
import { Turno } from '../turno/entities/turno.entity.js';
|
||||||
import { Configuracion } from '../configuracion/entities/configuracion.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 { AsistenciaService } from './asistencia.service.js';
|
||||||
import { AsistenciaController } from './asistencia.controller.js';
|
import { AsistenciaController } from './asistencia.controller.js';
|
||||||
|
|
||||||
|
|
@ -22,6 +23,7 @@ import { AsistenciaController } from './asistencia.controller.js';
|
||||||
ServicioTurno,
|
ServicioTurno,
|
||||||
Turno,
|
Turno,
|
||||||
Configuracion,
|
Configuracion,
|
||||||
|
Persona,
|
||||||
]),
|
]),
|
||||||
],
|
],
|
||||||
exports: [AsistenciaService, TypeOrmModule],
|
exports: [AsistenciaService, TypeOrmModule],
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@ import { ServicioEquipo } from '../servicio-equipo/entities/servicio-equipo.enti
|
||||||
import { ServicioTurno } from '../servicio-turno/entities/servicio-turno.entity.js';
|
import { ServicioTurno } from '../servicio-turno/entities/servicio-turno.entity.js';
|
||||||
import { Turno } from '../turno/entities/turno.entity.js';
|
import { Turno } from '../turno/entities/turno.entity.js';
|
||||||
import { Configuracion } from '../configuracion/entities/configuracion.entity.js';
|
import { Configuracion } from '../configuracion/entities/configuracion.entity.js';
|
||||||
|
import { Persona } from '../persona/entities/persona.entity.js';
|
||||||
import {
|
import {
|
||||||
AsistenciaDto,
|
AsistenciaDto,
|
||||||
MarcarAsistenciaDto,
|
MarcarAsistenciaDto,
|
||||||
|
|
@ -21,6 +22,7 @@ import {
|
||||||
import { WhereCondition } from '../../common/types/query-builder.types.js';
|
import { WhereCondition } from '../../common/types/query-builder.types.js';
|
||||||
import {
|
import {
|
||||||
EstadoAsistencia,
|
EstadoAsistencia,
|
||||||
|
EstadoGeneral,
|
||||||
EstadoMiembro,
|
EstadoMiembro,
|
||||||
EstadoServicio,
|
EstadoServicio,
|
||||||
} from '../../common/enums/estados.enum.js';
|
} from '../../common/enums/estados.enum.js';
|
||||||
|
|
@ -55,6 +57,8 @@ export class AsistenciaService {
|
||||||
private turnoRepository: Repository<Turno>,
|
private turnoRepository: Repository<Turno>,
|
||||||
@InjectRepository(Configuracion)
|
@InjectRepository(Configuracion)
|
||||||
private configuracionRepository: Repository<Configuracion>,
|
private configuracionRepository: Repository<Configuracion>,
|
||||||
|
@InjectRepository(Persona)
|
||||||
|
private personaRepository: Repository<Persona>,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async create(asistenciaDto: AsistenciaDto): Promise<ServiceResult> {
|
async create(asistenciaDto: AsistenciaDto): Promise<ServiceResult> {
|
||||||
|
|
@ -343,6 +347,10 @@ export class AsistenciaService {
|
||||||
estado: await this.estadoMarcado(servicio),
|
estado: await this.estadoMarcado(servicio),
|
||||||
observacion: dto.observacion ?? asistencia.observacion,
|
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 {
|
} else {
|
||||||
if (!asistencia.fecIngreso) {
|
if (!asistencia.fecIngreso) {
|
||||||
serviceResult.message = 'Debe registrar el ingreso antes de la salida.';
|
serviceResult.message = 'Debe registrar el ingreso antes de la salida.';
|
||||||
|
|
@ -376,6 +384,19 @@ export class AsistenciaService {
|
||||||
return serviceResult;
|
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<void> {
|
||||||
|
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
|
* Mensaje si coords cae fuera del radio `configuracion.distancia` del punto
|
||||||
* de marcado. Si no hay fila de configuración, no valida.
|
* de marcado. Si no hay fila de configuración, no valida.
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,10 @@ import { Configuracion } from '../configuracion/entities/configuracion.entity.js
|
||||||
import { HashService } from '../../common/services/hash.service.js';
|
import { HashService } from '../../common/services/hash.service.js';
|
||||||
import { TokenService } from '../../common/services/token.service.js';
|
import { TokenService } from '../../common/services/token.service.js';
|
||||||
import { OpenwaService } from '../../common/services/openwa.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 { EstadoGeneral } from '../../common/enums/estados.enum.js';
|
||||||
import { EnviarOtpDto, LoginDto, UpdatePerfilDto } from './dto/auth.dto.js';
|
import { EnviarOtpDto, LoginDto, UpdatePerfilDto } from './dto/auth.dto.js';
|
||||||
|
|
||||||
|
|
@ -51,7 +54,10 @@ export class AuthService {
|
||||||
return serviceResult;
|
return serviceResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (persona.estado !== EstadoGeneral.Activo) {
|
if (
|
||||||
|
persona.estado !== EstadoGeneral.Activo &&
|
||||||
|
persona.estado !== EstadoGeneral.Inhabilitado
|
||||||
|
) {
|
||||||
serviceResult.message =
|
serviceResult.message =
|
||||||
'La cuenta no está activa. Contacte a su líder o administrador.';
|
'La cuenta no está activa. Contacte a su líder o administrador.';
|
||||||
return serviceResult;
|
return serviceResult;
|
||||||
|
|
@ -90,7 +96,8 @@ export class AuthService {
|
||||||
return serviceResult;
|
return serviceResult;
|
||||||
}
|
}
|
||||||
serviceResult.boolean = true;
|
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;
|
serviceResult.number = 1;
|
||||||
// Solo en dev: idPersona + código. En producción no se expone nada.
|
// Solo en dev: idPersona + código. En producción no se expone nada.
|
||||||
serviceResult.object =
|
serviceResult.object =
|
||||||
|
|
@ -113,7 +120,9 @@ export class AuthService {
|
||||||
const codigo = this.generateOtpCode();
|
const codigo = this.generateOtpCode();
|
||||||
const codigoHash = await this.hashService.hashText(codigo);
|
const codigoHash = await this.hashService.hashText(codigo);
|
||||||
const fecCreacion = new Date();
|
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 this.codigoOtpRepository.manager.transaction(async (manager) => {
|
||||||
await manager
|
await manager
|
||||||
|
|
@ -172,7 +181,10 @@ export class AuthService {
|
||||||
return serviceResult;
|
return serviceResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (persona.estado !== EstadoGeneral.Activo) {
|
if (
|
||||||
|
persona.estado !== EstadoGeneral.Activo &&
|
||||||
|
persona.estado !== EstadoGeneral.Inhabilitado
|
||||||
|
) {
|
||||||
serviceResult.message = 'La cuenta no está activa.';
|
serviceResult.message = 'La cuenta no está activa.';
|
||||||
return serviceResult;
|
return serviceResult;
|
||||||
}
|
}
|
||||||
|
|
@ -193,11 +205,15 @@ export class AuthService {
|
||||||
if (otp.intentosFallidos >= OTP_MAX_INTENTS) {
|
if (otp.intentosFallidos >= OTP_MAX_INTENTS) {
|
||||||
await this.codigoOtpRepository.update(otp.idOtp, { usado: true });
|
await this.codigoOtpRepository.update(otp.idOtp, { usado: true });
|
||||||
this.otpCache.delete(persona.idPersona);
|
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;
|
return serviceResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
const match = await this.hashService.compareTexts(dto.codigo, otp.codigoHash);
|
const match = await this.hashService.compareTexts(
|
||||||
|
dto.codigo,
|
||||||
|
otp.codigoHash,
|
||||||
|
);
|
||||||
|
|
||||||
if (!match) {
|
if (!match) {
|
||||||
const intentos = otp.intentosFallidos + 1;
|
const intentos = otp.intentosFallidos + 1;
|
||||||
|
|
@ -263,7 +279,10 @@ export class AuthService {
|
||||||
return serviceResult;
|
return serviceResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (persona.estado !== EstadoGeneral.Activo) {
|
if (
|
||||||
|
persona.estado !== EstadoGeneral.Activo &&
|
||||||
|
persona.estado !== EstadoGeneral.Inhabilitado
|
||||||
|
) {
|
||||||
serviceResult.message = 'La cuenta no está activa.';
|
serviceResult.message = 'La cuenta no está activa.';
|
||||||
return serviceResult;
|
return serviceResult;
|
||||||
}
|
}
|
||||||
|
|
@ -304,7 +323,10 @@ export class AuthService {
|
||||||
return serviceResult;
|
return serviceResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
async updatePerfil(idPersona: string, dto: UpdatePerfilDto): Promise<ServiceResult> {
|
async updatePerfil(
|
||||||
|
idPersona: string,
|
||||||
|
dto: UpdatePerfilDto,
|
||||||
|
): Promise<ServiceResult> {
|
||||||
const serviceResult = defaultServiceResult();
|
const serviceResult = defaultServiceResult();
|
||||||
|
|
||||||
const clean: Partial<Persona> = {};
|
const clean: Partial<Persona> = {};
|
||||||
|
|
@ -336,7 +358,10 @@ export class AuthService {
|
||||||
return String(Math.floor(1000 + Math.random() * 9000));
|
return String(Math.floor(1000 + Math.random() * 9000));
|
||||||
}
|
}
|
||||||
|
|
||||||
private async sendOtpViaOpenwa(persona: Persona, codigo: string): Promise<void> {
|
private async sendOtpViaOpenwa(
|
||||||
|
persona: Persona,
|
||||||
|
codigo: string,
|
||||||
|
): Promise<void> {
|
||||||
const config = await this.configuracionRepository.findOneBy({});
|
const config = await this.configuracionRepository.findOneBy({});
|
||||||
const sessionId = this.openwaService.resolveSessionId(config);
|
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.`;
|
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);
|
await this.openwaService.sendText(chatId, text, sessionId);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
48
src/modules/mantenimiento/dto/purga.dto.ts
Normal file
48
src/modules/mantenimiento/dto/purga.dto.ts
Normal file
|
|
@ -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;
|
||||||
|
}
|
||||||
62
src/modules/mantenimiento/mantenimiento.controller.ts
Normal file
62
src/modules/mantenimiento/mantenimiento.controller.ts
Normal file
|
|
@ -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<ApiResult> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
38
src/modules/mantenimiento/mantenimiento.module.ts
Normal file
38
src/modules/mantenimiento/mantenimiento.module.ts
Normal file
|
|
@ -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 {}
|
||||||
6
src/modules/mantenimiento/mantenimiento.router.ts
Normal file
6
src/modules/mantenimiento/mantenimiento.router.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
export const routeMantenimiento = {
|
||||||
|
purga: {
|
||||||
|
route: '[POST].../v1/mantenimiento/purga',
|
||||||
|
title: 'Purga de datos (Developer)',
|
||||||
|
},
|
||||||
|
};
|
||||||
197
src/modules/mantenimiento/mantenimiento.service.ts
Normal file
197
src/modules/mantenimiento/mantenimiento.service.ts
Normal file
|
|
@ -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<any>;
|
||||||
|
/// Fragmento WHERE por categoría (columnas camelCase → entrecomilladas).
|
||||||
|
fragmentos: Partial<Record<PurgaCategoria, string>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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<Asistencia>,
|
||||||
|
@InjectRepository(Reemplazo) private reemplazoRepo: Repository<Reemplazo>,
|
||||||
|
@InjectRepository(SolicitudApoyo)
|
||||||
|
private solicitudApoyoRepo: Repository<SolicitudApoyo>,
|
||||||
|
@InjectRepository(EquipoPersona)
|
||||||
|
private equipoPersonaRepo: Repository<EquipoPersona>,
|
||||||
|
@InjectRepository(CodigoOtp) private codigoOtpRepo: Repository<CodigoOtp>,
|
||||||
|
@InjectRepository(Dispositivo)
|
||||||
|
private dispositivoRepo: Repository<Dispositivo>,
|
||||||
|
@InjectRepository(ServicioEquipo)
|
||||||
|
private servicioEquipoRepo: Repository<ServicioEquipo>,
|
||||||
|
@InjectRepository(ServicioTurno)
|
||||||
|
private servicioTurnoRepo: Repository<ServicioTurno>,
|
||||||
|
@InjectRepository(Equipo) private equipoRepo: Repository<Equipo>,
|
||||||
|
@InjectRepository(Servicio) private servicioRepo: Repository<Servicio>,
|
||||||
|
@InjectRepository(Turno) private turnoRepo: Repository<Turno>,
|
||||||
|
@InjectRepository(Persona) private personaRepo: Repository<Persona>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/// 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<ServiceResult> {
|
||||||
|
const serviceResult = defaultServiceResult();
|
||||||
|
const filas: Record<string, number> = {};
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
25
src/modules/reportes/dto/reporte.dto.ts
Normal file
25
src/modules/reportes/dto/reporte.dto.ts
Normal file
|
|
@ -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<string, unknown>;
|
||||||
|
}
|
||||||
24
src/modules/reportes/entities/reporte.entity.ts
Normal file
24
src/modules/reportes/entities/reporte.entity.ts
Normal file
|
|
@ -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<string, unknown> | 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;
|
||||||
|
}
|
||||||
210
src/modules/reportes/reportes.controller.ts
Normal file
210
src/modules/reportes/reportes.controller.ts
Normal file
|
|
@ -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<ApiResult> {
|
||||||
|
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<ApiResult> {
|
||||||
|
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<ApiResult> {
|
||||||
|
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<ApiResult> {
|
||||||
|
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<ApiResult> {
|
||||||
|
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<ApiResult> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
13
src/modules/reportes/reportes.module.ts
Normal file
13
src/modules/reportes/reportes.module.ts
Normal file
|
|
@ -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 {}
|
||||||
26
src/modules/reportes/reportes.router.ts
Normal file
26
src/modules/reportes/reportes.router.ts
Normal file
|
|
@ -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',
|
||||||
|
},
|
||||||
|
};
|
||||||
993
src/modules/reportes/reportes.service.ts
Normal file
993
src/modules/reportes/reportes.service.ts
Normal file
|
|
@ -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<string, unknown>;
|
||||||
|
|
||||||
|
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<Persona>,
|
||||||
|
@InjectRepository(Reporte)
|
||||||
|
private readonly reporteRepository: Repository<Reporte>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 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<string[] | null> {
|
||||||
|
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<ServiceResult> {
|
||||||
|
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<ServiceResult> {
|
||||||
|
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<ServiceResult> {
|
||||||
|
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<ServiceResult> {
|
||||||
|
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<ServiceResult> {
|
||||||
|
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<Fila[]> {
|
||||||
|
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<string, unknown> | undefined,
|
||||||
|
user: AuthUser | null,
|
||||||
|
): Promise<ServiceResult> {
|
||||||
|
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<string, unknown>,
|
||||||
|
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<DatosReporte> {
|
||||||
|
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<void> {
|
||||||
|
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();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -175,6 +175,25 @@ export class ServicioService {
|
||||||
throw new Error(`Atributo no permitido: ${attribute}`);
|
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 = {
|
const param = {
|
||||||
[paramKey]: operator === 'like' ? `%${value}%` : value,
|
[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
|
* Adjunta a cada fila del find sus turnos (con `nombre` y `horaInicio`
|
||||||
* nombre) en 4 queries por página: dos `IN` de filas de unión y dos `IN`
|
* del catálogo) y equipos (con nombre) en 4 queries por página: dos `IN`
|
||||||
* de catálogo. Así el card de la lista pinta grupos y turnos sin N+1.
|
* 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<Servicio[]> {
|
private async enriquecer(servicios: Servicio[]): Promise<Servicio[]> {
|
||||||
if (!servicios.length) return servicios;
|
if (!servicios.length) return servicios;
|
||||||
|
|
@ -247,6 +267,7 @@ export class ServicioService {
|
||||||
: [];
|
: [];
|
||||||
|
|
||||||
const nombreTurno = new Map(turnos.map((t) => [t.idTurno, t.nombre]));
|
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(
|
const nombreEquipo = new Map(
|
||||||
equipos.map((e) => [e.idEquipo, e.nombreEquipo]),
|
equipos.map((e) => [e.idEquipo, e.nombreEquipo]),
|
||||||
);
|
);
|
||||||
|
|
@ -256,7 +277,11 @@ export class ServicioService {
|
||||||
turnos: filasTurno
|
turnos: filasTurno
|
||||||
.filter((t) => t.idServicio === servicio.idServicio)
|
.filter((t) => t.idServicio === servicio.idServicio)
|
||||||
.sort((a, b) => a.sec - b.sec)
|
.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
|
equipos: filasEquipo
|
||||||
.filter((e) => e.idServicio === servicio.idServicio)
|
.filter((e) => e.idServicio === servicio.idServicio)
|
||||||
.map((e) => ({
|
.map((e) => ({
|
||||||
|
|
@ -426,16 +451,22 @@ export class ServicioService {
|
||||||
|
|
||||||
let mensaje = `Servicio actualizado a '${destino}'.`;
|
let mensaje = `Servicio actualizado a '${destino}'.`;
|
||||||
if (destino === EstadoServicio.Finalizado) {
|
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.
|
// Cierre de salidas: solo de quienes ingresaron y aún no salen.
|
||||||
// Líder → solo sus equipos convocados (marcadoSalidaPor = su id);
|
// Líder → solo sus equipos convocados; SuperAdmin/Dev → todos.
|
||||||
// SuperAdmin/Dev → todos los equipos (null, como hasta ahora).
|
|
||||||
let qb = this.asistenciaRepository
|
let qb = this.asistenciaRepository
|
||||||
.createQueryBuilder()
|
.createQueryBuilder()
|
||||||
.update(Asistencia)
|
.update(Asistencia)
|
||||||
.set({
|
.set({
|
||||||
fecSalida: () => 'now()',
|
fecSalida: () => 'now()',
|
||||||
metodoSalida: MetodoMarcado.Sistema,
|
metodoSalida,
|
||||||
marcadoSalidaPor: esGlobal ? null : user.idPersona,
|
marcadoSalidaPor: user.idPersona,
|
||||||
})
|
})
|
||||||
.where('"idServicio" = :idServicio', { idServicio })
|
.where('"idServicio" = :idServicio', { idServicio })
|
||||||
.andWhere('"fecIngreso" IS NOT NULL')
|
.andWhere('"fecIngreso" IS NOT NULL')
|
||||||
|
|
@ -448,37 +479,52 @@ export class ServicioService {
|
||||||
const cerradas = await qb.execute();
|
const cerradas = await qb.execute();
|
||||||
const n = cerradas.affected ?? 0;
|
const n = cerradas.affected ?? 0;
|
||||||
|
|
||||||
// Sin ingreso registrado → Falta con observación (tanda 2026-10-17):
|
// Re-evaluación de estado al finalizar (tanda 2026-10-22), en este
|
||||||
// solo filas aún 'Pendiente' (respeta Permiso/Falta manuales y
|
// orden de prioridad:
|
||||||
// Eliminado); mismo scoping por equipo que el cierre de salidas.
|
// 1) persona no Activa → Eliminado (aunque haya marcado o Permiso).
|
||||||
let qbFalta = this.asistenciaRepository
|
// 2) Permiso (manual) → se respeta, no se toca.
|
||||||
.createQueryBuilder()
|
// 3) sin ingreso → Falta, sin observación automática (la observación
|
||||||
.update(Asistencia)
|
// es solo para justificar Permiso/Falta manuales).
|
||||||
.set({
|
// 4) con ingreso → Presente/Atrasado según fecIngreso vs inicio del
|
||||||
estado: EstadoAsistencia.Falta,
|
// turno más temprano, sin tolerancia (igual que marcar()).
|
||||||
observacion:
|
// Un Eliminado existente no se re-abre.
|
||||||
'Cierre automático: sin ingreso al finalizar el servicio.',
|
const umbral = await this.umbralInicio(servicio);
|
||||||
})
|
const params: unknown[] = [idServicio];
|
||||||
.where('"idServicio" = :idServicio', { idServicio })
|
let alcance = '';
|
||||||
.andWhere('"fecIngreso" IS NULL')
|
|
||||||
.andWhere('"estado" = :estadoPendiente', {
|
|
||||||
estadoPendiente: EstadoAsistencia.Pendiente,
|
|
||||||
});
|
|
||||||
if (!esGlobal) {
|
if (!esGlobal) {
|
||||||
qbFalta = qbFalta.andWhere('"idEquipo" IN (:...idsEquipos)', {
|
params.push(equiposPropios);
|
||||||
idsEquipos: equiposPropios,
|
alcance = 'AND a."idEquipo" = ANY($2::uuid[])';
|
||||||
});
|
|
||||||
}
|
}
|
||||||
const faltas = await qbFalta.execute();
|
params.push(umbral);
|
||||||
const m = faltas.affected ?? 0;
|
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 =
|
const detalle =
|
||||||
n > 0 && m > 0
|
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
|
: n > 0
|
||||||
? `Se cerró la salida de ${n} integrante(s)`
|
? `Se cerró la salida de ${n} integrante(s)`
|
||||||
: m > 0
|
: m > 0
|
||||||
? `Se marcaron ${m} falta(s) por sin ingreso`
|
? `Se re-evaluó ${m} estado(s)`
|
||||||
: '';
|
: '';
|
||||||
mensaje = !detalle
|
mensaje = !detalle
|
||||||
? 'Servicio finalizado.'
|
? 'Servicio finalizado.'
|
||||||
|
|
@ -494,6 +540,28 @@ export class ServicioService {
|
||||||
return serviceResult;
|
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<Date | null> {
|
||||||
|
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**
|
* DELETE = borrado lógico (`estado = Eliminado`) de **cualquier estado**
|
||||||
* (decisión del usuario 2026-10-10: antes solo borradores). Aplica los
|
* (decisión del usuario 2026-10-10: antes solo borradores). Aplica los
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue