Compare commits

..

7 Commits

Author SHA1 Message Date
Angel Capetillo Zavala fa143a7746 Update: Exportar a PDF 2026-09-25 12:08:08 -06:00
Angel Capetillo Zavala 329ee2a61d Feature: Exportar Excel 2026-09-25 11:30:40 -06:00
Angel Capetillo Zavala 6543ddad7b Update: Opciones de exportar 2026-09-25 10:53:05 -06:00
Angel Capetillo Zavala 0fcc9fb70c Feature: Dashboard 2026-09-24 16:08:15 -06:00
Angel Capetillo Zavala 0795a971df Refactor: Reorganización de archivos 2026-09-24 13:17:21 -06:00
Angel Capetillo Zavala 88ba59c669 Feat: Diseño de flujo para el usuario 2026-09-24 11:18:24 -06:00
Angel Capetillo Zavala 473a269bed Feature: Flujo inicial 2026-09-23 16:39:33 -06:00
79 changed files with 3257 additions and 1024 deletions
-1
View File
@@ -60,7 +60,6 @@
},
"serve": {
"builder": "@angular/build:dev-server",
"options": { "proxyConfig": "proxy.conf.json" },
"configurations": {
"production": {
"buildTarget": "WebApp:build:production"
+258 -6
View File
@@ -16,9 +16,11 @@
"@angular/material": "^22.1.7",
"@angular/platform-browser": "^22.1.0",
"@angular/router": "^22.1.0",
"plotly.js-cartesian-dist-min": "4.1.2",
"jspdf": "4.2.1",
"plotly.js-basic-dist-min": "^4.1.1",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
"tslib": "^2.3.0",
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
},
"devDependencies": {
"@angular/build": "^22.1.8",
@@ -722,6 +724,15 @@
"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",
@@ -3716,6 +3727,26 @@
"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",
@@ -3980,6 +4011,16 @@
"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",
@@ -4173,6 +4214,26 @@
],
"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",
@@ -4377,6 +4438,21 @@
"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",
@@ -4410,6 +4486,16 @@
"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",
@@ -4573,6 +4659,16 @@
"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",
@@ -4893,6 +4989,17 @@
"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",
@@ -4955,6 +5062,12 @@
}
}
},
"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",
@@ -5186,6 +5299,20 @@
"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",
@@ -5321,6 +5448,12 @@
"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",
@@ -5558,6 +5691,23 @@
"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",
@@ -6336,6 +6486,22 @@
"@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",
@@ -6439,6 +6605,13 @@
"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",
@@ -6482,10 +6655,10 @@
"node": ">=16.20.0"
}
},
"node_modules/plotly.js-cartesian-dist-min": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/plotly.js-cartesian-dist-min/-/plotly.js-cartesian-dist-min-4.1.2.tgz",
"integrity": "sha512-3UkyAT7/U8f3sOLavLnUjA6mqFmnqEe246GZhxT0J3TT9oZ0mh6SgwsL1yo/3/4xfmRSDFdGOxe+EsvT2XiE0g==",
"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": {
@@ -6640,6 +6813,16 @@
"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",
@@ -6691,6 +6874,13 @@
"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",
@@ -6718,6 +6908,16 @@
"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",
@@ -7080,6 +7280,16 @@
"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",
@@ -7143,6 +7353,16 @@
"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",
@@ -7150,6 +7370,16 @@
"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",
@@ -7354,6 +7584,16 @@
"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",
@@ -8033,6 +8273,18 @@
"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",
+4 -2
View File
@@ -19,9 +19,11 @@
"@angular/material": "^22.1.7",
"@angular/platform-browser": "^22.1.0",
"@angular/router": "^22.1.0",
"plotly.js-cartesian-dist-min": "4.1.2",
"jspdf": "4.2.1",
"plotly.js-basic-dist-min": "^4.1.1",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
"tslib": "^2.3.0",
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
},
"devDependencies": {
"@angular/build": "^22.1.8",
-4
View File
@@ -1,4 +0,0 @@
{
"/tea/**": { "target": "http://127.0.0.1:5000", "secure": false },
"/health": { "target": "http://127.0.0.1:5000", "secure": false }
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

+13
View File
@@ -0,0 +1,13 @@
@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
@@ -0,0 +1,12 @@
<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
@@ -0,0 +1,14 @@
@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
@@ -0,0 +1,14 @@
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>();
}
+1 -3
View File
@@ -1,4 +1,3 @@
import { provideHttpClient } from '@angular/common/http';
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
@@ -6,7 +5,6 @@ import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
provideHttpClient()
provideRouter(routes)
]
};
+19 -6
View File
@@ -1,7 +1,20 @@
<mat-toolbar color="primary">
<span>{{ title }}</span>
</mat-toolbar>
<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>
<main>
<router-outlet />
</main>
<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>
-16
View File
@@ -1,16 +0,0 @@
import { routes } from './app.routes';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { IndicadoresPage } from './features/indicadores/indicadores-page';
it('permite acceso directo a /indicadores sin guard ni autenticación', async () => {
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] });
const harness = await RouterTestingHarness.create();
await harness.navigateByUrl('/indicadores', IndicadoresPage);
expect(harness.routeNativeElement?.textContent).toContain('Dashboard de indicadores');
const http = TestBed.inject(HttpTestingController);
http.expectOne('/tea/indicadores').flush([]);
http.verify();
});
+3 -1
View File
@@ -1,5 +1,7 @@
import { Routes } from '@angular/router';
import { Home } from './home';
export const routes: Routes = [
{ path: 'indicadores', loadComponent: () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage) },
{ path: '', component: Home },
{ path: 'dashboard', loadComponent: () => import('./dashboard/dashboard').then((module) => module.Dashboard) },
];
+85 -2
View File
@@ -1,3 +1,86 @@
main {
padding: 1.5rem;
.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;
}
}
+586 -4
View File
@@ -1,12 +1,31 @@
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 { vi } from 'vitest';
vi.mock('plotly.js-basic-dist-min', () => ({
default: {
react: vi.fn().mockResolvedValue(undefined),
purge: vi.fn(),
Plots: { resize: vi.fn() },
},
}));
describe('App', () => {
beforeEach(async () => {
vi.stubGlobal('ResizeObserver', class {
observe() {}
unobserve() {}
disconnect() {}
});
await TestBed.configureTestingModule({
imports: [App],
})
.compileComponents();
providers: [provideRouter(routes)],
}).compileComponents();
});
it('should create the app', () => {
@@ -15,11 +34,574 @@ describe('App', () => {
expect(app).toBeTruthy();
});
it('should render the toolbar title', async () => {
it('should render the ISSSTELEON header and home page', async () => {
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('mat-toolbar')?.textContent).toContain('ISSSTELEON');
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');
});
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('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('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();
});
});
+2 -5
View File
@@ -1,13 +1,10 @@
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { MatToolbarModule } from '@angular/material/toolbar';
@Component({
imports: [RouterOutlet, MatToolbarModule],
imports: [RouterOutlet],
selector: 'app-root',
styleUrl: './app.scss',
templateUrl: './app.html',
})
export class App {
protected readonly title = 'ISSSTELEON';
}
export class App {}
+57
View File
@@ -0,0 +1,57 @@
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
@@ -0,0 +1,42 @@
<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
@@ -0,0 +1,46 @@
// 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
@@ -0,0 +1,37 @@
: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
@@ -0,0 +1,50 @@
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;
}
@@ -0,0 +1,32 @@
<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>
@@ -0,0 +1,31 @@
: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; }
@@ -0,0 +1,94 @@
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);
});
});
@@ -0,0 +1,53 @@
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;
}
}
}
@@ -0,0 +1,40 @@
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
@@ -0,0 +1,49 @@
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));
}
@@ -0,0 +1,55 @@
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
@@ -0,0 +1,115 @@
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 });
}
@@ -0,0 +1,28 @@
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
@@ -0,0 +1,39 @@
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());
}
@@ -0,0 +1,3 @@
import { utils, writeFileXLSX } from 'xlsx';
export { utils, writeFileXLSX };
+11
View File
@@ -0,0 +1,11 @@
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
@@ -0,0 +1,53 @@
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);
}
}
@@ -1,79 +0,0 @@
<section class="dashboard" aria-labelledby="dashboard-title">
<header>
<span class="domain">Dominio TEA · Investigación</span>
<h1 id="dashboard-title">Dashboard de indicadores</h1>
<p>Explora las figuras de indicadores TEA generadas por el servicio de reportes.</p>
</header>
<p class="notice">Uso exclusivo de investigación. No usar para decisiones clínicas.</p>
@if (catalogLoading()) {
<mat-progress-bar mode="indeterminate" aria-label="Cargando catálogo" />
<p role="status">Cargando catálogo de indicadores…</p>
} @else if (catalogError()) {
<mat-card class="state" role="alert"><p>{{ catalogError() }}</p>
<button mat-stroked-button (click)="retryCatalog()">Reintentar catálogo</button></mat-card>
} @else if (!catalog().length) {
<mat-card class="state"><p role="status">No hay indicadores disponibles en el catálogo.</p>
<button mat-stroked-button (click)="retryCatalog()">Actualizar catálogo</button></mat-card>
} @else {
<mat-card class="filters" aria-label="Selección de figura">
<div class="fields">
<mat-form-field class="indicator"><mat-label>Indicador</mat-label>
<mat-select [ngModel]="indicadorId" (ngModelChange)="selectIndicador($event)">
@for (item of catalog(); track item.id) { <mat-option [value]="item.id">{{ item.titulo }}</mat-option> }
</mat-select>
</mat-form-field>
<mat-form-field><mat-label>Figura</mat-label>
<mat-select [ngModel]="figuraId" (ngModelChange)="selectFigura($event)" [disabled]="!selected?.figuras?.length">
@for (figure of selected?.figuras ?? []; track $index) { <mat-option [value]="figure">{{ figure }}</mat-option> }
</mat-select>
</mat-form-field>
<mat-form-field><mat-label>Periodos</mat-label>
<mat-select [ngModel]="periodMode" (ngModelChange)="changePeriodMode($event)">
<mat-option value="todos">Todos los periodos con reporte</mat-option>
<mat-option value="manual">Selección manual</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field><mat-label>Tema de la figura</mat-label>
<mat-select [ngModel]="tema" (ngModelChange)="changeTema($event)">
<mat-option value="claro">Claro</mat-option><mat-option value="oscuro">Oscuro</mat-option>
</mat-select>
</mat-form-field>
@if (periodMode === 'manual') {
<mat-form-field class="periods"><mat-label>Semestres (AAAA-S1,AAAA-S2)</mat-label>
<input matInput [ngModel]="periodText" (ngModelChange)="changePeriodText($event)" [attr.aria-invalid]="!!periodError" aria-describedby="period-help" />
<mat-hint id="period-help">Escribe los semestres a consultar. Su disponibilidad depende de los reportes.</mat-hint>
</mat-form-field>
}
</div>
@if (periodError) { <p class="validation" role="alert">{{ periodError }}</p> }
<p class="contract">Contrato: {{ selected?.contrato }} · Las figuras conservan las notas y categorías del servicio.</p>
</mat-card>
@if (selected) {
<section class="interpretation" aria-labelledby="interpretation-title">
<h2 id="interpretation-title">Cómo leer esta figura · {{ selected?.contrato }}</h2>
<ul>
@for (line of interpretation; track $index) { <li>{{ line }}</li> }
</ul>
<p class="period-note">Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.</p>
</section>
}
<mat-card class="figure-card" [class.dark]="tema === 'oscuro'" aria-label="Resultado de la selección" [attr.aria-busy]="result().status === 'loading'">
@if (result().status === 'loading') {
<mat-progress-bar mode="indeterminate" aria-label="Cargando figura" />
<p class="state" role="status">Cargando figura…</p>
} @else if (result().status === 'error') {
<div class="state" role="alert"><p>{{ result().message }}</p>
<button mat-stroked-button (click)="requestFigure()">Reintentar solicitud</button></div>
} @else if (result().figure; as figure) {
@if (hasNoVisibleValues(figure)) {
<p class="state" role="status">No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.</p>
}
<h2 class="figure-title">{{ selected?.titulo }}</h2>
<app-plotly-chart [figure]="figure" />
} @else {
<p class="state" role="status">{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}</p>
}
</mat-card>
}
</section>
@@ -1,29 +0,0 @@
:host { display: block; }
.dashboard { max-width: 1440px; margin: 0 auto; }
h1 { font: var(--mat-sys-headline-large); margin: .65rem 0; }
header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
.domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); }
.notice { padding: 1rem 1.25rem; border-left: 4px solid var(--mat-sys-primary); background: var(--mat-sys-surface-container); border-radius: 8px; }
.filters { padding: 1.5rem; margin: 1.5rem 0; }
.fields { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .75rem 1rem; }
.indicator { grid-column: span 2; }
.periods { grid-column: 1 / -1; margin-bottom: 1rem; }
mat-form-field { width: 100%; min-width: 0; }
.contract { color: var(--mat-sys-on-surface-variant); margin: .5rem 0 0; }
.interpretation { padding: 1rem 1.25rem; margin-bottom: 1.5rem; border-radius: 8px; background: var(--mat-sys-surface-container-low); color: var(--mat-sys-on-surface); font: var(--mat-sys-body-medium); line-height: 1.5; overflow-wrap: anywhere; }
.interpretation h2 { margin: 0 0 .5rem; font: var(--mat-sys-title-small); }
.interpretation ul { margin: 0; padding-left: 1.25rem; }
.interpretation li + li { margin-top: .25rem; }
.period-note { margin: .75rem 0 0; color: var(--mat-sys-on-surface-variant); }
.validation { color: var(--mat-sys-error); }
.figure-card { overflow: hidden; min-width: 0; }
.figure-title { display: none; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); overflow-wrap: anywhere; }
.state { padding: 1.25rem; margin: 0; }
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; }
@media (max-width: 850px) { .figure-title { display: block; } .fields { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 550px) {
.fields { grid-template-columns: minmax(0, 1fr); }
.indicator { grid-column: auto; }
.filters, .interpretation { padding: 1rem; }
h1 { font: var(--mat-sys-headline-medium); }
}
@@ -1,170 +0,0 @@
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { By } from '@angular/platform-browser';
import { PlotlyFigure } from './indicadores.models';
import { Component } from '@angular/core';
import { IndicadoresPage } from './indicadores-page';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
@Component({ selector: 'app-plotly-chart', inputs: ['figure'], template: '' })
class ChartStub { figure?: PlotlyFigure; }
const catalog = [
{ id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'] },
{ id: 'i2', titulo: 'Dos', contrato: 'C3r', figuras: ['box'] },
{ id: 'empty', titulo: 'Sin figuras', contrato: 'C1', figuras: [] },
];
describe('IndicadoresPage', () => {
let page: IndicadoresPage;
let http: HttpTestingController;
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadoresPage, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
fixture = TestBed.createComponent(IndicadoresPage);
page = fixture.componentInstance;
http = TestBed.inject(HttpTestingController);
});
afterEach(() => { fixture.destroy(); http.verify(); });
function load() { http.expectOne('/tea/indicadores').flush(catalog); }
function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); }
it('presenta carga y elige una primera figura válida desde el catálogo', () => {
expect(page.catalogLoading()).toBe(true);
load();
expect(page.indicadorId).toBe('i1');
expect(page.figuraId).toBe('f1');
expect(page.result().status).toBe('loading');
const request = figure();
expect(request.request.params.has('periodos')).toBe(false);
request.flush({ data: [], layout: {} });
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('No hay valores visibles');
expect(fixture.nativeElement.textContent).toContain('Uso exclusivo de investigación');
});
it.each([
['C1', ['proporción observada', 'Wilson al 95 %', 'denominadores pequeños', '100 % no implica certeza poblacional']],
['C2', ['composición porcentual', 'distribución de cada grupo y periodo', 'SIN_DATO']],
['C3r', ['Q1, mediana y Q3', 'no contiene observaciones individuales', 'min/max', 'derivados de Q1 y Q3', 'no deben interpretarse como los extremos observados de los pacientes']],
['C4', ['No hay una explicación específica', 'no se infiere su significado estadístico']],
['toString', ['No hay una explicación específica']],
])('explica el contrato %s y conserva el aviso de investigación', (contract, expected) => {
http.expectOne('/tea/indicadores').flush([{ ...catalog[0], contrato: contract }]);
figure().flush({ data: [], layout: {} });
fixture.detectChanges();
const help = fixture.nativeElement.querySelector('.interpretation').textContent;
for (const text of expected) expect(help).toContain(text);
if (contract === 'C3r') {
expect(help).toContain('Los límites de dibujo no representan necesariamente extremos observados');
expect(help).not.toMatch(/serving|corrección|fase independiente/i);
}
expect(fixture.nativeElement.querySelector('.notice').textContent).toContain('Uso exclusivo de investigación. No usar para decisiones clínicas.');
expect(help).toContain('Un periodo puede tener reportes calculados sin valores estadísticos representables');
});
it('actualiza la explicación al cambiar indicador, incluso durante la carga', () => {
load(); figure().flush({ data: [], layout: {} }); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('Wilson');
page.selectIndicador('i2'); fixture.detectChanges();
const help = fixture.nativeElement.querySelector('.interpretation').textContent;
expect(help).toContain('min/max'); expect(help).not.toContain('Wilson');
figure().flush({ data: [], layout: {} });
});
it('entrega al gráfico el JSON íntegro sin modificarlo al presentar la ayuda', () => {
load();
const received: PlotlyFigure = {
data: [{ type: 'scatter', x: ['grupo'], y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], marker: { color: '#123456' } }],
layout: { yaxis: { range: [0, 100] }, annotations: [{ text: 'Nota del servicio' }], showlegend: true },
config: { staticPlot: false }, frames: [], extra: { preserved: true },
};
const original = JSON.stringify(received);
figure().flush(received); fixture.detectChanges();
expect(JSON.stringify(received)).toBe(original);
expect(page.result().figure).toEqual(received);
const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance as ChartStub;
expect(chart.figure).toBe(page.result().figure);
expect(JSON.stringify(chart.figure)).toBe(original);
});
it('muestra catálogo vacío y permite recargar', () => {
http.expectOne('/tea/indicadores').flush([]);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles');
page.retryCatalog();
load();
figure().flush({ data: [], layout: {} });
});
it('cancela solicitudes previas al cambiar indicador y no muestra figura antigua', () => {
load();
const old = figure();
page.selectIndicador('i2');
expect(old.cancelled).toBe(true);
expect(page.figuraId).toBe('box');
expect(page.result().figure).toBeUndefined();
figure().flush({ data: [{ type: 'box', median: [2] }], layout: {} });
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
expect(page.result().figure?.data[0]['median']).toEqual([2]);
});
it('soporta varias figuras, volver al indicador y selección sin figuras', () => {
load(); figure().flush({ data: [], layout: {} });
page.selectFigura('f2');
expect(figure().request.url).toContain('/i1/figuras/f2');
// Cancel the previous request and verify its cancellation explicitly below.
page.selectIndicador('empty');
expect(page.figuraId).toBe('');
expect(page.result().status).toBe('idle');
page.selectIndicador('i1');
expect(page.figuraId).toBe('f1');
figure().flush({ data: [], layout: {} });
});
it('valida manuales antes del HTTP y vuelve a Todos sin query', () => {
load(); figure().flush({ data: [], layout: {} });
page.changePeriodMode('manual');
expect(page.periodError).not.toBe('');
http.expectNone(req => req.url.includes('/figuras/'));
page.changePeriodText('2025-S1, 2025-S2');
const manual = figure();
expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2');
page.changePeriodText('2025-S3');
expect(manual.cancelled).toBe(true);
expect(page.result().figure).toBeUndefined();
page.changePeriodMode('todos');
const all = figure();
expect(all.request.params.has('periodos')).toBe(false);
all.flush({ data: [], layout: {} });
});
it('cancela figuras al cambiar tema rápidamente', () => {
load();
const old = figure();
page.changeTema('oscuro');
const dark = figure();
expect(old.cancelled).toBe(true);
expect(dark.request.params.get('tema')).toBe('oscuro');
page.changeTema('claro');
expect(dark.cancelled).toBe(true);
figure().flush({ data: [], layout: {} });
});
it.each([
[400, 'rechazó los parámetros'], [404, 'reportes no están disponibles'], [500, 'error interno'],
])('controla HTTP %i con cuerpo no uniforme y permite reintentar', (status, message) => {
load();
figure().flush('<html>error privado</html>', { status: status as number, statusText: 'Error' });
expect(page.result().status).toBe('error');
expect(page.result().message).toContain(message);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).not.toContain('error privado');
page.requestFigure();
figure().flush({ data: [], layout: {} });
expect(page.result().status).toBe('ready');
});
it('distingue conexión fallida y cancela HTTP al destruirse', () => {
load(); figure().error(new ProgressEvent('error'));
expect(page.result().message).toContain('conectar');
page.requestFigure();
const pending = figure();
fixture.destroy();
expect(pending.cancelled).toBe(true);
});
it('controla errores de catálogo y puede recuperarse', () => {
http.expectOne('/tea/indicadores').flush('Error', { status: 500, statusText: 'Error' });
expect(page.catalogError()).toContain('error interno');
page.retryCatalog(); load(); figure().flush({ data: [], layout: {} });
});
});
@@ -1,119 +0,0 @@
import { Component, DestroyRef, inject, signal } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs';
import { FigureSelection, hasNoVisibleValues, Indicador, parsePeriodos, PlotlyFigure, Tema } from './indicadores.models';
import { IndicadoresService } from './indicadores.service';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
export function httpMessage(error: unknown, catalog = false): string {
if (!(error instanceof HttpErrorResponse)) return 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.';
if (error.status === 0) return 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.';
if (error.status === 400) return 'El servicio rechazó los parámetros. Revisa los periodos y la selección.';
if (error.status === 404) return catalog ? 'El catálogo no está disponible.' : 'La figura o los reportes no están disponibles para esta selección.';
if (error.status >= 500) return 'El servicio encontró un error interno. Intenta nuevamente más tarde.';
return 'No se pudo completar la solicitud. Intenta nuevamente.';
}
// Presentation only: contract semantics documented in G3 and G5C.
const CONTRACT_INTERPRETATIONS: Readonly<Record<string, readonly string[]>> = {
C1: [
'El punto representa la proporción observada.',
'La línea vertical representa el intervalo de confianza Wilson al 95 %.',
'Los intervalos amplios pueden deberse a denominadores pequeños.',
'Un porcentaje observado del 100 % no implica certeza poblacional.',
],
C2: [
'Las barras muestran la composición porcentual de cada grupo y periodo.',
'Las categorías corresponden a la distribución de cada grupo y periodo.',
'SIN_DATO, cuando aparece, es una categoría legítima de la representación.',
],
C3r: [
'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.',
'Los límites de dibujo no representan necesariamente extremos observados.',
'Plotly puede mostrar las etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.',
],
};
const UNKNOWN_INTERPRETATION = ['No hay una explicación específica disponible para este contrato. Consulta las notas de la figura; no se infiere su significado estadístico.'];
type FigureState = { status: 'idle' | 'loading' | 'ready' | 'error'; figure?: PlotlyFigure; message?: string };
@Component({
selector: 'app-indicadores-page',
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatProgressBarModule, PlotlyChart],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
export class IndicadoresPage {
private readonly service = inject(IndicadoresService);
private readonly destroyRef = inject(DestroyRef);
private readonly catalogRequests = new Subject<void>();
private readonly figureRequests = new Subject<FigureSelection | null>();
readonly catalog = signal<Indicador[]>([]);
readonly catalogLoading = signal(true);
readonly catalogError = signal('');
readonly result = signal<FigureState>({ status: 'idle' });
readonly hasNoVisibleValues = hasNoVisibleValues;
indicadorId = '';
figuraId = '';
periodMode: 'todos' | 'manual' = 'todos';
periodText = '';
periodError = '';
tema: Tema = 'claro';
get selected(): Indicador | undefined { return this.catalog().find(item => item.id === this.indicadorId); }
get interpretation(): readonly string[] {
const contract = this.selected?.contrato;
return contract && Object.hasOwn(CONTRACT_INTERPRETATIONS, contract)
? CONTRACT_INTERPRETATIONS[contract] : UNKNOWN_INTERPRETATION;
}
constructor() {
this.figureRequests.pipe(switchMap(selection => selection
? this.service.figura(selection).pipe(
map(figure => ({ status: 'ready', figure }) as FigureState),
catchError(error => of({ status: 'error', message: httpMessage(error) } as FigureState)),
startWith({ status: 'loading' } as FigureState))
: of({ status: 'idle' } as FigureState)), takeUntilDestroyed(this.destroyRef))
.subscribe(state => this.result.set(state));
this.catalogRequests.pipe(startWith(undefined), switchMap(() => {
this.catalogLoading.set(true);
this.catalogError.set('');
this.catalog.set([]);
this.indicadorId = this.figuraId = '';
this.figureRequests.next(null);
return this.service.catalogo().pipe(map(items => ({ items, error: '' })),
catchError(error => of({ items: [] as Indicador[], error: httpMessage(error, true) })));
}), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => {
this.catalogLoading.set(false);
this.catalog.set(items);
this.catalogError.set(error);
if (items.length) this.selectIndicador(items[0].id);
});
}
retryCatalog() { this.catalogRequests.next(); }
selectIndicador(id: string) {
this.indicadorId = id;
this.figuraId = this.selected?.figuras[0] ?? '';
this.requestFigure();
}
selectFigura(id: string) { this.figuraId = id; this.requestFigure(); }
changePeriodMode(mode: 'todos' | 'manual') { this.periodMode = mode; this.requestFigure(); }
changePeriodText(text: string) { this.periodText = text; this.requestFigure(); }
changeTema(tema: Tema) { this.tema = tema; this.requestFigure(); }
requestFigure() {
this.periodError = '';
const periodos = this.periodMode === 'manual' ? parsePeriodos(this.periodText) : undefined;
if (periodos === null) this.periodError = 'Introduce semestres AAAA-S1 o AAAA-S2 separados por comas.';
if (!this.selected || !this.selected.figuras.includes(this.figuraId) || periodos === null) {
this.figureRequests.next(null);
return;
}
this.figureRequests.next({ indicador: this.indicadorId, figura: this.figuraId, tema: this.tema, periodos });
}
}
@@ -1,23 +0,0 @@
import { hasNoVisibleValues, parsePeriodos } from './indicadores.models';
describe('Periodos y visibilidad conservadora', () => {
it('normaliza espacios y duplicados sin inventar periodos', () => {
expect(parsePeriodos('2025-S1, 2025-S2,2025-S1')).toEqual(['2025-S1', '2025-S2']);
expect(parsePeriodos('1900-S2')).toEqual(['1900-S2']);
});
it.each(['', '2025', '25-S1', '2025-S3', '2025-S1,', '2025-s1', '2025-S1 2025-S2'])('rechaza %s', value => {
expect(parsePeriodos(value)).toBeNull();
});
it('detecta trazos vacíos, nulos y cajas sin mediana', () => {
expect(hasNoVisibleValues({ data: [], layout: {} })).toBe(true);
expect(hasNoVisibleValues({ data: [{ type: 'scatter', y: [null] }, { type: 'bar', y: [] }, { type: 'box', median: [null] }], layout: {} })).toBe(true);
});
it('conserva cero, supresión y medianas válidas como valores visibles', () => {
expect(hasNoVisibleValues({ data: [{ y: [0] }], layout: {} })).toBe(false);
expect(hasNoVisibleValues({ data: [{ type: 'box', median: [10] }], layout: {} })).toBe(false);
});
it('no declara vacíos los formatos desconocidos o binarios', () => {
expect(hasNoVisibleValues({ data: [{ y: { bdata: 'AAAA', dtype: 'f8' } }], layout: {} })).toBe(false);
expect(hasNoVisibleValues({ data: [{ type: 'heatmap', z: [] }], layout: {} })).toBe(false);
});
});
@@ -1,36 +0,0 @@
export interface Indicador {
id: string;
titulo: string;
contrato: string;
figuras: string[];
}
// Keep the complete HTTP figure, including future attributes and interpretation notes.
export interface PlotlyFigure {
data: Record<string, unknown>[];
layout: Record<string, unknown>;
frames?: Record<string, unknown>[];
config?: Record<string, unknown>;
[key: string]: unknown;
}
export type Tema = 'claro' | 'oscuro';
export interface FigureSelection { indicador: string; figura: string; tema: Tema; periodos?: string[]; }
export function parsePeriodos(value: string): string[] | null {
const parts = value.split(',').map(part => part.trim());
return parts.length && parts.every(part => /^[0-9]{4}-S[12]$/.test(part))
? [...new Set(parts)] : null;
}
// Only assert emptiness for known TEA traces with ordinary arrays. Unknown/binary
// representations remain indeterminate; never infer counts or suppression causes.
export function hasNoVisibleValues(figure: PlotlyFigure): boolean {
return figure.data.every(trace => {
if (trace['visible'] === false || trace['visible'] === 'legendonly') return true;
const type = trace['type'] ?? 'scatter';
const values = type === 'box' ? trace['median'] ?? trace['y']
: type === 'scatter' || type === 'bar' ? trace['y'] : undefined;
if (!Array.isArray(values)) return false;
return !values.some(value => typeof value === 'number' && Number.isFinite(value));
});
}
@@ -1,53 +0,0 @@
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { IndicadoresService } from './indicadores.service';
describe('IndicadoresService HTTP', () => {
let service: IndicadoresService;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
service = TestBed.inject(IndicadoresService);
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it('consume un arreglo directo sin hardcodear catálogo', () => {
const data = [{ id: 'prueba', titulo: 'Título', contrato: 'C1', figuras: ['f1', 'f2'] }];
let actual: unknown;
service.catalogo().subscribe(value => actual = value);
http.expectOne('/tea/indicadores').flush(data);
expect(actual).toEqual(data);
});
it('acepta catálogo vacío y rechaza envelope inesperado', () => {
service.catalogo().subscribe(value => expect(value).toEqual([]));
http.expectOne('/tea/indicadores').flush([]);
let error: unknown;
service.catalogo().subscribe({ error: value => error = value });
http.expectOne('/tea/indicadores').flush({ items: [] });
expect(error).toBeInstanceOf(Error);
});
it('codifica segmentos y omite periodos en Todos', () => {
service.figura({ indicador: 'a/b ü', figura: 'f?#', tema: 'claro' }).subscribe();
const request = http.expectOne(req => req.url === '/tea/indicadores/a%2Fb%20%C3%BC/figuras/f%3F%23');
expect(request.request.method).toBe('GET');
expect(request.request.params.get('tema')).toBe('claro');
expect(request.request.params.has('periodos')).toBe(false);
request.flush({ data: [], layout: {} });
});
it('envía semestres y conserva atributos desconocidos, nulos y notas', () => {
const figure = { data: [{ y: [null, 0], customdata: [null] }], layout: { annotations: [{ text: 'Uso exclusivo de investigación' }] }, extension: { future: true }, frames: [] };
service.figura({ indicador: 'i', figura: 'f', tema: 'oscuro', periodos: ['2025-S1', '2025-S2'] })
.subscribe(value => expect(value).toEqual(figure));
const request = http.expectOne(req => req.url.endsWith('/i/figuras/f'));
expect(request.request.params.get('periodos')).toBe('2025-S1,2025-S2');
expect(request.request.params.get('tema')).toBe('oscuro');
request.flush(figure);
});
it('rechaza una figura estructuralmente inválida', () => {
let error: unknown;
service.figura({ indicador: 'i', figura: 'f', tema: 'claro' }).subscribe({ error: value => error = value });
http.expectOne(req => req.url.endsWith('/i/figuras/f')).flush({ data: null, layout: {} });
expect(error).toBeInstanceOf(Error);
});
});
@@ -1,33 +0,0 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { FigureSelection, Indicador, PlotlyFigure } from './indicadores.models';
function record(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
@Injectable({ providedIn: 'root' })
export class IndicadoresService {
private readonly http = inject(HttpClient);
catalogo() {
return this.http.get<unknown>('/tea/indicadores').pipe(map(value => {
if (!Array.isArray(value) || !value.every(item => record(item)
&& typeof item['id'] === 'string' && typeof item['titulo'] === 'string'
&& typeof item['contrato'] === 'string' && Array.isArray(item['figuras'])
&& item['figuras'].every((figure: unknown) => typeof figure === 'string'))) {
throw new Error('Respuesta de catálogo inválida');
}
return value as Indicador[];
}));
}
figura(selection: FigureSelection) {
let params = new HttpParams().set('tema', selection.tema);
if (selection.periodos?.length) params = params.set('periodos', selection.periodos.join(','));
const url = `/tea/indicadores/${encodeURIComponent(selection.indicador)}/figuras/${encodeURIComponent(selection.figura)}`;
return this.http.get<unknown>(url, { params }).pipe(map(value => {
if (!record(value) || !Array.isArray(value['data']) || !value['data'].every(record)
|| !record(value['layout'])) throw new Error('Respuesta de figura inválida');
return value as unknown as PlotlyFigure;
}));
}
}
+20
View File
@@ -0,0 +1,20 @@
<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
@@ -0,0 +1,92 @@
@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
@@ -0,0 +1,49 @@
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
@@ -0,0 +1,6 @@
<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
@@ -0,0 +1,11 @@
: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
@@ -0,0 +1,15 @@
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
@@ -0,0 +1,20 @@
<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
@@ -0,0 +1,87 @@
@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
@@ -0,0 +1,18 @@
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
@@ -0,0 +1,42 @@
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
@@ -0,0 +1,27 @@
<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
@@ -0,0 +1,131 @@
: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
@@ -0,0 +1,33 @@
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
@@ -0,0 +1,68 @@
@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
@@ -0,0 +1,194 @@
@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
@@ -0,0 +1,175 @@
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
@@ -0,0 +1,30 @@
<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
@@ -0,0 +1,33 @@
: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
@@ -0,0 +1,28 @@
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';
}
}
@@ -1,41 +0,0 @@
import { TestBed } from '@angular/core/testing';
import { vi } from 'vitest';
import { PlotlyChart } from './plotly-chart';
import { PLOTLY_LOADER } from './plotly-runtime';
const mocks = { load: vi.fn(), react: vi.fn(), purge: vi.fn(), resize: vi.fn() };
describe('PlotlyChart lifecycle', () => {
beforeEach(() => {
vi.resetAllMocks();
mocks.react.mockResolvedValue(undefined);
mocks.resize.mockResolvedValue(undefined);
mocks.load.mockResolvedValue({ react: mocks.react, purge: mocks.purge, Plots: { resize: mocks.resize } });
TestBed.configureTestingModule({ imports: [PlotlyChart], providers: [{ provide: PLOTLY_LOADER, useValue: mocks.load }] });
});
it('monta el host, actualiza inputs y desconecta ResizeObserver', async () => {
const disconnect = vi.fn(); const observe = vi.fn();
vi.stubGlobal('ResizeObserver', class { observe = observe; disconnect = disconnect; });
const fixture = TestBed.createComponent(PlotlyChart);
fixture.componentRef.setInput('figure', { data: [], layout: {} });
fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve();
expect(observe).toHaveBeenCalledWith(fixture.nativeElement.querySelector('.plot'));
expect(mocks.react).toHaveBeenCalledTimes(1);
fixture.componentRef.setInput('figure', { data: [{ y: [1] }], layout: {} });
fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve();
expect(mocks.react).toHaveBeenCalledTimes(2);
fixture.destroy(); expect(disconnect).toHaveBeenCalled(); expect(mocks.purge).toHaveBeenCalled();
vi.unstubAllGlobals();
});
it('muestra error asíncrono y se recupera con reintento', async () => {
mocks.react.mockRejectedValueOnce(new Error('render failed'));
const fixture = TestBed.createComponent(PlotlyChart);
fixture.componentRef.setInput('figure', { data: [], layout: {} });
fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('No se pudo representar');
fixture.nativeElement.querySelector('button').click();
await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges();
expect(fixture.componentInstance.status()).toBe('ready'); fixture.destroy();
});
});
-61
View File
@@ -1,61 +0,0 @@
import { AfterViewInit, Component, inject, ElementRef, Input, OnChanges, OnDestroy, output, signal, ViewChild } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
import { PlotlyController } from './plotly-controller';
import { PLOTLY_LOADER } from './plotly-runtime';
@Component({
selector: 'app-plotly-chart',
imports: [MatButtonModule, MatProgressBarModule],
template: `
@if (status() === 'loading') { <mat-progress-bar mode="indeterminate" aria-label="Representando figura" /> }
@if (status() === 'error') {
<div role="alert"><p>No se pudo representar la figura. Puedes reintentar.</p>
<button mat-stroked-button (click)="retry()">Reintentar renderizado</button></div>
}
<div #host class="plot" role="img" aria-label="Figura del indicador seleccionado" [attr.aria-hidden]="status() !== 'ready'"></div>
@if (status() === 'ready' && notes.length) {
<section class="notes" aria-label="Notas completas de la figura">
<h2>Notas de la figura</h2>
@for (note of notes; track $index) { <p [innerHTML]="note"></p> }
</section>
}
`,
styles: `:host { display: block; min-width: 0; } .plot { width: 100%; min-height: 620px; visibility: hidden; } [role=alert] { padding: 1rem; } .notes { display: none; padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; } @media (max-width: 850px) { .notes { display: block; } }`,
})
export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy {
@Input({ required: true }) figure!: PlotlyFigure;
@ViewChild('host', { static: true }) host!: ElementRef<HTMLElement>;
readonly renderError = output<void>();
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
get notes(): string[] {
const annotations = this.figure?.layout['annotations'];
if (!Array.isArray(annotations)) return [];
return annotations.flatMap(annotation =>
annotation && typeof annotation.text === 'string' ? [annotation.text] : []);
}
private readonly loadPlotly = inject(PLOTLY_LOADER);
private controller?: PlotlyController;
private observer?: ResizeObserver;
private readonly windowResize = () => this.controller?.resize();
ngAfterViewInit() {
this.controller = new PlotlyController(this.host.nativeElement, this.loadPlotly, state => {
this.status.set(state);
if (state === 'error') this.renderError.emit();
});
if (typeof ResizeObserver !== 'undefined') {
this.observer = new ResizeObserver(this.windowResize);
this.observer.observe(this.host.nativeElement);
} else window.addEventListener('resize', this.windowResize);
this.controller.setFigure(this.figure);
}
ngOnChanges() { if (this.figure) this.controller?.setFigure(this.figure); }
retry() { this.controller?.setFigure(this.figure); }
ngOnDestroy() {
this.observer?.disconnect();
window.removeEventListener('resize', this.windowResize);
this.controller?.destroy();
}
}
@@ -1,178 +0,0 @@
import { vi } from 'vitest';
import { PlotlyController } from './plotly-controller';
import { PlotlyRuntime } from './plotly-runtime';
import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
function deferred() {
let resolve!: (value?: unknown) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<unknown>((yes, no) => { resolve = yes; reject = no; });
return { promise, resolve, reject };
}
async function settle() { for (let i = 0; i < 12; i++) await Promise.resolve(); }
const fig = (value: number): PlotlyFigure => ({ data: [{ type: 'scatter', y: [value, null] }], layout: { annotations: [{ text: 'No usar para decisiones clínicas' }] } });
describe('PlotlyController async', () => {
let host: HTMLElement;
let plotly: PlotlyRuntime;
let state: ReturnType<typeof vi.fn<(state: 'loading' | 'ready' | 'error') => void>>;
let controller: PlotlyController;
beforeEach(() => {
host = document.createElement('div');
plotly = { react: vi.fn().mockResolvedValue(undefined), purge: vi.fn(), Plots: { resize: vi.fn().mockResolvedValue(undefined) }, addFrames: vi.fn().mockResolvedValue(undefined), deleteFrames: vi.fn().mockResolvedValue(undefined) };
state = vi.fn();
controller = new PlotlyController(host, () => Promise.resolve(plotly), state);
});
it('conserva valores y anotaciones, aislando mutaciones de Plotly', async () => {
const figure = fig(0);
vi.mocked(plotly.react).mockImplementation(async (_host, data) => { data[0]['y'] = [123]; });
controller.setFigure(figure); await settle();
expect(figure.data[0]['y']).toEqual([0, null]);
expect(plotly.react).toHaveBeenCalledWith(host, expect.any(Array), figure.layout, expect.objectContaining({ displaylogo: false }));
expect(host.style.visibility).toBe('visible');
expect(state).toHaveBeenLastCalledWith('ready');
});
it('desactiva el envío externo sin alterar el JSON ni las opciones locales recibidas', async () => {
const figure: PlotlyFigure = {
...fig(1),
config: { showSendToCloud: true, displaylogo: true, scrollZoom: true, doubleClick: 'reset+autosize' },
frames: [{ name: 'uno', data: [{ y: [2, null] }] }],
};
const original = JSON.stringify(figure);
controller.setFigure(figure); await settle();
expect(plotly.react).toHaveBeenCalledWith(host, figure.data, figure.layout, {
responsive: false, displaylogo: false, showSendToCloud: false,
modeBarButtonsToRemove: ['sendChartToCloud'], scrollZoom: true, doubleClick: 'reset+autosize',
});
expect(plotly.addFrames).toHaveBeenCalledWith(host, figure.frames);
expect(JSON.stringify(figure)).toBe(original);
});
it('elige sólo la figura reciente si la importación sigue pendiente', async () => {
const load = deferred();
controller = new PlotlyController(host, () => load.promise as Promise<PlotlyRuntime>, state);
controller.setFigure(fig(1)); controller.setFigure(fig(2));
load.resolve(plotly); await settle();
expect(plotly.react).toHaveBeenCalledTimes(1);
expect(vi.mocked(plotly.react).mock.calls[0][1][0]['y']).toEqual([2, null]);
});
it('serializa react y oculta completados obsoletos', async () => {
const old = deferred(); const latest = deferred();
vi.mocked(plotly.react).mockReturnValueOnce(old.promise).mockReturnValueOnce(latest.promise);
controller.setFigure(fig(1)); await settle();
controller.setFigure(fig(2));
expect(plotly.react).toHaveBeenCalledTimes(1);
old.resolve(); await settle();
expect(plotly.react).toHaveBeenCalledTimes(2);
expect(host.style.visibility).toBe('hidden');
expect(state).not.toHaveBeenCalledWith('ready');
latest.resolve(); await settle();
expect(host.style.visibility).toBe('visible');
expect(state).toHaveBeenLastCalledWith('ready');
});
it('ignora rechazo antiguo y representa la siguiente figura', async () => {
const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise);
controller.setFigure(fig(1)); await settle(); controller.setFigure(fig(2));
pending.reject(new Error('old')); await settle();
expect(state).not.toHaveBeenCalledWith('error');
expect(state).toHaveBeenLastCalledWith('ready');
});
it('maneja error asíncrono y permite reintentar', async () => {
vi.mocked(plotly.react).mockRejectedValueOnce(new Error('failed'));
controller.setFigure(fig(1)); await settle();
expect(state).toHaveBeenLastCalledWith('error');
expect(host.style.visibility).toBe('hidden');
controller.setFigure(fig(1)); await settle();
expect(state).toHaveBeenLastCalledWith('ready');
});
it('maneja importación fallida y recupera el cargador', async () => {
const load = vi.fn().mockRejectedValueOnce(new Error()).mockResolvedValue(plotly);
controller = new PlotlyController(host, load, state);
controller.setFigure(fig(1)); await settle(); expect(state).toHaveBeenLastCalledWith('error');
controller.setFigure(fig(1)); await settle(); expect(state).toHaveBeenLastCalledWith('ready');
});
it('purga al destruir y nuevamente tras terminar react pendiente', async () => {
const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise);
controller.setFigure(fig(1)); await settle();
controller.destroy(); expect(plotly.purge).toHaveBeenCalledTimes(1);
pending.resolve(); await settle(); expect(plotly.purge).toHaveBeenCalledTimes(2);
expect(state).not.toHaveBeenCalledWith('ready');
controller.setFigure(fig(2)); controller.resize(); await settle();
expect(plotly.react).toHaveBeenCalledTimes(1);
expect(plotly.Plots.resize).not.toHaveBeenCalled();
});
it('no renderiza tras destruir durante la importación', async () => {
const pending = deferred(); controller = new PlotlyController(host, () => pending.promise as Promise<PlotlyRuntime>, state);
controller.setFigure(fig(1)); controller.destroy(); pending.resolve(plotly); await settle();
expect(plotly.react).not.toHaveBeenCalled(); expect(plotly.purge).toHaveBeenCalledWith(host);
});
it('serializa resize y el siguiente react', async () => {
controller.setFigure(fig(1)); await settle();
const resize = deferred(); vi.mocked(plotly.Plots.resize).mockReturnValueOnce(resize.promise);
controller.resize(); await settle(); controller.setFigure(fig(2));
expect(plotly.react).toHaveBeenCalledTimes(1);
resize.resolve(); await settle(); expect(plotly.react).toHaveBeenCalledTimes(2);
});
it('conserva frames y los retira al cambiar figura', async () => {
controller.setFigure({ ...fig(1), frames: [{ name: 'uno', data: [] }] }); await settle();
expect(plotly.addFrames).toHaveBeenCalledWith(host, [{ name: 'uno', data: [] }]);
controller.setFigure(fig(2)); await settle();
expect(plotly.deleteFrames).toHaveBeenCalledWith(host, [0]);
});
});
// Exercise the installed bundle in jsdom: no cloud action is clicked.
describe('PlotlyController con Plotly instalado', () => {
let runtime: PlotlyRuntime & {
version: string;
PlotSchema: { get(): { config: Record<string, { valType: string }> } };
};
beforeAll(async () => {
// jsdom has no canvas renderer; cartesian SVG only needs this import-time probe.
const canvas = vi.spyOn(HTMLCanvasElement.prototype, 'getContext')
.mockReturnValue({ measureText: () => ({ width: 0 }) } as unknown as CanvasRenderingContext2D);
try {
const module = await import('plotly.js-cartesian-dist-min');
runtime = (module.default ?? module) as typeof runtime;
} finally { canvas.mockRestore(); }
});
it('usa propiedades admitidas por el esquema de Plotly 4.1.2', () => {
expect(runtime.version).toBe('4.1.2');
const config = runtime.PlotSchema.get().config;
expect(config['showSendToCloud'].valType).toBe('boolean');
expect(config['displaylogo'].valType).toBe('boolean');
expect(config['modeBarButtonsToRemove'].valType).toBe('any');
});
it.each([
['C1', { type: 'scatter', x: [1, 2], y: [3, 4] }],
['C2', { type: 'bar', x: ['grupo'], y: [100] }],
['C3r', { type: 'box', x: ['grupo'], q1: [23.5], median: [45], q3: [55], lowerfence: [23.5], upperfence: [55] }],
])('genera la modebar %s sin envío externo y conserva zoom/pan/restauración', async (_contract, trace) => {
const host = document.createElement('div');
document.body.append(host);
const figure: PlotlyFigure = { data: [trace], layout: { width: 600, height: 400 } };
const original = JSON.stringify(figure);
let controller!: PlotlyController;
try {
await new Promise<void>((resolve, reject) => {
controller = new PlotlyController(host, () => Promise.resolve(runtime), state => {
if (state === 'ready') resolve();
if (state === 'error') reject(new Error('Plotly failed to render'));
});
controller.setFigure(figure);
});
const buttons = Array.from(host.querySelectorAll<HTMLElement>('.modebar-btn'));
const titles = buttons.map(button => button.getAttribute('data-title'));
expect(titles).not.toContain('Share chart...');
expect(titles).toEqual(expect.arrayContaining(['Zoom', 'Pan', 'Zoom in', 'Zoom out', 'Autoscale', 'Reset axes', 'Download plot as a PNG']));
expect(host.querySelector('.modebar a[href]')).toBeNull();
const rendered = host as unknown as HTMLElement & { _fullLayout: { dragmode: string } };
for (const [title, mode] of [['Pan', 'pan'], ['Zoom', 'zoom']]) {
buttons.find(button => button.getAttribute('data-title') === title)!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
await vi.waitFor(() => expect(rendered._fullLayout.dragmode).toBe(mode));
}
expect(JSON.stringify(figure)).toBe(original);
} finally {
controller?.destroy(); host.remove();
}
});
});
@@ -1,87 +0,0 @@
import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
import { PlotlyRuntime } from './plotly-runtime';
// One serialized queue owns the host. A completed stale operation cannot expose
// its graph or overwrite a newer react operation. Resize uses the same queue.
export class PlotlyController {
private desired?: PlotlyFigure;
private version = 0;
private rendered = -1;
private busy = false;
private destroyed = false;
private resizePending = false;
private plotly?: PlotlyRuntime;
private frameCount = 0;
constructor(private host: HTMLElement, private load: () => Promise<PlotlyRuntime>,
private state: (state: 'loading' | 'ready' | 'error') => void) {}
setFigure(figure: PlotlyFigure) {
if (this.destroyed) return;
this.desired = figure;
this.version++;
this.host.style.visibility = 'hidden';
this.state('loading');
void this.drain();
}
resize() {
if (this.destroyed || this.rendered < 0) return;
this.resizePending = true;
void this.drain();
}
destroy() {
this.destroyed = true;
this.host.style.visibility = 'hidden';
this.plotly?.purge(this.host);
}
private async drain() {
if (this.busy || this.destroyed) return;
this.busy = true;
try {
this.plotly ??= await this.load();
while (!this.destroyed && (this.rendered !== this.version || this.resizePending)) {
const version = this.version;
try {
if (this.rendered !== version && this.desired) {
// Plotly may mutate inputs; clone the complete JSON without changing values.
const figure = structuredClone(this.desired);
if (this.frameCount) await this.plotly.deleteFrames(this.host, Array.from({ length: this.frameCount }, (_, i) => i));
this.frameCount = 0;
if (this.destroyed) break;
await this.plotly.react(this.host, figure.data, figure.layout, {
...figure.config, responsive: false, displaylogo: false,
showSendToCloud: false,
modeBarButtonsToRemove: ['sendChartToCloud'],
});
if (this.destroyed) break;
if (version !== this.version) continue;
if (figure.frames?.length) {
await this.plotly.addFrames(this.host, figure.frames);
this.frameCount = figure.frames.length;
}
if (this.destroyed) break;
if (version !== this.version) continue;
this.rendered = version;
this.host.style.visibility = 'visible';
this.state('ready');
} else {
this.resizePending = false;
await this.plotly.Plots.resize(this.host);
}
} catch {
if (this.destroyed) break;
if (version !== this.version) continue;
this.rendered = version;
this.resizePending = false;
this.host.style.visibility = 'hidden';
this.state('error');
}
}
} catch {
if (!this.destroyed) this.state('error');
} finally {
this.busy = false;
// A pending react can recreate internal resources after the first purge.
if (this.destroyed) this.plotly?.purge(this.host);
}
}
}
@@ -1,23 +0,0 @@
import { vi } from 'vitest';
import { loadPlotly } from './plotly-runtime';
it('carga una sola instancia oficial con el esquema requerido por C1/C2/C3r', async () => {
// No chart rendering in jsdom. Schema inspection only needs browser globals.
const canvas = vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null);
try {
const first = loadPlotly();
expect(loadPlotly()).toBe(first);
const runtime = await first as unknown as { version: string; PlotSchema: { get(): any } };
expect(runtime.version).toBe('4.1.2');
const schema = runtime.PlotSchema.get();
expect(schema.traces.scatter).toBeDefined();
expect(schema.traces.bar).toBeDefined();
expect(schema.traces.box).toBeDefined();
expect(schema.traces.scatter.attributes.error_y).toBeDefined();
expect(schema.layout.layoutAttributes.xaxis.type.values).toContain('multicategory');
expect(schema.traces.scatter.layoutAttributes.scattermode.values).toContain('group');
expect(schema.traces.box.layoutAttributes.boxmode.values).toContain('group');
for (const key of ['q1', 'median', 'q3', 'lowerfence', 'upperfence']) expect(schema.traces.box.attributes[key]).toBeDefined();
for (const key of ['annotations', 'template', 'paper_bgcolor', 'plot_bgcolor']) expect(schema.layout.layoutAttributes[key]).toBeDefined();
} finally { canvas.mockRestore(); }
});
-20
View File
@@ -1,20 +0,0 @@
import { InjectionToken } from '@angular/core';
import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
// Narrow boundary for the official partial bundle, which ships without declarations.
export interface PlotlyRuntime {
react(host: HTMLElement, data: PlotlyFigure['data'], layout: PlotlyFigure['layout'], config: Record<string, unknown>): Promise<unknown>;
purge(host: HTMLElement): void;
Plots: { resize(host: HTMLElement): Promise<unknown> };
addFrames(host: HTMLElement, frames: Record<string, unknown>[]): Promise<unknown>;
deleteFrames(host: HTMLElement, indices: number[]): Promise<unknown>;
}
let runtime: Promise<PlotlyRuntime> | undefined;
export function loadPlotly(): Promise<PlotlyRuntime> {
return runtime ??= import('plotly.js-cartesian-dist-min')
.then(module => (module.default ?? module) as unknown as PlotlyRuntime)
.catch(error => { runtime = undefined; throw error; });
}
export const PLOTLY_LOADER = new InjectionToken<() => Promise<PlotlyRuntime>>('PLOTLY_LOADER', { providedIn: 'root', factory: () => loadPlotly });
-1
View File
@@ -1 +0,0 @@
declare module 'plotly.js-cartesian-dist-min';
+12
View File
@@ -0,0 +1,12 @@
<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
@@ -0,0 +1,63 @@
@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
@@ -0,0 +1,15 @@
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
@@ -0,0 +1,33 @@
<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
@@ -0,0 +1,28 @@
: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
@@ -0,0 +1,52 @@
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
@@ -0,0 +1,35 @@
<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
@@ -0,0 +1,43 @@
: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
@@ -0,0 +1,19 @@
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>();
}
+2 -2
View File
@@ -1,8 +1,8 @@
<!doctype html>
<html lang="en">
<html lang="es">
<head>
<meta charset="utf-8" />
<title>WebApp</title>
<title>Análisis de información | ISSSTELEON</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
+30 -19
View File
@@ -1,10 +1,20 @@
// 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(
@@ -20,20 +30,21 @@ 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;
// 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.
background: var(--color-background);
color: var(--color-text);
font-family: var(--font-body);
margin: 0;
height: 100%;
min-height: 100%;
}
*,
*::before,
*::after {
box-sizing: border-box;
}
.information-upload-dialog-panel .mat-mdc-dialog-surface {
border-radius: 12px;
padding: 0;
}
/* You can add global styles to this file, and also import other style files */