Compare commits

..

1 Commits

Author SHA1 Message Date
Angel Capetillo Zavala a370f307b5 feat(auth): implementar flujo de login y acceso en WebApp 2026-09-29 10:23:09 -06:00
84 changed files with 1025 additions and 3260 deletions
+1 -1
View File
@@ -7,4 +7,4 @@ RUN npm install
COPY . .
EXPOSE 4200
CMD ["npx", "ng", "serve", "--host", "0.0.0.0", "--port", "4200"]
CMD ["npx", "ng", "serve", "--host", "0.0.0.0", "--port", "4200", "--proxy-config", "proxy.docker.json"]
+4 -2
View File
@@ -2,8 +2,7 @@
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"cli": {
"packageManager": "npm",
"analytics": false
"packageManager": "npm"
},
"newProjectRoot": "projects",
"projects": {
@@ -60,6 +59,9 @@
},
"serve": {
"builder": "@angular/build:dev-server",
"options": {
"proxyConfig": "proxy.local.json"
},
"configurations": {
"production": {
"buildTarget": "WebApp:build:production"
+1 -260
View File
@@ -16,11 +16,8 @@
"@angular/material": "^22.1.7",
"@angular/platform-browser": "^22.1.0",
"@angular/router": "^22.1.0",
"jspdf": "4.2.1",
"plotly.js-basic-dist-min": "^4.1.1",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
"tslib": "^2.3.0"
},
"devDependencies": {
"@angular/build": "^22.1.8",
@@ -724,15 +721,6 @@
"node": "^22.18.0 || >=24.11.0"
}
},
"node_modules/@babel/runtime": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",
"integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/template": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/@babel/template/-/template-8.0.0.tgz",
@@ -3727,26 +3715,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/pako": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/@types/pako/-/pako-2.0.4.tgz",
"integrity": "sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw==",
"license": "MIT"
},
"node_modules/@types/raf": {
"version": "3.4.3",
"resolved": "https://registry.npmjs.org/@types/raf/-/raf-3.4.3.tgz",
"integrity": "sha512-c4YAvMedbPZ5tEyxzQdMoOhhJ4RD3rngZIdwC2/qDN3d7JpEhB6fiBRKVY1lg5B7Wk+uPBjn5f39j1/2MY1oOw==",
"license": "MIT",
"optional": true
},
"node_modules/@types/trusted-types": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
"license": "MIT",
"optional": true
},
"node_modules/@vitejs/plugin-basic-ssl": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-basic-ssl/-/plugin-basic-ssl-2.3.0.tgz",
@@ -4011,16 +3979,6 @@
"node": ">=12"
}
},
"node_modules/base64-arraybuffer": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-1.0.2.tgz",
"integrity": "sha512-I3yl4r9QB5ZRY3XuJVEPfc2XhZO6YweFPI+UovAzn+8/hb3oJ6lnysaFcjVpkCPfVWFUDvoZ8kmVDP7WyRtYtQ==",
"license": "MIT",
"optional": true,
"engines": {
"node": ">= 0.6.0"
}
},
"node_modules/baseline-browser-mapping": {
"version": "2.11.25",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.25.tgz",
@@ -4214,26 +4172,6 @@
],
"license": "CC-BY-4.0"
},
"node_modules/canvg": {
"version": "3.0.11",
"resolved": "https://registry.npmjs.org/canvg/-/canvg-3.0.11.tgz",
"integrity": "sha512-5ON+q7jCTgMp9cjpu4Jo6XbvfYwSB2Ow3kzHKfIyJfaCAOHLbdKPQqGKgfED/R5B+3TFFfe8pegYA+b423SRyA==",
"license": "MIT",
"optional": true,
"dependencies": {
"@babel/runtime": "^7.12.5",
"@types/raf": "^3.4.0",
"core-js": "^3.8.3",
"raf": "^3.4.1",
"regenerator-runtime": "^0.13.7",
"rgbcolor": "^1.0.1",
"stackblur-canvas": "^2.0.0",
"svg-pathdata": "^6.0.3"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/chai": {
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
@@ -4438,21 +4376,6 @@
"node": ">=6.6.0"
}
},
"node_modules/core-js": {
"version": "3.50.0",
"resolved": "https://registry.npmjs.org/core-js/-/core-js-3.50.0.tgz",
"integrity": "sha512-BRWgOLKkFeCgRudR6zrs8p9XJZcE14grzKMMssoYrk6krtuEZ7MTKPIY5RzOnqsEKIR9kst7wNzphttraT+Yqw==",
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"engines": {
"node": "*"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/core-js"
}
},
"node_modules/cors": {
"version": "2.8.6",
"resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",
@@ -4486,16 +4409,6 @@
"node": ">= 8"
}
},
"node_modules/css-line-break": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/css-line-break/-/css-line-break-2.1.0.tgz",
"integrity": "sha512-FHcKFCZcAha3LwfVBhCQbW2nCNbkZXn7KVUJcsT5/P8YmfsVja0FMPJr0B903j/E69HUphKiV9iQArX8SDYA4w==",
"license": "MIT",
"optional": true,
"dependencies": {
"utrie": "^1.0.2"
}
},
"node_modules/css-select": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/css-select/-/css-select-6.0.0.tgz",
@@ -4659,16 +4572,6 @@
"url": "https://github.com/fb55/domhandler?sponsor=1"
}
},
"node_modules/dompurify": {
"version": "3.4.16",
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.16.tgz",
"integrity": "sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==",
"license": "(MPL-2.0 OR Apache-2.0)",
"optional": true,
"optionalDependencies": {
"@types/trusted-types": "^2.0.7"
}
},
"node_modules/domutils": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
@@ -4989,17 +4892,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/fast-png": {
"version": "6.4.0",
"resolved": "https://registry.npmjs.org/fast-png/-/fast-png-6.4.0.tgz",
"integrity": "sha512-kAqZq1TlgBjZcLr5mcN6NP5Rv4V2f22z00c3g8vRrwkcqjerx7BEhPbOnWCPqaHUl2XWQBJQvOT/FQhdMT7X/Q==",
"license": "MIT",
"dependencies": {
"@types/pako": "^2.0.3",
"iobuffer": "^5.3.2",
"pako": "^2.1.0"
}
},
"node_modules/fast-string-truncated-width": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz",
@@ -5062,12 +4954,6 @@
}
}
},
"node_modules/fflate": {
"version": "0.8.3",
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
"license": "MIT"
},
"node_modules/finalhandler": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",
@@ -5299,20 +5185,6 @@
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
}
},
"node_modules/html2canvas": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/html2canvas/-/html2canvas-1.4.1.tgz",
"integrity": "sha512-fPU6BHNpsyIhr8yyMpTLLxAbkaK8ArIBcmZIRiBLiDhjeqvXolaEmDGmELFuX9I4xDcaKKcJl+TKZLqruBbmWA==",
"license": "MIT",
"optional": true,
"dependencies": {
"css-line-break": "^2.1.0",
"text-segmentation": "^1.0.3"
},
"engines": {
"node": ">=8.0.0"
}
},
"node_modules/htmlparser2": {
"version": "10.1.0",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz",
@@ -5448,12 +5320,6 @@
"dev": true,
"license": "ISC"
},
"node_modules/iobuffer": {
"version": "5.4.0",
"resolved": "https://registry.npmjs.org/iobuffer/-/iobuffer-5.4.0.tgz",
"integrity": "sha512-DRebOWuqDvxunfkNJAlc3IzWIPD5xVxwUNbHr7xKB8E6aLJxIPfNX3CoMJghcFjpv6RWQsrcJbghtEwSPoJqMA==",
"license": "MIT"
},
"node_modules/ip-address": {
"version": "10.7.2",
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.2.tgz",
@@ -5691,23 +5557,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/jspdf": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/jspdf/-/jspdf-4.2.1.tgz",
"integrity": "sha512-YyAXyvnmjTbR4bHQRLzex3CuINCDlQnBqoSYyjJwTP2x9jDLuKDzy7aKUl0hgx3uhcl7xzg32agn5vlie6HIlQ==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.28.6",
"fast-png": "^6.2.0",
"fflate": "^0.8.1"
},
"optionalDependencies": {
"canvg": "^3.0.11",
"core-js": "^3.6.0",
"dompurify": "^3.3.1",
"html2canvas": "^1.0.0-rc.5"
}
},
"node_modules/lightningcss": {
"version": "1.33.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
@@ -6486,22 +6335,6 @@
"@oxc-parser/binding-win32-x64-msvc": "0.142.0"
}
},
"node_modules/pako": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/pako/-/pako-2.2.0.tgz",
"integrity": "sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/puzrin"
},
{
"type": "github",
"url": "https://github.com/sponsors/nodeca"
}
],
"license": "(MIT AND Zlib)"
},
"node_modules/parse5": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz",
@@ -6605,13 +6438,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/performance-now": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz",
"integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==",
"license": "MIT",
"optional": true
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -6655,12 +6481,6 @@
"node": ">=16.20.0"
}
},
"node_modules/plotly.js-basic-dist-min": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/plotly.js-basic-dist-min/-/plotly.js-basic-dist-min-4.1.1.tgz",
"integrity": "sha512-1oNF8PeQx2hv/y7tqEVWKD3JGwn/MGEMQ8mL9HUwsaqG9FGy/OU5FHUHvzqbqxN4mnwZGI9abTiE775C4kkjMQ==",
"license": "MIT"
},
"node_modules/postcss": {
"version": "8.5.28",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
@@ -6813,16 +6633,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/raf": {
"version": "3.4.1",
"resolved": "https://registry.npmjs.org/raf/-/raf-3.4.1.tgz",
"integrity": "sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA==",
"license": "MIT",
"optional": true,
"dependencies": {
"performance-now": "^2.1.0"
}
},
"node_modules/range-parser": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz",
@@ -6874,13 +6684,6 @@
"dev": true,
"license": "Apache-2.0"
},
"node_modules/regenerator-runtime": {
"version": "0.13.11",
"resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz",
"integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==",
"license": "MIT",
"optional": true
},
"node_modules/require-from-string": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
@@ -6908,16 +6711,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/rgbcolor": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/rgbcolor/-/rgbcolor-1.0.1.tgz",
"integrity": "sha512-9aZLIrhRaD97sgVhtJOW6ckOEh6/GnvQtdVNfdZ6s67+3/XwLS9lBcQYzEEhYVeUowN7pRzMLsyGhK2i/xvWbw==",
"license": "MIT OR SEE LICENSE IN FEEL-FREE.md",
"optional": true,
"engines": {
"node": ">= 0.8.15"
}
},
"node_modules/rolldown": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.0.tgz",
@@ -7280,16 +7073,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/stackblur-canvas": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/stackblur-canvas/-/stackblur-canvas-2.7.0.tgz",
"integrity": "sha512-yf7OENo23AGJhBriGx0QivY5JP6Y1HbrrDI6WLt6C5auYZXlQrheoY8hD4ibekFKz1HOfE48Ww8kMWMnJD/zcQ==",
"license": "MIT",
"optional": true,
"engines": {
"node": ">=0.1.14"
}
},
"node_modules/statuses": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
@@ -7353,16 +7136,6 @@
"url": "https://github.com/chalk/strip-ansi?sponsor=1"
}
},
"node_modules/svg-pathdata": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/svg-pathdata/-/svg-pathdata-6.0.3.tgz",
"integrity": "sha512-qsjeeq5YjBZ5eMdFuUa4ZosMLxgr5RZ+F+Y1OrDhuOCEInRMA3x74XdBtggJcj9kOeInz0WE+LgCPDkZFlBYJw==",
"license": "MIT",
"optional": true,
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/symbol-tree": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
@@ -7370,16 +7143,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/text-segmentation": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/text-segmentation/-/text-segmentation-1.0.3.tgz",
"integrity": "sha512-iOiPUo/BGnZ6+54OsWxZidGCsdU8YbE4PSpdPinp7DeMtUJNJBoJ/ouUSTJjHkh1KntHaltHl/gDs2FC4i5+Nw==",
"license": "MIT",
"optional": true,
"dependencies": {
"utrie": "^1.0.2"
}
},
"node_modules/tinybench": {
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
@@ -7584,16 +7347,6 @@
"browserslist": ">= 4.21.0"
}
},
"node_modules/utrie": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/utrie/-/utrie-1.0.2.tgz",
"integrity": "sha512-1MLa5ouZiOmQzUbjbu9VmjLzn1QLXBhwpUa7kdLUQK+KQ5KA9I1vk5U4YHe/X2Ch7PYnJfWuWT+VbuxbGwljhw==",
"license": "MIT",
"optional": true,
"dependencies": {
"base64-arraybuffer": "^1.0.2"
}
},
"node_modules/validate-npm-package-name": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-8.0.0.tgz",
@@ -8273,18 +8026,6 @@
"dev": true,
"license": "ISC"
},
"node_modules/xlsx": {
"version": "0.20.3",
"resolved": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
"integrity": "sha512-oLDq3jw7AcLqKWH2AhCpVTZl8mf6X2YReP+Neh0SJUzV/BdZYjth94tG5toiMB1PPrYtxOCfaoUCkvtuH+3AJA==",
"license": "Apache-2.0",
"bin": {
"xlsx": "bin/xlsx.njs"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/xml-name-validator": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
+1 -4
View File
@@ -19,11 +19,8 @@
"@angular/material": "^22.1.7",
"@angular/platform-browser": "^22.1.0",
"@angular/router": "^22.1.0",
"jspdf": "4.2.1",
"plotly.js-basic-dist-min": "^4.1.1",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
"tslib": "^2.3.0"
},
"devDependencies": {
"@angular/build": "^22.1.8",
+5
View File
@@ -0,0 +1,5 @@
{
"/auth/**": {
"target": "http://webapi:5000"
}
}
+5
View File
@@ -0,0 +1,5 @@
{
"/auth/**": {
"target": "http://127.0.0.1:5000"
}
}

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

-13
View File
@@ -1,13 +0,0 @@
@mixin base {
border-radius: 8px;
font: inherit;
font-weight: 600;
min-height: 44px;
padding: 10px 18px;
transition: background-color 0.18s ease;
}
@mixin focus {
outline: 3px solid rgb(168 194 67 / 65%);
outline-offset: 2px;
}
-12
View File
@@ -1,12 +0,0 @@
<div class="action-options" role="group" aria-label="Acción sobre el análisis actual">
<button class="action-card" [class.action-card--selected]="intent === 'append'" [attr.aria-pressed]="intent === 'append'" type="button" (click)="intentChange.emit('append')">
<span class="action-card__icon"><mat-icon aria-hidden="true">playlist_add</mat-icon></span>
<span class="action-card__copy"><span class="action-card__title">Agregar información</span><span class="action-card__description">Combina los nuevos datos con el análisis actual.</span></span>
@if (intent === 'append') { <mat-icon class="action-card__check" aria-hidden="true">check_circle</mat-icon> }
</button>
<button class="action-card" [class.action-card--selected]="intent === 'replace'" [attr.aria-pressed]="intent === 'replace'" type="button" (click)="intentChange.emit('replace')">
<span class="action-card__icon"><mat-icon aria-hidden="true">restart_alt</mat-icon></span>
<span class="action-card__copy"><span class="action-card__title">Nuevo análisis</span><span class="action-card__description">Descarta los resultados actuales y comienza un nuevo análisis.</span></span>
@if (intent === 'replace') { <mat-icon class="action-card__check" aria-hidden="true">check_circle</mat-icon> }
</button>
</div>
-14
View File
@@ -1,14 +0,0 @@
@use 'upload-button' as button;
:host { display: block; }
.action-options { display: grid; gap: 16px; grid-template-columns: repeat(2, minmax(0, 1fr)); }
.action-card { align-items: center; background: #fff; border: 1px solid var(--color-border); border-radius: 9px; color: var(--color-text); cursor: pointer; display: flex; gap: 16px; min-height: 126px; padding: 20px; position: relative; text-align: left; transition: background-color .18s ease, border-color .18s ease; }
.action-card:hover { background: var(--color-surface-hover); border-color: var(--color-primary); }
.action-card:focus-visible { @include button.focus; }
.action-card--selected { background: #fbfcf6; border: 2px solid var(--color-primary); padding: 19px; }
.action-card__icon { align-items: center; background: var(--color-step); border-radius: 8px; color: #71882b; display: inline-flex; flex: 0 0 46px; height: 46px; justify-content: center; }
.action-card__copy { display: grid; gap: 6px; min-width: 0; }
.action-card__title { font-size: 16px; font-weight: 600; }
.action-card__description { color: var(--color-text-secondary); font-size: 13px; line-height: 1.45; }
.action-card__check { color: #71882b; margin-left: auto; }
@media (max-width: 600px) { .action-options { grid-template-columns: 1fr; } .action-card { min-height: 94px; padding: 16px; } .action-card--selected { padding: 15px; } }
-14
View File
@@ -1,14 +0,0 @@
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { MatIconModule } from '@angular/material/icon';
import type { UploadIntent } from './information-upload-dialog';
@Component({
imports: [MatIconModule],
selector: 'app-action-selection',
styleUrl: './action-selection.scss',
templateUrl: './action-selection.html',
})
export class ActionSelectionComponent {
@Input() intent: UploadIntent | null = null;
@Output() readonly intentChange = new EventEmitter<UploadIntent>();
}
+2
View File
@@ -1,10 +1,12 @@
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideHttpClient(),
provideRouter(routes)
]
};
+12 -19
View File
@@ -1,20 +1,13 @@
<div class="app-shell">
<header class="site-header">
<div class="site-header__content">
<a class="brand" href="/" aria-label="ISSSTELEON, inicio">
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
</a>
<span class="site-header__section">Análisis de información</span>
</div>
</header>
@if (auth.isAuthenticated()) {
<mat-toolbar color="primary">
<span>{{ title }}</span>
<span class="spacer"></span>
<span class="username">{{ auth.user()?.username }}</span>
<button mat-button (click)="auth.logout()">Cerrar sesión</button>
</mat-toolbar>
}
<main class="app-main">
<router-outlet />
</main>
<footer class="site-footer">
<div class="site-footer__content">
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
</div>
</footer>
</div>
<main>
@if (auth.status() === 'checking') { <p role="status">Comprobando sesión…</p> }
<div [hidden]="auth.status() === 'checking'"><router-outlet /></div>
</main>
+10 -3
View File
@@ -1,7 +1,14 @@
import { Routes } from '@angular/router';
import { Home } from './home';
import { authGuard, anonymousGuard, areaGuard } from './auth/auth.guard';
import { AreaPlaceholder } from './auth/area-placeholder';
import { Home } from './auth/home';
import { Login } from './auth/login';
export const routes: Routes = [
{ path: '', component: Home },
{ path: 'dashboard', loadComponent: () => import('./dashboard/dashboard').then((module) => module.Dashboard) },
{ path: 'login', component: Login, canActivate: [anonymousGuard] },
{ path: '', pathMatch: 'full', component: Home, canActivate: [authGuard] },
{ path: 'cacu', component: AreaPlaceholder, data: { area: 'CACU' }, canActivate: [areaGuard('CACU')] },
{ path: 'cama', component: AreaPlaceholder, data: { area: 'CAMA' }, canActivate: [areaGuard('CAMA')] },
{ path: 'tea', component: AreaPlaceholder, data: { area: 'TEA' }, canActivate: [areaGuard('TEA')] },
{ path: '**', redirectTo: '' },
];
+4 -85
View File
@@ -1,86 +1,5 @@
.app-shell {
display: flex;
flex-direction: column;
min-height: 100vh;
min-height: 100dvh;
}
.site-header {
background: var(--color-surface);
border-bottom: 1px solid var(--color-border);
}
.site-header__content {
align-items: center;
display: flex;
justify-content: space-between;
min-height: 88px;
padding: 0 clamp(32px, 3.2vw, 48px);
}
.brand {
align-items: center;
display: inline-flex;
}
.brand img {
display: block;
height: auto;
width: clamp(180px, 16vw, 200px);
}
.site-header__section {
color: var(--color-text);
font-size: 15px;
font-weight: 500;
letter-spacing: 0.01em;
}
.app-main {
display: flex;
flex: 1;
}
.site-footer {
background: var(--color-text-secondary);
}
.site-footer__content {
align-items: center;
display: flex;
justify-content: center;
min-height: 86px;
padding: 0 clamp(32px, 3.2vw, 48px);
}
.site-footer img {
display: block;
filter: brightness(0) invert(1);
height: auto;
width: clamp(160px, 15vw, 185px);
}
@media (max-width: 600px) {
.site-header__content {
min-height: 70px;
padding: 0 20px;
}
.brand img {
width: clamp(132px, 42vw, 170px);
}
.site-header__section {
font-size: 13px;
text-align: right;
}
.site-footer__content {
min-height: 76px;
padding: 0 20px;
}
.site-footer img {
width: 155px;
}
main {
padding: 1.5rem;
}
.spacer { flex: 1; }
.username { font-size: .875rem; margin-right: .5rem; overflow: hidden; text-overflow: ellipsis; }
+32 -583
View File
@@ -1,31 +1,25 @@
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideRouter, Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { App } from './app';
import { routes } from './app.routes';
import { InformationUploadDialog } from './information-upload-dialog';
import { MatDialogRef } from '@angular/material/dialog';
import { provideRouter } from '@angular/router';
import { vi } from 'vitest';
vi.mock('plotly.js-basic-dist-min', () => ({
default: {
react: vi.fn().mockResolvedValue(undefined),
purge: vi.fn(),
Plots: { resize: vi.fn() },
},
}));
import { App } from './app';
import { AuthState } from './auth/auth.state';
import { routes } from './app.routes';
import { authGuard, anonymousGuard } from './auth/auth.guard';
describe('App', () => {
const status = signal('anonymous');
const user = signal({ id: 1, username: 'demo', roles: ['CAMA'] });
const logout = vi.fn();
beforeEach(async () => {
vi.stubGlobal('ResizeObserver', class {
observe() {}
unobserve() {}
disconnect() {}
});
status.set('anonymous'); logout.mockClear();
await TestBed.configureTestingModule({
imports: [App],
providers: [provideRouter(routes)],
}).compileComponents();
providers: [provideRouter([]), { provide: AuthState, useValue: {
status, user, isAuthenticated: () => status() === 'authenticated', logout,
} }],
})
.compileComponents();
});
it('should create the app', () => {
@@ -34,574 +28,29 @@ describe('App', () => {
expect(app).toBeTruthy();
});
it('should render the ISSSTELEON header and home page', async () => {
it('should render the toolbar title', async () => {
status.set('authenticated');
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
await TestBed.inject(Router).navigateByUrl('/');
await fixture.whenStable();
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON');
expect(compiled.querySelector('.site-header__section')?.textContent).toContain(
'Análisis de información',
);
expect(compiled.querySelector('h1')?.textContent).toContain('Analiza tu información');
expect(compiled.querySelector('mat-toolbar')?.textContent).toContain('ISSSTELEON');
});
it('opens one dialog and keeps it open on backdrop and Escape', async () => {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
await TestBed.inject(Router).navigateByUrl('/');
await fixture.whenStable();
fixture.detectChanges();
fixture.nativeElement.querySelector('.home__action').click();
fixture.detectChanges();
await fixture.whenStable();
const dialog = TestBed.inject(MatDialog);
expect(dialog.openDialogs).toHaveLength(1);
const overlay = document.querySelector('.cdk-overlay-container')!;
expect(overlay.querySelector('#upload-title')?.textContent).toContain('Cargar información');
overlay.querySelector<HTMLElement>('.cdk-overlay-backdrop')?.click();
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
expect(dialog.openDialogs).toHaveLength(1);
expect(overlay.querySelector('.upload-dialog__continue')?.hasAttribute('disabled')).toBe(true);
it('hides shell for anonymous and checking', () => {
const fixture = TestBed.createComponent(App); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('mat-toolbar')).toBeNull();
status.set('checking'); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('mat-toolbar')).toBeNull();
expect(fixture.nativeElement.querySelector('router-outlet').parentElement.hidden).toBe(true);
});
it('selects either source, continues, returns with selection, and closes explicitly', async () => {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
await TestBed.inject(Router).navigateByUrl('/');
await fixture.whenStable();
fixture.detectChanges();
fixture.nativeElement.querySelector('.home__action').click();
fixture.detectChanges();
await fixture.whenStable();
const overlay = document.querySelector('.cdk-overlay-container')!;
const cards = () => overlay.querySelectorAll<HTMLButtonElement>('.source-card');
const continueButton = overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')!;
const detectDialogChanges = () => TestBed.inject(MatDialog).openDialogs[0].componentRef?.changeDetectorRef.detectChanges();
expect(continueButton.disabled).toBe(true);
overlay.querySelector<HTMLButtonElement>('.source-card')!.click();
detectDialogChanges();
expect(continueButton.disabled).toBe(false);
overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')!.click();
detectDialogChanges();
fixture.detectChanges();
expect(overlay.querySelector('.upload-dialog__description')?.textContent).toContain(
'Selecciona los archivos que deseas procesar.',
);
expect(overlay.querySelector('.upload-steps__item--active')?.textContent).toContain(
'Configuración',
);
expect(continueButton.disabled).toBe(true);
const fileInput = overlay.querySelector<HTMLInputElement>('input[type="file"]')!;
const validFile = new File(['contenido'], 'pacientes.XLSX', {
type: 'application/octet-stream',
});
const csvFile = new File(['a,b'], 'consultas.csv', { type: 'text/csv' });
const invalidFile = new File(['x'], 'documento.docx');
const emptyFile = new File([], 'vacio.csv');
const selectFiles = (...files: File[]) => {
Object.defineProperty(fileInput, 'files', { configurable: true, value: files });
fileInput.dispatchEvent(new Event('change', { bubbles: true }));
detectDialogChanges();
fixture.detectChanges();
};
selectFiles(validFile, csvFile, invalidFile, emptyFile);
expect(overlay.querySelectorAll('.file-row')).toHaveLength(2);
expect(overlay.querySelector('.file-messages')?.textContent).toContain(
'documento.docx no fue agregado. Formato no compatible.',
);
expect(overlay.querySelector('.file-messages')?.textContent).toContain(
'vacio.csv no fue agregado. El archivo está vacío.',
);
expect(continueButton.disabled).toBe(false);
selectFiles(validFile);
expect(overlay.querySelectorAll('.file-row')).toHaveLength(2);
expect(overlay.querySelector('.file-messages')?.textContent).toContain(
'pacientes.XLSX ya se encuentra seleccionado.',
);
const jsonFile = new File(['{}'], 'nuevo.json', { type: 'application/json' });
const dialogComponent = TestBed.inject(MatDialog).openDialogs[0].componentRef!
.instance as import('./information-upload-dialog').InformationUploadDialog;
const drop = new Event('drop', { bubbles: true, cancelable: true });
Object.defineProperty(drop, 'dataTransfer', { value: { files: [jsonFile] } });
overlay.querySelector<HTMLElement>('.dropzone')!.dispatchEvent(drop);
detectDialogChanges();
fixture.detectChanges();
expect(overlay.querySelectorAll('.file-row')).toHaveLength(3);
overlay.querySelector<HTMLButtonElement>('.file-row__remove')!.click();
detectDialogChanges();
fixture.detectChanges();
expect(overlay.querySelectorAll('.file-row')).toHaveLength(2);
continueButton.click();
detectDialogChanges();
fixture.detectChanges();
expect(overlay.querySelector('h3')?.textContent).toContain('Archivos a procesar');
expect(overlay.querySelector('.upload-steps__item--complete')?.textContent).toContain('Fuente');
expect(overlay.querySelectorAll('.upload-steps__item--complete')[1]?.textContent).toContain('Configuración');
expect(overlay.querySelector('.upload-steps__item--active')?.textContent).toContain('Confirmación');
expect(overlay.querySelector('.upload-dialog__description')?.textContent).toContain(
'Revisa la información antes de iniciar el procesamiento.',
);
expect(overlay.querySelector('.confirmation-summary')?.textContent).toContain('Archivo');
expect(overlay.querySelector('.confirmation-summary')?.textContent).toContain('2');
expect(overlay.querySelectorAll('.confirmation-files .file-row')).toHaveLength(2);
expect(overlay.querySelector('.confirmation-files')?.textContent).not.toContain('pacientes.XLSX');
expect(overlay.querySelector('.confirmation-files')?.textContent).toContain('consultas.csv');
expect(overlay.querySelector('.confirmation-files')?.textContent).toContain('nuevo.json');
expect(overlay.querySelector('.confirmation-summary')?.textContent).toContain(
dialogComponent.formatFileSize(dialogComponent.totalFileSize()),
);
expect(overlay.querySelector('.confirmation-files .file-row__remove')).toBeNull();
expect(overlay.querySelector<HTMLButtonElement>('.upload-dialog__process')?.disabled).toBe(false);
overlay.querySelector<HTMLButtonElement>('.upload-dialog__back')!.click();
detectDialogChanges();
fixture.detectChanges();
expect(overlay.querySelectorAll('.file-configuration .file-row')).toHaveLength(2);
overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')!.click();
detectDialogChanges();
fixture.detectChanges();
expect(overlay.querySelectorAll('.confirmation-files .file-row')).toHaveLength(2);
expect(overlay.querySelector('.confirmation-summary')?.textContent).toContain(
dialogComponent.formatFileSize(dialogComponent.totalFileSize()),
);
overlay.querySelector<HTMLButtonElement>('.upload-dialog__back')!.click();
detectDialogChanges();
fixture.detectChanges();
while (overlay.querySelector('.file-row__remove')) {
overlay.querySelector<HTMLButtonElement>('.file-row__remove')!.click();
detectDialogChanges();
fixture.detectChanges();
}
expect(overlay.querySelectorAll('.file-row')).toHaveLength(0);
expect(overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')?.disabled).toBe(true);
overlay.querySelector<HTMLButtonElement>('.upload-dialog__back')!.click();
detectDialogChanges();
fixture.detectChanges();
expect(cards()[0].getAttribute('aria-pressed')).toBe('true');
overlay.querySelectorAll<HTMLButtonElement>('.source-card')[1].click();
detectDialogChanges();
const sqlContinueButton = overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')!;
expect(sqlContinueButton.disabled).toBe(false);
sqlContinueButton.click();
detectDialogChanges();
fixture.detectChanges();
expect(overlay.querySelector('input[formcontrolname="host"]')).not.toBeNull();
expect(overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')?.disabled).toBe(true);
overlay.querySelector<HTMLButtonElement>('.upload-dialog__back')!.click();
detectDialogChanges();
fixture.detectChanges();
expect(cards()[1].getAttribute('aria-pressed')).toBe('true');
overlay.querySelector<HTMLButtonElement>('.upload-dialog__close')!.click();
fixture.detectChanges();
await new Promise((resolve) => setTimeout(resolve, 200));
expect(TestBed.inject(MatDialog).openDialogs).toHaveLength(0);
fixture.nativeElement.querySelector('.home__action').click();
fixture.detectChanges();
await fixture.whenStable();
const reopenedOverlay = document.querySelector('.cdk-overlay-container')!;
reopenedOverlay.querySelector<HTMLButtonElement>('.source-card')!.click();
const reopenedDialog = TestBed.inject(MatDialog).openDialogs[0].componentRef!;
reopenedDialog.changeDetectorRef.detectChanges();
reopenedOverlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')!.click();
reopenedDialog.changeDetectorRef.detectChanges();
expect(reopenedOverlay.querySelector('.selected-files')).toBeNull();
expect(reopenedOverlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')?.disabled).toBe(true);
const singleFile = new File(['{}'], 'solo.json', { type: 'application/json' });
const reopenedFileInput = reopenedOverlay.querySelector<HTMLInputElement>('input[type="file"]')!;
Object.defineProperty(reopenedFileInput, 'files', { configurable: true, value: [singleFile] });
reopenedFileInput.dispatchEvent(new Event('change', { bubbles: true }));
reopenedDialog.changeDetectorRef.detectChanges();
reopenedOverlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')!.click();
reopenedDialog.changeDetectorRef.detectChanges();
expect(reopenedOverlay.querySelector('.confirmation-summary')?.textContent).toContain('1');
expect(reopenedOverlay.querySelector('.confirmation-files')?.textContent).toContain('solo.json');
expect(reopenedOverlay.querySelector('.confirmation-files .file-row__remove')).toBeNull();
reopenedOverlay.querySelector<HTMLButtonElement>('.upload-dialog__cancel')!.click();
fixture.detectChanges();
await new Promise((resolve) => setTimeout(resolve, 200));
expect(TestBed.inject(MatDialog).openDialogs).toHaveLength(0);
it('invokes local logout from shell', () => {
status.set('authenticated'); const fixture = TestBed.createComponent(App); fixture.detectChanges();
fixture.nativeElement.querySelector('button').click(); expect(logout).toHaveBeenCalledOnce();
});
it('validates SQL configuration locally and keeps its values through navigation', async () => {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
await TestBed.inject(Router).navigateByUrl('/');
await fixture.whenStable();
fixture.detectChanges();
fixture.nativeElement.querySelector('.home__action').click();
fixture.detectChanges();
await fixture.whenStable();
const dialog = TestBed.inject(MatDialog).openDialogs[0].componentRef!;
const detect = () => dialog.changeDetectorRef.detectChanges();
const overlay = document.querySelector('.cdk-overlay-container')!;
const type = (selector: string, value: string) => {
const input = overlay.querySelector<HTMLInputElement>(selector)!;
input.value = value;
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('blur', { bubbles: true }));
detect();
};
overlay.querySelectorAll<HTMLButtonElement>('.source-card')[1].click();
detect();
overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')!.click();
detect();
expect(overlay.querySelector('.sql-config__hint')?.textContent).toContain(
'Ingresa los datos de la base de datos que deseas utilizar.',
);
expect(overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')?.disabled).toBe(true);
const fillRequired = () => {
type('[formcontrolname="host"]', ' servidor.interno.local ');
type('[formcontrolname="database"]', ' datos ');
type('[formcontrolname="username"]', ' usuario ');
type('[formcontrolname="password"]', 'secreto');
};
fillRequired();
expect(overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')?.disabled).toBe(false);
type('[formcontrolname="port"]', '0');
expect(overlay.querySelector('.sql-config')?.textContent).toContain('El puerto debe estar entre 1 y 65535.');
expect(overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')?.disabled).toBe(true);
type('[formcontrolname="port"]', '65536');
expect(overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')?.disabled).toBe(true);
type('[formcontrolname="port"]', '1433');
expect(overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')?.disabled).toBe(false);
const password = overlay.querySelector<HTMLInputElement>('[formcontrolname="password"]')!;
expect(password.type).toBe('password');
const showPassword = overlay.querySelector<HTMLButtonElement>('[aria-label="Mostrar contraseña"]')!;
expect(showPassword.getAttribute('aria-pressed')).toBe('false');
showPassword.focus();
expect(document.activeElement).toBe(showPassword);
showPassword.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
showPassword.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter', bubbles: true }));
showPassword.click();
detect();
expect(password.type).toBe('text');
const hidePassword = overlay.querySelector<HTMLButtonElement>('[aria-label="Ocultar contraseña"]')!;
expect(hidePassword.getAttribute('aria-pressed')).toBe('true');
hidePassword.click();
detect();
expect(password.type).toBe('password');
overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')!.click();
detect();
expect(overlay.querySelector('.upload-dialog__description')?.textContent).toContain(
'Revisa la información antes de iniciar el procesamiento.',
);
expect(overlay.querySelector('.upload-steps__item--complete')?.textContent).toContain('Fuente');
expect(overlay.querySelectorAll('.upload-steps__item--complete')[1]?.textContent).toContain('Configuración');
expect(overlay.querySelector('.upload-steps__item--active')?.textContent).toContain('Confirmación');
expect(overlay.querySelector('.sql-summary')?.textContent).toContain('Conexión SQL');
expect(overlay.querySelector('.sql-summary')?.textContent).toContain('servidor.interno.local');
expect(overlay.querySelector('.sql-summary')?.textContent).toContain('1433');
expect(overlay.querySelector('.sql-summary')?.textContent).toContain('datos');
expect(overlay.querySelector('.sql-summary')?.textContent).toContain('usuario');
expect(overlay.querySelector('.sql-summary')?.textContent).toContain('Proporcionadas');
expect(overlay.querySelector('.sql-summary')?.textContent).not.toContain('secreto');
expect(overlay.querySelector('.upload-dialog')?.innerHTML).not.toContain('secreto');
expect(overlay.querySelector('#connection-check-title')?.textContent).toContain('Verificación de conexión');
expect(overlay.querySelector('#connection-check-state')?.textContent).toContain(
'La conexión todavía no ha sido verificada.',
);
const processButton = () => overlay.querySelector<HTMLButtonElement>('.upload-dialog__process')!;
const verifyButton = () => overlay.querySelector<HTMLButtonElement>('.connection-check__action button')!;
expect(verifyButton().textContent).toContain('Probar conexión');
expect(verifyButton().disabled).toBe(false);
expect(overlay.querySelector('.upload-dialog__process')?.hasAttribute('disabled')).toBe(true);
verifyButton().click();
detect();
expect(overlay.querySelector('#connection-check-state')?.textContent).toContain('Verificando conexión...');
expect(verifyButton().disabled).toBe(true);
expect(processButton().disabled).toBe(true);
await new Promise((resolve) => setTimeout(resolve, 1250));
detect();
expect(overlay.querySelector('#connection-check-state')?.textContent).toContain(
'Conexión verificada correctamente.',
);
expect(processButton().disabled).toBe(false);
overlay.querySelector<HTMLButtonElement>('.upload-dialog__back')!.click();
detect();
expect(overlay.querySelector<HTMLInputElement>('[formcontrolname="host"]')?.value).toBe(' servidor.interno.local ');
expect(overlay.querySelector<HTMLInputElement>('[formcontrolname="password"]')?.value).toBe('secreto');
const visiblePasswordButton = overlay.querySelector<HTMLButtonElement>('[aria-label="Mostrar contraseña"]')!;
visiblePasswordButton.click();
detect();
overlay.querySelector<HTMLButtonElement>('[aria-label="Ocultar contraseña"]')!.click();
detect();
overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')!.click();
detect();
expect(overlay.querySelector('#connection-check-state')?.textContent).toContain(
'Conexión verificada correctamente.',
);
expect(processButton().disabled).toBe(false);
const changedFields: Array<[string, string]> = [
['[formcontrolname="host"]', 'nuevo.servidor.local'],
['[formcontrolname="port"]', ''],
['[formcontrolname="database"]', 'otra_base'],
['[formcontrolname="username"]', 'otro_usuario'],
['[formcontrolname="password"]', 'otra_clave'],
];
for (let index = 0; index < changedFields.length; index++) {
overlay.querySelector<HTMLButtonElement>('.upload-dialog__back')!.click();
detect();
type(changedFields[index][0], changedFields[index][1]);
overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')!.click();
detect();
expect(overlay.querySelector('#connection-check-state')?.textContent).toContain(
'La conexión todavía no ha sido verificada.',
);
expect(processButton().disabled).toBe(true);
if (changedFields[index][0] === '[formcontrolname="port"]') {
expect(overlay.querySelector('.sql-summary')?.textContent).toContain('No especificado');
}
if (index < changedFields.length - 1) {
verifyButton().click();
detect();
expect(overlay.querySelector('#connection-check-state')?.textContent).toContain('Verificando conexión...');
await new Promise((resolve) => setTimeout(resolve, 1250));
detect();
expect(processButton().disabled).toBe(false);
}
}
expect(overlay.querySelector('.sql-summary')?.textContent).not.toContain('otra_clave');
expect(overlay.querySelector('.upload-dialog')?.innerHTML).not.toContain('otra_clave');
verifyButton().click();
detect();
expect(overlay.querySelector('#connection-check-state')?.textContent).toContain('Verificando conexión...');
overlay.querySelector<HTMLButtonElement>('.upload-dialog__cancel')!.click();
detect();
fixture.detectChanges();
await new Promise((resolve) => setTimeout(resolve, 200));
fixture.nativeElement.querySelector('.home__action').click();
fixture.detectChanges();
await fixture.whenStable();
const reopened = document.querySelector('.cdk-overlay-container')!;
reopened.querySelectorAll<HTMLButtonElement>('.source-card')[1].click();
const reopenedDialog = TestBed.inject(MatDialog).openDialogs[0].componentRef!;
expect(
(reopenedDialog.instance as import('./information-upload-dialog').InformationUploadDialog)
.sqlVerificationState(),
).toBe('idle');
reopenedDialog.changeDetectorRef.detectChanges();
reopened.querySelector<HTMLButtonElement>('.upload-dialog__continue')!.click();
reopenedDialog.changeDetectorRef.detectChanges();
expect(reopened.querySelector<HTMLInputElement>('[formcontrolname="host"]')?.value).toBe('');
expect(reopened.querySelector<HTMLInputElement>('[formcontrolname="password"]')?.value).toBe('');
reopened.querySelector<HTMLButtonElement>('.upload-dialog__cancel')!.click();
}, 15000);
it('processes selected files in the same dialog and only exits from success', async () => {
const close = vi.fn();
await TestBed.configureTestingModule({
imports: [InformationUploadDialog],
providers: [{ provide: MatDialogRef, useValue: { close, disableClose: true } }],
}).compileComponents();
vi.useFakeTimers();
const fixture = TestBed.createComponent(InformationUploadDialog);
const component = fixture.componentInstance;
component.step.set('confirmation');
component.source.set('file');
component.files.set([new File(['data'], 'datos.csv')]);
fixture.detectChanges();
const root = fixture.nativeElement as HTMLElement;
expect(root.querySelector<HTMLButtonElement>('.upload-dialog__process')?.disabled).toBe(false);
root.querySelector<HTMLButtonElement>('.upload-dialog__process')!.click();
fixture.detectChanges();
expect(component.processingState()).toBe('processing');
expect(root.querySelector('.upload-dialog__close')).toBeNull();
expect(root.querySelector('.upload-steps')).toBeNull();
expect(root.querySelector('.upload-dialog__cancel')).toBeNull();
expect(root.querySelector('.upload-dialog__back')).toBeNull();
expect(root.querySelector('.upload-dialog__process')).toBeNull();
component.close();
expect(close).not.toHaveBeenCalled();
vi.advanceTimersByTime(2250);
fixture.detectChanges();
expect(component.processingProgress()).toBe(50);
expect(root.querySelector('.processing__percentage')?.textContent).toContain('50 %');
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
expect(component.processingState()).toBe('processing');
vi.advanceTimersByTime(2250);
fixture.detectChanges();
expect(component.processingState()).toBe('success');
expect(root.querySelector('#processing-success-title')?.textContent).toContain('Procesamiento completado');
expect(root.querySelector('.processing__finish')).not.toBeNull();
root.querySelector<HTMLButtonElement>('.processing__finish')!.click();
expect(close).toHaveBeenCalledWith('completed');
fixture.destroy();
vi.useRealTimers();
});
it('requires successful SQL verification and uses the shared processing screen', async () => {
const close = vi.fn();
await TestBed.configureTestingModule({
imports: [InformationUploadDialog],
providers: [{ provide: MatDialogRef, useValue: { close, disableClose: true } }],
}).compileComponents();
vi.useFakeTimers();
const fixture = TestBed.createComponent(InformationUploadDialog);
const component = fixture.componentInstance;
component.step.set('confirmation');
component.source.set('sql');
fixture.detectChanges();
const root = fixture.nativeElement as HTMLElement;
expect(root.querySelector<HTMLButtonElement>('.upload-dialog__process')?.disabled).toBe(true);
component.sqlVerificationState.set('success');
fixture.detectChanges();
expect(root.querySelector<HTMLButtonElement>('.upload-dialog__process')?.disabled).toBe(false);
root.querySelector<HTMLButtonElement>('.upload-dialog__process')!.click();
fixture.detectChanges();
expect(component.processingState()).toBe('processing');
vi.advanceTimersByTime(4500);
fixture.detectChanges();
expect(component.processingState()).toBe('success');
expect(root.querySelector('.processing__finish')).not.toBeNull();
root.querySelector<HTMLButtonElement>('.processing__finish')!.click();
expect(close).toHaveBeenCalledWith('completed');
fixture.destroy();
vi.useRealTimers();
});
it('closes after success, then navigates to the Dashboard', async () => {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const router = TestBed.inject(Router);
await router.navigateByUrl('/');
fixture.detectChanges();
(fixture.nativeElement as HTMLElement).querySelector<HTMLButtonElement>('.home__action')!.click();
const dialog = TestBed.inject(MatDialog);
const dialogRef = dialog.openDialogs[0];
const dialogComponent = dialogRef.componentInstance as InformationUploadDialog;
dialogComponent.processingState.set('success');
dialogRef.componentRef!.changeDetectorRef.detectChanges();
document.querySelector<HTMLButtonElement>('.processing__finish')!.click();
await new Promise<void>((resolve) => dialogRef.afterClosed().subscribe(() => resolve()));
await fixture.whenStable();
fixture.detectChanges();
expect(dialog.openDialogs).toHaveLength(0);
expect(router.url).toBe('/dashboard');
expect((fixture.nativeElement as HTMLElement).querySelector('#dashboard-title')?.textContent).toContain('Resultados del análisis');
});
it('renders the mock Dashboard with three KPIs and three charts', async () => {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
await TestBed.inject(Router).navigateByUrl('/dashboard');
await fixture.whenStable();
fixture.detectChanges();
const root = fixture.nativeElement as HTMLElement;
expect(root.querySelector('.dashboard__area')?.textContent).toContain('CAMA');
expect(root.querySelector('.dashboard__demo')?.textContent).toContain('Datos de demostración');
expect(root.querySelectorAll('.kpi')).toHaveLength(3);
expect(root.querySelectorAll('app-plotly-chart')).toHaveLength(3);
expect(root.querySelector('.dashboard__back')?.textContent).toContain('Volver al inicio');
expect(root.querySelector('.dashboard__export')?.textContent).toContain('Exportar');
expect(root.querySelector('.site-footer img')).not.toBeNull();
});
it('returns to Home and supports local PDF and Excel selection in the export dialog', async () => {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const root = fixture.nativeElement as HTMLElement;
const router = TestBed.inject(Router);
await router.navigateByUrl('/dashboard');
await fixture.whenStable();
fixture.detectChanges();
root.querySelector<HTMLButtonElement>('.dashboard__back')!.click();
await fixture.whenStable();
fixture.detectChanges();
expect(router.url).toBe('/');
expect((fixture.nativeElement as HTMLElement).querySelector('app-home')).not.toBeNull();
await router.navigateByUrl('/dashboard');
await fixture.whenStable();
fixture.detectChanges();
root.querySelector<HTMLButtonElement>('.dashboard__export')!.click();
fixture.detectChanges();
await fixture.whenStable();
const overlay = document.querySelector('.cdk-overlay-container')!;
const dialogRef = TestBed.inject(MatDialog).openDialogs[0];
const detect = () => dialogRef.componentRef?.changeDetectorRef.detectChanges();
const options = () => overlay.querySelectorAll<HTMLButtonElement>('.export-option');
expect(overlay.querySelector('#export-title')?.textContent).toContain('Exportar resultados');
expect(options()[0].getAttribute('aria-pressed')).toBe('false');
expect(options()[1].getAttribute('aria-pressed')).toBe('false');
expect(overlay.querySelector<HTMLButtonElement>('.export-dialog__submit')?.disabled).toBe(true);
options()[0].focus();
options()[0].click();
detect();
expect(options()[0].getAttribute('aria-pressed')).toBe('true');
expect(overlay.querySelector('.export-option--selected strong')?.textContent).toBe('PDF');
options()[1].click();
detect();
expect(options()[0].getAttribute('aria-pressed')).toBe('false');
expect(options()[1].getAttribute('aria-pressed')).toBe('true');
expect(overlay.querySelector<HTMLButtonElement>('.export-dialog__submit')?.disabled).toBe(false);
overlay.querySelector<HTMLButtonElement>('.export-dialog__cancel')!.click();
fixture.detectChanges();
await new Promise((resolve) => setTimeout(resolve, 200));
expect(TestBed.inject(MatDialog).openDialogs).toHaveLength(0);
expect(router.url).toBe('/dashboard');
root.querySelector<HTMLButtonElement>('.dashboard__export')!.click();
fixture.detectChanges();
await fixture.whenStable();
const reopenedOverlay = document.querySelector('.cdk-overlay-container')!;
expect(reopenedOverlay.querySelectorAll('.export-option--selected')).toHaveLength(0);
reopenedOverlay.querySelector<HTMLButtonElement>('.export-dialog__close')!.click();
fixture.detectChanges();
await new Promise((resolve) => setTimeout(resolve, 200));
expect(TestBed.inject(MatDialog).openDialogs).toHaveLength(0);
expect(router.url).toBe('/dashboard');
});
it('opens the Dashboard action step, preserves its intent on back, and cancels without leaving results', async () => {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const router = TestBed.inject(Router);
await router.navigateByUrl('/dashboard');
await fixture.whenStable();
fixture.detectChanges();
const dashboard = fixture.nativeElement as HTMLElement;
dashboard.querySelector<HTMLButtonElement>('.dashboard__upload')!.click();
fixture.detectChanges();
await fixture.whenStable();
const overlay = document.querySelector('.cdk-overlay-container')!;
const dialog = TestBed.inject(MatDialog).openDialogs[0].componentRef!;
const detect = () => dialog.changeDetectorRef.detectChanges();
expect(overlay.querySelector('.action-options')).not.toBeNull();
const continueButton = overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')!;
expect(continueButton.disabled).toBe(true);
const cards = overlay.querySelectorAll<HTMLButtonElement>('.action-card');
cards[0].click();
detect();
expect(continueButton.disabled).toBe(false);
continueButton.click();
detect();
expect(overlay.querySelector('.source-options')).not.toBeNull();
overlay.querySelector<HTMLButtonElement>('.upload-dialog__back')!.click();
detect();
expect(overlay.querySelector<HTMLButtonElement>('.action-card')?.getAttribute('aria-pressed')).toBe('true');
overlay.querySelectorAll<HTMLButtonElement>('.action-card')[1].click();
detect();
expect(continueButton.disabled).toBe(false);
continueButton.click();
detect();
overlay.querySelector<HTMLButtonElement>('.source-card')!.click();
detect();
continueButton.click();
detect();
expect(overlay.querySelector('.file-configuration')).not.toBeNull();
overlay.querySelector<HTMLButtonElement>('.upload-dialog__cancel')!.click();
fixture.detectChanges();
await new Promise((resolve) => setTimeout(resolve, 200));
expect(TestBed.inject(MatDialog).openDialogs).toHaveLength(0);
expect(router.url).toBe('/dashboard');
expect((fixture.nativeElement as HTMLElement).querySelector('#dashboard-title')).not.toBeNull();
it('preserves login, protected home and wildcard alongside area routes', () => {
expect(routes.map(route => route.path)).toEqual(['login', '', 'cacu', 'cama', 'tea', '**']);
expect(routes[0].canActivate).toEqual([anonymousGuard]);
expect(routes[1].canActivate).toEqual([authGuard]);
expect(routes.at(-1)?.redirectTo).toBe('');
});
});
+9 -3
View File
@@ -1,10 +1,16 @@
import { Component } from '@angular/core';
import { Component, inject } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatButtonModule } from '@angular/material/button';
import { AuthState } from './auth/auth.state';
@Component({
imports: [RouterOutlet],
imports: [RouterOutlet, MatToolbarModule, MatButtonModule],
selector: 'app-root',
styleUrl: './app.scss',
templateUrl: './app.html',
})
export class App {}
export class App {
protected readonly auth = inject(AuthState);
protected readonly title = 'ISSSTELEON';
}
+13
View File
@@ -0,0 +1,13 @@
import { Component, inject } from '@angular/core';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { Area } from './auth.roles';
@Component({
selector: 'app-area-placeholder',
imports: [RouterLink, MatButtonModule],
template: `<h1>Área {{ area }}</h1><a mat-button routerLink="/">Volver a áreas</a>`,
})
export class AreaPlaceholder {
protected readonly area: Area = inject(ActivatedRoute).snapshot.data['area'];
}
+94
View File
@@ -0,0 +1,94 @@
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot, provideRouter } from '@angular/router';
import { authGuard, anonymousGuard, areaGuard } from './auth.guard';
import { Role } from './auth.models';
import { Area } from './auth.roles';
import { routes } from '../app.routes';
import { AuthState } from './auth.state';
describe('Auth guards', () => {
let http: HttpTestingController;
const user = { id: 1, username: 'demo', roles: ['CAMA'] };
beforeEach(() => {
sessionStorage.clear();
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([])] });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => { http.verify(); sessionStorage.clear(); });
const run = (guard: typeof authGuard) => TestBed.runInInjectionContext(() =>
guard({} as ActivatedRouteSnapshot, {} as RouterStateSnapshot));
const url = (result: unknown) => TestBed.inject(Router).serializeUrl(result as ReturnType<Router['createUrlTree']>);
it('anonymous redirects protected route to login', async () => {
expect(url(await run(authGuard))).toBe('/login');
});
it('anonymous can open login', async () => { expect(await run(anonymousGuard)).toBe(true); });
it('authenticated allows home and redirects login', async () => {
const login = TestBed.inject(AuthState).login('demo', 'test-password');
http.expectOne('/auth/login').flush({ token: 'test-token', expires_in: 28800, user }); await login;
expect(await run(authGuard)).toBe(true); expect(url(await run(anonymousGuard))).toBe('/');
});
it('both guards wait on the same restore', async () => {
sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token');
let resolved = false;
const home = Promise.resolve(run(authGuard)).then(result => { resolved = true; return result; });
const login = run(anonymousGuard);
await Promise.resolve(); expect(resolved).toBe(false);
expect(TestBed.inject(AuthState).status()).toBe('checking');
http.expectOne('/auth/me').flush({ user });
expect(await home).toBe(true); expect(url(await login)).toBe('/');
});
it('rejected restore redirects home and allows login', async () => {
sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token');
const home = run(authGuard); const login = run(anonymousGuard);
http.expectOne('/auth/me').flush({}, { status: 401, statusText: 'Unauthorized' });
expect(url(await home)).toBe('/login'); expect(await login).toBe(true);
});
it('anonymous is redirected to login for every area', async () => {
for (const area of ['CACU', 'CAMA', 'TEA'] as const) {
expect(url(await run(areaGuard(area)))).toBe('/login');
}
});
const cases: [Role[], Area[]][] = [
[['CAMA'], ['CAMA']], [['CACU', 'CAMA'], ['CACU', 'CAMA']],
[['ADMIN'], ['CACU', 'CAMA', 'TEA']], [[], []],
];
for (const [roles, allowed] of cases) {
it(`evaluates area guards and configured routes for ${JSON.stringify(roles)}`, async () => {
const login = TestBed.inject(AuthState).login('demo', 'test-password');
http.expectOne('/auth/login').flush({ token: 'test-token', expires_in: 28800, user: { ...user, roles } });
await login;
for (const area of ['CACU', 'CAMA', 'TEA'] as const) {
const result = await run(areaGuard(area));
expect(result === true ? true : url(result)).toBe(allowed.includes(area) ? true : '/');
const route = routes.find(route => route.path === area.toLowerCase())!;
expect(route.data?.['area']).toBe(area);
expect(route.component).toBeDefined();
expect(route.canActivate?.length).toBe(1);
const routed = await run(route.canActivate![0] as typeof authGuard);
expect(routed === true ? true : url(routed)).toBe(allowed.includes(area) ? true : '/');
}
http.expectNone('/auth/me');
expect(TestBed.inject(AuthState).isAuthenticated()).toBe(true);
});
}
it('waits for shared restore and uses server roles instead of cached roles', async () => {
sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token');
sessionStorage.setItem('ISSSTELEON.auth.user', JSON.stringify({ ...user, roles: ['ADMIN'] }));
let resolved = false;
const cama = Promise.resolve(run(areaGuard('CAMA'))).then(result => { resolved = true; return result; });
const cacu = run(areaGuard('CACU')); const home = run(authGuard);
await Promise.resolve(); expect(resolved).toBe(false);
http.expectOne('/auth/me').flush({ user });
expect(await cama).toBe(true); expect(url(await cacu)).toBe('/'); expect(await home).toBe(true);
expect(await run(areaGuard('CAMA'))).toBe(true); http.expectNone('/auth/me');
});
it('rejected restore redirects pending area guards to login', async () => {
sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token');
const cama = run(areaGuard('CAMA')); const tea = run(areaGuard('TEA'));
http.expectOne('/auth/me').flush({}, { status: 401, statusText: 'Unauthorized' });
expect(url(await cama)).toBe('/login'); expect(url(await tea)).toBe('/login');
});
});
+28
View File
@@ -0,0 +1,28 @@
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthState } from './auth.state';
import { Area, canAccessArea } from './auth.roles';
export function areaGuard(area: Area): CanActivateFn {
return async () => {
const auth = inject(AuthState);
const router = inject(Router);
await auth.restore();
if (!auth.isAuthenticated()) return router.createUrlTree(['/login']);
return canAccessArea(auth.user()?.roles ?? [], area) || router.createUrlTree(['/']);
};
}
export const authGuard: CanActivateFn = async () => {
const auth = inject(AuthState);
const router = inject(Router);
await auth.restore();
return auth.isAuthenticated() || router.createUrlTree(['/login']);
};
export const anonymousGuard: CanActivateFn = async () => {
const auth = inject(AuthState);
const router = inject(Router);
await auth.restore();
return !auth.isAuthenticated() || router.createUrlTree(['/']);
};
+17
View File
@@ -0,0 +1,17 @@
export type Role = 'ADMIN' | 'CACU' | 'CAMA' | 'TEA';
export interface AuthUser {
id: number;
username: string;
roles: Role[];
}
export interface LoginResponse {
token: string;
expires_in: number;
user: AuthUser;
}
export interface MeResponse {
user: AuthUser;
}
+30
View File
@@ -0,0 +1,30 @@
import { Role } from './auth.models';
import { Area, canAccessArea, getAccessibleAreas } from './auth.roles';
describe('Area access', () => {
const cases: [Role[], Area[]][] = [
[[], []],
[['CACU'], ['CACU']],
[['CAMA'], ['CAMA']],
[['TEA'], ['TEA']],
[['CACU', 'CAMA'], ['CACU', 'CAMA']],
[['CACU', 'TEA'], ['CACU', 'TEA']],
[['CAMA', 'TEA'], ['CAMA', 'TEA']],
[['CACU', 'CAMA', 'TEA'], ['CACU', 'CAMA', 'TEA']],
[['ADMIN'], ['CACU', 'CAMA', 'TEA']],
[['ADMIN', 'CAMA'], ['CACU', 'CAMA', 'TEA']],
];
for (const [roles, allowed] of cases) {
it(`evaluates all areas and stable list for ${JSON.stringify(roles)}`, () => {
for (const area of ['CACU', 'CAMA', 'TEA'] as const) {
expect(canAccessArea(roles, area)).toBe(allowed.includes(area));
}
expect(getAccessibleAreas(roles)).toEqual(allowed);
});
}
it('keeps canonical order without modifying or duplicating input', () => {
const roles: readonly Role[] = Object.freeze(['TEA', 'CAMA', 'CACU', 'CAMA']);
expect(getAccessibleAreas(roles)).toEqual(['CACU', 'CAMA', 'TEA']);
expect(roles).toEqual(['TEA', 'CAMA', 'CACU', 'CAMA']);
});
});
+12
View File
@@ -0,0 +1,12 @@
import { Role } from './auth.models';
export type Area = 'CACU' | 'CAMA' | 'TEA';
export function canAccessArea(roles: readonly Role[], area: Area): boolean {
return roles.includes('ADMIN') || roles.includes(area);
}
export function getAccessibleAreas(roles: readonly Role[]): Area[] {
const areas: Area[] = ['CACU', 'CAMA', 'TEA'];
return areas.filter(area => canAccessArea(roles, area));
}
+32
View File
@@ -0,0 +1,32 @@
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { AuthService } from './auth.service';
describe('AuthService', () => {
let api: AuthService;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
api = TestBed.inject(AuthService);
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it('posts credentials using a relative URL without Bearer', () => {
const response = { token: 'test-token', expires_in: 28800, user: { id: 1, username: 'demo', roles: [] } };
api.login('demo', 'test-password').subscribe(value => expect(value).toEqual(response));
const request = http.expectOne('/auth/login');
expect(request.request.method).toBe('POST');
expect(request.request.body).toEqual({ username: 'demo', password: 'test-password' });
expect(request.request.headers.has('Authorization')).toBe(false);
request.flush(response);
});
it('gets current identity with explicit Bearer', () => {
const response = { user: { id: 1, username: 'demo', roles: ['CAMA'] } };
api.me('test-token').subscribe(value => expect(value).toEqual(response));
const request = http.expectOne('/auth/me');
expect(request.request.method).toBe('GET');
expect(request.request.headers.get('Authorization')).toBe('Bearer test-token');
request.flush(response);
});
});
+18
View File
@@ -0,0 +1,18 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { LoginResponse, MeResponse } from './auth.models';
@Injectable({ providedIn: 'root' })
export class AuthService {
private readonly http = inject(HttpClient);
login(username: string, password: string) {
return this.http.post<LoginResponse>('/auth/login', { username, password });
}
me(token: string) {
return this.http.get<MeResponse>('/auth/me', {
headers: { Authorization: `Bearer ${token}` },
});
}
}
+79
View File
@@ -0,0 +1,79 @@
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { Router, provideRouter } from '@angular/router';
import { vi } from 'vitest';
import { AuthState } from './auth.state';
import { AuthStorage } from './auth.storage';
describe('AuthState', () => {
const user = { id: 1, username: 'demo', roles: ['CAMA'] };
let auth: AuthState;
let http: HttpTestingController;
beforeEach(() => {
sessionStorage.clear();
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([])] });
auth = TestBed.inject(AuthState); http = TestBed.inject(HttpTestingController);
});
afterEach(() => { http.verify(); sessionStorage.clear(); vi.restoreAllMocks(); });
const seed = () => sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token');
it('starts checking without trusting cache', () => {
expect(auth.status()).toBe('checking'); expect(auth.user()).toBeNull(); expect(auth.isAuthenticated()).toBe(false);
});
it('restores without token without HTTP and clears cached identity', async () => {
sessionStorage.setItem('ISSSTELEON.auth.user', JSON.stringify(user));
await auth.restore(); expect(auth.status()).toBe('anonymous'); expect(auth.user()).toBeNull();
http.expectNone('/auth/me'); expect(TestBed.inject(AuthStorage).readUser()).toBeNull();
});
it('shares concurrent restore and trusts only the current server identity', async () => {
seed(); sessionStorage.setItem('ISSSTELEON.auth.user', JSON.stringify(user));
const first = auth.restore(); const second = auth.restore(); expect(first).toBe(second);
expect(auth.status()).toBe('checking'); expect(auth.user()).toBeNull();
const current = { ...user, roles: ['TEA'] };
http.expectOne('/auth/me').flush({ user: current }); await Promise.all([first, second]);
expect(auth.isAuthenticated()).toBe(true); expect(auth.user()).toEqual(current);
expect(TestBed.inject(AuthStorage).readUser()).toEqual(current);
expect(TestBed.inject(AuthStorage).readToken()).toBe('test-token');
await auth.restore(); http.expectNone('/auth/me');
});
for (const status of [401, 500, 0]) {
it(`clears session on restore error ${status}`, async () => {
seed(); const pending = auth.restore();
const request = http.expectOne('/auth/me');
if (status === 0) request.error(new ProgressEvent('error'));
else request.flush({}, { status, statusText: 'Rejected' });
await pending; expect(auth.status()).toBe('anonymous'); expect(auth.user()).toBeNull();
expect(TestBed.inject(AuthStorage).readToken()).toBeNull();
});
}
it('login saves identity and local logout clears it and navigates', async () => {
const navigate = vi.spyOn(TestBed.inject(Router), 'navigateByUrl').mockResolvedValue(true);
const pending = auth.login('demo', 'test-password');
http.expectOne('/auth/login').flush({ token: 'test-token', expires_in: 28800, user }); await pending;
expect(auth.isAuthenticated()).toBe(true); expect(auth.user()).toEqual(user);
expect(TestBed.inject(AuthStorage).readToken()).toBe('test-token');
expect(TestBed.inject(AuthStorage).readUser()).toEqual(user);
auth.logout(); expect(auth.status()).toBe('anonymous'); expect(auth.user()).toBeNull();
expect(TestBed.inject(AuthStorage).readToken()).toBeNull(); expect(navigate).toHaveBeenCalledWith('/login');
await auth.restore(); http.expectNone('/auth/me');
});
it('failed login remains anonymous', async () => {
const pending = auth.login('demo', 'test-password');
const assertion = expect(pending).rejects.toMatchObject({ status: 401 });
http.expectOne('/auth/login').flush({}, { status: 401, statusText: 'Unauthorized' });
await assertion; expect(auth.status()).toBe('anonymous'); expect(auth.user()).toBeNull();
});
it('late restore cannot undo logout', async () => {
vi.spyOn(TestBed.inject(Router), 'navigateByUrl').mockResolvedValue(true);
seed(); const pending = auth.restore(); auth.logout();
http.expectOne('/auth/me').flush({ user }); await pending;
expect(auth.status()).toBe('anonymous'); expect(TestBed.inject(AuthStorage).readToken()).toBeNull();
});
it('late restore cannot overwrite a new login', async () => {
seed(); const restoring = auth.restore(); const login = auth.login('demo', 'test-password');
const current = { ...user, roles: ['ADMIN'] };
http.expectOne('/auth/login').flush({ token: 'new-test-token', expires_in: 28800, user: current });
await login; http.expectOne('/auth/me').flush({ user }); await restoring;
expect(auth.user()).toEqual(current); expect(TestBed.inject(AuthStorage).readToken()).toBe('new-test-token');
});
});
+77
View File
@@ -0,0 +1,77 @@
import { computed, inject, Injectable, signal } from '@angular/core';
import { Router } from '@angular/router';
import { firstValueFrom } from 'rxjs';
import { AuthUser } from './auth.models';
import { AuthService } from './auth.service';
import { AuthStorage } from './auth.storage';
@Injectable({ providedIn: 'root' })
export class AuthState {
private readonly api = inject(AuthService);
private readonly storage = inject(AuthStorage);
private readonly router = inject(Router);
private readonly currentUser = signal<AuthUser | null>(null);
private readonly token = signal<string | null>(null);
private readonly currentStatus = signal<'checking' | 'authenticated' | 'anonymous'>('checking');
readonly user = this.currentUser.asReadonly();
readonly status = this.currentStatus.asReadonly();
readonly isAuthenticated = computed(() => this.status() === 'authenticated');
private restoration?: Promise<void>;
private generation = 0;
restore(): Promise<void> {
if (this.restoration) return this.restoration;
if (this.status() !== 'checking') return Promise.resolve();
const token = this.storage.readToken();
if (!token) {
this.clear();
return Promise.resolve();
}
const generation = this.generation;
const pending = this.validate(token, generation);
this.restoration = pending;
void pending.finally(() => {
if (this.restoration === pending) this.restoration = undefined;
});
return pending;
}
private async validate(token: string, generation: number): Promise<void> {
try {
const response = await firstValueFrom(this.api.me(token));
if (generation !== this.generation) return;
this.token.set(token);
this.currentUser.set(response.user);
this.storage.updateUser(response.user);
this.currentStatus.set('authenticated');
} catch {
if (generation === this.generation) this.clear();
}
}
async login(username: string, password: string): Promise<void> {
const generation = ++this.generation;
this.restoration = undefined;
this.clear();
const response = await firstValueFrom(this.api.login(username, password));
if (generation !== this.generation) return;
this.token.set(response.token);
this.currentUser.set(response.user);
this.storage.save(response.token, response.user);
this.currentStatus.set('authenticated');
}
logout(): void {
++this.generation;
this.restoration = undefined;
this.clear();
void this.router.navigateByUrl('/login');
}
private clear(): void {
this.token.set(null);
this.currentUser.set(null);
this.storage.clear();
this.currentStatus.set('anonymous');
}
}
+40
View File
@@ -0,0 +1,40 @@
import { AuthStorage } from './auth.storage';
import { vi } from 'vitest';
describe('AuthStorage', () => {
const user = { id: 1, username: 'demo', roles: ['CAMA'] as const };
let storage: AuthStorage;
beforeEach(() => { sessionStorage.clear(); storage = new AuthStorage(); });
afterEach(() => { vi.restoreAllMocks(); sessionStorage.clear(); });
it('reads empty storage safely', () => {
expect(storage.readToken()).toBeNull(); expect(storage.readUser()).toBeNull();
});
it('saves and clears the tab session', () => {
storage.save('test-token', { ...user, roles: ['CAMA'] });
expect(storage.readToken()).toBe('test-token'); expect(storage.readUser()).toEqual(user);
storage.updateUser({ ...user, roles: ['ADMIN'] });
expect(storage.readUser()?.roles).toEqual(['ADMIN']);
storage.clear(); expect(storage.readToken()).toBeNull(); expect(storage.readUser()).toBeNull();
});
it('ignores malformed JSON and invalid cache shapes', () => {
for (const value of ['{', '123', '{"id":1}', '{"id":1,"username":"demo","roles":["OTHER"]}']) {
sessionStorage.setItem('ISSSTELEON.auth.user', value);
expect(storage.readUser()).toBeNull();
}
});
it('tolerates unavailable sessionStorage', () => {
vi.spyOn(window, 'sessionStorage', 'get').mockImplementation(() => { throw new Error('disabled'); });
expect(storage.readToken()).toBeNull(); expect(storage.readUser()).toBeNull();
expect(() => storage.save('test-token', { ...user, roles: ['CAMA'] })).not.toThrow();
expect(() => storage.updateUser({ ...user, roles: ['CAMA'] })).not.toThrow();
expect(() => storage.clear()).not.toThrow();
});
it('tolerates read, write and removal failures', () => {
vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new Error('read'); });
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('write'); });
vi.spyOn(Storage.prototype, 'removeItem').mockImplementation(() => { throw new Error('remove'); });
expect(storage.readToken()).toBeNull(); expect(storage.readUser()).toBeNull();
expect(() => storage.save('test-token', { ...user, roles: ['CAMA'] })).not.toThrow();
expect(() => storage.clear()).not.toThrow();
});
});
+41
View File
@@ -0,0 +1,41 @@
import { Injectable } from '@angular/core';
import { AuthUser } from './auth.models';
@Injectable({ providedIn: 'root' })
export class AuthStorage {
private readonly tokenKey = 'ISSSTELEON.auth.token';
private readonly userKey = 'ISSSTELEON.auth.user';
readToken(): string | null {
try { return sessionStorage.getItem(this.tokenKey); } catch { return null; }
}
readUser(): AuthUser | null {
try {
const value: unknown = JSON.parse(sessionStorage.getItem(this.userKey) ?? 'null');
if (typeof value !== 'object' || value === null) return null;
const user = value as AuthUser;
return typeof user.id === 'number' && typeof user.username === 'string' &&
Array.isArray(user.roles) && user.roles.every(role =>
['ADMIN', 'CACU', 'CAMA', 'TEA'].includes(role)) ? user : null;
} catch { return null; }
}
save(token: string, user: AuthUser): void {
try {
sessionStorage.setItem(this.tokenKey, token);
sessionStorage.setItem(this.userKey, JSON.stringify(user));
} catch { this.clear(); }
}
updateUser(user: AuthUser): void {
try { sessionStorage.setItem(this.userKey, JSON.stringify(user)); } catch { this.clear(); }
}
clear(): void {
// Attempt both removals even if one storage operation fails.
for (const key of [this.tokenKey, this.userKey]) {
try { sessionStorage.removeItem(key); } catch { /* Storage may be disabled. */ }
}
}
}
+40
View File
@@ -0,0 +1,40 @@
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { AuthUser, Role } from './auth.models';
import { AuthState } from './auth.state';
import { Home } from './home';
describe('Home areas', () => {
const user = signal<AuthUser>({ id: 1, username: 'demo', roles: [] });
beforeEach(() => {
user.set({ id: 1, username: 'demo', roles: [] });
TestBed.configureTestingModule({ imports: [Home], providers: [
provideRouter([]), { provide: AuthState, useValue: { user } },
] });
});
const cases: [Role[], string[]][] = [
[['CAMA'], ['CAMA']], [['CACU', 'CAMA'], ['CACU', 'CAMA']],
[['ADMIN'], ['CACU', 'CAMA', 'TEA']], [[], []],
];
for (const [roles, areas] of cases) {
it(`renders only authorized links for ${JSON.stringify(roles)}`, () => {
user.set({ id: 1, username: 'demo', roles });
const fixture = TestBed.createComponent(Home); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
const links = Array.from(root.querySelectorAll('a'));
expect(links.map(link => link.textContent?.trim())).toEqual(areas);
expect(links.map(link => link.getAttribute('href'))).toEqual(areas.map(area => '/' + area.toLowerCase()));
expect(root.querySelector('[role="status"]')?.textContent ?? null)
.toBe(areas.length ? null : 'No tienes áreas asignadas.');
});
}
it('updates navigation from current AuthState roles', () => {
user.set({ id: 1, username: 'demo', roles: ['ADMIN'] });
const fixture = TestBed.createComponent(Home); fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('a').length).toBe(3);
user.set({ id: 1, username: 'demo', roles: ['TEA'] }); fixture.detectChanges();
expect(Array.from(fixture.nativeElement.querySelectorAll('a') as NodeListOf<HTMLAnchorElement>)
.map(link => link.textContent?.trim())).toEqual(['TEA']);
});
});
+25
View File
@@ -0,0 +1,25 @@
import { Component, computed, inject } from '@angular/core';
import { RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { AuthState } from './auth.state';
import { getAccessibleAreas } from './auth.roles';
@Component({
selector: 'app-home',
imports: [RouterLink, MatButtonModule],
template: `
<h1>Áreas disponibles</h1>
<nav aria-label="Áreas disponibles">
@for (area of areas(); track area) {
<a mat-stroked-button [routerLink]="'/' + area.toLowerCase()">{{ area }}</a>
} @empty {
<p role="status">No tienes áreas asignadas.</p>
}
</nav>
`,
styles: `nav { display: flex; flex-wrap: wrap; gap: 1rem; }`,
})
export class Home {
private readonly auth = inject(AuthState);
protected readonly areas = computed(() => getAccessibleAreas(this.auth.user()?.roles ?? []));
}
+39
View File
@@ -0,0 +1,39 @@
<section class="login" aria-labelledby="login-title" lang="es">
<h1 id="login-title">Inicio de sesión</h1>
<form [formGroup]="form" (ngSubmit)="submit()" [attr.aria-busy]="loading()">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="login-field">
<mat-label>Usuario</mat-label>
<input matInput formControlName="username" autocomplete="username" maxlength="64"
[errorStateMatcher]="usernameErrorMatcher"
(focus)="usernameEditing.set(true)" (blur)="usernameEditing.set(false)" />
@if (showUsernameError()) { <mat-error>Ingresa un usuario válido.</mat-error> }
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="login-field">
<mat-label>Contraseña</mat-label>
<input matInput [type]="passwordVisible() ? 'text' : 'password'" formControlName="password"
autocomplete="current-password" maxlength="128" [errorStateMatcher]="passwordErrorMatcher"
(focus)="passwordEditing.set(true)" (blur)="passwordEditing.set(false)" />
<button mat-icon-button matSuffix type="button" class="password-toggle"
(click)="$event.stopPropagation(); passwordVisible.set(!passwordVisible())"
[attr.aria-label]="passwordVisible() ? 'Ocultar contraseña' : 'Mostrar contraseña'"
[attr.aria-pressed]="passwordVisible()">
<mat-icon aria-hidden="true">
<svg viewBox="0 0 24 24" focusable="false" aria-hidden="true">
<path d="M12 6c4.2 0 7.5 3.1 9 6-1.5 2.9-4.8 6-9 6s-7.5-3.1-9-6c1.5-2.9 4.8-6 9-6Z" />
<circle cx="12" cy="12" r="3" />
@if (passwordVisible()) { <path d="m3 3 18 18" /> }
</svg>
</mat-icon>
</button>
@if (showPasswordError()) { <mat-error>Ingresa tu contraseña.</mat-error> }
</mat-form-field>
<button mat-flat-button class="login-action" type="submit" [disabled]="loading()">
{{ loading() ? 'Iniciando sesión…' : 'Iniciar sesión' }}
</button>
<div class="login-feedback">
@if (error()) { <p role="alert">{{ error() }}</p> }
@if (loading()) { <p role="status">Comprobando credenciales…</p> }
</div>
</form>
<img class="login-logo" src="branding/LogoISSSTELEON.png" alt="ISSSTELEON" width="1125" height="358" />
</section>
+120
View File
@@ -0,0 +1,120 @@
@use '@angular/material' as mat;
:host {
--login-page-bg: #f7f7f7;
--login-surface: #ffffff;
--login-text: #333333;
--login-text-muted: #667085;
--login-border: #cccccc;
--login-focus: #00833c;
--isssteleon-lime: #99ca3c;
--isssteleon-green: #00833c;
--login-icon-teal: #5f9ea0;
--login-action-bg: #f8f9fa;
--login-action-border: #e9ecef;
display: grid;
box-sizing: border-box;
min-height: 100dvh;
margin: -1.5rem; // Compensate the existing main padding only while Login is mounted.
padding: 2rem 24px;
place-items: center;
background: var(--login-page-bg);
color: var(--login-text);
font-family: Roboto, Arial, sans-serif;
}
.login { width: min(100%, 26rem); min-width: 0; }
h1 {
display: flex;
align-items: center;
gap: 1rem;
margin: 0 0 2rem;
font-size: 1.5rem;
font-weight: 500;
line-height: 1.3;
white-space: nowrap;
&::before, &::after {
content: '';
flex: 1;
min-width: 0;
border-top: 1px solid var(--login-border);
}
}
form { display: flex; flex-direction: column; gap: .75rem; }
.login-field {
width: 100%;
position: relative;
isolation: isolate;
@include mat.form-field-overrides((
outlined-container-shape: 5px,
outlined-outline-color: var(--login-border),
outlined-hover-outline-color: var(--login-text-muted),
outlined-focus-outline-color: var(--login-focus),
outlined-focus-label-text-color: var(--login-focus),
outlined-label-text-color: var(--login-text-muted),
outlined-input-text-color: var(--login-text),
outlined-caret-color: var(--login-focus),
container-text-size: 16px,
));
// Keep the validation subscript on the page background.
&::before { content: ''; position: absolute; inset: 0 0 auto; height: 56px;
background: var(--login-surface); border-radius: 5px; z-index: -1; }
}
.password-toggle {
color: var(--login-text-muted);
margin-inline-end: 4px;
min-width: 48px;
min-height: 48px;
svg { width: 24px; height: 24px; fill: none; stroke: currentColor; stroke-width: 1.8; }
}
.login-action.mat-mdc-unelevated-button {
@include mat.button-overrides((
filled-container-color: var(--login-action-bg),
filled-label-text-color: var(--login-text),
filled-container-shape: 8px,
filled-container-height: 50px,
filled-label-text-size: 16px,
filled-label-text-weight: 500,
filled-state-layer-color: var(--login-focus),
filled-disabled-container-color: #e9ecef,
filled-disabled-label-text-color: #707780,
));
width: 100%;
min-height: 50px;
border: 1px solid var(--login-action-border);
border-radius: 8px;
background: var(--login-action-bg);
color: var(--login-text);
font: 500 16px Roboto, Arial, sans-serif;
cursor: pointer;
box-shadow: 0 1px 2px #00000014;
transition: transform 160ms cubic-bezier(.2, 0, 0, 1), background-color 160ms ease,
border-color 160ms ease, box-shadow 160ms ease;
&:hover:not(:disabled) {
transform: translateY(-1px);
background: #eef2ed;
border-color: var(--login-focus);
box-shadow: 0 3px 7px #0000001c;
}
&:active:not(:disabled) { transform: translateY(0) scale(.99); background: #e4ebdf; box-shadow: none; }
&:disabled { transform: none; transition: none; background: #e9ecef; color: #707780; box-shadow: none; cursor: default; }
}
button:focus-visible { outline: 2px solid var(--login-focus); outline-offset: 3px; }
@media (prefers-reduced-motion: reduce) {
.login-action.mat-mdc-unelevated-button {
transition: none;
&:hover:not(:disabled), &:active:not(:disabled) { transform: none; }
}
}
.login-feedback { min-height: 2.5rem; font-size: .875rem; line-height: 1.4; }
[role='alert'] { color: var(--mat-sys-error); margin: 0; }
[role='status'] { color: var(--login-text-muted); margin: 0; }
.login-logo { display: block; width: min(100%, clamp(200px, 17vw, 240px)); height: auto; object-fit: contain; margin: 1.5rem auto 0; }
+139
View File
@@ -0,0 +1,139 @@
import { TestBed } from '@angular/core/testing';
import { HttpErrorResponse } from '@angular/common/http';
import { Router, provideRouter } from '@angular/router';
import { vi } from 'vitest';
import { AuthState } from './auth.state';
import { Login } from './login';
describe('Login', () => {
let login: ReturnType<typeof vi.fn>;
beforeEach(() => {
login = vi.fn().mockResolvedValue(undefined);
TestBed.configureTestingModule({ imports: [Login], providers: [provideRouter([]),
{ provide: AuthState, useValue: { login, isAuthenticated: () => true } }] });
vi.spyOn(TestBed.inject(Router), 'navigateByUrl').mockResolvedValue(true);
});
afterEach(() => vi.restoreAllMocks());
const create = () => {
const fixture = TestBed.createComponent(Login); fixture.detectChanges(); return fixture;
};
const fill = (component: Login) => component.form.setValue({ username: 'Demo', password: 'test-password' });
const usernameInput = (fixture: ReturnType<typeof TestBed.createComponent<Login>>) =>
fixture.nativeElement.querySelector('input[autocomplete="username"]') as HTMLInputElement;
const hasUsernameError = (fixture: { nativeElement: HTMLElement }) =>
!!fixture.nativeElement.querySelector('mat-error');
it('renders required credentials and submit button', () => {
const fixture = create(); const element: HTMLElement = fixture.nativeElement;
expect(element.querySelector('input[autocomplete="username"]')).toBeTruthy();
expect(element.querySelector('input[type="password"]')).toBeTruthy();
expect(element.querySelector('button[type="submit"]')?.textContent).toContain('Iniciar sesión');
expect(fixture.componentInstance.form.invalid).toBe(true);
});
it('rejects empty and invalid credentials', async () => {
const component = create().componentInstance; await component.submit(); expect(login).not.toHaveBeenCalled();
for (const username of ['ab', 'a'.repeat(65), 'demo@']) {
component.form.setValue({ username, password: 'test-password' }); expect(component.form.invalid).toBe(true);
}
component.form.setValue({ username: 'demo', password: 'a'.repeat(129) }); expect(component.form.invalid).toBe(true);
});
it('shows the username error after blur, hides it while editing, and restores it on blur if still invalid', () => {
const fixture = create(); const input = usernameInput(fixture); const control = fixture.componentInstance.form.controls.username;
input.dispatchEvent(new Event('focus')); input.dispatchEvent(new Event('blur')); fixture.detectChanges();
expect(control.invalid).toBe(true);
expect(hasUsernameError(fixture)).toBe(true);
expect(input.closest('mat-form-field')?.classList.contains('mat-form-field-invalid')).toBe(true);
input.dispatchEvent(new Event('focus')); fixture.detectChanges();
expect(fixture.componentInstance.usernameEditing()).toBe(true);
expect(hasUsernameError(fixture)).toBe(false);
expect(input.closest('mat-form-field')?.classList.contains('mat-form-field-invalid')).toBe(false);
input.dispatchEvent(new Event('input')); input.dispatchEvent(new Event('blur')); fixture.detectChanges();
expect(hasUsernameError(fixture)).toBe(true);
expect(input.closest('mat-form-field')?.classList.contains('mat-form-field-invalid')).toBe(true);
});
it('keeps the username error cleared after editing to a valid value', () => {
const fixture = create(); const input = usernameInput(fixture); const control = fixture.componentInstance.form.controls.username;
input.dispatchEvent(new Event('focus')); input.dispatchEvent(new Event('blur')); fixture.detectChanges();
expect(hasUsernameError(fixture)).toBe(true);
input.dispatchEvent(new Event('focus'));
input.value = 'valid-user'; input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('blur')); fixture.detectChanges();
expect(control.valid).toBe(true);
expect(hasUsernameError(fixture)).toBe(false);
});
it('shows field errors on invalid submit and suppresses them once editing starts', async () => {
const fixture = create(); const component = fixture.componentInstance;
await component.submit(); fixture.detectChanges();
expect(component.submitted()).toBe(true);
expect(fixture.nativeElement.querySelectorAll('mat-error').length).toBe(2);
const input = usernameInput(fixture); input.dispatchEvent(new Event('focus')); fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('mat-error').length).toBe(1);
expect(component.form.controls.username.invalid).toBe(true);
});
it('uses dynamic subscripts for both fields', () => {
const fixture = create();
expect(fixture.nativeElement.querySelectorAll('mat-form-field[subscriptsizing="dynamic"]').length).toBe(2);
});
it('submits normalized credentials, clears password and navigates home', async () => {
const component = create().componentInstance; fill(component); await component.submit();
expect(login).toHaveBeenCalledWith('demo', 'test-password');
expect(TestBed.inject(Router).navigateByUrl).toHaveBeenCalledWith('/');
expect(component.form.controls.password.value).toBe(''); expect(component.loading()).toBe(false);
});
it('shows loading and prevents duplicate submissions', async () => {
let resolve!: () => void;
login.mockReturnValue(new Promise<void>(done => { resolve = done; }));
const fixture = create(); const component = fixture.componentInstance; fill(component);
const pending = component.submit(); fixture.detectChanges();
expect(component.loading()).toBe(true);
expect((fixture.nativeElement.querySelector('button[type="submit"]') as HTMLButtonElement).disabled).toBe(true);
expect(fixture.nativeElement.querySelector('[role="status"]')).toBeTruthy();
await component.submit(); expect(login).toHaveBeenCalledTimes(1); resolve(); await pending;
});
it('starts with the password hidden and an accessible unpressed toggle', () => {
const fixture = create();
const element: HTMLElement = fixture.nativeElement;
const toggle = element.querySelector('.password-toggle') as HTMLButtonElement;
expect(element.querySelector('input[autocomplete="current-password"]')?.getAttribute('type')).toBe('password');
expect(toggle.type).toBe('button');
expect(toggle.getAttribute('aria-label')).toBe('Mostrar contraseña');
expect(toggle.getAttribute('aria-pressed')).toBe('false');
});
it('shows and hides the password with matching aria states without submitting', () => {
const fixture = create(); fill(fixture.componentInstance);
const element: HTMLElement = fixture.nativeElement;
const toggle = element.querySelector('.password-toggle') as HTMLButtonElement;
toggle.click(); fixture.detectChanges();
expect(element.querySelector('input[autocomplete="current-password"]')?.getAttribute('type')).toBe('text');
expect(toggle.getAttribute('aria-label')).toBe('Ocultar contraseña');
expect(toggle.getAttribute('aria-pressed')).toBe('true');
expect(login).not.toHaveBeenCalled();
toggle.click(); fixture.detectChanges();
expect(element.querySelector('input[autocomplete="current-password"]')?.getAttribute('type')).toBe('password');
expect(toggle.getAttribute('aria-label')).toBe('Mostrar contraseña');
expect(toggle.getAttribute('aria-pressed')).toBe('false');
expect(login).not.toHaveBeenCalled();
expect(fixture.componentInstance.form.controls.password.value).toBe('test-password');
});
it('submits the unchanged password while it is visible', async () => {
const fixture = create(); fill(fixture.componentInstance);
(fixture.nativeElement.querySelector('.password-toggle') as HTMLButtonElement).click();
fixture.detectChanges();
fixture.nativeElement.querySelector('form').dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
await fixture.whenStable();
expect(login).toHaveBeenCalledExactlyOnceWith('demo', 'test-password');
expect(TestBed.inject(Router).navigateByUrl).toHaveBeenCalledWith('/');
expect(fixture.componentInstance.form.controls.password.value).toBe('');
});
for (const status of [401, 500, 0, 404]) {
it(`shows generic error for ${status}`, async () => {
login.mockRejectedValue(new HttpErrorResponse({ status, error: 'PRIVATE TECHNICAL BODY' }));
const fixture = create(); const component = fixture.componentInstance; fill(component); await component.submit();
fixture.detectChanges();
expect(component.error()).toBe(status === 401 ? 'Usuario o contraseña incorrectos.'
: 'No fue posible iniciar sesión. Inténtalo de nuevo.');
expect(fixture.nativeElement.textContent).not.toContain('PRIVATE TECHNICAL BODY');
expect(TestBed.inject(Router).navigateByUrl).not.toHaveBeenCalled();
expect(component.loading()).toBe(false); expect(component.form.controls.password.value).toBe('');
});
}
});
+73
View File
@@ -0,0 +1,73 @@
import { Component, inject, signal } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { FormBuilder, FormGroupDirective, NgForm, ReactiveFormsModule, Validators } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';
import { Router } from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { AuthState } from './auth.state';
class LoginFieldErrorStateMatcher implements ErrorStateMatcher {
constructor(private readonly isEditing: () => boolean) {}
isErrorState(control: { invalid: boolean; touched: boolean } | null, form: FormGroupDirective | NgForm | null): boolean {
return !!control?.invalid && (control.touched || !!form?.submitted) && !this.isEditing();
}
}
@Component({
selector: 'app-login',
imports: [ReactiveFormsModule, MatIconModule, MatFormFieldModule, MatInputModule, MatButtonModule],
templateUrl: './login.html',
styleUrl: './login.scss',
})
export class Login {
private readonly auth = inject(AuthState);
private readonly router = inject(Router);
readonly loading = signal(false);
readonly error = signal('');
readonly passwordVisible = signal(false);
readonly submitted = signal(false);
readonly usernameEditing = signal(false);
readonly passwordEditing = signal(false);
readonly usernameErrorMatcher = new LoginFieldErrorStateMatcher(() => this.usernameEditing());
readonly passwordErrorMatcher = new LoginFieldErrorStateMatcher(() => this.passwordEditing());
readonly form = inject(FormBuilder).nonNullable.group({
username: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(64),
Validators.pattern(/^[a-zA-Z0-9._-]+$/)]],
password: ['', [Validators.required, Validators.maxLength(128)]],
});
showUsernameError(): boolean {
return this.form.controls.username.invalid && (this.form.controls.username.touched || this.submitted())
&& !this.usernameEditing();
}
showPasswordError(): boolean {
return this.form.controls.password.invalid && (this.form.controls.password.touched || this.submitted())
&& !this.passwordEditing();
}
async submit(): Promise<void> {
if (this.loading()) return;
this.submitted.set(true);
if (this.form.invalid) { this.form.markAllAsTouched(); return; }
this.loading.set(true);
this.error.set('');
const { username, password } = this.form.getRawValue();
try {
await this.auth.login(username.trim().toLowerCase(), password);
this.form.controls.password.reset();
if (this.auth.isAuthenticated()) await this.router.navigateByUrl('/');
} catch (error) {
this.form.controls.password.reset();
this.error.set(error instanceof HttpErrorResponse && error.status === 401
? 'Usuario o contraseña incorrectos.'
: 'No fue posible iniciar sesión. Inténtalo de nuevo.');
} finally {
this.loading.set(false);
}
}
}
-57
View File
@@ -1,57 +0,0 @@
import type { AnalysisResult } from './dashboard.mock';
import type { ChartFigure } from './plotly-chart';
const ink = '#081839';
const grid = '#e9ede5';
const green = '#6f821c';
const darkGreen = '#465d1e';
const teal = '#5f9ea0';
const font = { family: 'Roboto, sans-serif', color: ink, size: 12 };
export function createChartFigures(result: AnalysisResult): { bars: ChartFigure; donut: ChartFigure; line: ChartFigure } {
const bars: ChartFigure = {
data: [{
type: 'bar',
x: result.charts.categories.map((item) => item.label),
y: result.charts.categories.map((item) => item.value),
marker: { color: [green, darkGreen, teal, '#a8c243'] },
hovertemplate: '%{x}: %{y}<extra></extra>',
}],
layout: {
paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font,
margin: { l: 36, r: 12, t: 12, b: 48 }, showlegend: false,
xaxis: { showgrid: false, linecolor: grid, automargin: true },
yaxis: { showgrid: true, gridcolor: grid, zeroline: false, rangemode: 'tozero', automargin: true },
},
};
const donut: ChartFigure = {
data: [{
type: 'pie', hole: 0.62,
labels: result.charts.composition.map((item) => item.label),
values: result.charts.composition.map((item) => item.value),
marker: { colors: [green, teal, '#b5c69b'] },
textinfo: 'none', hovertemplate: '%{label}: %{value}<extra></extra>', sort: false,
}],
layout: {
paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font,
margin: { l: 8, r: 8, t: 8, b: 8 },
showlegend: true, legend: { orientation: 'h', x: 0.5, xanchor: 'center', y: -0.06, font: { color: ink, size: 11 } },
},
};
const line: ChartFigure = {
data: [{
type: 'scatter', mode: 'lines+markers',
x: result.charts.periods.map((item) => item.label),
y: result.charts.periods.map((item) => item.value),
line: { color: darkGreen, width: 3 }, marker: { color: green, size: 8 },
hovertemplate: '%{x}: %{y}<extra></extra>',
}],
layout: {
paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font,
margin: { l: 36, r: 16, t: 12, b: 48 }, showlegend: false,
xaxis: { showgrid: false, linecolor: grid, automargin: true },
yaxis: { showgrid: true, gridcolor: grid, zeroline: false, rangemode: 'tozero', automargin: true },
},
};
return { bars, donut, line };
}
-42
View File
@@ -1,42 +0,0 @@
<section class="dashboard" aria-labelledby="dashboard-title">
<button class="dashboard__back" type="button" (click)="returnHome()"><mat-icon aria-hidden="true">arrow_back</mat-icon><span>Volver al inicio</span></button>
<div class="dashboard__heading">
<div class="dashboard__intro">
<p class="dashboard__eyebrow">ISSSTELEON · Análisis de información</p>
<h1 id="dashboard-title">Resultados del análisis</h1>
<div class="dashboard__metadata">
<span class="dashboard__area">{{ result.analysisType }}</span>
<span class="dashboard__demo">{{ result.dataType }}</span>
</div>
<p class="dashboard__note">Los indicadores y las gráficas muestran valores obtenidos del procesamiento de los datos.</p>
</div>
<div class="dashboard__actions">
<button class="dashboard__upload" type="button" (click)="openInformationDialog()"><mat-icon aria-hidden="true">upload_file</mat-icon><span>Cargar información</span></button>
<button class="dashboard__export" type="button" (click)="openExportDialog()"><mat-icon aria-hidden="true">download</mat-icon><span>Exportar</span></button>
</div>
</div>
<div class="dashboard__kpis" aria-label="Indicadores de demostración">
@for (kpi of result.kpis; track kpi.label) {
<article class="kpi">
<p class="kpi__value">{{ formatKpi(kpi) }}</p>
<h2 class="kpi__label">{{ kpi.label }}</h2>
</article>
}
</div>
<div class="dashboard__charts">
<article class="chart-card chart-card--bars" aria-labelledby="bars-title">
<h2 id="bars-title">Distribución por categoría</h2>
<app-plotly-chart [figure]="bars" aria-label="Gráfica de barras con categorías A a D, datos de demostración" />
</article>
<article class="chart-card chart-card--donut" aria-labelledby="donut-title">
<h2 id="donut-title">Composición</h2>
<app-plotly-chart [figure]="donut" aria-label="Gráfica de dona con segmentos A a C, datos de demostración" />
</article>
<article class="chart-card chart-card--line" aria-labelledby="line-title">
<h2 id="line-title">Evolución por periodo</h2>
<app-plotly-chart [figure]="line" aria-label="Gráfica de línea con periodos 1 a 6, datos de demostración" />
</article>
</div>
</section>
-46
View File
@@ -1,46 +0,0 @@
// Datos exclusivos de demostración. No representan resultados clínicos ni un contrato de WebApi.
export interface AnalysisResult {
analysisType: string;
dataType: string;
kpis: ReadonlyArray<{ label: string; value: number; unit?: '%' }>;
charts: {
categories: ReadonlyArray<{ label: string; value: number }>;
composition: ReadonlyArray<{ label: string; value: number }>;
periods: ReadonlyArray<{ label: string; value: number }>;
};
}
export const mockAnalysisResult: AnalysisResult = {
analysisType: 'CAMA',
dataType: 'Datos de demostración',
kpis: [
{ label: 'Indicador 1', value: 1248 },
{ label: 'Indicador 2', value: 64.2, unit: '%' },
{ label: 'Indicador 3', value: 327 },
],
charts: {
categories: [
{ label: 'Categoría A', value: 12 },
{ label: 'Categoría B', value: 19 },
{ label: 'Categoría C', value: 9 },
{ label: 'Categoría D', value: 15 },
],
composition: [
{ label: 'Segmento A', value: 40 },
{ label: 'Segmento B', value: 35 },
{ label: 'Segmento C', value: 25 },
],
periods: [
{ label: 'Periodo 1', value: 8 },
{ label: 'Periodo 2', value: 11 },
{ label: 'Periodo 3', value: 10 },
{ label: 'Periodo 4', value: 15 },
{ label: 'Periodo 5', value: 13 },
{ label: 'Periodo 6', value: 18 },
],
},
};
export function formatKpi(kpi: AnalysisResult['kpis'][number]): string {
return `${new Intl.NumberFormat('en-US', { maximumFractionDigits: 1 }).format(kpi.value)}${kpi.unit ? ` ${kpi.unit}` : ''}`;
}
-37
View File
@@ -1,37 +0,0 @@
:host { display: block; flex: 1; min-width: 0; }
.dashboard { margin: 0 auto; max-width: 1440px; padding: 42px clamp(20px, 4vw, 56px) 72px; width: 100%; }
.dashboard__back { align-items: center; background: transparent; border: 0; border-radius: 6px; color: var(--color-text); cursor: pointer; display: inline-flex; font: inherit; gap: 7px; margin: 0 0 22px; min-height: 40px; padding: 6px 8px; }
.dashboard__back:hover { background: #eef1e8; }
.dashboard__back mat-icon { font-size: 20px; height: 20px; width: 20px; }
.dashboard__back:focus-visible, .dashboard__export:focus-visible { outline: 3px solid rgb(168 194 67 / 55%); outline-offset: 3px; }
.dashboard__heading { align-items: center; display: flex; gap: 24px; justify-content: space-between; }
.dashboard__intro { min-width: 0; }
.dashboard__actions { align-items: center; display: flex; flex: 0 0 auto; flex-wrap: wrap; gap: 10px; }
.dashboard__upload { align-items: center; background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; color: var(--color-text); cursor: pointer; display: inline-flex; flex: 0 0 auto; font: inherit; font-weight: 600; gap: 9px; min-height: 50px; padding: 12px 20px; transition: background-color .2s ease, border-color .2s ease; }
.dashboard__upload:hover { background: #e9ecef; border-color: #5f9ea0; }
.dashboard__upload mat-icon { color: #5f9ea0; }
.dashboard__upload:focus-visible { outline: 3px solid rgb(168 194 67 / 55%); outline-offset: 3px; }
.dashboard__export { align-items: center; background: #fff; border: 1px solid #d7dccf; border-radius: 8px; color: var(--color-text); cursor: pointer; display: inline-flex; font: inherit; font-weight: 600; gap: 9px; min-height: 50px; padding: 12px 20px; transition: background-color .2s ease, border-color .2s ease; }
.dashboard__export:hover { background: #f3f6e9; border-color: #a8c243; }
.dashboard__export mat-icon { color: #52691f; }
.dashboard__eyebrow { color: var(--color-text-secondary); font-size: 12px; font-weight: 600; letter-spacing: .12em; margin: 0 0 12px; text-transform: uppercase; }
h1, h2, p { margin-top: 0; }
h1 { color: var(--color-text); font-family: var(--font-heading); font-size: clamp(32px, 3.8vw, 46px); line-height: 1.1; margin-bottom: 16px; }
.dashboard__metadata { align-items: center; display: flex; flex-wrap: wrap; gap: 9px; }
.dashboard__area, .dashboard__demo { border-radius: 999px; font-size: 13px; font-weight: 700; padding: 6px 12px; }
.dashboard__area { background: #eaf0db; color: #465d1e; }
.dashboard__demo { background: #eff4f3; color: #326a6c; }
.dashboard__note { color: var(--color-text-secondary); font-size: 14px; line-height: 1.5; margin: 14px 0 0; }
.dashboard__kpis { display: grid; gap: 18px; grid-template-columns: repeat(3, minmax(0, 1fr)); margin: 32px 0 22px; }
.kpi, .chart-card { background: #fff; border: 1px solid var(--color-border); border-radius: 12px; min-width: 0; }
.kpi { padding: 22px 24px; }
.kpi__value { color: #52691f; font-family: var(--font-heading); font-size: clamp(32px, 3.5vw, 42px); font-weight: 700; line-height: 1; margin: 0 0 8px; overflow-wrap: anywhere; }
.kpi__label { color: var(--color-text); font-family: var(--font-body); font-size: 14px; font-weight: 500; margin: 0; }
.dashboard__charts { display: grid; gap: 20px; grid-template-columns: minmax(0, 1.8fr) minmax(0, 1fr); }
.chart-card { overflow: hidden; padding: 22px 22px 16px; }
.chart-card h2 { color: var(--color-text); font-family: var(--font-heading); font-size: 22px; font-weight: 700; line-height: 1.2; margin: 0 0 12px; }
.chart-card--line { grid-column: 1 / -1; }
@media (max-width: 860px) { .dashboard__charts { grid-template-columns: minmax(0, 1fr); } .chart-card--line { grid-column: auto; } }
@media (max-width: 700px) { .dashboard__heading { align-items: flex-start; flex-direction: column; gap: 18px; } .dashboard__actions { width: 100%; } }
@media (max-width: 420px) { .dashboard__actions { align-items: stretch; flex-direction: column; } .dashboard__actions button { justify-content: center; width: 100%; } }
@media (max-width: 600px) { .dashboard { padding: 30px 16px 48px; } .dashboard__kpis { grid-template-columns: minmax(0, 1fr); gap: 12px; margin-top: 26px; } .kpi { padding: 18px 20px; } .chart-card { padding: 18px 12px 12px; } .chart-card h2 { font-size: 20px; margin-left: 6px; } }
-50
View File
@@ -1,50 +0,0 @@
import { Component, inject } from '@angular/core';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { Router } from '@angular/router';
import { take } from 'rxjs';
import { formatKpi, mockAnalysisResult } from './dashboard.mock';
import { PlotlyChart } from './plotly-chart';
import { createChartFigures } from './dashboard.figures';
import { InformationUploadDialog } from '../information-upload-dialog';
import { ExportResultsDialog } from './export-results-dialog';
@Component({
imports: [MatDialogModule, MatIconModule, PlotlyChart],
selector: 'app-dashboard',
styleUrl: './dashboard.scss',
templateUrl: './dashboard.html',
})
export class Dashboard {
private readonly dialog = inject(MatDialog);
private readonly router = inject(Router);
readonly result = mockAnalysisResult;
readonly formatKpi = formatKpi;
returnHome(): void { void this.router.navigateByUrl('/'); }
openExportDialog(): void {
if (this.dialog.openDialogs.length > 0) return;
this.dialog.open(ExportResultsDialog, {
data: this.result,
width: '640px', maxWidth: 'calc(100vw - 32px)',
autoFocus: 'first-tabbable', restoreFocus: true,
panelClass: 'export-results-dialog-panel',
});
}
openInformationDialog(): void {
if (this.dialog.openDialogs.length > 0) return;
this.dialog.open<InformationUploadDialog, { entryPoint: 'dashboard' }, 'completed' | undefined>(InformationUploadDialog, {
data: { entryPoint: 'dashboard' }, width: '800px', maxWidth: 'calc(100vw - 32px)',
autoFocus: 'first-tabbable', restoreFocus: true, disableClose: true,
panelClass: 'information-upload-dialog-panel',
}).afterClosed().pipe(take(1)).subscribe((result) => {
if (result === 'completed') void this.router.navigateByUrl('/dashboard');
});
}
readonly figures = createChartFigures(this.result);
readonly bars = this.figures.bars;
readonly donut = this.figures.donut;
readonly line = this.figures.line;
}
@@ -1,32 +0,0 @@
<section class="export-dialog" aria-labelledby="export-title" aria-describedby="export-description">
<header class="export-dialog__header">
<div>
<h2 id="export-title">Exportar resultados</h2>
<p id="export-description">Selecciona el formato en el que deseas exportar los resultados del análisis.</p>
</div>
<button class="export-dialog__close" type="button" aria-label="Cerrar diálogo" [disabled]="generating()" (click)="close()"><mat-icon aria-hidden="true">close</mat-icon></button>
</header>
<div class="export-options" role="group" aria-label="Formato de exportación">
<button class="export-option" [class.export-option--selected]="selection() === 'pdf'" [attr.aria-pressed]="selection() === 'pdf'" [disabled]="generating()" type="button" (click)="select('pdf')">
<mat-icon class="export-option__icon" aria-hidden="true">picture_as_pdf</mat-icon>
<span class="export-option__copy"><strong>PDF</strong><span>Reporte visual del análisis y sus gráficas.</span></span>
@if (selection() === 'pdf') { <mat-icon class="export-option__check" aria-hidden="true">check_circle</mat-icon> }
</button>
<button class="export-option" [class.export-option--selected]="selection() === 'excel'" [attr.aria-pressed]="selection() === 'excel'" [disabled]="generating()" type="button" (click)="select('excel')">
<mat-icon class="export-option__icon" aria-hidden="true">table_chart</mat-icon>
<span class="export-option__copy"><strong>Excel</strong><span>Datos utilizados por los indicadores y las gráficas.</span></span>
@if (selection() === 'excel') { <mat-icon class="export-option__check" aria-hidden="true">check_circle</mat-icon> }
</button>
</div>
<footer class="export-dialog__footer">
<div class="export-dialog__messages">
@if (error()) { <p class="export-dialog__error" role="alert">No fue posible generar el archivo. Intenta nuevamente.</p> }
</div>
<div class="export-dialog__actions">
<button class="export-dialog__cancel" type="button" [disabled]="generating()" (click)="close()">Cancelar</button>
<button class="export-dialog__submit" type="button" [disabled]="!selection() || generating()" (click)="submit()">{{ generating() ? 'Generando...' : 'Exportar' }}</button>
</div>
</footer>
</section>
@@ -1,31 +0,0 @@
:host { display: block; }
.export-dialog { background: #fff; color: var(--color-text); padding: 28px 32px 24px; }
.export-dialog__header { align-items: flex-start; display: flex; gap: 20px; justify-content: space-between; }
.export-dialog__header h2 { font-family: var(--font-heading); font-size: 30px; line-height: 1.15; margin: 0; }
.export-dialog__header p { color: var(--color-text-secondary); font-size: 15px; line-height: 1.5; margin: 12px 0 0; }
.export-dialog__close { align-items: center; background: transparent; border: 0; border-radius: 50%; color: #596273; cursor: pointer; display: inline-flex; flex: 0 0 auto; height: 40px; justify-content: center; margin: -8px -10px 0 0; width: 40px; }
.export-dialog__close:hover { background: #f0f2ed; }
.export-options { display: grid; gap: 14px; grid-template-columns: repeat(2, minmax(0, 1fr)); margin: 26px 0; }
.export-option { align-items: flex-start; background: #fff; border: 1px solid #d7dccf; border-radius: 10px; color: var(--color-text); cursor: pointer; display: flex; gap: 13px; min-height: 112px; padding: 18px 15px; text-align: left; transition: background-color .18s ease, border-color .18s ease, box-shadow .18s ease; }
.export-option:hover { background: #f7f9f3; border-color: #9aaa64; }
.export-option:focus-visible, .export-dialog button:focus-visible { outline: 3px solid rgb(168 194 67 / 55%); outline-offset: 3px; }
.export-option--selected { background: #f4f7e9; border: 2px solid #6f821c; padding: 17px 14px; }
.export-option__icon { color: #52691f; flex: 0 0 auto; margin-top: 1px; }
.export-option__copy { display: grid; gap: 7px; line-height: 1.4; }
.export-option__copy strong { font-size: 16px; }
.export-option__copy > span { color: var(--color-text-secondary); font-size: 13px; }
.export-option__check { color: #52691f; flex: 0 0 auto; font-size: 20px; height: 20px; margin-left: auto; width: 20px; }
.export-dialog__footer { align-items: flex-end; border-top: 1px solid var(--color-border); display: flex; gap: 16px; justify-content: space-between; padding-top: 18px; }
.export-dialog__footer p { color: var(--color-text-secondary); font-size: 12px; line-height: 1.4; margin: 0; max-width: 240px; }
.export-dialog__messages { max-width: 240px; }
.export-dialog__messages .export-dialog__error { color: #a12b2b; }
.export-dialog button:disabled { cursor: not-allowed; }
.export-dialog__actions { display: flex; flex: 0 0 auto; gap: 10px; }
.export-dialog__actions button { border-radius: 7px; cursor: pointer; font: inherit; font-weight: 600; min-height: 44px; padding: 10px 18px; }
.export-dialog__cancel { background: #fff; border: 1px solid var(--color-border-subtle); color: var(--color-text); }
.export-dialog__cancel:hover { background: var(--color-surface-hover); }
.export-dialog__submit { background: var(--color-primary-action); border: 1px solid var(--color-primary-action); color: #fff; }
.export-dialog__submit:disabled { background: #e8ecdf; border-color: #e8ecdf; color: #9da38f; cursor: not-allowed; }
@media (max-width: 560px) { .export-dialog { padding: 22px 20px 18px; } .export-dialog__header h2 { font-size: 26px; } .export-options { grid-template-columns: minmax(0, 1fr); margin: 20px 0; } .export-option { min-height: 88px; } .export-dialog__footer { align-items: stretch; flex-direction: column; } .export-dialog__footer p { max-width: none; } .export-dialog__actions { justify-content: flex-end; } }
@media (max-width: 360px) { .export-dialog { padding-inline: 16px; } .export-dialog__actions { gap: 6px; } .export-dialog__actions button { padding-inline: 12px; } }
.export-dialog__close:focus-visible { outline: 3px solid rgb(168 194 67 / 55%); outline-offset: 2px; }
@@ -1,94 +0,0 @@
import { TestBed } from '@angular/core/testing';
import { MatDialog } from '@angular/material/dialog';
import { vi } from 'vitest';
import { mockAnalysisResult } from './dashboard.mock';
import { EXCEL_EXPORT, PDF_EXPORT, ExportResultsDialog } from './export-results-dialog';
describe('ExportResultsDialog', () => {
const open = (
runExport: (result: typeof mockAnalysisResult) => Promise<void>,
runPdf: (result: typeof mockAnalysisResult) => Promise<void> = vi.fn(),
) => {
TestBed.configureTestingModule({
imports: [ExportResultsDialog],
providers: [{ provide: EXCEL_EXPORT, useValue: runExport }, { provide: PDF_EXPORT, useValue: runPdf }],
});
const dialog = TestBed.inject(MatDialog);
const ref = dialog.open(ExportResultsDialog, { data: mockAnalysisResult });
const detect = () => ref.componentRef!.changeDetectorRef.detectChanges();
const root = () => document.querySelector('.cdk-overlay-container')!;
detect();
return { ref, detect, root };
};
it('enables PDF and Excel after selection', () => {
const { ref, detect, root } = open(vi.fn());
const options = root().querySelectorAll<HTMLButtonElement>('.export-option');
options[0].click(); detect();
expect(root().querySelector<HTMLButtonElement>('.export-dialog__submit')!.disabled).toBe(false);
options[1].click(); detect();
expect(root().querySelector<HTMLButtonElement>('.export-dialog__submit')!.disabled).toBe(false);
ref.close();
});
it('sends each format to its own exporter with the same result', async () => {
const runExcel = vi.fn().mockResolvedValue(undefined);
const runPdf = vi.fn().mockResolvedValue(undefined);
const { ref, detect, root } = open(runExcel, runPdf);
root().querySelectorAll<HTMLButtonElement>('.export-option')[0].click(); detect();
await ref.componentInstance.submit();
expect(runPdf).toHaveBeenCalledWith(mockAnalysisResult);
expect(runExcel).not.toHaveBeenCalled();
});
it('prevents duplicate PDF generation and keeps the dialog open on error', async () => {
let reject!: (error: Error) => void;
const runPdf = vi.fn(() => new Promise<void>((_, fail) => { reject = fail; }));
const { ref, detect, root } = open(vi.fn(), runPdf);
root().querySelectorAll<HTMLButtonElement>('.export-option')[0].click(); detect();
root().querySelector<HTMLButtonElement>('.export-dialog__submit')!.click(); detect();
expect(root().querySelector<HTMLButtonElement>('.export-dialog__submit')!.disabled).toBe(true);
expect(root().querySelector<HTMLButtonElement>('.export-dialog__cancel')!.disabled).toBe(true);
await ref.componentInstance.submit();
expect(runPdf).toHaveBeenCalledOnce();
reject(new Error('failure'));
await Promise.resolve();
await Promise.resolve();
detect();
expect(TestBed.inject(MatDialog).openDialogs).toHaveLength(1);
expect(root().querySelector('[role="alert"]')?.textContent).toContain('No fue posible generar el archivo');
expect(root().querySelector<HTMLButtonElement>('.export-dialog__submit')!.disabled).toBe(false);
ref.close();
});
it('prevents duplicate generation and closes only after success', async () => {
let finish!: () => void;
const runExport = vi.fn(() => new Promise<void>((resolve) => { finish = resolve; }));
const { ref, detect, root } = open(runExport);
root().querySelectorAll<HTMLButtonElement>('.export-option')[1].click(); detect();
const submit = root().querySelector<HTMLButtonElement>('.export-dialog__submit')!;
submit.click(); detect();
expect(runExport).toHaveBeenCalledWith(mockAnalysisResult);
expect(submit.disabled).toBe(true);
expect(submit.textContent).toContain('Generando...');
expect(root().querySelectorAll<HTMLButtonElement>('.export-option')[0].disabled).toBe(true);
await ref.componentInstance.submit();
expect(runExport).toHaveBeenCalledOnce();
expect(TestBed.inject(MatDialog).openDialogs).toHaveLength(1);
finish();
await new Promise<void>((resolve) => ref.afterClosed().subscribe(() => resolve()));
expect(TestBed.inject(MatDialog).openDialogs).toHaveLength(0);
});
it('keeps the dialog open and allows retry after an error', async () => {
const runExport = vi.fn().mockRejectedValueOnce(new Error('failure')).mockResolvedValueOnce(undefined);
const { ref, detect, root } = open(runExport);
root().querySelectorAll<HTMLButtonElement>('.export-option')[1].click(); detect();
await ref.componentInstance.submit(); detect();
expect(TestBed.inject(MatDialog).openDialogs).toHaveLength(1);
expect(root().querySelector('[role="alert"]')?.textContent).toContain('No fue posible generar el archivo');
expect(root().querySelector<HTMLButtonElement>('.export-dialog__submit')!.disabled).toBe(false);
await ref.componentInstance.submit();
expect(runExport).toHaveBeenCalledTimes(2);
});
});
@@ -1,53 +0,0 @@
import { Component, inject, InjectionToken, signal } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import type { AnalysisResult } from './dashboard.mock';
import { exportExcel } from './exports/excel-export';
export type ExportFormat = 'pdf' | 'excel';
export const EXCEL_EXPORT = new InjectionToken<typeof exportExcel>('EXCEL_EXPORT', { factory: () => exportExcel });
export const PDF_EXPORT = new InjectionToken<(result: AnalysisResult) => Promise<void>>('PDF_EXPORT', {
factory: () => (result) => import('./exports/pdf-export').then(({ exportPdf }) => exportPdf(result)),
});
@Component({
imports: [MatDialogModule, MatIconModule],
selector: 'app-export-results-dialog',
styleUrl: './export-results-dialog.scss',
templateUrl: './export-results-dialog.html',
})
export class ExportResultsDialog {
readonly selection = signal<ExportFormat | null>(null);
readonly generating = signal(false);
readonly error = signal(false);
private readonly result = inject<AnalysisResult>(MAT_DIALOG_DATA);
private readonly runExcelExport = inject(EXCEL_EXPORT);
private readonly runPdfExport = inject(PDF_EXPORT);
constructor(private readonly dialogRef: MatDialogRef<ExportResultsDialog>) {}
select(format: ExportFormat): void {
if (this.generating()) return;
this.selection.set(format);
this.error.set(false);
}
close(): void { if (!this.generating()) this.dialogRef.close(); }
async submit(): Promise<void> {
const format = this.selection();
if (this.generating() || !format) return;
this.generating.set(true);
this.error.set(false);
this.dialogRef.disableClose = true;
try {
await (format === 'excel' ? this.runExcelExport(this.result) : this.runPdfExport(this.result));
this.dialogRef.close();
} catch {
this.error.set(true);
} finally {
this.generating.set(false);
this.dialogRef.disableClose = false;
}
}
}
@@ -1,40 +0,0 @@
import { read, utils, write } from 'xlsx';
import { vi } from 'vitest';
import { mockAnalysisResult } from '../dashboard.mock';
import { buildWorkbook, excelFilename, exportExcel } from './excel-export';
describe('Excel export', () => {
it('builds four sheets from the same result used by the Dashboard', () => {
const workbook = buildWorkbook(mockAnalysisResult, utils);
expect(workbook.SheetNames).toEqual(['Resumen', 'Distribución', 'Composición', 'Evolución']);
const rows = (name: string) => utils.sheet_to_json<(string | number)[]>(workbook.Sheets[name], { header: 1 });
expect(rows('Resumen')).toEqual([
['Área de análisis', 'CAMA'],
[],
['Tipo de datos', mockAnalysisResult.dataType],
[],
['Indicador', 'Valor'],
...mockAnalysisResult.kpis.map((kpi) => [kpi.label, kpi.unit === '%' ? kpi.value / 100 : kpi.value]),
]);
expect(workbook.Sheets['Resumen']['B7'].z).toBe('0.0%');
expect(rows('Distribución').slice(1)).toEqual(mockAnalysisResult.charts.categories.map((item) => [item.label, item.value]));
expect(rows('Composición').slice(1)).toEqual(mockAnalysisResult.charts.composition.map((item) => [item.label, item.value]));
expect(rows('Evolución').slice(1)).toEqual(mockAnalysisResult.charts.periods.map((item) => [item.label, item.value]));
});
it('requests an xlsx download with a sanitized analysis filename', async () => {
const writeFileXLSX = vi.fn();
await exportExcel(mockAnalysisResult, async () => ({ utils, writeFileXLSX }));
expect(writeFileXLSX).toHaveBeenCalledOnce();
expect(writeFileXLSX.mock.calls[0][1]).toBe('ISSSTELEON_CAMA_resultados_demo.xlsx');
expect(excelFilename({ ...mockAnalysisResult, analysisType: 'CAMA/otro:*' })).toBe('ISSSTELEON_CAMA_otro_resultados_demo.xlsx');
});
it('produces an XLSX that SheetJS can read with the four sheets intact', () => {
const bytes = write(buildWorkbook(mockAnalysisResult, utils), { type: 'array', bookType: 'xlsx' });
const opened = read(bytes, { type: 'array' });
expect(opened.SheetNames).toEqual(['Resumen', 'Distribución', 'Composición', 'Evolución']);
expect(opened.Sheets['Resumen']['B7'].v).toBeCloseTo(0.642);
expect(opened.Sheets['Evolución']['A7'].v).toBe('Periodo 6');
});
});
-49
View File
@@ -1,49 +0,0 @@
import type { WorkBook, WorkSheet } from 'xlsx';
import type { AnalysisResult } from '../dashboard.mock';
type SheetUtils = typeof import('xlsx')['utils'];
type Writer = Pick<typeof import('./sheetjs-write-wrapper'), 'utils' | 'writeFileXLSX'>;
export function buildWorkbook(result: AnalysisResult, utils: SheetUtils): WorkBook {
const workbook = utils.book_new();
const summary = utils.aoa_to_sheet([
['Área de análisis', result.analysisType],
[],
['Tipo de datos', result.dataType],
[],
['Indicador', 'Valor'],
...result.kpis.map((kpi) => [kpi.label, kpi.unit === '%' ? kpi.value / 100 : kpi.value]),
]);
summary['!cols'] = [{ wch: 25 }, { wch: 24 }];
result.kpis.forEach((kpi, index) => {
if (kpi.unit === '%') {
const cell = summary[`B${index + 6}`];
if (cell) cell.z = '0.0%';
}
});
utils.book_append_sheet(workbook, summary, 'Resumen');
const appendData = (name: string, heading: string, rows: ReadonlyArray<{ label: string; value: number }>): void => {
const sheet: WorkSheet = utils.aoa_to_sheet([[heading, 'Valor'], ...rows.map(({ label, value }) => [label, value])]);
sheet['!cols'] = [{ wch: 25 }, { wch: 16 }];
utils.book_append_sheet(workbook, sheet, name);
};
appendData('Distribución', 'Categoría', result.charts.categories);
appendData('Composición', 'Segmento', result.charts.composition);
appendData('Evolución', 'Periodo', result.charts.periods);
return workbook;
}
export function excelFilename(result: AnalysisResult): string {
const safeType = result.analysisType.normalize('NFKD').replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-zA-Z0-9_-]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 50) || 'analisis';
return `ISSSTELEON_${safeType}_resultados_demo.xlsx`;
}
export async function exportExcel(
result: AnalysisResult,
loadWriter: () => Promise<Writer> = () => import('./sheetjs-write-wrapper'),
): Promise<void> {
const { utils, writeFileXLSX } = await loadWriter();
writeFileXLSX(buildWorkbook(result, utils), excelFilename(result));
}
@@ -1,55 +0,0 @@
import { vi } from 'vitest';
import { mockAnalysisResult } from '../dashboard.mock';
import { createChartFigures } from '../dashboard.figures';
import { buildReport, exportPdf, pdfFilename } from './pdf-export';
function fakeDocument() {
let pages = 1;
return {
addPage: vi.fn(() => { pages++; }),
setPage: vi.fn(),
getNumberOfPages: vi.fn(() => pages),
setFont: vi.fn(), setFontSize: vi.fn(), setTextColor: vi.fn(),
setDrawColor: vi.fn(), setFillColor: vi.fn(), rect: vi.fn(), line: vi.fn(),
text: vi.fn(), addImage: vi.fn(),
splitTextToSize: vi.fn((value: string) => [value]),
save: vi.fn().mockResolvedValue(undefined),
};
}
describe('PDF export', () => {
it('composes the logo, metadata, all KPIs, three charts, and page footers', () => {
const doc = fakeDocument();
buildReport(doc as unknown as Parameters<typeof buildReport>[0], mockAnalysisResult, new Uint8Array([1]), {
bars: 'bar-image', donut: 'donut-image', line: 'line-image',
});
const text = doc.text.mock.calls.map((call) => call[0]).flat().join(' | ');
expect(text).toContain('Reporte de resultados del análisis');
expect(text).toContain('Área de análisis: CAMA');
expect(text).toContain('Tipo de datos: Datos de demostración');
expect(text).toContain('DATOS DE DEMOSTRACIÓN');
for (const label of ['Indicador 1', 'Indicador 2', 'Indicador 3', '1,248', '64.2 %', '327']) {
expect(text).toContain(label);
}
for (const title of ['Distribución por categoría', 'Composición', 'Evolución por periodo']) {
expect(text).toContain(title);
}
expect(text).toContain('Página 1 de 2');
expect(text).toContain('Página 2 de 2');
expect(doc.getNumberOfPages()).toBe(2);
expect(doc.addImage.mock.calls.map((call) => call[0])).toEqual([new Uint8Array([1]), 'bar-image', 'donut-image', 'line-image']);
});
it('renders the three figures derived from AnalysisResult and saves a sanitized PDF filename', async () => {
const doc = fakeDocument();
const renderChart = vi.fn().mockResolvedValue('image');
const jsPDF = vi.fn(function () { return doc; });
await exportPdf(mockAnalysisResult, async () => ({
jsPDF, renderChart, loadLogo: vi.fn().mockResolvedValue(new Uint8Array([1])),
}) as unknown as typeof import('./pdf-runtime'));
expect(renderChart).toHaveBeenCalledTimes(3);
expect(renderChart.mock.calls.map((call) => call[0])).toEqual(Object.values(createChartFigures(mockAnalysisResult)));
expect(doc.save).toHaveBeenCalledWith('ISSSTELEON_CAMA_reporte_demo.pdf', { returnPromise: true });
expect(pdfFilename({ ...mockAnalysisResult, analysisType: 'CAMA/otro:*' })).toBe('ISSSTELEON_CAMA_otro_reporte_demo.pdf');
});
});
-115
View File
@@ -1,115 +0,0 @@
import type { jsPDF } from 'jspdf';
import type { AnalysisResult } from '../dashboard.mock';
import { formatKpi } from '../dashboard.mock';
import { createChartFigures } from '../dashboard.figures';
type ReportDocument = Pick<jsPDF, 'addPage' | 'setPage' | 'getNumberOfPages' | 'setFont' | 'setFontSize' |
'setTextColor' | 'setDrawColor' | 'setFillColor' | 'rect' | 'line' | 'text' | 'addImage' | 'splitTextToSize' | 'save'>;
type Runtime = typeof import('./pdf-runtime');
type ChartImages = { bars: string; donut: string; line: string };
const navy = '#081839';
const green = '#6f821c';
const gray = '#667080';
const pageWidth = 210;
const margin = 18;
const contentWidth = pageWidth - margin * 2;
const chartHeight = 87;
export function pdfFilename(result: AnalysisResult): string {
const area = result.analysisType.normalize('NFKD').replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-zA-Z0-9_-]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 50) || 'analisis';
return `ISSSTELEON_${area}_reporte_demo.pdf`;
}
function drawKpis(doc: ReportDocument, result: AnalysisResult, startY: number): number {
doc.setTextColor(navy);
doc.setFont('helvetica', 'bold');
doc.setFontSize(12);
doc.text('Resumen de indicadores', margin, startY);
const columns = 3;
const gap = 4;
const cardWidth = (contentWidth - gap * (columns - 1)) / columns;
result.kpis.forEach((kpi, index) => {
const column = index % columns;
const row = Math.floor(index / columns);
const x = margin + column * (cardWidth + gap);
const y = startY + 8 + row * 34;
doc.setFillColor('#f4f7e9');
doc.rect(x, y, cardWidth, 29, 'F');
doc.setTextColor(gray);
doc.setFont('helvetica', 'normal');
doc.setFontSize(9);
doc.text(doc.splitTextToSize(kpi.label, cardWidth - 8), x + 4, y + 8);
doc.setTextColor(navy);
doc.setFont('helvetica', 'bold');
doc.setFontSize(15);
doc.text(formatKpi(kpi), x + 4, y + 23);
});
return startY + 8 + Math.ceil(result.kpis.length / columns) * 34;
}
function drawChart(doc: ReportDocument, title: string, image: string, y: number): number {
doc.setTextColor(navy);
doc.setFont('helvetica', 'bold');
doc.setFontSize(12);
doc.text(title, margin, y);
doc.addImage(image, 'PNG', margin, y + 4, contentWidth, chartHeight, undefined, 'FAST');
return y + chartHeight + 15;
}
export function buildReport(doc: ReportDocument, result: AnalysisResult, logo: Uint8Array, images: ChartImages): void {
doc.addImage(logo, 'PNG', margin, 13, 63, 20);
doc.setDrawColor('#d8ddd2');
doc.line(margin, 38, pageWidth - margin, 38);
doc.setTextColor(navy);
doc.setFont('helvetica', 'bold');
doc.setFontSize(18);
doc.text('Reporte de resultados del análisis', margin, 51);
doc.setFont('helvetica', 'normal');
doc.setFontSize(10);
doc.setTextColor(gray);
doc.text(`Área de análisis: ${result.analysisType}`, margin, 63);
doc.text(`Tipo de datos: ${result.dataType}`, margin, 70);
doc.setTextColor(green);
doc.setFont('helvetica', 'bold');
doc.text(result.dataType.toLocaleUpperCase('es-MX'), margin, 81);
let nextY = drawKpis(doc, result, 97) + 10;
if (nextY + chartHeight + 8 > 264) {
doc.addPage();
nextY = 27;
}
drawChart(doc, 'Distribución por categoría', images.bars, nextY);
doc.addPage();
drawChart(doc, 'Composición', images.donut, 31);
drawChart(doc, 'Evolución por periodo', images.line, 145);
const count = doc.getNumberOfPages();
for (let page = 1; page <= count; page++) {
doc.setPage(page);
doc.setDrawColor('#d8ddd2');
doc.line(margin, 275, pageWidth - margin, 275);
doc.setTextColor(gray);
doc.setFont('helvetica', 'normal');
doc.setFontSize(8);
doc.text(`ISSSTELEON · Análisis de información · ${result.dataType}`, margin, 282);
doc.text(`Página ${page} de ${count}`, pageWidth - margin, 282, { align: 'right' });
}
}
export async function exportPdf(
result: AnalysisResult,
loadRuntime: () => Promise<Runtime> = () => import('./pdf-runtime'),
): Promise<void> {
const { jsPDF, renderChart, loadLogo } = await loadRuntime();
const figures = createChartFigures(result);
const logo = await loadLogo();
const bars = await renderChart(figures.bars);
const donut = await renderChart(figures.donut);
const line = await renderChart(figures.line);
const doc = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4', compress: true });
buildReport(doc, result, logo, { bars, donut, line });
await doc.save(pdfFilename(result), { returnPromise: true });
}
@@ -1,28 +0,0 @@
import { vi } from 'vitest';
import { createChartFigures } from '../dashboard.figures';
import { mockAnalysisResult } from '../dashboard.mock';
const plotly = vi.hoisted(() => ({ newPlot: vi.fn().mockResolvedValue(undefined), toImage: vi.fn().mockResolvedValue('data:image/png;base64,AA=='), purge: vi.fn() }));
vi.mock('plotly.js-basic-dist-min', () => ({ default: plotly }));
import { renderChart } from './pdf-runtime';
describe('temporary Plotly rendering', () => {
it('exports a high-resolution PNG and purges the temporary figure', async () => {
const before = document.body.children.length;
const image = await renderChart(createChartFigures(mockAnalysisResult).bars);
expect(image).toMatch(/^data:image\/png/);
expect(plotly.newPlot).toHaveBeenCalledOnce();
expect(plotly.toImage).toHaveBeenCalledWith(expect.any(HTMLElement), { format: 'png', width: 900, height: 450, scale: 2 });
expect(plotly.purge).toHaveBeenCalledOnce();
expect(document.body.children.length).toBe(before);
});
it('purges and removes the temporary figure if image generation fails', async () => {
plotly.toImage.mockRejectedValueOnce(new Error('image failure'));
const before = document.body.children.length;
await expect(renderChart(createChartFigures(mockAnalysisResult).donut)).rejects.toThrow('image failure');
expect(plotly.purge).toHaveBeenCalledTimes(2);
expect(document.body.children.length).toBe(before);
});
});
-39
View File
@@ -1,39 +0,0 @@
import { jsPDF } from 'jspdf';
import Plotly from 'plotly.js-basic-dist-min';
import type { ChartFigure } from '../plotly-chart';
export { jsPDF };
const imageWidth = 900;
const imageHeight = 450;
const imageScale = 2;
export async function renderChart(figure: ChartFigure): Promise<string> {
const host = document.createElement('div');
host.style.cssText = `position:fixed;left:-10000px;top:0;width:${imageWidth}px;height:${imageHeight}px;pointer-events:none`;
document.body.appendChild(host);
try {
await Plotly.newPlot(host, [...figure.data], {
...figure.layout,
width: imageWidth,
height: imageHeight,
autosize: false,
paper_bgcolor: '#ffffff',
plot_bgcolor: '#ffffff',
font: { family: 'Arial, sans-serif', color: '#081839', size: 14 },
}, { staticPlot: true, responsive: false, displayModeBar: false, displaylogo: false });
return await Plotly.toImage(host, { format: 'png', width: imageWidth, height: imageHeight, scale: imageScale });
} finally {
try {
Plotly.purge(host);
} finally {
host.remove();
}
}
}
export async function loadLogo(): Promise<Uint8Array> {
const response = await fetch(new URL('assets/branding/isssteleon-logo.png', document.baseURI));
if (!response.ok) throw new Error('Logo unavailable');
return new Uint8Array(await response.arrayBuffer());
}
@@ -1,3 +0,0 @@
import { utils, writeFileXLSX } from 'xlsx';
export { utils, writeFileXLSX };
-11
View File
@@ -1,11 +0,0 @@
declare module 'plotly.js-basic-dist-min' {
interface PlotlyBasic {
react(element: HTMLElement, data: ReadonlyArray<Record<string, unknown>>, layout: Record<string, unknown>, config: Record<string, unknown>): Promise<unknown>;
newPlot(element: HTMLElement, data: ReadonlyArray<Record<string, unknown>>, layout: Record<string, unknown>, config: Record<string, unknown>): Promise<unknown>;
toImage(element: HTMLElement, options: { format: 'png'; width: number; height: number; scale: number }): Promise<string>;
purge(element: HTMLElement): void;
Plots: { resize(element: HTMLElement): void };
}
const Plotly: PlotlyBasic;
export default Plotly;
}
-53
View File
@@ -1,53 +0,0 @@
import { isPlatformBrowser } from '@angular/common';
import { AfterViewInit, Component, ElementRef, inject, input, OnChanges, OnDestroy, PLATFORM_ID, viewChild } from '@angular/core';
export interface ChartFigure {
data: ReadonlyArray<Record<string, unknown>>;
layout: Record<string, unknown>;
}
@Component({
selector: 'app-plotly-chart',
template: '<div #plot class="plotly-chart__plot"></div>',
styles: [':host { display: block; min-width: 0; width: 100%; } .plotly-chart__plot { min-width: 0; width: 100%; height: 290px; }'],
})
export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy {
readonly figure = input.required<ChartFigure>();
private readonly plot = viewChild.required<ElementRef<HTMLDivElement>>('plot');
private readonly browser = isPlatformBrowser(inject(PLATFORM_ID));
private plotly: (typeof import('plotly.js-basic-dist-min'))['default'] | null = null;
private observer: ResizeObserver | null = null;
private ready = false;
private destroyed = false;
ngAfterViewInit(): void {
if (!this.browser) return;
this.ready = true;
void this.render();
this.observer = new ResizeObserver(() => {
if (this.plotly && !this.destroyed) this.plotly.Plots.resize(this.plot().nativeElement);
});
this.observer.observe(this.plot().nativeElement);
}
ngOnChanges(): void {
if (this.ready) void this.render();
}
private async render(): Promise<void> {
// The import is evaluated only when a chart is mounted on the Dashboard route.
const module = await import('plotly.js-basic-dist-min');
if (this.destroyed) return;
this.plotly = module.default;
await this.plotly.react(this.plot().nativeElement, [...this.figure().data], {
...this.figure().layout,
autosize: true,
}, { responsive: true, displayModeBar: false, displaylogo: false });
}
ngOnDestroy(): void {
this.destroyed = true;
this.observer?.disconnect();
if (this.plotly) this.plotly.purge(this.plot().nativeElement);
}
}
-20
View File
@@ -1,20 +0,0 @@
<div class="dropzone" [class.dropzone--active]="isDragOver" (dragenter)="onDragEnter($event)" (dragover)="onDragOver($event)" (dragleave)="onDragLeave($event)" (drop)="onDrop($event)">
<mat-icon class="dropzone__icon" aria-hidden="true">cloud_upload</mat-icon>
<p class="dropzone__title">Arrastra tus archivos aquí</p>
<p class="dropzone__formats">Excel · CSV · JSON · PDF</p>
<input #fileInput class="visually-hidden" type="file" multiple accept=".xlsx,.csv,.json,.pdf,application/pdf,application/json,text/csv" aria-label="Seleccionar archivos" (change)="onFileSelection($event)" />
<button class="upload-action upload-action--outlined select-files-button" mat-stroked-button type="button" (click)="fileInput.click()">
<mat-icon aria-hidden="true">upload_file</mat-icon>
<span>Seleccionar archivos</span>
</button>
</div>
@if (messages.length > 0) {
<ul class="file-messages" aria-live="polite" aria-label="Mensajes sobre archivos">
@for (message of messages; track $index) { <li>{{ message }}</li> }
</ul>
}
@if (files.length > 0) {
<app-file-list [files]="files" (removeRequested)="removeRequested.emit($event)" />
}
-92
View File
@@ -1,92 +0,0 @@
@use 'upload-button' as button;
:host { display: block; }
.dropzone {
align-items: center;
background: #fcfdfb;
border: 1.5px dashed #cbd2c4;
border-radius: 10px;
display: flex;
flex-direction: column;
justify-content: center;
min-height: 244px;
padding: 24px;
text-align: center;
}
.dropzone--active {
background: #f5f8e9;
border-color: var(--color-primary);
border-style: solid;
}
.dropzone__icon {
color: #71882b;
font-size: 40px;
height: 40px;
width: 40px;
}
.dropzone__title {
font-size: 16px;
font-weight: 600;
margin: 14px 0 4px;
}
.dropzone__formats {
color: var(--color-text-secondary);
font-size: 13px;
margin: 0 0 16px;
}
.select-files-button {
--mat-button-outlined-label-text-color: var(--color-text);
--mat-button-outlined-outline-color: var(--color-border-subtle);
--mat-button-outlined-state-layer-color: transparent;
--mat-button-outlined-ripple-color: transparent;
background: #fff;
border: 1px solid var(--mat-button-outlined-outline-color);
transition: border-color 0.18s ease;
}
.select-files-button:hover {
background: var(--color-surface-hover);
border-color: var(--color-primary);
}
.select-files-button:active {
background: #e8eed5;
}
.select-files-button mat-icon {
color: #5f9ea0;
margin: 0;
}
.visually-hidden {
clip: rect(0, 0, 0, 0);
clip-path: inset(50%);
height: 1px;
overflow: hidden;
position: absolute;
white-space: nowrap;
width: 1px;
}
.file-messages {
background: #fffaf0;
border: 1px solid #ead8a7;
border-radius: 7px;
color: #634d13;
font-size: 13px;
line-height: 1.45;
list-style: none;
margin: 12px 0 0;
padding: 10px 14px;
}
.file-messages li + li {
margin-top: 4px;
}
.upload-action {
@include button.base;
}
.select-files-button:focus-visible {
@include button.focus;
}
@media (max-width: 600px) {
.dropzone {
min-height: 220px;
padding: 20px 12px;
}
}
-49
View File
@@ -1,49 +0,0 @@
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { FileListComponent } from './file-list';
@Component({
imports: [MatButtonModule, MatIconModule, FileListComponent],
selector: 'app-file-configuration',
styleUrl: './file-configuration.scss',
templateUrl: './file-configuration.html',
})
export class FileConfigurationComponent {
@Input({ required: true }) files: File[] = [];
@Input() messages: string[] = [];
@Output() readonly filesAdded = new EventEmitter<File[]>();
@Output() readonly removeRequested = new EventEmitter<File>();
isDragOver = false;
private dragDepth = 0;
onFileSelection(event: Event): void {
const input = event.target as HTMLInputElement;
this.filesAdded.emit(input.files ? Array.from(input.files) : []);
input.value = '';
}
onDragEnter(event: DragEvent): void {
event.preventDefault();
this.dragDepth++;
this.isDragOver = true;
}
onDragOver(event: DragEvent): void {
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';
}
onDragLeave(event: DragEvent): void {
event.preventDefault();
this.dragDepth = Math.max(0, this.dragDepth - 1);
if (this.dragDepth === 0) this.isDragOver = false;
}
onDrop(event: DragEvent): void {
event.preventDefault();
this.dragDepth = 0;
this.isDragOver = false;
this.filesAdded.emit(event.dataTransfer?.files ? Array.from(event.dataTransfer.files) : []);
}
}
-6
View File
@@ -1,6 +0,0 @@
<dl class="confirmation-summary" aria-label="Resumen de la selección">
<div><dt>Fuente</dt><dd>Archivo</dd></div>
<div><dt>Archivos seleccionados</dt><dd>{{ files.length }}</dd></div>
<div><dt>Tamaño total</dt><dd>{{ formatFileSize(totalSize) }}</dd></div>
</dl>
<app-file-list [files]="files" [readonly]="true" />
-11
View File
@@ -1,11 +0,0 @@
:host { display: block; }
.confirmation-summary {
display: grid;
gap: 10px;
grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
margin: 0;
padding: 0;
}
.confirmation-summary div { background: #fcfdfb; border: 1px solid #e7eae3; border-radius: 8px; min-width: 0; padding: 10px 12px; }
.confirmation-summary dt { color: var(--color-text-secondary); font-size: 12px; }
.confirmation-summary dd { font-size: 15px; font-weight: 600; margin: 4px 0 0; overflow-wrap: anywhere; }
-15
View File
@@ -1,15 +0,0 @@
import { Component, Input } from '@angular/core';
import { FileListComponent } from './file-list';
import { formatFileSize } from './file-selection';
@Component({
imports: [FileListComponent],
selector: 'app-file-confirmation',
styleUrl: './file-confirmation.scss',
templateUrl: './file-confirmation.html',
})
export class FileConfirmationComponent {
@Input({ required: true }) files: File[] = [];
@Input({ required: true }) totalSize = 0;
readonly formatFileSize = formatFileSize;
}
-20
View File
@@ -1,20 +0,0 @@
<section class="selected-files" [class.confirmation-files]="readonly" [attr.aria-labelledby]="readonly ? 'confirmation-files-title' : 'selected-files-title'">
<header class="selected-files__header">
<h3 [id]="readonly ? 'confirmation-files-title' : 'selected-files-title'">{{ readonly ? 'Archivos a procesar' : 'Archivos seleccionados' }}</h3>
<span class="selected-files__count" aria-label="Cantidad de archivos">{{ files.length }}</span>
</header>
<ul class="selected-files__list">
@for (file of files; track file.name + ':' + file.size) {
<li class="file-row" [class.file-row--readonly]="readonly">
<mat-icon class="file-row__icon" aria-hidden="true">{{ fileIcon(file) }}</mat-icon>
<span class="file-row__name" [title]="file.name">{{ file.name }}</span>
<span class="file-row__size">{{ formatFileSize(file.size) }}</span>
@if (!readonly) {
<button class="file-row__remove" mat-icon-button type="button" [attr.aria-label]="'Eliminar ' + file.name" (click)="removeRequested.emit(file)">
<mat-icon aria-hidden="true">close</mat-icon>
</button>
}
</li>
}
</ul>
</section>
-87
View File
@@ -1,87 +0,0 @@
@use 'upload-button' as button;
:host { display: block; }
.selected-files {
margin-top: 20px;
}
.selected-files__header {
align-items: center;
display: flex;
gap: 10px;
justify-content: space-between;
margin-bottom: 8px;
}
.selected-files__header h3 {
font-size: 15px;
font-weight: 600;
margin: 0;
}
.selected-files__count {
align-items: center;
background: var(--color-step);
border-radius: 20px;
color: #52651d;
display: inline-flex;
font-size: 12px;
font-weight: 600;
height: 25px;
justify-content: center;
min-width: 25px;
padding: 0 7px;
}
.selected-files__list {
border: 1px solid #e7eae3;
border-radius: 8px;
list-style: none;
margin: 0;
max-height: 220px;
overflow-y: auto;
padding: 0;
}
.file-row--readonly { grid-template-columns: 22px minmax(0, 1fr) auto; padding-right: 12px; }
.file-row {
align-items: center;
display: grid;
gap: 10px;
grid-template-columns: 22px minmax(0, 1fr) auto 40px;
min-height: 54px;
padding: 6px 8px 6px 12px;
}
.file-row + .file-row {
border-top: 1px solid #eef0eb;
}
.file-row__icon {
color: #71882b;
font-size: 20px;
height: 20px;
width: 20px;
}
.file-row__name {
font-size: 13px;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.file-row__size {
color: #737b6b;
font-size: 12px;
white-space: nowrap;
}
.file-row__remove {
color: #596273;
}
.file-row__remove:focus-visible {
@include button.focus;
}
@media (max-width: 600px) {
.file-row {
gap: 6px;
grid-template-columns: 20px minmax(0, 1fr) auto 36px;
padding-left: 8px;
}
.file-row--readonly { grid-template-columns: 20px minmax(0, 1fr) auto; }
.file-row__name { font-size: 12px; }
.file-row__size { font-size: 11px; }
}
-18
View File
@@ -1,18 +0,0 @@
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { fileIcon, formatFileSize } from './file-selection';
@Component({
imports: [MatButtonModule, MatIconModule],
selector: 'app-file-list',
styleUrl: './file-list.scss',
templateUrl: './file-list.html',
})
export class FileListComponent {
@Input({ required: true }) files: File[] = [];
@Input() readonly = false;
@Output() readonly removeRequested = new EventEmitter<File>();
readonly fileIcon = fileIcon;
readonly formatFileSize = formatFileSize;
}
-42
View File
@@ -1,42 +0,0 @@
const allowedExtensions = new Set(['xlsx', 'csv', 'json', 'pdf']);
function extensionOf(fileName: string): string {
const finalDot = fileName.lastIndexOf('.');
return finalDot >= 0 ? fileName.slice(finalDot + 1).toLowerCase() : '';
}
export function selectFiles(selected: File[], incomingFiles: File[]): { files: File[]; messages: string[] } {
const messages: string[] = [];
const files = [...selected];
for (const file of incomingFiles) {
if (!allowedExtensions.has(extensionOf(file.name))) {
messages.push(`${file.name} no fue agregado. Formato no compatible.`);
} else if (file.size === 0) {
messages.push(`${file.name} no fue agregado. El archivo está vacío.`);
} else if (files.some((existing) => existing.name === file.name && existing.size === file.size)) {
messages.push(`${file.name} ya se encuentra seleccionado.`);
} else {
files.push(file);
}
}
return { files, messages };
}
export function formatFileSize(size: number): string {
if (size < 1024) return `${size} bytes`;
const units = ['KB', 'MB', 'GB'];
let value = size / 1024;
let unit = 0;
while (value >= 1024 && unit < units.length - 1) {
value /= 1024;
unit++;
}
return `${new Intl.NumberFormat('es-MX', { maximumFractionDigits: 1 }).format(value)} ${units[unit]}`;
}
export function fileIcon(file: File): string {
const extension = extensionOf(file.name);
if (extension === 'pdf') return 'picture_as_pdf';
if (extension === 'csv' || extension === 'xlsx') return 'table_chart';
return 'data_object';
}
-27
View File
@@ -1,27 +0,0 @@
<section class="home" aria-labelledby="home-title">
<div class="home__content">
<p class="home__eyebrow">ISSSTELEON · Análisis de información</p>
<h1 id="home-title">Analiza tu información</h1>
<p class="home__description">
Carga tus datos para procesarlos y consultar resultados de forma clara y sencilla.
</p>
<button class="home__action" type="button" (click)="openInformationDialog()">
<mat-icon aria-hidden="true">upload_file</mat-icon>
<span>Cargar información</span>
</button>
<ol class="steps" aria-label="Pasos del análisis de información">
<li class="steps__item">
<span class="steps__icon"><mat-icon aria-hidden="true">upload_file</mat-icon></span>
<span>Carga información</span>
</li>
<li class="steps__item">
<span class="steps__icon"><mat-icon aria-hidden="true">data_object</mat-icon></span>
<span>Procesa los datos</span>
</li>
<li class="steps__item">
<span class="steps__icon"><mat-icon aria-hidden="true">insights</mat-icon></span>
<span>Consulta resultados</span>
</li>
</ol>
</div>
</section>
-131
View File
@@ -1,131 +0,0 @@
:host {
display: flex;
flex: 1;
min-width: 0;
}
.home {
align-items: flex-start;
display: flex;
flex: 1;
justify-content: center;
min-height: inherit;
padding: 72px 32px;
text-align: center;
}
.home__content {
margin-inline: auto;
max-width: 780px;
width: 100%;
}
.home__eyebrow {
color: var(--color-text-secondary);
font-size: 12px;
font-weight: 500;
letter-spacing: 0.12em;
margin: 0 0 18px;
text-transform: uppercase;
}
h1 {
color: var(--color-primary);
font-family: var(--font-heading);
font-size: clamp(2.75rem, 5.1vw, 3.375rem);
font-weight: 700;
letter-spacing: -0.045em;
line-height: 1.08;
margin: 0;
}
.home__description {
color: var(--color-text-secondary);
font-size: 16px;
line-height: 1.6;
margin: 20px auto 30px;
max-width: 560px;
}
.home__action {
align-items: center;
background: #f8f9fa;
border: 1px solid #e9ecef;
border-radius: 8px;
color: var(--color-text);
cursor: pointer;
display: inline-flex;
font: inherit;
font-weight: 600;
gap: 9px;
min-height: 50px;
padding: 12px 20px;
transition:
background-color 0.2s ease,
border-color 0.2s ease,
color 0.2s ease,
transform 0.2s ease;
}
.home__action:hover {
background: #e9ecef;
border-color: #5f9ea0;
transform: translateY(-1px);
}
.home__action:focus-visible {
outline: 3px solid rgb(168 194 67 / 55%);
outline-offset: 3px;
}
.home__action:active {
transform: translateY(0);
}
.home__action mat-icon {
color: #5f9ea0;
margin: 0;
}
.steps {
align-items: center;
color: var(--color-text-secondary);
display: flex;
flex-wrap: wrap;
gap: 24px 36px;
justify-content: center;
list-style: none;
margin: 74px 0 0;
padding: 0;
}
.steps__item {
align-items: center;
display: inline-flex;
font-size: 14px;
gap: 10px;
}
.steps__icon {
align-items: center;
background: var(--color-step);
border-radius: 50%;
color: var(--color-primary);
display: inline-flex;
height: 38px;
justify-content: center;
width: 38px;
}
@media (max-width: 600px) {
.home {
padding: 56px 22px;
}
h1 {
font-size: clamp(2.35rem, 10vw, 2.8rem);
}
.home__description {
font-size: 15px;
margin-top: 16px;
}
.steps {
align-items: flex-start;
flex-direction: column;
gap: 16px;
margin: 52px auto 0;
max-width: 230px;
}
}
-33
View File
@@ -1,33 +0,0 @@
import { Component, inject } from '@angular/core';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { Router } from '@angular/router';
import { take } from 'rxjs';
import { InformationUploadDialog } from './information-upload-dialog';
@Component({
imports: [MatDialogModule, MatIconModule],
selector: 'app-home',
styleUrl: './home.scss',
templateUrl: './home.html',
})
export class Home {
private readonly dialog = inject(MatDialog);
private readonly router = inject(Router);
openInformationDialog(): void {
if (this.dialog.openDialogs.length > 0) return;
this.dialog.open<InformationUploadDialog, { entryPoint: 'home' }, 'completed' | undefined>(InformationUploadDialog, {
data: { entryPoint: 'home' },
width: '800px',
maxWidth: 'calc(100vw - 32px)',
autoFocus: 'first-tabbable',
restoreFocus: true,
disableClose: true,
panelClass: 'information-upload-dialog-panel',
}).afterClosed().pipe(take(1)).subscribe((result) => {
if (result === 'completed') void this.router.navigateByUrl('/dashboard');
});
}
}
-68
View File
@@ -1,68 +0,0 @@
@if (processingState()) {
<app-processing-status [state]="processingState()!" [progress]="processingProgress()" (finishRequested)="finishProcessing()" />
} @else {
<section class="upload-dialog" aria-labelledby="upload-title">
<header class="upload-dialog__header">
<h2 id="upload-title">Cargar información</h2>
<button class="upload-dialog__close" mat-icon-button type="button" aria-label="Cerrar diálogo de carga de información" (click)="close()">
<mat-icon aria-hidden="true">close</mat-icon>
</button>
</header>
@if (step() !== 'action') { <ol class="upload-steps" aria-label="Etapas de carga de información">
<li [class.upload-steps__item--active]="step() === 'source'" [class.upload-steps__item--complete]="step() !== 'source'" [attr.aria-current]="step() === 'source' ? 'step' : null">
<span class="upload-steps__number"><mat-icon aria-hidden="true">{{ step() === 'source' ? 'looks_one' : 'check' }}</mat-icon></span><span>Fuente</span>
</li>
<li [class.upload-steps__item--active]="step() === 'configuration'" [class.upload-steps__item--complete]="step() === 'confirmation'" [attr.aria-current]="step() === 'configuration' ? 'step' : null">
<span class="upload-steps__number"><mat-icon aria-hidden="true">{{ step() === 'confirmation' ? 'check' : 'looks_two' }}</mat-icon></span><span>Configuración</span>
</li>
<li [class.upload-steps__item--active]="step() === 'confirmation'" [attr.aria-current]="step() === 'confirmation' ? 'step' : null">
<span class="upload-steps__number"><mat-icon aria-hidden="true">looks_3</mat-icon></span><span>Confirmación</span>
</li>
</ol> }
@if (step() === 'action') {
<p class="upload-dialog__description">¿Qué deseas hacer con la nueva información?</p>
<div class="upload-dialog__content">
<app-action-selection [intent]="intent()" (intentChange)="selectIntent($event)" />
</div>
} @else if (step() === 'source') {
<p class="upload-dialog__description">Selecciona cómo deseas proporcionar los datos.</p>
<div class="upload-dialog__content">
<app-source-selection [source]="source()" (sourceChange)="selectSource($event)" />
</div>
} @else if (step() === 'configuration' && source() === 'file') {
<p class="upload-dialog__description">Selecciona los archivos que deseas procesar.</p>
<div class="upload-dialog__content file-configuration">
<app-file-configuration [files]="files()" [messages]="fileMessages()" (filesAdded)="addFiles($event)" (removeRequested)="removeFile($event)" />
</div>
} @else if (step() === 'configuration') {
<p class="upload-dialog__description">Configura la fuente seleccionada.</p>
<div class="upload-dialog__content" aria-live="polite">
<app-sql-connection-config [config]="sqlConfig()" (configChange)="updateSqlConfig($event)" (validChange)="isSqlConfigValid($event)" />
</div>
} @else if (source() === 'sql') {
<p class="upload-dialog__description">Revisa la información antes de iniciar el procesamiento.</p>
<div class="upload-dialog__content" aria-live="polite">
<app-sql-connection-confirmation [config]="sqlConfig()" [verificationState]="sqlVerificationState()" (verifyRequested)="simulateConnectionCheck()" />
</div>
} @else {
<p class="upload-dialog__description">Revisa la información antes de iniciar el procesamiento.</p>
<div class="upload-dialog__content" aria-live="polite">
<app-file-confirmation [files]="files()" [totalSize]="totalFileSize()" />
</div>
}
<footer class="upload-dialog__footer">
<button class="upload-action action-cancel upload-dialog__cancel" mat-button type="button" (click)="close()">Cancelar</button>
<div class="upload-dialog__navigation">
@if ((step() !== 'source' && step() !== 'action') || (step() === 'source' && entryPoint === 'dashboard')) {
<button class="upload-action upload-action--outlined action-back upload-dialog__back" mat-button type="button" (click)="back()">Regresar</button>
}
@if (step() !== 'confirmation') {
<button class="upload-action action-continue upload-dialog__continue" mat-flat-button type="button" [disabled]="step() === 'action' ? !intent() : step() === 'source' ? !source() : source() === 'file' ? files().length === 0 : !sqlConfigValid()" (click)="continue()">Continuar</button>
} @else { <button class="upload-action action-continue upload-dialog__process" mat-flat-button type="button" [disabled]="source() === 'file' ? files().length === 0 : sqlVerificationState() !== 'success'" (click)="process()">Procesar</button> }
</div>
</footer>
</section>
}
-194
View File
@@ -1,194 +0,0 @@
@use 'upload-button' as button;
:host {
display: block;
}
.upload-dialog {
background: #fff;
color: var(--color-text);
max-height: 100dvh;
overflow: auto;
padding: 28px 32px 24px;
}
.upload-dialog__header {
align-items: flex-start;
display: flex;
gap: 20px;
justify-content: space-between;
}
.upload-dialog__header h2 {
font-family: var(--font-heading);
font-size: 30px;
line-height: 1.15;
margin: 0;
}
.upload-dialog__description {
color: var(--color-text-secondary);
font-size: 15px;
line-height: 1.5;
margin: 14px 0 0;
}
.upload-dialog__close {
color: #596273;
margin: -8px -10px 0 0;
}
.upload-steps {
align-items: center;
border-bottom: 1px solid var(--color-border);
color: var(--color-text-secondary);
display: flex;
justify-content: center;
list-style: none;
margin: 24px 0 0;
padding: 0 0 20px;
}
.upload-steps li {
align-items: center;
display: flex;
font-size: 13px;
gap: 8px;
}
.upload-steps li + li::before {
background: #dfe3dc;
content: '';
height: 1px;
margin: 0 14px;
width: clamp(20px, 8vw, 70px);
}
.upload-steps__number {
align-items: center;
background: #f0f2ed;
border-radius: 50%;
display: inline-flex;
font-size: 12px;
height: 25px;
justify-content: center;
width: 25px;
}
.upload-steps__number mat-icon {
font-size: 16px;
height: 16px;
width: 16px;
}
.upload-steps__item--active {
color: var(--color-text);
font-weight: 600;
}
.upload-steps__item--active .upload-steps__number {
background: var(--color-primary);
color: var(--color-text);
}
.upload-steps__item--complete {
color: #71882b;
}
.upload-steps__item--complete .upload-steps__number {
background: var(--color-step);
color: #71882b;
}
.upload-dialog__content {
padding: 18px 0 28px;
}
.upload-dialog__footer {
align-items: center;
border-top: 1px solid var(--color-border);
display: grid;
gap: 10px;
grid-template-columns: minmax(0, 1fr) auto;
padding-top: 18px;
}
.action-cancel {
justify-self: start;
}
.upload-dialog__navigation {
align-items: center;
display: flex;
gap: 10px;
justify-self: end;
}
.upload-action {
@include button.base;
}
.action-cancel,
.action-back {
--mat-button-text-state-layer-color: transparent;
--mat-button-text-ripple-color: transparent;
}
.action-cancel {
--mat-button-text-label-text-color: #fff;
background: var(--color-text-secondary);
}
.action-cancel:hover {
background: #696969;
}
.action-back {
--mat-button-text-label-text-color: var(--color-text);
background: #fff;
border: 1px solid var(--color-border-subtle);
}
.action-back:hover {
background: var(--color-surface-hover);
border-color: var(--color-primary);
}
.action-continue {
--mat-button-filled-container-color: var(--color-primary-action);
--mat-button-filled-label-text-color: #f7f9ef;
--mat-button-filled-state-layer-color: transparent;
--mat-button-filled-ripple-color: transparent;
min-width: 124px;
}
.action-continue:hover:not(:disabled) {
--mat-button-filled-container-color: #809625;
}
.action-continue:disabled {
--mat-button-filled-disabled-container-color: #e8ecdf;
--mat-button-filled-disabled-label-text-color: #9da38f;
--mat-button-filled-disabled-state-layer-color: transparent;
}
@media (max-width: 600px) {
.upload-dialog {
padding: 22px 20px 18px;
}
.upload-dialog__header h2 {
font-size: 26px;
}
.upload-dialog__description {
font-size: 14px;
margin-top: 12px;
}
.upload-steps {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.upload-steps li {
flex-direction: column;
font-size: 11px;
gap: 4px;
text-align: center;
}
.upload-steps li + li::before {
display: none;
}
.upload-steps__number {
height: 22px;
width: 22px;
}
.upload-dialog__content {
padding: 20px 0;
}
}
@media (max-width: 360px) {
.upload-dialog { padding-inline: 16px; }
.upload-dialog__footer, .upload-dialog__navigation { gap: 4px; }
.action-cancel,
.action-back {
min-width: 56px;
padding-inline: 6px;
}
.action-continue { min-width: 92px; padding-inline: 10px; }
}
.upload-dialog__close:focus-visible, .upload-action:focus-visible {
@include button.focus;
}
-175
View File
@@ -1,175 +0,0 @@
import { Component, computed, Inject, OnDestroy, Optional, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { SqlConnectionConfig, SqlConnectionConfigComponent } from './sql-connection-config';
import { SqlConnectionConfirmationComponent, SqlConnectionVerificationState } from './sql-connection-confirmation';
import { ProcessingStatusComponent } from './processing-status';
import { SourceSelectionComponent, UploadSource } from './source-selection';
import { FileConfigurationComponent } from './file-configuration';
import { FileConfirmationComponent } from './file-confirmation';
import { formatFileSize, selectFiles } from './file-selection';
import { ActionSelectionComponent } from './action-selection';
type UploadStep = 'action' | 'source' | 'configuration' | 'confirmation';
/** Future WebApi contract: append adds to the current analysis; replace starts an independent analysis.
* Adding data may require analysis-type compatibility checks (CaCu/CAMA/TEA); those rules are not defined here.
*/
export type UploadIntent = 'append' | 'replace';
export type UploadEntryPoint = 'home' | 'dashboard';
export interface InformationUploadDialogData { entryPoint: UploadEntryPoint; }
export type ProcessingState = 'processing' | 'success' | 'error';
@Component({
imports: [MatButtonModule, MatDialogModule, MatIconModule, ActionSelectionComponent, SqlConnectionConfigComponent, SqlConnectionConfirmationComponent, ProcessingStatusComponent, SourceSelectionComponent, FileConfigurationComponent, FileConfirmationComponent],
selector: 'app-information-upload-dialog',
styleUrl: './information-upload-dialog.scss',
templateUrl: './information-upload-dialog.html',
})
export class InformationUploadDialog implements OnDestroy {
readonly entryPoint: UploadEntryPoint;
readonly step = signal<UploadStep>('source');
readonly intent = signal<UploadIntent | null>(null);
readonly source = signal<UploadSource | null>(null);
readonly files = signal<File[]>([]);
readonly totalFileSize = computed(() => this.files().reduce((total, file) => total + file.size, 0));
readonly fileMessages = signal<string[]>([]);
readonly sqlConfig = signal<SqlConnectionConfig>({ host: '', port: '', database: '', username: '', password: '' });
readonly sqlConfigValid = signal(false);
readonly sqlVerificationState = signal<SqlConnectionVerificationState>('idle');
readonly processingState = signal<ProcessingState | null>(null);
readonly processingProgress = signal(0);
private verifiedSqlConfig: SqlConnectionConfig | null = null;
private verificationTimer: ReturnType<typeof setTimeout> | null = null;
private processingTimer: ReturnType<typeof setInterval> | null = null;
constructor(
private readonly dialogRef: MatDialogRef<InformationUploadDialog>,
@Optional() @Inject(MAT_DIALOG_DATA) data: InformationUploadDialogData | null,
) {
this.entryPoint = data?.entryPoint ?? 'home';
if (this.entryPoint === 'dashboard') this.step.set('action');
}
selectIntent(intent: UploadIntent): void { this.intent.set(intent); }
selectSource(source: UploadSource): void {
this.source.set(source);
}
continue(): void {
if (this.step() === 'action' && this.intent()) this.step.set('source');
else if (this.step() === 'source' && this.source()) this.step.set('configuration');
else if (this.step() === 'configuration' && this.source() === 'file' && this.files().length > 0) {
this.step.set('confirmation');
} else if (this.step() === 'configuration' && this.source() === 'sql' && this.sqlConfigValid()) {
this.step.set('confirmation');
}
}
updateSqlConfig(config: SqlConnectionConfig): void {
this.sqlConfig.set(config);
if (this.verifiedSqlConfig && !this.sameSqlConfig(this.verifiedSqlConfig, config)) {
this.clearVerificationTimer();
this.verifiedSqlConfig = null;
this.sqlVerificationState.set('idle');
}
}
simulateConnectionCheck(): void {
if (this.sqlVerificationState() === 'checking') return;
// TODO: replace this fixed frontend simulation with verification via WebApi.
this.clearVerificationTimer();
this.verifiedSqlConfig = { ...this.sqlConfig() };
this.sqlVerificationState.set('checking');
this.verificationTimer = setTimeout(() => {
this.verificationTimer = null;
if (this.verifiedSqlConfig && this.sameSqlConfig(this.verifiedSqlConfig, this.sqlConfig())) {
this.sqlVerificationState.set('success');
} else {
this.verifiedSqlConfig = null;
this.sqlVerificationState.set('idle');
}
}, 1200);
}
private sameSqlConfig(left: SqlConnectionConfig, right: SqlConnectionConfig): boolean {
return left.host === right.host && left.port === right.port && left.database === right.database &&
left.username === right.username && left.password === right.password;
}
private clearVerificationTimer(): void {
if (this.verificationTimer !== null) clearTimeout(this.verificationTimer);
this.verificationTimer = null;
}
back(): void {
if (this.step() === 'confirmation') this.step.set('configuration');
else if (this.step() === 'source' && this.entryPoint === 'dashboard') this.step.set('action');
else if (this.step() === 'configuration') this.step.set('source');
}
isSqlConfigValid(valid: boolean): void {
this.sqlConfigValid.set(valid);
}
close(): void {
if (this.processingState() === 'processing') return;
this.clearVerificationTimer();
this.verifiedSqlConfig = null;
this.sqlVerificationState.set('idle');
this.dialogRef.close();
}
process(): void {
const allowed = this.source() === 'file'
? this.files().length > 0
: this.source() === 'sql' && this.sqlVerificationState() === 'success';
if (this.step() !== 'confirmation' || !allowed) return;
this.processingState.set('processing');
this.dialogRef.disableClose = true;
this.simulateProcessing();
}
finishProcessing(): void {
if (this.processingState() !== 'success') return;
this.dialogRef.close('completed');
}
ngOnDestroy(): void {
this.clearVerificationTimer();
this.clearProcessingTimer();
}
private simulateProcessing(): void {
// TODO: reemplazar simulación por estado/progreso reportado por WebApi
this.clearProcessingTimer();
this.processingProgress.set(0);
this.processingTimer = setInterval(() => {
const progress = Math.min(this.processingProgress() + 1, 100);
this.processingProgress.set(progress);
if (progress === 100) {
this.clearProcessingTimer();
this.processingState.set('success');
}
}, 45);
}
private clearProcessingTimer(): void {
if (this.processingTimer !== null) clearInterval(this.processingTimer);
this.processingTimer = null;
}
removeFile(fileToRemove: File): void {
this.files.update((files) => files.filter((file) => file !== fileToRemove));
}
readonly formatFileSize = formatFileSize;
addFiles(incomingFiles: File[]): void {
const selection = selectFiles(this.files(), incomingFiles);
if (selection.files.length !== this.files().length) this.files.set(selection.files);
this.fileMessages.set(selection.messages);
}
}
-30
View File
@@ -1,30 +0,0 @@
<section class="processing" [attr.aria-labelledby]="state === 'success' ? 'processing-success-title' : 'processing-title'">
@if (state === 'success') {
<div class="processing__success" aria-live="polite" aria-atomic="true">
<span class="processing__success-icon"><mat-icon aria-hidden="true">check</mat-icon></span>
<h2 id="processing-success-title">Procesamiento completado</h2>
<p>Los resultados están listos.</p>
<button class="processing__finish" mat-flat-button type="button" (click)="finishRequested.emit()">Finalizar</button>
</div>
} @else {
<div class="processing__active" aria-live="polite" aria-atomic="true">
<h2 id="processing-title">Procesando información</h2>
<p class="processing__intro">Estamos preparando los resultados.<br />Este proceso puede tardar unos minutos.</p>
<div class="processing__meter">
<mat-progress-bar mode="determinate" [value]="progress" aria-label="Progreso del procesamiento" />
<span class="processing__percentage">{{ progress }} %</span>
</div>
<p class="processing__current">{{ currentStage }}...</p>
<ol class="processing__stages" aria-label="Etapas del procesamiento">
@for (stage of ['Preparando información', 'Procesando datos', 'Generando resultados']; track stage; let i = $index) {
<li [class.processing__stage--complete]="stageStatus(i) === 'complete'" [class.processing__stage--active]="stageStatus(i) === 'active'" [class.processing__stage--pending]="stageStatus(i) === 'pending'">
<mat-icon aria-hidden="true">{{ stageStatus(i) === 'complete' ? 'check_circle' : stageStatus(i) === 'active' ? 'radio_button_checked' : 'radio_button_unchecked' }}</mat-icon>
<span>{{ stage }}</span>
<span class="visually-hidden">{{ stageStatus(i) === 'complete' ? 'completada' : stageStatus(i) === 'active' ? 'activa' : 'pendiente' }}</span>
</li>
}
</ol>
<p class="processing__note">No cierres esta ventana mientras termina el procesamiento.</p>
</div>
}
</section>
-33
View File
@@ -1,33 +0,0 @@
:host { display: block; }
.processing {
align-items: center;
background: #fff;
color: var(--color-text);
display: flex;
justify-content: center;
min-height: min(500px, 100dvh);
padding: 36px clamp(20px, 7vw, 64px);
text-align: center;
}
.processing__active, .processing__success { margin: auto; max-width: 520px; width: 100%; }
.processing h2 { font-family: var(--font-heading); font-size: clamp(24px, 4vw, 30px); line-height: 1.2; margin: 0; }
.processing__intro, .processing__success p { color: var(--color-text-secondary); font-size: 15px; line-height: 1.55; margin: 14px 0 30px; }
.processing__meter { align-items: center; display: flex; gap: 14px; }
.processing__meter mat-progress-bar { --mat-progress-bar-active-indicator-color: #71882b; --mat-progress-bar-track-color: #e9eddf; flex: 1; }
.processing__percentage { color: var(--color-text); font-size: 14px; font-variant-numeric: tabular-nums; font-weight: 600; min-width: 42px; text-align: right; }
.processing__current { color: #52651d; font-size: 15px; font-weight: 600; margin: 18px 0 26px; }
.processing__stages { display: grid; gap: 14px; list-style: none; margin: 0 auto; max-width: 320px; padding: 0; text-align: left; }
.processing__stages li { align-items: center; display: flex; gap: 10px; font-size: 14px; }
.processing__stages mat-icon { flex: 0 0 20px; font-size: 20px; height: 20px; width: 20px; }
.processing__stage--complete { color: #71882b; }
.processing__stage--active { color: var(--color-text); font-weight: 600; }
.processing__stage--pending { color: #858585; }
.processing__note { color: #858585; font-size: 13px; line-height: 1.5; margin: 30px auto 0; max-width: 300px; }
.processing__success { padding: 28px 0; }
.processing__success-icon { align-items: center; background: var(--color-step); border-radius: 50%; color: #71882b; display: inline-flex; height: 64px; justify-content: center; margin-bottom: 22px; width: 64px; }
.processing__success-icon mat-icon { font-size: 34px; height: 34px; width: 34px; }
.processing__success p { margin-bottom: 28px; }
.processing__finish { --mat-button-filled-container-color: var(--color-primary-action); --mat-button-filled-label-text-color: #f7f9ef; --mat-button-filled-state-layer-color: transparent; border-radius: 8px; font-weight: 600; min-height: 46px; min-width: 150px; }
.processing__finish:hover { --mat-button-filled-container-color: #809625; }
.visually-hidden { clip: rect(0, 0, 0, 0); clip-path: inset(50%); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; }
@media (max-width: 480px) { .processing { min-height: min(440px, 100dvh); padding: 28px 4px; } .processing__intro { font-size: 14px; } .processing__stages { gap: 12px; } }
-28
View File
@@ -1,28 +0,0 @@
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import type { ProcessingState } from './information-upload-dialog';
@Component({
imports: [MatButtonModule, MatIconModule, MatProgressBarModule],
selector: 'app-processing-status',
styleUrl: './processing-status.scss',
templateUrl: './processing-status.html',
})
export class ProcessingStatusComponent {
@Input({ required: true }) state!: ProcessingState;
@Input({ required: true }) progress = 0;
@Output() readonly finishRequested = new EventEmitter<void>();
get currentStage(): string {
if (this.progress <= 20) return 'Preparando información';
if (this.progress <= 80) return 'Procesando datos';
return 'Generando resultados';
}
stageStatus(stage: number): 'complete' | 'active' | 'pending' {
const active = this.progress <= 20 ? 0 : this.progress <= 80 ? 1 : 2;
return stage < active ? 'complete' : stage === active ? 'active' : 'pending';
}
}
-12
View File
@@ -1,12 +0,0 @@
<div class="source-options" role="group" aria-label="Selecciona una fuente de información">
<button class="source-card" [class.source-card--selected]="source === 'file'" [attr.aria-pressed]="source === 'file'" type="button" (click)="sourceChange.emit('file')">
<span class="source-card__icon"><mat-icon aria-hidden="true">upload_file</mat-icon></span>
<span class="source-card__copy"><span class="source-card__title">Archivo</span><span class="source-card__description">Excel, CSV, JSON o PDF</span></span>
@if (source === 'file') { <mat-icon class="source-card__check" aria-hidden="true">check_circle</mat-icon> }
</button>
<button class="source-card" [class.source-card--selected]="source === 'sql'" [attr.aria-pressed]="source === 'sql'" type="button" (click)="sourceChange.emit('sql')">
<span class="source-card__icon"><mat-icon aria-hidden="true">storage</mat-icon></span>
<span class="source-card__copy"><span class="source-card__title">Conexión SQL</span><span class="source-card__description">Conecta una base de datos para utilizar su información.</span></span>
@if (source === 'sql') { <mat-icon class="source-card__check" aria-hidden="true">check_circle</mat-icon> }
</button>
</div>
-63
View File
@@ -1,63 +0,0 @@
@use 'upload-button' as button;
:host { display: block; }
.source-options {
display: grid;
gap: 16px;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.source-card {
align-items: center;
background: #fff;
border: 1px solid var(--color-border);
border-radius: 9px;
color: var(--color-text);
cursor: pointer;
display: flex;
gap: 16px;
min-height: 126px;
padding: 20px;
position: relative;
text-align: left;
}
.source-card:focus-visible {
@include button.focus;
}
.source-card--selected {
background: #fbfcf6;
border: 2px solid var(--color-primary);
padding: 19px;
}
.source-card__icon {
align-items: center;
background: var(--color-step);
border-radius: 8px;
color: #71882b;
display: inline-flex;
flex: 0 0 46px;
height: 46px;
justify-content: center;
}
.source-card__copy {
display: grid;
gap: 6px;
min-width: 0;
}
.source-card__title {
font-size: 16px;
font-weight: 600;
}
.source-card__description {
color: var(--color-text-secondary);
font-size: 13px;
line-height: 1.45;
}
.source-card__check {
color: #71882b;
margin-left: auto;
}
@media (max-width: 600px) {
.source-options { grid-template-columns: 1fr; }
.source-card { min-height: 94px; padding: 16px; }
.source-card--selected { padding: 15px; }
}
-15
View File
@@ -1,15 +0,0 @@
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { MatIconModule } from '@angular/material/icon';
export type UploadSource = 'file' | 'sql';
@Component({
imports: [MatIconModule],
selector: 'app-source-selection',
styleUrl: './source-selection.scss',
templateUrl: './source-selection.html',
})
export class SourceSelectionComponent {
@Input() source: UploadSource | null = null;
@Output() readonly sourceChange = new EventEmitter<UploadSource>();
}
-33
View File
@@ -1,33 +0,0 @@
<form class="sql-config" [formGroup]="form" aria-label="Configuración de conexión SQL" novalidate>
<p class="sql-config__hint">Ingresa los datos de la base de datos que deseas utilizar.</p>
<div class="sql-config__host-row">
<mat-form-field appearance="outline">
<mat-label>Servidor / Host</mat-label>
<input matInput formControlName="host" autocomplete="off" />
@if (form.controls.host.invalid && (form.controls.host.dirty || form.controls.host.touched)) { <mat-error>El servidor es obligatorio.</mat-error> }
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Puerto</mat-label>
<input matInput formControlName="port" type="text" inputmode="numeric" placeholder="Ej. 1433" />
@if (form.controls.port.hasError('portRange') && (form.controls.port.dirty || form.controls.port.touched)) { <mat-error>El puerto debe estar entre 1 y 65535.</mat-error> }
</mat-form-field>
</div>
<mat-form-field appearance="outline">
<mat-label>Base de datos</mat-label>
<input matInput formControlName="database" autocomplete="off" />
@if (form.controls.database.invalid && (form.controls.database.dirty || form.controls.database.touched)) { <mat-error>La base de datos es obligatoria.</mat-error> }
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Usuario</mat-label>
<input matInput formControlName="username" autocomplete="username" />
@if (form.controls.username.invalid && (form.controls.username.dirty || form.controls.username.touched)) { <mat-error>El usuario es obligatorio.</mat-error> }
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Contraseña</mat-label>
<input matInput formControlName="password" [type]="passwordVisible ? 'text' : 'password'" autocomplete="off" />
<button class="password-toggle" mat-icon-button matSuffix type="button" [attr.aria-label]="passwordVisible ? 'Ocultar contraseña' : 'Mostrar contraseña'" [attr.aria-pressed]="passwordVisible" (click)="passwordVisible = !passwordVisible">
<mat-icon aria-hidden="true">{{ passwordVisible ? 'visibility_off' : 'visibility' }}</mat-icon>
</button>
@if (form.controls.password.invalid && (form.controls.password.dirty || form.controls.password.touched)) { <mat-error>La contraseña es obligatoria.</mat-error> }
</mat-form-field>
</form>
-28
View File
@@ -1,28 +0,0 @@
:host { display: block; min-width: 0; }
.sql-config { display: grid; gap: 2px; min-width: 0; }
.sql-config__hint { color: var(--color-text-secondary); font-size: 14px; margin: 0 0 10px; }
.sql-config__host-row { display: grid; gap: 12px; grid-template-columns: minmax(0, 2.5fr) minmax(130px, 1fr); }
mat-form-field {
--mat-form-field-outlined-focus-outline-color: var(--color-primary);
--mat-form-field-outlined-focus-label-text-color: #71882b;
--mat-form-field-outlined-label-text-color: #596273;
min-width: 0;
width: 100%;
}
mat-form-field input { color: var(--color-text); }
.password-toggle {
--mat-icon-button-icon-color: var(--color-text-secondary);
--mat-icon-button-state-layer-color: transparent;
--mat-icon-button-ripple-color: transparent;
background: transparent;
border: 0;
border-radius: 50%;
box-shadow: none;
color: var(--color-text-secondary);
opacity: 0.82;
transition: color 120ms ease, opacity 120ms ease;
}
.password-toggle:hover { background: transparent; color: #596273; opacity: 1; }
.password-toggle:active { background: transparent; color: #4d586a; }
.password-toggle:focus-visible { outline: 2px solid var(--color-primary); outline-offset: -3px; }
@media (max-width: 560px) { .sql-config__host-row { grid-template-columns: minmax(0, 1fr); gap: 2px; } }
-52
View File
@@ -1,52 +0,0 @@
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, ValidationErrors, ValidatorFn } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
export interface SqlConnectionConfig {
host: string;
port: string;
database: string;
username: string;
password: string;
}
const requiredTrimmed: ValidatorFn = (control): ValidationErrors | null =>
String(control.value ?? '').trim() ? null : { required: true };
const optionalPort: ValidatorFn = (control): ValidationErrors | null => {
const value = String(control.value ?? '').trim();
if (!value) return null;
return /^\d+$/.test(value) && Number(value) >= 1 && Number(value) <= 65535 ? null : { portRange: true };
};
@Component({
imports: [ReactiveFormsModule, MatFormFieldModule, MatIconModule, MatInputModule],
selector: 'app-sql-connection-config',
styleUrl: './sql-connection-config.scss',
templateUrl: './sql-connection-config.html',
})
export class SqlConnectionConfigComponent implements OnInit {
@Input({ required: true }) config!: SqlConnectionConfig;
@Output() readonly configChange = new EventEmitter<SqlConnectionConfig>();
@Output() readonly validChange = new EventEmitter<boolean>();
readonly form = new FormGroup({
host: new FormControl('', { nonNullable: true, validators: [requiredTrimmed] }),
port: new FormControl('', { nonNullable: true, validators: [optionalPort] }),
database: new FormControl('', { nonNullable: true, validators: [requiredTrimmed] }),
username: new FormControl('', { nonNullable: true, validators: [requiredTrimmed] }),
password: new FormControl('', { nonNullable: true, validators: [requiredTrimmed] }),
});
passwordVisible = false;
ngOnInit(): void {
this.form.setValue(this.config);
this.emitState();
this.form.valueChanges.subscribe(() => this.emitState());
}
private emitState(): void {
this.configChange.emit(this.form.getRawValue());
this.validChange.emit(this.form.valid);
}
}
-35
View File
@@ -1,35 +0,0 @@
<dl class="sql-summary" aria-label="Resumen de la conexión SQL">
<div class="sql-summary__item"><dt>Fuente</dt><dd>Conexión SQL</dd></div>
<div class="sql-summary__item"><dt>Servidor / Host</dt><dd [title]="config.host">{{ config.host }}</dd></div>
<div class="sql-summary__item"><dt>Puerto</dt><dd>{{ config.port.trim() ? config.port : 'No especificado' }}</dd></div>
<div class="sql-summary__item"><dt>Base de datos</dt><dd [title]="config.database">{{ config.database }}</dd></div>
<div class="sql-summary__item"><dt>Usuario</dt><dd [title]="config.username">{{ config.username }}</dd></div>
<div class="sql-summary__item"><dt>Credenciales</dt><dd>✓ Proporcionadas</dd></div>
</dl>
<section class="connection-check" aria-labelledby="connection-check-title">
<div class="connection-check__copy">
<h3 id="connection-check-title">Verificación de conexión</h3>
<div class="connection-check__status" id="connection-check-state" role="status" aria-live="polite">
@if (verificationState === 'idle') {
<p>La conexión todavía no ha sido verificada.</p>
} @else if (verificationState === 'checking') {
<mat-progress-spinner class="connection-check__spinner" mode="indeterminate" diameter="18" aria-hidden="true" />
<p>Verificando conexión...</p>
} @else if (verificationState === 'success') {
<mat-icon class="connection-check__success" aria-hidden="true">check_circle</mat-icon>
<p>Conexión verificada correctamente.</p>
} @else {
<mat-icon class="connection-check__error" aria-hidden="true">error_outline</mat-icon>
<p>No se pudo verificar la conexión.</p>
}
</div>
</div>
<div class="connection-check__action">
<button mat-stroked-button type="button" [disabled]="verificationState === 'checking'" aria-describedby="connection-check-state" (click)="verifyRequested.emit()">
<mat-icon aria-hidden="true">{{ verificationState === 'success' ? 'refresh' : 'sync' }}</mat-icon>
{{ verificationState === 'success' ? 'Verificar nuevamente' : 'Probar conexión' }}
</button>
@if (verificationState === 'idle') { <span>Pendiente de integración con WebApi</span> }
</div>
</section>
-43
View File
@@ -1,43 +0,0 @@
:host { display: block; min-width: 0; }
.sql-summary {
display: grid;
gap: 10px;
grid-template-columns: repeat(3, minmax(0, 1fr));
margin: 0;
}
.sql-summary__item {
background: #fcfdfb;
border: 1px solid #e7eae3;
border-radius: 8px;
min-width: 0;
padding: 10px 12px;
}
.sql-summary dt { color: var(--color-text-secondary); font-size: 12px; }
.sql-summary dd { color: var(--color-text); font-size: 15px; font-weight: 600; margin: 4px 0 0; overflow-wrap: anywhere; }
.connection-check {
align-items: center;
background: #fcfdfb;
border: 1px solid #e7eae3;
border-radius: 8px;
display: flex;
gap: 16px;
justify-content: space-between;
margin-top: 14px;
padding: 12px 14px;
}
.connection-check h3 { color: var(--color-text); font-size: 14px; font-weight: 600; margin: 0; }
.connection-check p { color: var(--color-text-secondary); font-size: 13px; margin: 4px 0 0; }
.connection-check__status { align-items: center; display: flex; gap: 7px; min-height: 20px; }
.connection-check__status p { margin: 4px 0 0; }
.connection-check__spinner { --mat-progress-spinner-active-indicator-color: #71882b; flex: 0 0 auto; }
.connection-check__success { color: #71882b; }
.connection-check__error { color: var(--color-text-secondary); }
.connection-check__action { align-items: flex-end; display: flex; flex-direction: column; gap: 3px; }
.connection-check__action button { --mat-button-outlined-label-text-color: #596273; --mat-button-outlined-outline-color: var(--color-border-subtle); white-space: nowrap; }
.connection-check__action span { color: var(--color-text-secondary); font-size: 11px; }
@media (max-width: 760px) { .sql-summary { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 480px) {
.sql-summary { grid-template-columns: minmax(0, 1fr); }
.connection-check { align-items: flex-start; flex-direction: column; }
.connection-check__action { align-items: flex-start; }
}
-19
View File
@@ -1,19 +0,0 @@
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { SqlConnectionConfig } from './sql-connection-config';
export type SqlConnectionVerificationState = 'idle' | 'checking' | 'success' | 'error';
@Component({
imports: [MatButtonModule, MatIconModule, MatProgressSpinnerModule],
selector: 'app-sql-connection-confirmation',
styleUrl: './sql-connection-confirmation.scss',
templateUrl: './sql-connection-confirmation.html',
})
export class SqlConnectionConfirmationComponent {
@Input({ required: true }) config!: SqlConnectionConfig;
@Input({ required: true }) verificationState: SqlConnectionVerificationState = 'idle';
@Output() readonly verifyRequested = new EventEmitter<void>();
}
+3 -3
View File
@@ -1,11 +1,11 @@
<!doctype html>
<html lang="es">
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Análisis de información | ISSSTELEON</title>
<title>WebApp</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<link rel="icon" type="image/png" href="branding/favicon-isssteleon.png" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
+19 -30
View File
@@ -1,20 +1,10 @@
// Include theming for Angular Material with `mat.theme()`.
// This Sass mixin will define CSS variables that are used for styling Angular Material
// components according to the Material 3 design spec.
// Learn more about theming and how to use it for your application's
// custom components at https://material.angular.dev/guide/theming
@use '@angular/material' as mat;
:root {
--color-primary: #a8c243;
--color-text: #081839;
--color-text-secondary: #7a7a7a;
--color-background: #f7f8f6;
--color-surface: #ffffff;
--color-border: #e3e7df;
--color-step: #f0f3e8;
--color-border-subtle: #d7dccf;
--color-surface-hover: #f3f6e9;
--color-primary-action: #6f821c;
--font-body: 'Roboto', sans-serif;
--font-heading: 'Rajdhani', 'Roboto Condensed', 'Arial Narrow', sans-serif;
}
html {
height: 100%;
@include mat.theme(
@@ -30,21 +20,20 @@ html {
}
body {
// Default the application to a light color theme. This can be changed to
// `dark` to enable the dark color theme, or to `light dark` to defer to the
// user's system settings.
color-scheme: light;
background: var(--color-background);
color: var(--color-text);
font-family: var(--font-body);
// Set a default background, font and text colors for the application using
// Angular Material's system-level CSS variables. Learn more about these
// variables at https://material.angular.dev/guide/system-variables
background-color: var(--mat-sys-surface);
color: var(--mat-sys-on-surface);
font: var(--mat-sys-body-medium);
// Reset the user agent margin.
margin: 0;
min-height: 100%;
}
*,
*::before,
*::after {
box-sizing: border-box;
}
.information-upload-dialog-panel .mat-mdc-dialog-surface {
border-radius: 12px;
padding: 0;
height: 100%;
}
/* You can add global styles to this file, and also import other style files */