Compare commits

...

6 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
53 changed files with 2527 additions and 480 deletions
+260 -1
View File
@@ -16,8 +16,11 @@
"@angular/material": "^22.1.7",
"@angular/platform-browser": "^22.1.0",
"@angular/router": "^22.1.0",
"jspdf": "4.2.1",
"plotly.js-basic-dist-min": "^4.1.1",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
"tslib": "^2.3.0",
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
},
"devDependencies": {
"@angular/build": "^22.1.8",
@@ -721,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",
@@ -3715,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",
@@ -3979,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",
@@ -4172,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",
@@ -4376,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",
@@ -4409,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",
@@ -4572,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",
@@ -4892,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",
@@ -4954,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",
@@ -5185,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",
@@ -5320,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",
@@ -5557,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",
@@ -6335,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",
@@ -6438,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",
@@ -6481,6 +6655,12 @@
"node": ">=16.20.0"
}
},
"node_modules/plotly.js-basic-dist-min": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/plotly.js-basic-dist-min/-/plotly.js-basic-dist-min-4.1.1.tgz",
"integrity": "sha512-1oNF8PeQx2hv/y7tqEVWKD3JGwn/MGEMQ8mL9HUwsaqG9FGy/OU5FHUHvzqbqxN4mnwZGI9abTiE775C4kkjMQ==",
"license": "MIT"
},
"node_modules/postcss": {
"version": "8.5.28",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
@@ -6633,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",
@@ -6684,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",
@@ -6711,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",
@@ -7073,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",
@@ -7136,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",
@@ -7143,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",
@@ -7347,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",
@@ -8026,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 -1
View File
@@ -19,8 +19,11 @@
"@angular/material": "^22.1.7",
"@angular/platform-browser": "^22.1.0",
"@angular/router": "^22.1.0",
"jspdf": "4.2.1",
"plotly.js-basic-dist-min": "^4.1.1",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
"tslib": "^2.3.0",
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
},
"devDependencies": {
"@angular/build": "^22.1.8",
+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>();
}
+4 -1
View File
@@ -1,4 +1,7 @@
import { Routes } from '@angular/router';
import { Home } from './home';
export const routes: Routes = [{ path: '', component: Home }];
export const routes: Routes = [
{ path: '', component: Home },
{ path: 'dashboard', loadComponent: () => import('./dashboard/dashboard').then((module) => module.Dashboard) },
];
+435 -10
View File
@@ -3,9 +3,25 @@ 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],
providers: [provideRouter(routes)],
@@ -72,7 +88,7 @@ describe('App', () => {
overlay.querySelector<HTMLButtonElement>('.source-card')!.click();
detectDialogChanges();
expect(continueButton.disabled).toBe(false);
continueButton.click();
overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')!.click();
detectDialogChanges();
fixture.detectChanges();
expect(overlay.querySelector('.upload-dialog__description')?.textContent).toContain(
@@ -112,10 +128,9 @@ describe('App', () => {
const jsonFile = new File(['{}'], 'nuevo.json', { type: 'application/json' });
const dialogComponent = TestBed.inject(MatDialog).openDialogs[0].componentRef!
.instance as import('./information-upload-dialog').InformationUploadDialog;
dialogComponent.onDrop({
preventDefault: () => undefined,
dataTransfer: { files: [jsonFile] },
} as unknown as DragEvent);
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);
@@ -126,14 +141,38 @@ describe('App', () => {
continueButton.click();
detectDialogChanges();
fixture.detectChanges();
expect(overlay.querySelector('h3')?.textContent).toContain('Confirmación');
expect(overlay.querySelector('.configuration-placeholder p')?.textContent).toContain(
'La confirmación de los archivos se implementará en la siguiente fase.',
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();
expect(overlay.querySelectorAll('.file-row')).toHaveLength(2);
while (overlay.querySelector('.file-row__remove')) {
overlay.querySelector<HTMLButtonElement>('.file-row__remove')!.click();
detectDialogChanges();
@@ -152,7 +191,7 @@ describe('App', () => {
sqlContinueButton.click();
detectDialogChanges();
fixture.detectChanges();
expect(overlay.querySelector('h3')?.textContent).toContain('Conexión SQL');
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();
@@ -174,9 +213,395 @@ describe('App', () => {
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();
});
});
+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);
}
}
+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';
}
+7 -1
View File
@@ -1,6 +1,8 @@
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({
@@ -11,17 +13,21 @@ import { InformationUploadDialog } from './information-upload-dialog';
})
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, {
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');
});
}
}
+27 -64
View File
@@ -1,3 +1,6 @@
@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>
@@ -6,7 +9,7 @@
</button>
</header>
<ol class="upload-steps" aria-label="Etapas de carga de información">
@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>
@@ -16,90 +19,50 @@
<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>
</ol> }
@if (step() === 'source') {
@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">
<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)="selectSource('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)="selectSource('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>
<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">
<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 (fileMessages().length > 0) {
<ul class="file-messages" aria-live="polite" aria-label="Mensajes sobre archivos">
@for (message of fileMessages(); track $index) { <li>{{ message }}</li> }
</ul>
}
@if (files().length > 0) {
<section class="selected-files" aria-labelledby="selected-files-title">
<header class="selected-files__header">
<h3 id="selected-files-title">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">
<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>
<button class="file-row__remove" mat-icon-button type="button" [attr.aria-label]="'Eliminar ' + file.name" (click)="removeFile(file)">
<mat-icon aria-hidden="true">close</mat-icon>
</button>
</li>
}
</ul>
</section>
}
<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 configuration-placeholder" aria-live="polite">
<span class="configuration-placeholder__icon"><mat-icon aria-hidden="true">storage</mat-icon></span>
<h3>Conexión SQL</h3>
<p>La configuración de la conexión se implementará en la siguiente fase.</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 el siguiente paso de la carga de información.</p>
<div class="upload-dialog__content configuration-placeholder" aria-live="polite">
<span class="configuration-placeholder__icon"><mat-icon aria-hidden="true">checklist</mat-icon></span>
<h3>Confirmación</h3>
<p>La confirmación de los archivos se implementará en la siguiente fase.</p>
<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') {
@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() === 'source' ? !source() : source() !== 'file' || files().length === 0" (click)="continue()">Continuar</button>
}
<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>
}
+25 -325
View File
@@ -1,10 +1,14 @@
@use 'upload-button' as button;
:host {
display: block;
}
.upload-dialog {
background: #fff;
color: #081839;
color: var(--color-text);
max-height: 100dvh;
overflow: auto;
padding: 28px 32px 24px;
}
.upload-dialog__header {
@@ -20,7 +24,7 @@
margin: 0;
}
.upload-dialog__description {
color: #7a7a7a;
color: var(--color-text-secondary);
font-size: 15px;
line-height: 1.5;
margin: 14px 0 0;
@@ -31,8 +35,8 @@
}
.upload-steps {
align-items: center;
border-bottom: 1px solid #e3e7df;
color: #7a7a7a;
border-bottom: 1px solid var(--color-border);
color: var(--color-text-secondary);
display: flex;
justify-content: center;
list-style: none;
@@ -68,276 +72,26 @@
width: 16px;
}
.upload-steps__item--active {
color: #081839;
color: var(--color-text);
font-weight: 600;
}
.upload-steps__item--active .upload-steps__number {
background: #a8c243;
color: #081839;
background: var(--color-primary);
color: var(--color-text);
}
.upload-steps__item--complete {
color: #71882b;
}
.upload-steps__item--complete .upload-steps__number {
background: #f0f3e8;
background: var(--color-step);
color: #71882b;
}
.upload-dialog__content {
padding: 18px 0 28px;
}
.source-options {
display: grid;
gap: 16px;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.source-card {
align-items: center;
background: #fff;
border: 1px solid #e3e7df;
border-radius: 9px;
color: #081839;
cursor: pointer;
display: flex;
gap: 16px;
min-height: 126px;
padding: 20px;
position: relative;
text-align: left;
transition:
background-color 0.16s ease,
border-color 0.16s ease;
}
.source-card:hover {
background: #fafbf7;
border-color: #c7d49a;
}
.source-card:focus-visible,
.upload-dialog__close:focus-visible,
.file-row__remove:focus-visible,
.upload-action:focus-visible {
outline: 3px solid rgb(168 194 67 / 65%);
outline-offset: 2px;
}
.source-card--selected {
background: #fbfcf6;
border: 2px solid #a8c243;
padding: 19px;
}
.source-card__icon {
align-items: center;
background: #f0f3e8;
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: #7a7a7a;
font-size: 13px;
line-height: 1.45;
}
.source-card__check {
color: #71882b;
margin-left: auto;
}
.configuration-placeholder {
align-items: center;
display: flex;
flex-direction: column;
justify-content: center;
min-height: 164px;
text-align: center;
}
.configuration-placeholder__icon {
align-items: center;
background: #f0f3e8;
border-radius: 50%;
color: #71882b;
display: inline-flex;
height: 48px;
justify-content: center;
width: 48px;
}
.configuration-placeholder h3 {
font-family: var(--font-heading);
font-size: 22px;
margin: 14px 0 6px;
}
.configuration-placeholder p {
color: #7a7a7a;
font-size: 14px;
line-height: 1.55;
margin: 0;
max-width: 460px;
}
.file-configuration {
padding-top: 18px;
}
.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;
transition:
background-color 0.14s ease,
border-color 0.14s ease;
}
.dropzone--active {
background: #f5f8e9;
border-color: #a8c243;
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: #7a7a7a;
font-size: 13px;
margin: 0 0 16px;
}
.select-files-button {
--mat-button-outlined-label-text-color: #081839;
--mat-button-outlined-outline-color: #d7dccf;
--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;
}
.upload-action--outlined:hover {
background: #f3f6e9;
border-color: #a8c243;
}
.upload-action--outlined: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;
}
.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: #f0f3e8;
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 {
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;
height: 36px;
line-height: 36px;
width: 36px;
}
.upload-dialog__footer {
align-items: center;
border-top: 1px solid #e3e7df;
border-top: 1px solid var(--color-border);
display: grid;
gap: 10px;
grid-template-columns: minmax(0, 1fr) auto;
@@ -353,12 +107,7 @@
justify-self: end;
}
.upload-action {
border-radius: 8px;
font: inherit;
font-weight: 600;
min-height: 44px;
padding: 10px 18px;
transition: background-color 0.18s ease;
@include button.base;
}
.action-cancel,
.action-back {
@@ -367,28 +116,22 @@
}
.action-cancel {
--mat-button-text-label-text-color: #fff;
background: #7a7a7a;
background: var(--color-text-secondary);
}
.action-cancel:hover {
background: #696969;
}
.action-cancel:active {
background: #5d5d5d;
}
.action-back {
--mat-button-text-label-text-color: #081839;
--mat-button-text-label-text-color: var(--color-text);
background: #fff;
border: 1px solid #d7dccf;
border: 1px solid var(--color-border-subtle);
}
.action-back:hover {
background: #f3f6e9;
border-color: #a8c243;
}
.action-back:active {
background: #e8eed5;
background: var(--color-surface-hover);
border-color: var(--color-primary);
}
.action-continue {
--mat-button-filled-container-color: #6f821c;
--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;
@@ -397,9 +140,6 @@
.action-continue:hover:not(:disabled) {
--mat-button-filled-container-color: #809625;
}
.action-continue:active:not(:disabled) {
--mat-button-filled-container-color: #607216;
}
.action-continue:disabled {
--mat-button-filled-disabled-container-color: #e8ecdf;
--mat-button-filled-disabled-label-text-color: #9da38f;
@@ -433,62 +173,22 @@
height: 22px;
width: 22px;
}
.source-options {
grid-template-columns: 1fr;
}
.source-card {
min-height: 94px;
padding: 16px;
}
.source-card--selected {
padding: 15px;
}
.upload-dialog__content {
padding: 20px 0;
}
.dropzone {
min-height: 220px;
padding: 20px 12px;
}
.file-row {
gap: 6px;
grid-template-columns: 20px minmax(0, 1fr) auto 36px;
padding-left: 8px;
}
.file-row__name {
font-size: 12px;
}
.file-row__size {
font-size: 11px;
}
}
@media (max-width: 360px) {
.upload-dialog {
padding-inline: 16px;
}
.upload-steps li {
font-size: 10px;
}
.upload-dialog__footer {
gap: 4px;
}
.upload-dialog__navigation {
gap: 4px;
}
.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;
}
.action-continue { min-width: 92px; padding-inline: 10px; }
}
@media (max-width: 300px) {
.upload-dialog__footer {
grid-template-columns: minmax(0, 1fr);
}
.upload-dialog__close:focus-visible, .upload-action:focus-visible {
@include button.focus;
}
+123 -77
View File
@@ -1,129 +1,175 @@
import { Component, signal } from '@angular/core';
import { Component, computed, Inject, OnDestroy, Optional, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatDialogModule, MatDialogRef } from '@angular/material/dialog';
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 UploadSource = 'file' | 'sql';
type UploadStep = 'source' | 'configuration' | 'confirmation';
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],
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 {
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 isDragOver = signal(false);
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 dragDepth = 0;
private readonly allowedExtensions = new Set(['xlsx', 'csv', 'json', 'pdf']);
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>) {}
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() === 'source' && this.source()) this.step.set('configuration');
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();
}
onFileSelection(event: Event): void {
const input = event.target as HTMLInputElement;
this.addFiles(input.files ? Array.from(input.files) : []);
input.value = '';
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();
}
onDragEnter(event: DragEvent): void {
event.preventDefault();
this.dragDepth++;
this.isDragOver.set(true);
finishProcessing(): void {
if (this.processingState() !== 'success') return;
this.dialogRef.close('completed');
}
onDragOver(event: DragEvent): void {
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';
ngOnDestroy(): void {
this.clearVerificationTimer();
this.clearProcessingTimer();
}
onDragLeave(event: DragEvent): void {
event.preventDefault();
this.dragDepth = Math.max(0, this.dragDepth - 1);
if (this.dragDepth === 0) this.isDragOver.set(false);
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);
}
onDrop(event: DragEvent): void {
event.preventDefault();
this.dragDepth = 0;
this.isDragOver.set(false);
this.addFiles(event.dataTransfer?.files ? Array.from(event.dataTransfer.files) : []);
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));
}
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]}`;
}
readonly formatFileSize = formatFileSize;
fileIcon(file: File): string {
const extension = this.extensionOf(file.name);
if (extension === 'pdf') return 'picture_as_pdf';
if (extension === 'csv' || extension === 'xlsx') return 'table_chart';
return 'data_object';
}
private addFiles(incomingFiles: File[]): void {
const messages: string[] = [];
const accepted = [...this.files()];
for (const file of incomingFiles) {
const extension = this.extensionOf(file.name);
if (!this.allowedExtensions.has(extension)) {
messages.push(`${file.name} no fue agregado. Formato no compatible.`);
continue;
}
if (file.size === 0) {
messages.push(`${file.name} no fue agregado. El archivo está vacío.`);
continue;
}
if (accepted.some((existing) => existing.name === file.name && existing.size === file.size)) {
messages.push(`${file.name} ya se encuentra seleccionado.`);
continue;
}
accepted.push(file);
}
if (accepted.length !== this.files().length) this.files.set(accepted);
this.fileMessages.set(messages);
}
private extensionOf(fileName: string): string {
const finalDot = fileName.lastIndexOf('.');
return finalDot >= 0 ? fileName.slice(finalDot + 1).toLowerCase() : '';
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';
}
}
+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>();
}
+3
View File
@@ -8,6 +8,9 @@
--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;
}