Update: Exportar a PDF
This commit is contained in:
Generated
+239
@@ -16,6 +16,7 @@
|
||||
"@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",
|
||||
@@ -723,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",
|
||||
@@ -3717,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",
|
||||
@@ -3981,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",
|
||||
@@ -4174,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",
|
||||
@@ -4378,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",
|
||||
@@ -4411,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",
|
||||
@@ -4574,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",
|
||||
@@ -4894,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",
|
||||
@@ -4956,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",
|
||||
@@ -5187,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",
|
||||
@@ -5322,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",
|
||||
@@ -5559,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",
|
||||
@@ -6337,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",
|
||||
@@ -6440,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",
|
||||
@@ -6641,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",
|
||||
@@ -6692,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",
|
||||
@@ -6719,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",
|
||||
@@ -7081,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",
|
||||
@@ -7144,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",
|
||||
@@ -7151,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",
|
||||
@@ -7355,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",
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
"@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",
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
<h1 id="dashboard-title">Resultados del análisis</h1>
|
||||
<div class="dashboard__metadata">
|
||||
<span class="dashboard__area">{{ result.analysisType }}</span>
|
||||
<span class="dashboard__demo">Datos de demostración</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>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// 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 }>;
|
||||
@@ -11,6 +12,7 @@ export interface AnalysisResult {
|
||||
|
||||
export const mockAnalysisResult: AnalysisResult = {
|
||||
analysisType: 'CAMA',
|
||||
dataType: 'Datos de demostración',
|
||||
kpis: [
|
||||
{ label: 'Indicador 1', value: 1248 },
|
||||
{ label: 'Indicador 2', value: 64.2, unit: '%' },
|
||||
|
||||
@@ -4,18 +4,11 @@ import { MatIconModule } from '@angular/material/icon';
|
||||
import { Router } from '@angular/router';
|
||||
import { take } from 'rxjs';
|
||||
import { formatKpi, mockAnalysisResult } from './dashboard.mock';
|
||||
import { ChartFigure, PlotlyChart } from './plotly-chart';
|
||||
import { PlotlyChart } from './plotly-chart';
|
||||
import { createChartFigures } from './dashboard.figures';
|
||||
import { InformationUploadDialog } from '../information-upload-dialog';
|
||||
import { ExportResultsDialog } from './export-results-dialog';
|
||||
|
||||
const ink = '#081839';
|
||||
const grid = '#e9ede5';
|
||||
const green = '#6f821c';
|
||||
const darkGreen = '#465d1e';
|
||||
const teal = '#5f9ea0';
|
||||
const muted = '#7a7a7a';
|
||||
const font = { family: 'Roboto, sans-serif', color: ink, size: 12 };
|
||||
|
||||
@Component({
|
||||
imports: [MatDialogModule, MatIconModule, PlotlyChart],
|
||||
selector: 'app-dashboard',
|
||||
@@ -50,48 +43,8 @@ export class Dashboard {
|
||||
if (result === 'completed') void this.router.navigateByUrl('/dashboard');
|
||||
});
|
||||
}
|
||||
readonly bars: ChartFigure = {
|
||||
data: [{
|
||||
type: 'bar',
|
||||
x: this.result.charts.categories.map((item) => item.label),
|
||||
y: this.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 },
|
||||
},
|
||||
};
|
||||
readonly donut: ChartFigure = {
|
||||
data: [{
|
||||
type: 'pie', hole: 0.62,
|
||||
labels: this.result.charts.composition.map((item) => item.label),
|
||||
values: this.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 } },
|
||||
},
|
||||
};
|
||||
readonly line: ChartFigure = {
|
||||
data: [{
|
||||
type: 'scatter', mode: 'lines+markers',
|
||||
x: this.result.charts.periods.map((item) => item.label),
|
||||
y: this.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 },
|
||||
},
|
||||
};
|
||||
readonly figures = createChartFigures(this.result);
|
||||
readonly bars = this.figures.bars;
|
||||
readonly donut = this.figures.donut;
|
||||
readonly line = this.figures.line;
|
||||
}
|
||||
|
||||
@@ -22,12 +22,11 @@
|
||||
|
||||
<footer class="export-dialog__footer">
|
||||
<div class="export-dialog__messages">
|
||||
@if (selection() === 'pdf') { <p>La generación de PDF está pendiente.</p> }
|
||||
@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() !== 'excel' || generating()" (click)="submit()">{{ generating() ? 'Generando...' : 'Exportar' }}</button>
|
||||
<button class="export-dialog__submit" type="button" [disabled]="!selection() || generating()" (click)="submit()">{{ generating() ? 'Generando...' : 'Exportar' }}</button>
|
||||
</div>
|
||||
</footer>
|
||||
</section>
|
||||
|
||||
@@ -2,13 +2,16 @@ import { TestBed } from '@angular/core/testing';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { vi } from 'vitest';
|
||||
import { mockAnalysisResult } from './dashboard.mock';
|
||||
import { EXCEL_EXPORT, ExportResultsDialog } from './export-results-dialog';
|
||||
import { EXCEL_EXPORT, PDF_EXPORT, ExportResultsDialog } from './export-results-dialog';
|
||||
|
||||
describe('ExportResultsDialog', () => {
|
||||
const open = (runExport: (result: typeof mockAnalysisResult) => Promise<void>) => {
|
||||
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 }],
|
||||
providers: [{ provide: EXCEL_EXPORT, useValue: runExport }, { provide: PDF_EXPORT, useValue: runPdf }],
|
||||
});
|
||||
const dialog = TestBed.inject(MatDialog);
|
||||
const ref = dialog.open(ExportResultsDialog, { data: mockAnalysisResult });
|
||||
@@ -18,17 +21,46 @@ describe('ExportResultsDialog', () => {
|
||||
return { ref, detect, root };
|
||||
};
|
||||
|
||||
it('keeps PDF unavailable and enables Excel', () => {
|
||||
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(true);
|
||||
expect(root().textContent).toContain('La generación de PDF está pendiente.');
|
||||
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; }));
|
||||
|
||||
@@ -6,6 +6,9 @@ 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],
|
||||
@@ -19,6 +22,7 @@ export class ExportResultsDialog {
|
||||
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>) {}
|
||||
|
||||
@@ -31,12 +35,13 @@ export class ExportResultsDialog {
|
||||
close(): void { if (!this.generating()) this.dialogRef.close(); }
|
||||
|
||||
async submit(): Promise<void> {
|
||||
if (this.generating() || this.selection() !== 'excel') return;
|
||||
const format = this.selection();
|
||||
if (this.generating() || !format) return;
|
||||
this.generating.set(true);
|
||||
this.error.set(false);
|
||||
this.dialogRef.disableClose = true;
|
||||
try {
|
||||
await this.runExcelExport(this.result);
|
||||
await (format === 'excel' ? this.runExcelExport(this.result) : this.runPdfExport(this.result));
|
||||
this.dialogRef.close();
|
||||
} catch {
|
||||
this.error.set(true);
|
||||
|
||||
@@ -11,7 +11,7 @@ describe('Excel export', () => {
|
||||
expect(rows('Resumen')).toEqual([
|
||||
['Área de análisis', 'CAMA'],
|
||||
[],
|
||||
['Tipo de datos', 'Datos de demostración'],
|
||||
['Tipo de datos', mockAnalysisResult.dataType],
|
||||
[],
|
||||
['Indicador', 'Valor'],
|
||||
...mockAnalysisResult.kpis.map((kpi) => [kpi.label, kpi.unit === '%' ? kpi.value / 100 : kpi.value]),
|
||||
|
||||
@@ -9,7 +9,7 @@ export function buildWorkbook(result: AnalysisResult, utils: SheetUtils): WorkBo
|
||||
const summary = utils.aoa_to_sheet([
|
||||
['Área de análisis', result.analysisType],
|
||||
[],
|
||||
['Tipo de datos', 'Datos de demostración'],
|
||||
['Tipo de datos', result.dataType],
|
||||
[],
|
||||
['Indicador', 'Valor'],
|
||||
...result.kpis.map((kpi) => [kpi.label, kpi.unit === '%' ? kpi.value / 100 : kpi.value]),
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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());
|
||||
}
|
||||
Vendored
+2
@@ -1,6 +1,8 @@
|
||||
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 };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user