Compare commits
82 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| baf5edca42 | |||
| 58ff3870be | |||
| 439a039ff4 | |||
| 049a9ca43c | |||
| f128f2e13a | |||
| 20b8c80aaf | |||
| 8e85c91f15 | |||
| 1ac8d5c258 | |||
| 23cd89e882 | |||
| 47a0ab5f1b | |||
| dc37c54938 | |||
| 2834fac85c | |||
| be77c50b45 | |||
| 40d8c8655e | |||
| 7580319fc8 | |||
| 7a2f0f42a9 | |||
| 4ffd3797b6 | |||
| b42428b068 | |||
| 01d6e71f07 | |||
| 3b246b4f1f | |||
| caf5f954b7 | |||
| edb868f372 | |||
| d9009a2e1e | |||
| 2e0938628c | |||
| 3783505dbd | |||
| 0acee49de2 | |||
| 18e9260705 | |||
| 3f4cf2217f | |||
| 7971a49dcd | |||
| c06cce20df | |||
| 2b0f6dfbed | |||
| c509cb7f87 | |||
| 5807f218b1 | |||
| 1d43ebff3b | |||
| eb92b99a1d | |||
| ee75e7a2a0 | |||
| b84d428814 | |||
| 17a91d3924 | |||
| cda3563184 | |||
| 7a6f87d141 | |||
| 78313adb4a | |||
| 7dc420773f | |||
| 552e2c194f | |||
| 8f01f8693d | |||
| ad8444a788 | |||
| f78db1ae37 | |||
| 0914b8db23 | |||
| 8aa66c6277 | |||
| 1e1999f264 | |||
| e95c175f9b | |||
| ff03a88ea0 | |||
| d761a6fb1a | |||
| 2982d482bf | |||
| 5e16f5454b | |||
| ce3ed34fbf | |||
| d159067efd | |||
| 7b8fd9e01d | |||
| 8a3f68df6b | |||
| bc75c058e1 | |||
| 62cdb252ca | |||
| 8f2906fe6f | |||
| e8628508d8 | |||
| 53edec8692 | |||
| a1ea31039e | |||
| ef631e2c0b | |||
| 27dc7a0166 | |||
| e6353f9f4c | |||
| 3bb9c2121d | |||
| 737c6f9f14 | |||
| 8e543cbcc6 | |||
| ea7aad5067 | |||
| 09b52e6b0a | |||
| 078db53ae4 | |||
| 957f4cd024 | |||
| 1ce8d98663 | |||
| 1771cb7ec6 | |||
| b74f188b15 | |||
| 5196f20e47 | |||
| 5d4cd6f654 | |||
| a05717f92d | |||
| 123232592f | |||
| 2cbb994667 |
Generated
+246
-2
@@ -20,9 +20,11 @@
|
||||
"@fontsource/roboto": "^5.3.0",
|
||||
"@fontsource/roboto-mono": "^5.3.0",
|
||||
"material-icons": "^1.13.14",
|
||||
"pdfmake": "0.3.14",
|
||||
"plotly.js-cartesian-dist-min": "4.1.2",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0"
|
||||
"tslib": "^2.3.0",
|
||||
"write-excel-file": "4.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular/build": "^22.1.8",
|
||||
@@ -2701,6 +2703,30 @@
|
||||
"@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/ciphers": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz",
|
||||
"integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^14.21.3 || >=16"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/hashes": {
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
|
||||
"integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^14.21.3 || >=16"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@oxc-parser/binding-android-arm-eabi": {
|
||||
"version": "0.142.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.142.0.tgz",
|
||||
@@ -3697,6 +3723,12 @@
|
||||
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@swc/helpers": {
|
||||
"version": "0.5.24",
|
||||
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.24.tgz",
|
||||
"integrity": "sha512-6tcXo4kA8HgGO7AVmawB57RYi/piBPYVHVcO6dXjX+SZw8GoHmi262sp4v2Ha2kNP9Cx84qei27yT+fjS1lxgg==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@tybys/wasm-util": {
|
||||
"version": "0.10.4",
|
||||
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz",
|
||||
@@ -4011,6 +4043,15 @@
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/base64-js": {
|
||||
"version": "0.0.8",
|
||||
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.8.tgz",
|
||||
"integrity": "sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/baseline-browser-mapping": {
|
||||
"version": "2.11.25",
|
||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.25.tgz",
|
||||
@@ -4101,6 +4142,35 @@
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/brotli": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/brotli/-/brotli-1.3.3.tgz",
|
||||
"integrity": "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"base64-js": "^1.1.2"
|
||||
}
|
||||
},
|
||||
"node_modules/brotli/node_modules/base64-js": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
|
||||
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/browserslist": {
|
||||
"version": "4.29.0",
|
||||
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.0.tgz",
|
||||
@@ -4357,6 +4427,15 @@
|
||||
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/clone": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz",
|
||||
"integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/content-disposition": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",
|
||||
@@ -4560,6 +4639,12 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/dfa": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz",
|
||||
"integrity": "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/dom-serializer": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
|
||||
@@ -4921,7 +5006,6 @@
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
|
||||
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-string-truncated-width": {
|
||||
@@ -4986,6 +5070,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",
|
||||
@@ -5018,6 +5108,23 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/fontkit": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/fontkit/-/fontkit-2.0.4.tgz",
|
||||
"integrity": "sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@swc/helpers": "^0.5.12",
|
||||
"brotli": "^1.3.2",
|
||||
"clone": "^2.1.2",
|
||||
"dfa": "^1.2.0",
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"restructure": "^3.0.0",
|
||||
"tiny-inflate": "^1.0.3",
|
||||
"unicode-properties": "^1.4.0",
|
||||
"unicode-trie": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/forwarded": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
|
||||
@@ -5862,6 +5969,16 @@
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/linebreak": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz",
|
||||
"integrity": "sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"base64-js": "0.0.8",
|
||||
"unicode-trie": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/listr2": {
|
||||
"version": "11.0.0",
|
||||
"resolved": "https://registry.npmjs.org/listr2/-/listr2-11.0.0.tgz",
|
||||
@@ -6373,6 +6490,12 @@
|
||||
"@oxc-parser/binding-win32-x64-msvc": "0.142.0"
|
||||
}
|
||||
},
|
||||
"node_modules/pako": {
|
||||
"version": "0.2.9",
|
||||
"resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz",
|
||||
"integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/parse5": {
|
||||
"version": "8.0.1",
|
||||
"resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz",
|
||||
@@ -6476,6 +6599,34 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pdfkit": {
|
||||
"version": "0.20.2",
|
||||
"resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.20.2.tgz",
|
||||
"integrity": "sha512-Q/w03ICAQyXfHNfTsg1udp0ADerdBN0s7a6XSPL7J7Ro6ABnafoBOCDBstIO9U02mvzHEV8HrvFIw5iV5ejIRA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "^1.3.0",
|
||||
"@noble/hashes": "^1.8.0",
|
||||
"fflate": "^0.8.3",
|
||||
"fontkit": "^2.0.4",
|
||||
"linebreak": "^1.1.0",
|
||||
"png-js": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/pdfmake": {
|
||||
"version": "0.3.14",
|
||||
"resolved": "https://registry.npmjs.org/pdfmake/-/pdfmake-0.3.14.tgz",
|
||||
"integrity": "sha512-EDyOlwiDnE8e0eITSpHwZCVAP/veWq0TxA2RyhoDO0cSLat7HEGNtKUN6UiW9+YovO2GhcWlK99Q7tj9sof9gg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"linebreak": "^1.1.0",
|
||||
"pdfkit": "^0.20.2",
|
||||
"xmldoc": "^2.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/picocolors": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
||||
@@ -6525,6 +6676,14 @@
|
||||
"integrity": "sha512-3UkyAT7/U8f3sOLavLnUjA6mqFmnqEe246GZhxT0J3TT9oZ0mh6SgwsL1yo/3/4xfmRSDFdGOxe+EsvT2XiE0g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/png-js": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/png-js/-/png-js-2.0.0.tgz",
|
||||
"integrity": "sha512-GdzJuUMc6ZSpxFJWVxtOH1bzYHym+TOnveqUjb+VJIbZWbZzyiRGFiKhbiielfpYbgMlhHVhsJ0FTazfuRFkMA==",
|
||||
"dependencies": {
|
||||
"fflate": "^0.8.2"
|
||||
}
|
||||
},
|
||||
"node_modules/postcss": {
|
||||
"version": "8.5.28",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
|
||||
@@ -6755,6 +6914,12 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/restructure": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/restructure/-/restructure-3.0.2.tgz",
|
||||
"integrity": "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/rolldown": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.0.tgz",
|
||||
@@ -6853,6 +7018,15 @@
|
||||
"@parcel/watcher": "^2.4.1"
|
||||
}
|
||||
},
|
||||
"node_modules/sax": {
|
||||
"version": "1.6.1",
|
||||
"resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",
|
||||
"integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",
|
||||
"license": "BlueOak-1.0.0",
|
||||
"engines": {
|
||||
"node": ">=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/saxes": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
|
||||
@@ -7187,6 +7361,12 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tiny-inflate": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz",
|
||||
"integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tinybench": {
|
||||
"version": "2.9.0",
|
||||
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
|
||||
@@ -7350,6 +7530,46 @@
|
||||
"node": ">=20.18.1"
|
||||
}
|
||||
},
|
||||
"node_modules/unicode-properties": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz",
|
||||
"integrity": "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"base64-js": "^1.3.0",
|
||||
"unicode-trie": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/unicode-properties/node_modules/base64-js": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
|
||||
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/unicode-trie": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz",
|
||||
"integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pako": "^0.2.5",
|
||||
"tiny-inflate": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/unpipe": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
|
||||
@@ -8070,6 +8290,18 @@
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/write-excel-file": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/write-excel-file/-/write-excel-file-4.1.1.tgz",
|
||||
"integrity": "sha512-MUnCnNtQrcZek832ZcU24uU0rSphFmKPD1DvIjXOlygVb93CV7Tme6H3jUTkxsMmjB2W7HIzERzjqTi5kui71A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fflate": "^0.8.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/xml-name-validator": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
|
||||
@@ -8087,6 +8319,18 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/xmldoc": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/xmldoc/-/xmldoc-2.0.3.tgz",
|
||||
"integrity": "sha512-6gRk4NY/Jvg67xn7OzJuxLRsGgiXBaPUQplVJ/9l99uIugxh4FTOewYz5ic8WScj7Xx/2WvhENiQKwkK9RpE4w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"sax": "^1.4.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/y18n": {
|
||||
"version": "5.0.8",
|
||||
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
|
||||
|
||||
+3
-1
@@ -23,9 +23,11 @@
|
||||
"@fontsource/roboto": "^5.3.0",
|
||||
"@fontsource/roboto-mono": "^5.3.0",
|
||||
"material-icons": "^1.13.14",
|
||||
"pdfmake": "0.3.14",
|
||||
"plotly.js-cartesian-dist-min": "4.1.2",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0"
|
||||
"tslib": "^2.3.0",
|
||||
"write-excel-file": "4.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular/build": "^22.1.8",
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
// Covers the shell's header: on an indicators page it carries the platform title and the domain selector; on
|
||||
// the institutional routes it keeps the breadcrumb. The pages are stubs: only the header and the router matter.
|
||||
import { Component } from '@angular/core';
|
||||
import { Location } from '@angular/common';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter, Router } from '@angular/router';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { App } from './app';
|
||||
import { routes } from './app.routes';
|
||||
import { DOMINIOS } from './features/indicadores/indicadores.models';
|
||||
|
||||
@Component({ template: 'página', selector: 'app-stub' })
|
||||
class Stub {}
|
||||
|
||||
describe('Encabezado del marco', () => {
|
||||
const rutas = [
|
||||
{ path: '', component: Stub },
|
||||
{ path: 'conectar', component: Stub, data: { workspace: true, breadcrumb: 'Conectar datos' } },
|
||||
{ path: 'gobernanza', component: Stub, data: { workspace: true, breadcrumb: 'Gobernanza de modelos' } },
|
||||
...DOMINIOS.map(dominio => ({ path: `indicadores/${dominio}`, component: Stub, data: { workspace: true, breadcrumb: 'Indicadores', dominio } })),
|
||||
];
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<App>>, router: Router;
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({ imports: [App], providers: [provideRouter(rutas), provideHttpClient(), provideHttpClientTesting()] }).compileComponents();
|
||||
fixture = TestBed.createComponent(App); router = TestBed.inject(Router);
|
||||
fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); document.querySelectorAll('.cdk-overlay-container').forEach(e => e.replaceChildren()); });
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
async function ir(url: string) { await router.navigateByUrl(url); await fixture.whenStable(); fixture.detectChanges(); }
|
||||
const selector = () => root().querySelector('.domain-selector') as HTMLButtonElement | null;
|
||||
async function abrirMenu() {
|
||||
selector()!.click(); fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
||||
return [...document.querySelectorAll('.mat-mdc-menu-panel a[mat-menu-item]')] as HTMLAnchorElement[];
|
||||
}
|
||||
|
||||
it('las rutas de los tres dominios existen en el enrutador de la aplicación', () => {
|
||||
// Fails if the selector would point at a route the application does not have.
|
||||
const paths = routes.map(r => r.path);
|
||||
for (const dominio of DOMINIOS) expect(paths).toContain(`indicadores/${dominio}`);
|
||||
});
|
||||
it.each([['tea', 'TEA'], ['cacu', 'CaCu'], ['cama', 'Cáncer de mama']] as const)('en /indicadores/%s muestra el título de la plataforma y el selector con «%s»', async (dominio, etiqueta) => {
|
||||
await ir('/indicadores/' + dominio);
|
||||
expect(root().querySelector('.platform-title')?.textContent).toBe('Plataforma de Indicadores');
|
||||
expect(selector()?.textContent?.replace(/\s+/g, ' ').trim()).toBe(etiqueta + ' ▾');
|
||||
expect(root().querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON');
|
||||
// The breadcrumb is replaced, not duplicated beside the selector.
|
||||
expect(root().querySelector('.site-header__nav')).toBeNull();
|
||||
expect(root().querySelector('.app-shell--indicadores')).not.toBeNull();
|
||||
});
|
||||
it('el selector tiene nombre accesible con el dominio actual y anuncia un menú', async () => {
|
||||
await ir('/indicadores/cama');
|
||||
expect(selector()!.getAttribute('aria-label')).toBe('Dominio actual: Cáncer de mama. Cambiar dominio');
|
||||
expect(selector()!.getAttribute('aria-haspopup')).toBe('menu');
|
||||
expect(selector()!.tagName).toBe('BUTTON');
|
||||
expect(selector()!.tabIndex).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
it('el menú ofrece los otros dos dominios con sus rutas institucionales', async () => {
|
||||
await ir('/indicadores/cama');
|
||||
const items = await abrirMenu();
|
||||
expect(items.map(a => a.textContent?.trim())).toEqual(['TEA', 'CaCu']);
|
||||
expect(items.map(a => a.getAttribute('href'))).toEqual(['/indicadores/tea', '/indicadores/cacu']);
|
||||
expect(selector()!.getAttribute('aria-expanded')).toBe('true');
|
||||
});
|
||||
it('elegir otro dominio navega por el enrutador, actualiza el selector y deja una entrada en el historial', async () => {
|
||||
await ir('/indicadores/cama');
|
||||
const items = await abrirMenu();
|
||||
items[1].click(); await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(router.url).toBe('/indicadores/cacu');
|
||||
expect(selector()!.textContent).toContain('CaCu');
|
||||
// The choice is a router navigation (a history entry), not a page reload: going back lands on the previous domain.
|
||||
const ubicacion = TestBed.inject(Location);
|
||||
ubicacion.back(); await new Promise(r => setTimeout(r, 100));
|
||||
expect(ubicacion.path()).toBe('/indicadores/cama');
|
||||
});
|
||||
it.each(['/', '/conectar', '/gobernanza'])('en %s conserva el encabezado institucional sin selector', async url => {
|
||||
// Fails if the indicators header leaks into the institutional routes.
|
||||
await ir(url);
|
||||
expect(selector()).toBeNull();
|
||||
expect(root().querySelector('.platform-title')).toBeNull();
|
||||
expect(root().querySelector('.site-header__section')?.textContent).toBe('Análisis de información');
|
||||
expect(root().querySelector('.app-shell--indicadores')).toBeNull();
|
||||
if (url !== '/') expect(root().querySelector('.site-header__crumb')?.textContent).toContain(url === '/conectar' ? 'Conectar datos' : 'Gobernanza de modelos');
|
||||
});
|
||||
it('una ruta parecida que no es de indicadores no activa el selector', async () => {
|
||||
await router.navigateByUrl('/'); fixture.detectChanges();
|
||||
expect(selector()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -2,11 +2,21 @@ import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { routes } from './app.routes';
|
||||
import { IndicadoresService } from './features/indicadores/indicadores.service';
|
||||
import { IndicadoresPeriodos } from './features/indicadores/indicadores-periodos';
|
||||
import { TeaSeguimientoService } from './features/indicadores/tea-seguimiento.service';
|
||||
import { FhirIndicadoresPeriodos, FhirIndicadoresService } from './features/indicadores/indicadores-fhir';
|
||||
import { FhirTeaSeguimientoService } from './features/indicadores/tea-seguimiento-fhir';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
provideBrowserGlobalErrorListeners(),
|
||||
provideRouter(routes),
|
||||
provideHttpClient(),
|
||||
// The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract
|
||||
// (`/<domain>/indicadores/<id>/datos`, `/tea/seguimiento`).
|
||||
{ provide: IndicadoresService, useClass: FhirIndicadoresService },
|
||||
{ provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos },
|
||||
{ provide: TeaSeguimientoService, useClass: FhirTeaSeguimientoService },
|
||||
]
|
||||
};
|
||||
|
||||
+16
-6
@@ -1,15 +1,25 @@
|
||||
<div class="app-shell" [class.app-shell--workspace]="workspace()">
|
||||
<div class="app-shell" [class.app-shell--workspace]="workspace()" [class.app-shell--indicadores]="!!activeDomain()">
|
||||
<header class="site-header">
|
||||
<div class="site-header__content">
|
||||
<a class="brand" routerLink="/" aria-label="ISSSTELEON, inicio">
|
||||
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
|
||||
</a>
|
||||
<nav class="site-header__nav" aria-label="Secciones">
|
||||
<a class="site-header__section" routerLink="/">Análisis de información</a>
|
||||
@if (breadcrumb(); as crumb) {
|
||||
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
|
||||
@if (activeDomain(); as domain) {
|
||||
<span class="platform-title">{{ title }}</span>
|
||||
@defer (on immediate) {
|
||||
<app-domain-selector [actual]="domain" [otros]="otherDomains()" [labels]="domainLabels" />
|
||||
} @placeholder {
|
||||
<!-- Same size as the selector until its code arrives, so the header does not jump. -->
|
||||
<span class="domain-selector domain-selector--espera" aria-hidden="true">{{ domainLabels[domain] }}</span>
|
||||
}
|
||||
</nav>
|
||||
} @else {
|
||||
<nav class="site-header__nav" aria-label="Secciones">
|
||||
<a class="site-header__section" routerLink="/">Análisis de información</a>
|
||||
@if (breadcrumb(); as crumb) {
|
||||
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
|
||||
}
|
||||
</nav>
|
||||
}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
|
||||
@@ -6,6 +6,12 @@ const loadIndicadores = () => import('./features/indicadores/indicadores-page').
|
||||
|
||||
export const routes: Routes = [
|
||||
{ path: '', component: Home, title: 'Análisis de información | ISSSTELEON' },
|
||||
{
|
||||
path: 'indicadores/tea-estatus',
|
||||
title: 'Casos por estatus | ISSSTELEON',
|
||||
loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage),
|
||||
data: { workspace: true, breadcrumb: 'Casos por estatus' },
|
||||
},
|
||||
{
|
||||
path: 'conectar',
|
||||
title: 'Conectar datos | ISSSTELEON',
|
||||
|
||||
@@ -103,3 +103,26 @@
|
||||
width: 155px;
|
||||
}
|
||||
}
|
||||
|
||||
.platform-title {
|
||||
color: var(--color-text);
|
||||
font-family: var(--issste-font-heading);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
line-height: 1.15;
|
||||
margin-inline-start: var(--issste-space-4);
|
||||
margin-inline-end: auto;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.domain-selector--espera {
|
||||
align-items: center; border-radius: var(--issste-radius); box-sizing: border-box; display: inline-flex; flex: 0 0 auto;
|
||||
background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; min-height: 40px; padding: 0 16px; white-space: nowrap;
|
||||
}
|
||||
|
||||
// Narrow screens: logo and selector share the first row and the title takes the second, so neither is squeezed.
|
||||
@media (max-width: 599px) {
|
||||
.app-shell--indicadores .site-header__content { flex-wrap: wrap; row-gap: 0; padding-block: 6px 8px; }
|
||||
.app-shell--indicadores .brand { margin-inline-end: auto; }
|
||||
.platform-title { order: 3; flex: 1 0 100%; margin: 4px 0 0; font-size: 1.125rem; min-width: 0; }
|
||||
}
|
||||
|
||||
+12
-1
@@ -2,9 +2,11 @@ import { Component, computed, inject } from '@angular/core';
|
||||
import { toSignal } from '@angular/core/rxjs-interop';
|
||||
import { ActivatedRoute, NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router';
|
||||
import { filter, map } from 'rxjs';
|
||||
import { DomainSelector } from './domain-selector';
|
||||
import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models';
|
||||
|
||||
@Component({
|
||||
imports: [RouterLink, RouterOutlet],
|
||||
imports: [RouterLink, RouterOutlet, DomainSelector],
|
||||
selector: 'app-root',
|
||||
styleUrl: './app.scss',
|
||||
templateUrl: './app.html',
|
||||
@@ -28,4 +30,13 @@ export class App {
|
||||
/** Full-height workspace routes (`data.workspace`) drop the marketing footer. */
|
||||
readonly workspace = computed(() => !!this.leafRouteData()['workspace']);
|
||||
readonly breadcrumb = computed(() => this.leafRouteData()['breadcrumb'] as string | undefined);
|
||||
|
||||
protected readonly title = 'Plataforma de Indicadores';
|
||||
protected readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'Cáncer de mama' };
|
||||
private readonly url = toSignal(this.router.events.pipe(
|
||||
filter((event) => event instanceof NavigationEnd), map(event => event.urlAfterRedirects)), { initialValue: this.router.url });
|
||||
/** On an indicators page the header names its domain and switches to the others. */
|
||||
protected readonly activeDomain = computed(() =>
|
||||
DOMINIOS.find(domain => new RegExp(`^/indicadores/${domain}(?:[/?#]|$)`).test(this.url())));
|
||||
protected readonly otherDomains = computed(() => DOMINIOS.filter(domain => domain !== this.activeDomain()));
|
||||
}
|
||||
|
||||
@@ -100,8 +100,8 @@
|
||||
type="button"
|
||||
class="saved-connection__forget"
|
||||
(click)="forgetSaved(saved, $event)"
|
||||
aria-label="Olvidar esta conexión guardada"
|
||||
matTooltip="Olvidar"
|
||||
aria-label="Eliminar esta conexión guardada"
|
||||
matTooltip="Eliminar"
|
||||
>
|
||||
<mat-icon aria-hidden="true">close</mat-icon>
|
||||
</button>
|
||||
@@ -134,7 +134,7 @@
|
||||
</mat-form-field>
|
||||
</form>
|
||||
<mat-checkbox [checked]="remember()" (change)="remember.set($event.checked)">
|
||||
Recordar servidor, usuario y base de datos (nunca la contraseña)
|
||||
Guardar servidor, usuario y base de datos para conexiones futuras (la contraseña no se guarda)
|
||||
</mat-checkbox>
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import { ImportFlow } from '../domain/import-flow';
|
||||
|
||||
export const DOMAINS: { id: Domain; label: string; description: string }[] = [
|
||||
{ id: 'cacu', label: 'CaCu', description: 'Cáncer cervicouterino' },
|
||||
{ id: 'cama', label: 'CaMa', description: 'Cáncer de mama' },
|
||||
{ id: 'cama', label: 'Cáncer de mama', description: 'Cáncer de mama' },
|
||||
{ id: 'tea', label: 'TEA', description: 'Trastorno del espectro autista' },
|
||||
];
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
:host { display: contents; }
|
||||
.domain-selector {
|
||||
flex: 0 0 auto;
|
||||
background-color: var(--issste-accent);
|
||||
color: var(--issste-text);
|
||||
font-weight: 700;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.domain-selector:hover { background-color: var(--issste-accent); filter: brightness(.94); }
|
||||
.domain-selector:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Component, input } from '@angular/core';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatMenuModule } from '@angular/material/menu';
|
||||
import { Dominio } from './features/indicadores/indicadores.models';
|
||||
|
||||
/** The header's domain menu. Loaded deferred: Material's menu and overlay are not needed by the institutional routes. */
|
||||
@Component({
|
||||
selector: 'app-domain-selector',
|
||||
imports: [RouterLink, MatButtonModule, MatMenuModule],
|
||||
template: `
|
||||
<button class="domain-selector" mat-button [matMenuTriggerFor]="domainMenu"
|
||||
[attr.aria-label]="'Dominio actual: ' + labels()[actual()] + '. Cambiar dominio'">
|
||||
{{ labels()[actual()] }} <span aria-hidden="true">▾</span>
|
||||
</button>
|
||||
<mat-menu #domainMenu="matMenu" aria-label="Cambiar dominio de indicadores">
|
||||
@for (option of otros(); track option) {
|
||||
<a mat-menu-item [routerLink]="['/indicadores', option]">{{ labels()[option] }}</a>
|
||||
}
|
||||
</mat-menu>
|
||||
`,
|
||||
styleUrl: './domain-selector.scss',
|
||||
})
|
||||
export class DomainSelector {
|
||||
readonly actual = input.required<Dominio>();
|
||||
readonly otros = input.required<readonly Dominio[]>();
|
||||
readonly labels = input.required<Record<Dominio, string>>();
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; page: number; page_size: number; }
|
||||
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; }
|
||||
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
|
||||
// A row names its patient with `pac_id` (a decimal string) or the legacy `id_seudonimo`.
|
||||
export interface SeguimientoPaciente {
|
||||
id_seudonimo: string;
|
||||
pac_id?: string;
|
||||
id_seudonimo?: string;
|
||||
grupo_edad: string;
|
||||
estatus: SeguimientoStatus;
|
||||
ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models';
|
||||
import { identidadDe, identidadesDe } from './paciente-identidad';
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string';
|
||||
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
||||
@@ -19,12 +20,12 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
||||
|| !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string))
|
||||
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|
||||
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => {
|
||||
if (!record(item) || typeof item['id_seudonimo'] !== 'string' || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false;
|
||||
if (!record(item) || !identidadDe(item) || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false;
|
||||
const c = item['ultima_citologia'], h = item['ultimo_vph'];
|
||||
return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string'))
|
||||
&& (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean'))
|
||||
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']));
|
||||
})) throw new Error('Respuesta de seguimiento inválida');
|
||||
}) || !identidadesDe(v['items'])) throw new Error('Respuesta de seguimiento inválida');
|
||||
return v as unknown as SeguimientoResponse;
|
||||
}
|
||||
@Injectable({ providedIn: 'root' })
|
||||
|
||||
@@ -16,11 +16,10 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
afterEach(()=>{ fixture.destroy(); http.verify(); });
|
||||
function open() { fixture.componentRef.setInput('active',true); fixture.detectChanges(); return http.expectOne(r=>r.url==='/cacu/seguimiento'); }
|
||||
function respond() { open().flush(fixtureData); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{NORMAL:{etiqueta:'Normal'}}}); fixture.detectChanges(); }
|
||||
it('prioridad deshabilitada con una sola opción y sin parámetros nuevos al consultar o paginar', () => {
|
||||
it('sin selector de prioridad ni filtros de TEA, y sin parámetros nuevos al consultar o paginar', () => {
|
||||
respond();
|
||||
const select = fixture.nativeElement.querySelector('select[name="prioridad"]') as HTMLSelectElement;
|
||||
expect(select.disabled).toBe(true); expect(select.labels?.[0].textContent).toContain('Ordenar por prioridad');
|
||||
expect(Array.from(select.options).map(o => o.text)).toEqual(['No disponible']);
|
||||
expect(fixture.nativeElement.querySelector('select[name="prioridad"]')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('select[name="mchat"]')).toBeNull();
|
||||
const order = fixture.componentInstance.data!.items.map(i => i.id_seudonimo);
|
||||
expect(Array.from(fixture.nativeElement.querySelectorAll('tbody tr td:first-child')).map(e => (e as HTMLElement).textContent)).toEqual(order);
|
||||
fixture.componentInstance.apply();
|
||||
@@ -92,13 +91,6 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow();
|
||||
open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
|
||||
});
|
||||
it.each(['tea','cama'])('%s conserva su estado pendiente sin consultas de pacientes', dominio => {
|
||||
fixture.componentRef.setInput('dominio',dominio); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true);
|
||||
expect(fixture.nativeElement.textContent).toContain('El seguimiento aún no está disponible');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Columnas propuestas para revisión.');
|
||||
expect(fixture.nativeElement.querySelector('table')).not.toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('caption')).toBeNull();
|
||||
});
|
||||
it('valida parámetros antes del transporte sin confundir fechas del filtro general', () => {
|
||||
const service=TestBed.inject(CacuSeguimientoService);
|
||||
for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow();
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
// Display only codes confirmed by the cohort and CaMa catalog; preserve unknown values as received.
|
||||
const EDADES: Readonly<Record<string, string>> = {
|
||||
MENOR_40: 'Menores de 40 años', '<40': 'Menores de 40 años', '40-49': '40 a 49 años', '50-59': '50 a 59 años', '60-69': '60 a 69 años', '70+': '70 años o más', SIN_DATO: 'Sin dato',
|
||||
};
|
||||
const BIRADS = /^BIRADS_(4[ABC]?|5|6)$/;
|
||||
const HISTOLOGIA: Readonly<Record<string, string>> = {
|
||||
BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ',
|
||||
CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido',
|
||||
};
|
||||
|
||||
/** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». Any other text is returned as it came. */
|
||||
export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo;
|
||||
/** «50-59» as «50 a 59 años». Any other text is returned as it came. */
|
||||
export const etiquetaEdad = (codigo: string) => EDADES[codigo] ?? codigo;
|
||||
export const etiquetaHistologia = (codigo: string) => HISTOLOGIA[codigo] ?? codigo;
|
||||
|
||||
const POR_CLAVE: Readonly<Record<string, (codigo: string) => string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia };
|
||||
|
||||
/** The label of a value of a filter of the cohort's list, or the value itself when its meaning is not confirmed. */
|
||||
export const etiquetaDeFiltro = (clave: string, codigo: string) => (POR_CLAVE[clave] ?? ((c: string) => c))(codigo);
|
||||
@@ -0,0 +1,7 @@
|
||||
// A cell that starts with one of these is read as a formula by spreadsheet programs once the text is pasted or converted.
|
||||
const FORMULA_START = /^[=+\-@\t\r]/;
|
||||
|
||||
/** Text that is safe to write into a spreadsheet cell: a leading formula character is neutralised with an apostrophe. */
|
||||
export function neutralizeFormula(text: string): string {
|
||||
return FORMULA_START.test(text) ? `'${text}` : text;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
|
||||
/**
|
||||
* Name of a downloaded file. It carries the report kind, the cut-off date and the moment it was made, and never a
|
||||
* patient identifier, because file names end up in download lists, backups and mail attachments.
|
||||
*/
|
||||
export function exportFilename(kind: 'seguimiento-cancer-de-mama' | 'seguimiento-cancer-de-mama-seleccion' | 'ficha-cancer-de-mama', corte: string, extension: 'xlsx' | 'pdf', now = new Date()): string {
|
||||
const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}`;
|
||||
return `${kind}_corte-${corte.replace(/[^0-9-]/g, '')}_${stamp}.${extension}`;
|
||||
}
|
||||
|
||||
/** Hands a generated file to the browser's download. */
|
||||
export function downloadBlob(blob: Blob, filename: string): void {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
link.rel = 'noopener';
|
||||
document.body.append(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 0);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// Covers that nothing a user can read in the exports (PDF of the list, spreadsheet, PDF of one record) or in the
|
||||
// individual record alludes to tests, simulation or a development environment, and that none carries a note line. Fixture: fixtures/cama_seguimiento.json.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { strFromU8, unzipSync } from 'fflate';
|
||||
import fixtureData from '../fixtures/cama_seguimiento.json';
|
||||
import { seguimientoTablaResponse } from '../seguimiento-tabla.service';
|
||||
import { CamaPatientCard } from '../paciente-detalle/cama/cama-patient-card';
|
||||
import { camaPatientDocument } from '../paciente-detalle/cama/cama-patient-pdf';
|
||||
import { toCamaPatientSummary } from '../paciente-detalle/cama/cama-patient.models';
|
||||
import { exportFilename } from './download-file';
|
||||
import { TrackingExportBar } from './tracking-export-bar';
|
||||
import { trackingDocument } from './tracking-pdf';
|
||||
import { buildTrackingXlsx } from './tracking-xlsx';
|
||||
import { TrackingSnapshot } from './tracking-export.models';
|
||||
|
||||
const NOTE_TEXT = 'Documento de consulta; verificar información con el expediente fuente';
|
||||
const FORBIDDEN = /simulad|sint[eé]tic|entorno|\bdev\b|prueba|demostraci|ficticio|ejemplo|valor cl[ií]nico|test/i;
|
||||
const r = seguimientoTablaResponse(structuredClone(fixtureData));
|
||||
const snapshot: TrackingSnapshot = { corte: r.corte, ventana: r.ventana, filtros: r.filtros, filtros_disponibles: r.filtros_disponibles, columnas: r.columnas, items: r.items };
|
||||
const NOW = new Date(Date.UTC(2026, 10, 12, 21, 30));
|
||||
function texts(node: unknown, out: string[] = []): string[] {
|
||||
if (typeof node === 'string') out.push(node);
|
||||
else if (Array.isArray(node)) node.forEach(n => texts(n, out));
|
||||
else if (node && typeof node === 'object') Object.values(node).forEach(n => texts(n, out));
|
||||
return out;
|
||||
}
|
||||
// Every text a PDF definition can print: header, footer, content and document properties.
|
||||
const pdfTexts = (d: Record<string, any>) => [...texts(d['header']()), ...texts(d['footer'](1, 2)), ...texts(d['content']), ...texts(d['info'])];
|
||||
|
||||
describe('Documentos y ficha: sin leyendas alusivas a pruebas', () => {
|
||||
// Fails if any text of the list PDF (frame, parameters, table, notes, properties) mentions tests or simulation.
|
||||
it('the list PDF has no such wording and no note', () => {
|
||||
const all = pdfTexts(trackingDocument(snapshot, NOW, 'data:image/png;base64,AAAA') as Record<string, any>);
|
||||
expect(all.filter(t => FORBIDDEN.test(t))).toEqual([]);
|
||||
expect(all).not.toContain(NOTE_TEXT);
|
||||
});
|
||||
|
||||
// Fails if any cell, sheet name or parameter of the spreadsheet mentions tests or simulation.
|
||||
it('the spreadsheet has no such wording and no note', async () => {
|
||||
const files = unzipSync(new Uint8Array(await (await buildTrackingXlsx(snapshot, NOW)).arrayBuffer()));
|
||||
const strings = strFromU8(files['xl/sharedStrings.xml']), workbook = strFromU8(files['xl/workbook.xml']);
|
||||
expect(FORBIDDEN.test(strings.replace(/<[^>]+>/g, ' '))).toBe(false);
|
||||
expect(FORBIDDEN.test(workbook.replace(/xmlns[^ >]*/g, ''))).toBe(false);
|
||||
expect(strings).not.toContain(NOTE_TEXT);
|
||||
expect(strings).not.toContain('Tipo de datos');
|
||||
});
|
||||
|
||||
// Fails if the record's PDF mentions tests, simulation or the synthetic nature of the identifier.
|
||||
it('the record PDF has no such wording and no note', () => {
|
||||
const summary = toCamaPatientSummary(snapshot.items[0], snapshot.corte)!;
|
||||
const all = pdfTexts(camaPatientDocument(summary, NOW, 'data:image/png;base64,AAAA') as Record<string, any>);
|
||||
expect(all.filter(t => FORBIDDEN.test(t))).toEqual([]);
|
||||
expect(all).not.toContain(NOTE_TEXT);
|
||||
});
|
||||
|
||||
// Fails if the record on screen or the export buttons mention tests or simulation.
|
||||
it('the record and the export buttons show no such wording', () => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient()] });
|
||||
const card = TestBed.createComponent(CamaPatientCard);
|
||||
card.componentRef.setInput('summary', toCamaPatientSummary(snapshot.items[0], snapshot.corte)!);
|
||||
card.detectChanges();
|
||||
expect(FORBIDDEN.test(card.nativeElement.textContent)).toBe(false);
|
||||
expect(card.nativeElement.textContent).not.toContain(NOTE_TEXT);
|
||||
const bar = TestBed.createComponent(TrackingExportBar);
|
||||
bar.componentRef.setInput('dominio', 'cama'); bar.componentRef.setInput('respuesta', r);
|
||||
bar.detectChanges();
|
||||
expect(FORBIDDEN.test(bar.nativeElement.textContent)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Documentos y ficha: nombre funcional del dominio', () => {
|
||||
// Fails if "CaMa" (an internal name) or a wrong title reaches the titles, properties or text of a document.
|
||||
it('both PDFs use the functional name, with accents, and never "CaMa"', () => {
|
||||
const list = pdfTexts(trackingDocument(snapshot, NOW, 'data:image/png;base64,AAAA') as Record<string, any>);
|
||||
const record = pdfTexts(camaPatientDocument(toCamaPatientSummary(snapshot.items[0], snapshot.corte)!, NOW, 'data:image/png;base64,AAAA') as Record<string, any>);
|
||||
expect(list).toContain('Cáncer de mama');
|
||||
expect(record).toContain('Ficha de paciente — Cáncer de mama');
|
||||
expect(list.filter(t => /cama/i.test(t))).toEqual([]);
|
||||
expect(record.filter(t => /cama/i.test(t))).toEqual([]);
|
||||
});
|
||||
|
||||
// Fails if the spreadsheet names the report or its sheets with the internal name.
|
||||
it('the spreadsheet names the report "Cáncer de mama" and never "CaMa"', async () => {
|
||||
const files = unzipSync(new Uint8Array(await (await buildTrackingXlsx(snapshot, NOW)).arrayBuffer()));
|
||||
const strings = strFromU8(files['xl/sharedStrings.xml']).replace(/<[^>]+>/g, '|');
|
||||
expect(strings).toContain('|Cáncer de mama|');
|
||||
expect(/cama/i.test(strings + strFromU8(files['xl/workbook.xml']).replace(/xmlns[^ >]*/g, ''))).toBe(false);
|
||||
});
|
||||
|
||||
// Fails if a downloaded file name exposes the internal name or a patient.
|
||||
it('file names use the functional name', () => {
|
||||
expect(exportFilename('seguimiento-cancer-de-mama', snapshot.corte, 'xlsx', NOW)).not.toMatch(/cama|M-\d/i);
|
||||
expect(exportFilename('ficha-cancer-de-mama', snapshot.corte, 'pdf', NOW)).not.toMatch(/cama|M-\d/i);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
export type PdfDefinition = Record<string, unknown>;
|
||||
|
||||
let fontsReady = false;
|
||||
|
||||
/** Renders a pdfmake document definition. pdfmake and its Roboto fonts download only when the first PDF is made. */
|
||||
export async function renderPdf(definition: PdfDefinition): Promise<Blob> {
|
||||
const [{ default: pdfMake }, { default: roboto }] = await Promise.all([
|
||||
import('pdfmake/build/pdfmake'),
|
||||
import('pdfmake/build/fonts/Roboto'),
|
||||
]);
|
||||
if (!fontsReady) {
|
||||
pdfMake.addFontContainer(roboto);
|
||||
// A document only carries inline data; it must never make pdfmake fetch an address.
|
||||
pdfMake.setUrlAccessPolicy(() => false);
|
||||
fontsReady = true;
|
||||
}
|
||||
return pdfMake.createPdf(definition).getBlob();
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { PdfDefinition } from './pdf-engine';
|
||||
|
||||
export const PDF_CONFIDENTIAL = 'Confidencial · uso interno';
|
||||
export const LOGO_URL = 'assets/branding/isssteleon-logo.png';
|
||||
// The logo is 1125 x 358 pixels.
|
||||
const LOGO_WIDTH = 110;
|
||||
|
||||
export const COLORS = { ink: '#081839', accent: '#a8c243', muted: '#7a7a7a', rule: '#e3e7df', band: '#f0f3e8' } as const;
|
||||
|
||||
export interface PdfTemplateOptions {
|
||||
/** Title in the page header and in the document properties. */
|
||||
title: string;
|
||||
/** Data URL of the institutional logo; without it the header shows the name as text. */
|
||||
logo?: string;
|
||||
now: Date;
|
||||
/** Page size: reports are landscape letter, individual records portrait. */
|
||||
orientation: 'landscape' | 'portrait';
|
||||
}
|
||||
|
||||
/** The logo as a data URL, or `undefined` when it cannot be read (the header then falls back to text). */
|
||||
export async function loadLogo(url = LOGO_URL): Promise<string | undefined> {
|
||||
try {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) return undefined;
|
||||
const blob = await response.blob();
|
||||
return await new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(String(reader.result));
|
||||
reader.onerror = () => reject(reader.error);
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function formatGenerated(now: Date): string {
|
||||
return new Intl.DateTimeFormat('es-MX', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'America/Mexico_City' }).format(now);
|
||||
}
|
||||
|
||||
/**
|
||||
* The institutional frame shared by every PDF: header with the logo, and the title on every
|
||||
* page, footer with the generation time, the confidentiality line and "Página X de Y", and generic document properties
|
||||
* (no author, no user). `content` is what goes between them.
|
||||
*/
|
||||
export function institutionalDocument(options: PdfTemplateOptions, content: unknown[]): PdfDefinition {
|
||||
const margin = 36;
|
||||
// Letter is 792 x 612 points; the header rule spans the page between its margins.
|
||||
const usableWidth = (options.orientation === 'landscape' ? 792 : 612) - 2 * margin;
|
||||
return {
|
||||
pageSize: 'LETTER',
|
||||
pageOrientation: options.orientation,
|
||||
pageMargins: [margin, 84, margin, 52],
|
||||
// Named, so the logo is embedded once and not again on every page.
|
||||
images: options.logo ? { logo: options.logo } : {},
|
||||
info: { title: options.title, author: 'ISSSTELEON', creator: 'ISSSTELEON', producer: 'ISSSTELEON' },
|
||||
defaultStyle: { font: 'Roboto', fontSize: 9, color: COLORS.ink },
|
||||
styles: {
|
||||
h1: { fontSize: 15, bold: true, margin: [0, 0, 0, 6] },
|
||||
h2: { fontSize: 11, bold: true, margin: [0, 10, 0, 4] },
|
||||
muted: { color: COLORS.muted },
|
||||
th: { bold: true, fillColor: COLORS.accent, color: COLORS.ink },
|
||||
small: { fontSize: 8, color: COLORS.muted },
|
||||
},
|
||||
header: () => ({
|
||||
margin: [margin, 20, margin, 0],
|
||||
stack: [
|
||||
{
|
||||
columns: [
|
||||
options.logo ? { image: 'logo', width: LOGO_WIDTH } : { text: 'ISSSTELEON', bold: true, fontSize: 14 },
|
||||
{ text: options.title, alignment: 'center', width: '*', bold: true, fontSize: 12, margin: [0, 8, 0, 0] },
|
||||
{ text: '', width: LOGO_WIDTH },
|
||||
],
|
||||
},
|
||||
{ canvas: [{ type: 'line', x1: 0, y1: 8, x2: usableWidth, y2: 8, lineWidth: 1, lineColor: COLORS.accent }] },
|
||||
],
|
||||
}),
|
||||
footer: (currentPage: number, pageCount: number) => ({
|
||||
margin: [margin, 14, margin, 0],
|
||||
columns: [
|
||||
{ text: `Generado: ${formatGenerated(options.now)} (hora de la Ciudad de México)`, style: 'small' },
|
||||
{ text: PDF_CONFIDENTIAL, style: 'small', alignment: 'center' },
|
||||
{ text: `Página ${currentPage} de ${pageCount}`, style: 'small', alignment: 'right' },
|
||||
],
|
||||
}),
|
||||
content,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// pdfmake ships no type declarations; only the calls the export layer makes are declared.
|
||||
declare module 'pdfmake/build/pdfmake' {
|
||||
interface PdfDocumentHandle { getBlob(): Promise<Blob>; getBuffer(): Promise<Uint8Array>; }
|
||||
const pdfMake: { createPdf(definition: unknown): PdfDocumentHandle; addFontContainer(container: unknown): void; setUrlAccessPolicy(policy: (url: string) => boolean): void };
|
||||
export default pdfMake;
|
||||
}
|
||||
|
||||
declare module 'pdfmake/build/fonts/Roboto' {
|
||||
const fontContainer: unknown;
|
||||
export default fontContainer;
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// Covers the export buttons of the follow-up table: when they are enabled, what they ask the service for, the file
|
||||
// they hand to the browser, cancelling and the messages of each failure. Fixture: fixtures/cama_seguimiento.json.
|
||||
// The service is a stub that pages the fixture; the download is observed through the anchor the browser would click.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { Observable, of, Subject } from 'rxjs';
|
||||
import fixtureData from '../fixtures/cama_seguimiento.json';
|
||||
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from '../seguimiento-tabla.service';
|
||||
import { TrackingExportBar } from './tracking-export-bar';
|
||||
|
||||
const base = () => structuredClone(fixtureData) as unknown as Record<string, any>;
|
||||
const respuesta = (extra: Record<string, any> = {}) => seguimientoTablaResponse({ ...base(), ...extra });
|
||||
|
||||
describe('Exportación: botones', () => {
|
||||
let requests: SeguimientoTablaQuery[], downloads: { name: string; blob: Blob }[], answers: (q: SeguimientoTablaQuery) => Observable<SeguimientoTablaResponse>;
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<TrackingExportBar>>;
|
||||
|
||||
beforeEach(() => {
|
||||
requests = []; downloads = [];
|
||||
// Like the API, the stub reports the filters it was asked to apply.
|
||||
answers = q => of(respuesta({ filtros: { ...base()['filtros'], ...q.filtros }, paginacion: { page: q.page, page_size: q.page_size, total_items: 27, total_pages: 1 } }));
|
||||
TestBed.configureTestingModule({
|
||||
providers: [{ provide: SeguimientoTablaService, useValue: { consultar: (_d: string, q: SeguimientoTablaQuery) => { requests.push(q); return answers(q); } } }],
|
||||
});
|
||||
let pending: Blob | undefined;
|
||||
vi.spyOn(URL, 'createObjectURL').mockImplementation(blob => { pending = blob as Blob; return 'blob:test'; });
|
||||
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
|
||||
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { downloads.push({ name: this.download, blob: pending! }); });
|
||||
});
|
||||
afterEach(() => { fixture?.destroy(); vi.restoreAllMocks(); });
|
||||
|
||||
function montar(response = respuesta(), habilitado = true) {
|
||||
fixture = TestBed.createComponent(TrackingExportBar);
|
||||
fixture.componentRef.setInput('dominio', 'cama');
|
||||
fixture.componentRef.setInput('respuesta', response);
|
||||
fixture.componentRef.setInput('habilitado', habilitado);
|
||||
fixture.detectChanges();
|
||||
return fixture.nativeElement as HTMLElement;
|
||||
}
|
||||
const boton = (root: HTMLElement, texto: string) => [...root.querySelectorAll('button')].find(b => b.textContent!.includes(texto)) as HTMLButtonElement | undefined;
|
||||
const esperar = async () => { for (let i = 0; i < 20; i++) { await fixture.whenStable(); await new Promise(r => setTimeout(r, 10)); fixture.detectChanges(); } };
|
||||
|
||||
// Fails if the buttons stop being a bare group (the title row of the table holds them) or bring back their own block.
|
||||
it('has no block of its own: only the buttons, and messages after them', () => {
|
||||
const root = montar();
|
||||
expect(root.querySelector('h3, section')).toBeNull();
|
||||
expect(root.firstElementChild!.classList.contains('actions')).toBe(true);
|
||||
});
|
||||
|
||||
// Fails if the button stops being available for a query that fits the limit.
|
||||
it('enables the spreadsheet export for a query within the limit', () => {
|
||||
expect(boton(montar(), 'Excel')!.disabled).toBe(false);
|
||||
});
|
||||
|
||||
// Fails if the export is allowed above the limit or the reason is not shown: the user would get a silent subset.
|
||||
it('disables the export above the limit and says why', () => {
|
||||
const root = montar(respuesta({ paginacion: { page: 1, page_size: 50, total_items: 5001, total_pages: 101 } }));
|
||||
expect(boton(root, 'Excel')!.disabled).toBe(true);
|
||||
expect(root.textContent).toContain('admite hasta 5,000 registros');
|
||||
expect(root.textContent).toContain('Acota los filtros');
|
||||
});
|
||||
|
||||
// Fails if the PDF is allowed above its own, lower limit, or if hitting it also blocks the spreadsheet.
|
||||
it('limits the PDF to 1,000 rows while the spreadsheet still accepts the query', () => {
|
||||
const root = montar(respuesta({ paginacion: { page: 1, page_size: 50, total_items: 1001, total_pages: 21 } }));
|
||||
expect(boton(root, 'PDF')!.disabled).toBe(true);
|
||||
expect(boton(root, 'Excel')!.disabled).toBe(false);
|
||||
expect(root.textContent).toContain('PDF admite hasta 1,000 registros');
|
||||
});
|
||||
|
||||
// Fails if an empty result offers a file with no rows.
|
||||
it('disables the export when there are no rows', () => {
|
||||
expect(boton(montar(respuesta({ paginacion: { page: 1, page_size: 50, total_items: 0, total_pages: 0 }, items: [] })), 'Excel')!.disabled).toBe(true);
|
||||
});
|
||||
|
||||
// Fails if the export reads a query that is about to be replaced by the one being loaded.
|
||||
it('disables the export while a page is loading', () => {
|
||||
expect(boton(montar(respuesta(), false), 'Excel')!.disabled).toBe(true);
|
||||
});
|
||||
|
||||
// Fails if the file is built from the form instead of the shown answer, or the name carries a patient id.
|
||||
it('exports the shown query in full and downloads a file named without any patient', async () => {
|
||||
const root = montar(respuesta({ filtros: { ...base()['filtros'], estatus: 'BENIGNO' } }));
|
||||
boton(root, 'Excel')!.click();
|
||||
await esperar();
|
||||
expect(requests[0]).toMatchObject({ corte: '2026-10-20', meses: 3, page: 1, page_size: 200, filtros: { estatus: 'BENIGNO' } });
|
||||
expect(downloads).toHaveLength(1);
|
||||
expect(downloads[0].name).toMatch(/^seguimiento-cancer-de-mama_corte-2026-10-20_\d{8}-\d{4}\.xlsx$/);
|
||||
expect(downloads[0].name).not.toMatch(/M-\d/);
|
||||
expect(downloads[0].blob.size).toBeGreaterThan(1000);
|
||||
expect(root.textContent).toContain('Se generó el archivo con 27 registros');
|
||||
});
|
||||
|
||||
// Fails if the success message of one query stays on screen after another query is shown.
|
||||
it('drops the result message when another query is shown, but keeps it while paging', async () => {
|
||||
const root = montar();
|
||||
boton(root, 'Excel')!.click();
|
||||
await esperar();
|
||||
expect(root.textContent).toContain('Se generó el archivo');
|
||||
// Another page of the same query: the message stays.
|
||||
fixture.componentRef.setInput('respuesta', respuesta({ items: [], paginacion: { page: 2, page_size: 10, total_items: 27, total_pages: 3 } }));
|
||||
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(root.textContent).toContain('Se generó el archivo');
|
||||
// Another filter: the message goes.
|
||||
fixture.componentRef.setInput('respuesta', respuesta({ filtros: { ...base()['filtros'], prioridad: 'ALTA' }, paginacion: { page: 1, page_size: 50, total_items: 9, total_pages: 1 } }));
|
||||
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(root.textContent).not.toContain('Se generó el archivo');
|
||||
});
|
||||
|
||||
// Fails if cancelling leaves the export running or still downloads a file afterwards.
|
||||
it('stops and downloads nothing when cancelled', async () => {
|
||||
const never = new Subject<SeguimientoTablaResponse>();
|
||||
answers = () => never;
|
||||
const root = montar();
|
||||
boton(root, 'Excel')!.click();
|
||||
fixture.detectChanges();
|
||||
expect(root.textContent).toContain('Preparando exportación');
|
||||
boton(root, 'Cancelar')!.click();
|
||||
fixture.detectChanges();
|
||||
never.next(respuesta());
|
||||
await esperar();
|
||||
expect(downloads).toEqual([]);
|
||||
expect(boton(root, 'Cancelar')).toBeUndefined();
|
||||
expect(boton(root, 'Excel')!.disabled).toBe(false);
|
||||
});
|
||||
|
||||
// Fails if a failed read is shown as success or leaves the buttons locked.
|
||||
it('shows an error and unlocks the buttons when the service fails', async () => {
|
||||
answers = () => { throw new Error('boom'); };
|
||||
const root = montar();
|
||||
boton(root, 'Excel')!.click();
|
||||
await esperar();
|
||||
expect(root.querySelector('[role="alert"]')!.textContent).toContain('No se pudo generar el archivo');
|
||||
expect(downloads).toEqual([]);
|
||||
expect(boton(root, 'Excel')!.disabled).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
import { Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core';
|
||||
import { DecimalPipe } from '@angular/common';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { Subscription } from 'rxjs';
|
||||
import { Dominio } from '../indicadores.models';
|
||||
import { SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service';
|
||||
import { downloadBlob, exportFilename } from './download-file';
|
||||
import { EXPORT_LIMITS, ExportFormat, ExportInconsistent, ExportLimitExceeded, TrackingSnapshot } from './tracking-export.models';
|
||||
import { fetchAllTracking, queryOf } from './tracking-export-source';
|
||||
|
||||
type State = 'idle' | 'working' | 'error';
|
||||
|
||||
const FORMAT_LABEL: Record<ExportFormat, string> = { xlsx: 'Excel (.xlsx)', pdf: 'PDF' };
|
||||
|
||||
/**
|
||||
* Export buttons of a follow-up list. They export the answer on screen (its cut-off, window and filters) and every
|
||||
* row it matches, not the visible page; a query above a format's limit is refused with a message, never truncated.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-seguimiento-exportar',
|
||||
imports: [DecimalPipe],
|
||||
template: `
|
||||
<div class="actions" role="group" aria-label="Exportar resultados"
|
||||
[attr.title]="'Se exportan los ' + (total() | number) + ' registros de la consulta mostrada, no solo la página visible.'">
|
||||
@for (formato of formatos; track formato) {
|
||||
<button type="button" [disabled]="!available(formato)" (click)="exportar(formato)">Exportar {{ label[formato] }}</button>
|
||||
}
|
||||
@if (estado() === 'working') { <button type="button" (click)="cancelar()">Cancelar</button> }
|
||||
</div>
|
||||
@for (formato of formatos; track formato) {
|
||||
@if (total() > limits[formato]) {
|
||||
<p class="message hint">{{ label[formato] }} admite hasta {{ limits[formato] | number }} registros; la consulta tiene {{ total() | number }}. Acota los filtros para exportar.</p>
|
||||
}
|
||||
}
|
||||
@if (estado() === 'working') { <p class="message" role="status">{{ progressText() }}</p> }
|
||||
@if (estado() === 'error') { <p class="message" role="alert">{{ mensaje() }}</p> }
|
||||
@if (listo()) { <p class="message" role="status">{{ listo() }}</p> }
|
||||
`,
|
||||
// The host takes no box of its own: the buttons sit in the title row that holds it, and each message
|
||||
// takes a full line below that row.
|
||||
styles: `
|
||||
:host { display: contents; }
|
||||
.message { flex: 0 0 100%; margin: 0; }
|
||||
.hint { color: var(--issste-text-secondary); }
|
||||
.actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: .75rem; margin-inline-start: auto; }
|
||||
button { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px;
|
||||
padding: .6rem 1rem; min-height: 44px; box-sizing: border-box; font: inherit; cursor: pointer; }
|
||||
button:disabled { opacity: .5; cursor: default; }
|
||||
button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
`,
|
||||
})
|
||||
export class TrackingExportBar {
|
||||
readonly dominio = input.required<Dominio>();
|
||||
/** The answer on screen: its metadata says which query to export. */
|
||||
readonly respuesta = input.required<SeguimientoTablaResponse>();
|
||||
/** False while a page is being loaded, so the export never reads a query that is about to change. */
|
||||
readonly habilitado = input(true);
|
||||
/** How the analysis named the selection this answer belongs to; it travels into the files. */
|
||||
readonly seleccion = input<string | undefined>(undefined);
|
||||
|
||||
private readonly service = inject(SeguimientoTablaService);
|
||||
private subscription?: Subscription;
|
||||
readonly formatos: readonly ExportFormat[] = ['xlsx', 'pdf'];
|
||||
readonly label = FORMAT_LABEL;
|
||||
readonly limits = EXPORT_LIMITS;
|
||||
readonly estado = signal<State>('idle');
|
||||
readonly mensaje = signal('');
|
||||
readonly listo = signal('');
|
||||
readonly progress = signal({ fetched: 0, total: 0 });
|
||||
readonly total = computed(() => this.respuesta().paginacion.total_items);
|
||||
readonly progressText = computed(() => {
|
||||
const { fetched, total } = this.progress();
|
||||
return total ? `Leyendo registros: ${fetched} de ${total}…` : 'Preparando exportación…';
|
||||
});
|
||||
|
||||
// Identifies the query on screen: paging through its pages keeps it, changing a filter or the cut-off replaces it.
|
||||
private readonly queryKey = computed(() => {
|
||||
const r = this.respuesta();
|
||||
return JSON.stringify([r.corte, r.ventana.meses, r.filtros, r.paginacion.total_items, this.seleccion() ?? null]);
|
||||
});
|
||||
|
||||
constructor() {
|
||||
inject(DestroyRef).onDestroy(() => this.subscription?.unsubscribe());
|
||||
// A result message belongs to the query it was made for: it goes away when another query is shown. An export still
|
||||
// being read belongs to a query that is no longer on screen: it is cancelled, never downloaded as the current one.
|
||||
effect(() => {
|
||||
this.queryKey();
|
||||
untracked(() => {
|
||||
if (this.estado() === 'working') {
|
||||
this.subscription?.unsubscribe();
|
||||
this.estado.set('error'); this.listo.set(''); this.mensaje.set('La consulta cambió; se canceló la exportación. Vuelve a exportar.');
|
||||
} else { this.listo.set(''); this.mensaje.set(''); if (this.estado() === 'error') this.estado.set('idle'); }
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
available(formato: ExportFormat): boolean {
|
||||
return this.habilitado() && this.estado() !== 'working' && this.total() > 0 && this.total() <= EXPORT_LIMITS[formato];
|
||||
}
|
||||
|
||||
exportar(formato: ExportFormat) {
|
||||
if (!this.available(formato)) return;
|
||||
this.estado.set('working'); this.mensaje.set(''); this.listo.set(''); this.progress.set({ fetched: 0, total: 0 });
|
||||
this.subscription?.unsubscribe();
|
||||
const clave = this.queryKey(), seleccion = this.seleccion();
|
||||
this.subscription = fetchAllTracking(this.service, this.dominio(), queryOf(this.respuesta()), EXPORT_LIMITS[formato]).subscribe({
|
||||
next: event => {
|
||||
if (event.kind === 'progress') this.progress.set({ fetched: event.fetched, total: event.total });
|
||||
else void this.generar(formato, seleccion ? { ...event.snapshot, seleccion } : event.snapshot, clave);
|
||||
},
|
||||
error: error => this.fallar(error),
|
||||
});
|
||||
}
|
||||
|
||||
cancelar() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.estado.set('idle');
|
||||
}
|
||||
|
||||
private async generar(formato: ExportFormat, snapshot: TrackingSnapshot, clave: string) {
|
||||
try {
|
||||
// Each generator (and its library) downloads only when its button is used.
|
||||
const blob = formato === 'xlsx'
|
||||
? await (await import('./tracking-xlsx')).buildTrackingXlsx(snapshot)
|
||||
: await (await import('./tracking-pdf')).buildTrackingPdf(snapshot);
|
||||
// The query on screen changed while the file was being made: it is not the one that was asked for.
|
||||
if (clave !== this.queryKey()) return;
|
||||
downloadBlob(blob, exportFilename(snapshot.seleccion ? 'seguimiento-cancer-de-mama-seleccion' : 'seguimiento-cancer-de-mama', snapshot.corte, formato));
|
||||
this.estado.set('idle');
|
||||
this.listo.set(`Se generó el archivo con ${snapshot.items.length} registros.`);
|
||||
} catch {
|
||||
this.fallar(new Error('generation'));
|
||||
}
|
||||
}
|
||||
|
||||
private fallar(error: unknown) {
|
||||
this.estado.set('error');
|
||||
const estatus = error instanceof HttpErrorResponse ? error.status : 0;
|
||||
this.mensaje.set(error instanceof ExportLimitExceeded || estatus === 413 ? 'La consulta excede el límite de este formato. Acota los filtros.'
|
||||
: estatus === 403 ? 'No hay acceso para exportar esta lista, o la selección tiene muy pocos pacientes para publicarse.'
|
||||
: estatus === 409 ? 'La cohorte cambió mientras se leía. Vuelve al análisis, consúltalo de nuevo y exporta otra vez.'
|
||||
: error instanceof ExportInconsistent ? 'La lista cambió mientras se leía. Vuelve a consultar e intenta de nuevo.'
|
||||
: 'No se pudo generar el archivo. Intenta nuevamente.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// Covers the files of a list opened from the analysis: they state the selection, the cut-off and «Toda la cohorte», and
|
||||
// hold exactly the patients the table holds, over several pages; and an export never outlives the query it was made for.
|
||||
// Fixture: fixtures/cama_seguimiento.json, whose rows are repeated to make a list of several pages.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { Observable, of, Subject } from 'rxjs';
|
||||
import { strFromU8, unzipSync } from 'fflate';
|
||||
import fixtureData from '../fixtures/cama_seguimiento.json';
|
||||
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from '../seguimiento-tabla.service';
|
||||
import { TrackingExportBar } from './tracking-export-bar';
|
||||
import { CONTEXTO } from '../indicadores-analisis.testing';
|
||||
import { fetchAllTracking, queryOf } from './tracking-export-source';
|
||||
import { TrackingSnapshot } from './tracking-export.models';
|
||||
import { trackingDocument } from './tracking-pdf';
|
||||
import { buildTrackingXlsx } from './tracking-xlsx';
|
||||
|
||||
const ETIQUETA = 'Cáncer confirmado: Categoría BI-RADS, BI-RADS 5';
|
||||
const base = () => structuredClone(fixtureData) as unknown as Record<string, any>;
|
||||
// A cohort of `n` patients, M-0001 onwards, served in the pages that were asked for, with the filters it applied.
|
||||
function cohorte(n: number) {
|
||||
const plantilla = (base()['items'] as Record<string, unknown>[])[0];
|
||||
const todos = Array.from({ length: n }, (_, i) => ({ ...plantilla, id_seudonimo: `M-${String(i + 1).padStart(4, '0')}` }));
|
||||
return (q: SeguimientoTablaQuery): SeguimientoTablaResponse => seguimientoTablaResponse({
|
||||
...base(), ventana: { meses: q.meses, desde: '2025-01-01', hasta: '2026-10-20' }, corte: q.corte ?? '2026-10-20',
|
||||
filtros: { ...base()['filtros'], ...q.filtros }, ...(q.contexto ?? {}),
|
||||
paginacion: { page: q.page, page_size: q.page_size, total_items: n, total_pages: Math.ceil(n / q.page_size) },
|
||||
items: todos.slice((q.page - 1) * q.page_size, q.page * q.page_size),
|
||||
});
|
||||
}
|
||||
const consulta = (extra: Partial<SeguimientoTablaQuery> = {}): SeguimientoTablaQuery =>
|
||||
({ corte: '2026-10-20', meses: 0, page: 1, page_size: 50, filtros: { birads: 'BIRADS_5' }, contexto: CONTEXTO, ...extra });
|
||||
const textos = (nodo: unknown, salida: string[] = []): string[] => {
|
||||
if (typeof nodo === 'string') salida.push(nodo); else if (Array.isArray(nodo)) nodo.forEach(n => textos(n, salida)); else if (nodo && typeof nodo === 'object') Object.values(nodo).forEach(n => textos(n, salida));
|
||||
return salida;
|
||||
};
|
||||
|
||||
describe('Archivos de una selección del análisis', () => {
|
||||
const servicio = { consultar: (_d: string, q: SeguimientoTablaQuery) => of(cohorte(450)(q)) } as unknown as SeguimientoTablaService;
|
||||
|
||||
it('el PDF y el XLSX dicen la selección, el corte y «Toda la cohorte», y traen los mismos pacientes que la tabla en todas sus páginas', async () => {
|
||||
// Fails if a file loses the selection, calls the whole cohort «0 meses», or its patients differ from the table's pages.
|
||||
const q = consulta();
|
||||
// The table, page by page (50 per page), as the user would walk it.
|
||||
const filasTabla: string[] = [];
|
||||
for (let p = 1; p <= 9; p++) filasTabla.push(...cohorte(450)({ ...q, page: p }).items.map(i => String(i['id_seudonimo'])));
|
||||
let snapshot!: TrackingSnapshot;
|
||||
await new Promise<void>((ok, fallo) => fetchAllTracking(servicio, 'cama', { ...q, page_size: 200 }, 1000).subscribe({
|
||||
next: e => { if (e.kind === 'done') snapshot = { ...e.snapshot, seleccion: ETIQUETA }; }, error: fallo, complete: ok }));
|
||||
expect(snapshot.items.map(i => String(i['id_seudonimo']))).toEqual(filasTabla);
|
||||
expect(new Set(filasTabla).size).toBe(450);
|
||||
|
||||
const pdf = textos(trackingDocument(snapshot, new Date(Date.UTC(2026, 10, 13, 18, 0)), 'data:image/png;base64,AAAA'));
|
||||
expect(pdf).toContain('Selección del análisis'); expect(pdf).toContain(ETIQUETA);
|
||||
expect(pdf).toContain('Fecha de corte'); expect(pdf).toContain('2026-10-20');
|
||||
expect(pdf).toContain('Toda la cohorte, al 2026-10-20');
|
||||
expect(pdf.some(t => /0 meses/.test(t))).toBe(false);
|
||||
expect(pdf.filter(t => /^M-\d{4}$/.test(t))).toEqual(filasTabla);
|
||||
const PROHIBIDO = /simulad|sint[eé]tic|entorno|\bdev\b|prueba|demostraci|ficticio|mock|valor cl[ií]nico/i;
|
||||
expect(pdf.filter(t => PROHIBIDO.test(t))).toEqual([]);
|
||||
|
||||
const hojas = unzipSync(new Uint8Array(await (await buildTrackingXlsx(snapshot, new Date(Date.UTC(2026, 10, 13, 18, 0)))).arrayBuffer()));
|
||||
const cadenas = strFromU8(hojas['xl/sharedStrings.xml']);
|
||||
expect(cadenas).toContain(ETIQUETA); expect(cadenas).toContain('Selección del análisis'); expect(cadenas).toContain('Toda la cohorte, al 2026-10-20');
|
||||
expect(cadenas).not.toMatch(/0 meses/);
|
||||
expect(cadenas.replace(/<[^>]+>/g, ' ')).not.toMatch(PROHIBIDO);
|
||||
expect([...cadenas.matchAll(/M-\d{4}/g)].map(m => m[0]).filter((v, i, a) => a.indexOf(v) === i)).toEqual(filasTabla);
|
||||
});
|
||||
it('sin una selección los archivos no llevan esa línea y conservan la ventana de meses', async () => {
|
||||
// Fails if a plain list gets a selection line, or a window of months stops being written as dates and months.
|
||||
const q = consulta({ meses: 3, filtros: {} });
|
||||
let snapshot!: TrackingSnapshot;
|
||||
await new Promise<void>((ok, fallo) => fetchAllTracking(servicio, 'cama', { ...q, page_size: 200 }, 1000).subscribe({ next: e => { if (e.kind === 'done') snapshot = e.snapshot; }, error: fallo, complete: ok }));
|
||||
const pdf = textos(trackingDocument(snapshot, new Date(), 'data:image/png;base64,AAAA'));
|
||||
expect(pdf).not.toContain('Selección del análisis');
|
||||
expect(pdf).toContain('2025-01-01 al 2026-10-20 (3 meses)');
|
||||
});
|
||||
it('la consulta de una respuesta conserva la cohorte y su revisión, y todas las páginas del archivo la citan', async () => {
|
||||
// Fails if the export reads a cohort's list without quoting its revision (the server refuses it) or from another one.
|
||||
const respuesta = cohorte(450)(consulta());
|
||||
expect(queryOf(respuesta)).toMatchObject({ corte: '2026-10-20', meses: 0, page: 1, page_size: 200, filtros: { birads: 'BIRADS_5' }, contexto: CONTEXTO });
|
||||
const pedidas: SeguimientoTablaQuery[] = [];
|
||||
const espia = { consultar: (_d: string, q: SeguimientoTablaQuery) => { pedidas.push(q); return of(cohorte(450)(q)); } } as unknown as SeguimientoTablaService;
|
||||
await new Promise<void>((ok, fallo) => fetchAllTracking(espia, 'cama', queryOf(respuesta), 1000).subscribe({ error: fallo, complete: ok }));
|
||||
expect(pedidas.map(q => q.page).sort()).toEqual([1, 2, 3]);
|
||||
expect(pedidas.every(q => q.contexto?.revision === CONTEXTO.revision && q.contexto?.cohorte === CONTEXTO.cohorte && q.meses === 0)).toBe(true);
|
||||
// A plain list quotes no cohort.
|
||||
expect(queryOf(seguimientoTablaResponse(base())).contexto).toBeUndefined();
|
||||
});
|
||||
it('una página posterior de otra revisión hace fallar la lectura', async () => {
|
||||
// Fails if a file mixes pages of two revisions of the cohort.
|
||||
const respuestas = (q: SeguimientoTablaQuery) => of(q.page === 2 ? cohorte(450)({ ...q, contexto: { ...CONTEXTO, revision: 'f'.repeat(64) } }) : cohorte(450)(q));
|
||||
const malo = { consultar: (_d: string, q: SeguimientoTablaQuery) => respuestas(q) } as unknown as SeguimientoTablaService;
|
||||
const error = await new Promise<unknown>(ok => fetchAllTracking(malo, 'cama', { ...consulta(), page_size: 200 }, 1000).subscribe({ error: ok, complete: () => ok(undefined) }));
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
});
|
||||
it('una página posterior que pierde un filtro hace fallar la lectura: no se exporta un subconjunto de otra consulta', async () => {
|
||||
// Fails if a file mixes the pages of the selection with a page of another population.
|
||||
const respuestas = (q: SeguimientoTablaQuery) => of(q.page === 2 ? cohorte(450)({ ...q, filtros: {} }) : cohorte(450)(q));
|
||||
const malo = { consultar: (_d: string, q: SeguimientoTablaQuery) => respuestas(q) } as unknown as SeguimientoTablaService;
|
||||
const error = await new Promise<unknown>(ok => fetchAllTracking(malo, 'cama', { ...consulta(), page_size: 200 }, 1000).subscribe({ error: ok, complete: () => ok(undefined) }));
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Exportación: la consulta cambia mientras se exporta', () => {
|
||||
let respuestas: (q: SeguimientoTablaQuery) => Observable<SeguimientoTablaResponse>, descargas: string[];
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<TrackingExportBar>>;
|
||||
beforeEach(() => {
|
||||
descargas = [];
|
||||
respuestas = q => of(cohorte(27)(q));
|
||||
TestBed.configureTestingModule({ providers: [{ provide: SeguimientoTablaService, useValue: { consultar: (_d: string, q: SeguimientoTablaQuery) => respuestas(q) } }] });
|
||||
vi.spyOn(URL, 'createObjectURL').mockImplementation(() => 'blob:test');
|
||||
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
|
||||
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { descargas.push(this.download); });
|
||||
});
|
||||
afterEach(() => { fixture?.destroy(); vi.restoreAllMocks(); });
|
||||
const montar = (r: SeguimientoTablaResponse, seleccion?: string) => {
|
||||
fixture = TestBed.createComponent(TrackingExportBar);
|
||||
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('respuesta', r);
|
||||
fixture.componentRef.setInput('seleccion', seleccion); fixture.detectChanges();
|
||||
return fixture.nativeElement as HTMLElement;
|
||||
};
|
||||
const excel = (root: HTMLElement) => [...root.querySelectorAll('button')].find(b => b.textContent!.includes('Excel')) as HTMLButtonElement;
|
||||
const esperar = async () => { for (let i = 0; i < 20; i++) { await fixture.whenStable(); await new Promise(r => setTimeout(r, 10)); fixture.detectChanges(); } };
|
||||
|
||||
it('un archivo de una selección se llama como tal y no lleva a ningún paciente en el nombre', async () => {
|
||||
// Fails if the file of a selection is told apart from a plain list by nothing, or names a patient.
|
||||
const root = montar(cohorte(27)(consulta()), ETIQUETA);
|
||||
excel(root).click(); await esperar();
|
||||
expect(descargas).toHaveLength(1);
|
||||
expect(descargas[0]).toMatch(/^seguimiento-cancer-de-mama-seleccion_corte-2026-10-20_\d{8}-\d{4}\.xlsx$/);
|
||||
expect(descargas[0]).not.toMatch(/M-\d|cama/i);
|
||||
});
|
||||
it('si la consulta en pantalla cambia mientras se lee, se cancela y no se descarga nada', async () => {
|
||||
// Fails if a list read for the old selection is downloaded as the one now on screen.
|
||||
const lenta = new Subject<SeguimientoTablaResponse>();
|
||||
respuestas = () => lenta;
|
||||
const root = montar(cohorte(27)(consulta()), ETIQUETA);
|
||||
excel(root).click(); fixture.detectChanges();
|
||||
expect(root.textContent).toContain('Preparando exportación');
|
||||
fixture.componentRef.setInput('respuesta', cohorte(27)(consulta({ filtros: { birads: 'BIRADS_6' } })));
|
||||
fixture.componentRef.setInput('seleccion', 'Cáncer confirmado: Categoría BI-RADS, BI-RADS 6'); fixture.detectChanges();
|
||||
lenta.next(cohorte(27)(consulta()));
|
||||
await esperar();
|
||||
expect(descargas).toEqual([]);
|
||||
expect(root.querySelector('[role=alert]')?.textContent).toContain('La consulta cambió; se canceló la exportación');
|
||||
expect(excel(root).disabled).toBe(false);
|
||||
});
|
||||
it('si cambia mientras se genera el archivo, tampoco se descarga', async () => {
|
||||
// Fails if a file finished after the selection changed still reaches the downloads.
|
||||
const root = montar(cohorte(27)(consulta()), ETIQUETA);
|
||||
excel(root).click();
|
||||
fixture.componentRef.setInput('seleccion', 'Cáncer confirmado: Categoría BI-RADS, BI-RADS 6'); fixture.detectChanges();
|
||||
await esperar();
|
||||
expect(descargas).toEqual([]);
|
||||
expect(root.querySelector('[role=alert]')?.textContent).toContain('La consulta cambió');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
// Covers the layer that reads every row of a follow-up query: the page size it asks for, the cut-off and filters it
|
||||
// keeps, the limit that refuses instead of truncating, the checks that the pages form one list, and cancellation.
|
||||
// Fixture: fixtures/cama_seguimiento.json (27 synthetic rows). `servidor` pages it like the API does and counts
|
||||
// the requests it receives.
|
||||
import { Observable, of, Subject, toArray, lastValueFrom } from 'rxjs';
|
||||
import fixtureData from '../fixtures/cama_seguimiento.json';
|
||||
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from '../seguimiento-tabla.service';
|
||||
import { ExportInconsistent, ExportLimitExceeded, TrackingExportEvent } from './tracking-export.models';
|
||||
import { fetchAllTracking, queryOf } from './tracking-export-source';
|
||||
|
||||
const base = () => structuredClone(fixtureData) as unknown as Record<string, any>;
|
||||
const TOTAL = (base()['items'] as unknown[]).length;
|
||||
|
||||
// A server that pages the fixture. `tweak` can alter the answer of a page to simulate a list that changes, and
|
||||
// `size` makes it serve smaller pages than asked for, so that 27 rows span several pages.
|
||||
function servidor(tweak: (page: number, answer: Record<string, any>) => Record<string, any> = (_, a) => a, size?: number) {
|
||||
const requests: SeguimientoTablaQuery[] = [];
|
||||
const service = {
|
||||
consultar(_dominio: string, q: SeguimientoTablaQuery): Observable<SeguimientoTablaResponse> {
|
||||
requests.push(q);
|
||||
const d = base(), all = d['items'] as unknown[], tam = size ?? q.page_size;
|
||||
d['items'] = all.slice((q.page - 1) * tam, q.page * tam);
|
||||
d['paginacion'] = { page: q.page, page_size: tam, total_items: all.length, total_pages: Math.max(1, Math.ceil(all.length / tam)) };
|
||||
d['corte'] = q.corte ?? d['corte'];
|
||||
d['ventana'] = { ...d['ventana'], meses: q.meses };
|
||||
d['filtros'] = { ...d['filtros'], ...q.filtros };
|
||||
return of(seguimientoTablaResponse(tweak(q.page, d)));
|
||||
},
|
||||
};
|
||||
return { service: service as unknown as SeguimientoTablaService, requests };
|
||||
}
|
||||
const consulta: SeguimientoTablaQuery = { corte: '2026-10-20', meses: 3, page: 1, page_size: 5, filtros: { estatus: 'BENIGNO' } };
|
||||
const eventos = (obs: Observable<TrackingExportEvent>) => lastValueFrom(obs.pipe(toArray()));
|
||||
|
||||
describe('Exportación: lectura completa del seguimiento', () => {
|
||||
// Fails if the layer asks for the page size the user was looking at instead of the largest one, or loses a row.
|
||||
it('reads every row in pages of 200 and returns them in the server order, whatever page the user was on', async () => {
|
||||
const { service, requests } = servidor();
|
||||
const out = await eventos(fetchAllTracking(service, 'cama', { ...consulta, page: 3 }, 5000));
|
||||
const done = out.at(-1)!;
|
||||
expect(done.kind).toBe('done');
|
||||
if (done.kind !== 'done') return;
|
||||
expect(done.snapshot.items).toHaveLength(TOTAL);
|
||||
expect(done.snapshot.items.map(i => i['id_seudonimo'])).toEqual((base()['items'] as Record<string, any>[]).map(i => i['id_seudonimo']));
|
||||
expect(requests.map(r => r.page_size)).toEqual([200]);
|
||||
});
|
||||
|
||||
// Fails if later pages are asked without the first answer's cut-off and filters, which would mix two lists.
|
||||
it('keeps the cut-off, window and filters of the shown query in every request', async () => {
|
||||
const { service, requests } = servidor(undefined, 10);
|
||||
await eventos(fetchAllTracking(service, 'cama', consulta, 5000));
|
||||
expect(requests).toHaveLength(3);
|
||||
for (const r of requests) expect(r).toMatchObject({ corte: '2026-10-20', meses: 3, filtros: { estatus: 'BENIGNO' } });
|
||||
});
|
||||
|
||||
// Fails if progress stops being reported or does not end at the announced total.
|
||||
it('reports progress up to the announced total and then the finished snapshot', async () => {
|
||||
const { service } = servidor();
|
||||
const out = await eventos(fetchAllTracking(service, 'cama', consulta, 5000));
|
||||
expect(out[0]).toEqual({ kind: 'progress', fetched: TOTAL, total: TOTAL });
|
||||
expect(out.at(-1)!.kind).toBe('done');
|
||||
});
|
||||
|
||||
// Fails if a query above the limit starts downloading pages, or if it returns a subset without saying so.
|
||||
it('refuses a query above the limit before asking for more pages and never returns a subset', async () => {
|
||||
const { service, requests } = servidor();
|
||||
await expect(eventos(fetchAllTracking(service, 'cama', consulta, TOTAL - 1))).rejects.toBeInstanceOf(ExportLimitExceeded);
|
||||
expect(requests).toHaveLength(1);
|
||||
});
|
||||
|
||||
// Fails if the limit becomes exclusive: a list of exactly the limit must still be exported.
|
||||
it('accepts a query that is exactly at the limit', async () => {
|
||||
const { service } = servidor();
|
||||
const out = await eventos(fetchAllTracking(service, 'cama', consulta, TOTAL));
|
||||
expect(out.at(-1)!.kind).toBe('done');
|
||||
});
|
||||
|
||||
// Fails if an answer that did not apply the asked filter is accepted: the file would list other patients.
|
||||
it('fails when the server does not report the filters that were asked for', async () => {
|
||||
const { service } = servidor((_page, a) => ({ ...a, filtros: { ...a['filtros'], estatus: null } }));
|
||||
await expect(eventos(fetchAllTracking(service, 'cama', consulta, 5000))).rejects.toBeInstanceOf(ExportInconsistent);
|
||||
});
|
||||
|
||||
// Fails if a total that changes between pages is accepted: the file would mix two states of the list.
|
||||
it('fails when the total changes between pages', async () => {
|
||||
const { service } = servidor((page, a) => page === 1 ? a : { ...a, paginacion: { ...a['paginacion'], total_items: TOTAL + 1 } }, 10);
|
||||
await expect(eventos(fetchAllTracking(service, 'cama', consulta, 5000))).rejects.toBeInstanceOf(ExportInconsistent);
|
||||
});
|
||||
|
||||
// Fails if a repeated row (the same id on two pages) is accepted as if it were two patients.
|
||||
it('fails when a row repeats across pages', async () => {
|
||||
const { service } = servidor((page, a) => page === 1 ? a : { ...a, items: [(base()['items'] as unknown[])[0]] }, 10);
|
||||
await expect(eventos(fetchAllTracking(service, 'cama', consulta, 5000))).rejects.toBeInstanceOf(ExportInconsistent);
|
||||
});
|
||||
|
||||
// Fails if cancelling (unsubscribing) leaves requests pending or still emits events afterwards.
|
||||
it('stops asking when the subscriber cancels', () => {
|
||||
const first = new Subject<SeguimientoTablaResponse>();
|
||||
const requests: SeguimientoTablaQuery[] = [];
|
||||
const service = { consultar: (_d: string, q: SeguimientoTablaQuery) => { requests.push(q); return first; } } as unknown as SeguimientoTablaService;
|
||||
const seen: TrackingExportEvent[] = [];
|
||||
const subscription = fetchAllTracking(service, 'cama', consulta, 5000).subscribe(e => seen.push(e));
|
||||
subscription.unsubscribe();
|
||||
first.next(seguimientoTablaResponse(base()));
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(seen).toEqual([]);
|
||||
});
|
||||
|
||||
// Fails if an invalid query reaches the network instead of failing inside the stream.
|
||||
it('turns an invalid query into an error of the stream', async () => {
|
||||
const real = { consultar: (_d: string, _q: SeguimientoTablaQuery) => { throw new Error('invalid'); } } as unknown as SeguimientoTablaService;
|
||||
await expect(eventos(fetchAllTracking(real, 'cama', consulta, 5000))).rejects.toThrow('invalid');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Exportación: consulta de una respuesta', () => {
|
||||
// Fails if the export is built from the form being edited instead of what the shown answer says it applied.
|
||||
it('rebuilds the query from the answer: cut-off, window months and only the filters that were applied', () => {
|
||||
const answer = seguimientoTablaResponse({ ...base(), filtros: { estatus: 'BENIGNO', birads: null, grupo_edad: null, prioridad: null } });
|
||||
expect(queryOf(answer)).toEqual({ corte: answer.corte, meses: answer.ventana.meses, page: 1, page_size: 200, filtros: { estatus: 'BENIGNO' } });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import { concatWith, defer, from, map, mergeMap, Observable, of, startWith, switchMap, tap } from 'rxjs';
|
||||
import { Dominio } from '../indicadores.models';
|
||||
import { identidadesDe } from '../paciente-identidad';
|
||||
import { consultaAplicada, contextoDe, PAGE_SIZE_MAX, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service';
|
||||
import { ExportInconsistent, ExportLimitExceeded, TrackingExportEvent, TrackingRow } from './tracking-export.models';
|
||||
|
||||
const CONCURRENCY = 3;
|
||||
|
||||
/** The query that produced a shown answer: its cut-off, window and the filters the server applied. */
|
||||
export function queryOf(response: SeguimientoTablaResponse): SeguimientoTablaQuery {
|
||||
return {
|
||||
corte: response.corte,
|
||||
meses: response.ventana.meses,
|
||||
page: 1,
|
||||
page_size: PAGE_SIZE_MAX,
|
||||
filtros: Object.fromEntries(Object.entries(response.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])),
|
||||
// A cohort's list is exported as that cohort, at the revision it was read at: another revision is refused by the server.
|
||||
contexto: contextoDe(response),
|
||||
};
|
||||
}
|
||||
|
||||
// The server must report having applied the window and the filters that were asked for; otherwise the file would
|
||||
// hold rows of another query under the title of this one.
|
||||
const sameQuery = consultaAplicada;
|
||||
|
||||
/**
|
||||
* Reads every row a follow-up query matches, page by page, with the cut-off fixed by the first answer.
|
||||
* Unsubscribing cancels the pending requests. It fails instead of returning a partial or unstable list.
|
||||
*/
|
||||
export function fetchAllTracking(service: SeguimientoTablaService, dominio: Dominio, query: SeguimientoTablaQuery, limit: number): Observable<TrackingExportEvent> {
|
||||
const ask = (q: SeguimientoTablaQuery) => defer(() => service.consultar(dominio, q));
|
||||
return ask({ ...query, page: 1, page_size: PAGE_SIZE_MAX }).pipe(
|
||||
switchMap(first => {
|
||||
const { total_items: total, total_pages: pages } = first.paginacion;
|
||||
if (!sameQuery(query, first)) throw new ExportInconsistent('The answer does not apply the query that was asked');
|
||||
if (total > limit) throw new ExportLimitExceeded(total, limit);
|
||||
// The rest of the pages are asked for exactly what the first one was, with the cut-off it answered.
|
||||
const pinned = { ...query, corte: first.corte, page_size: PAGE_SIZE_MAX };
|
||||
const collected = new Map<number, TrackingRow[]>([[1, first.items]]);
|
||||
const count = () => [...collected.values()].reduce((sum, rows) => sum + rows.length, 0);
|
||||
const rest = from(Array.from({ length: Math.max(0, pages - 1) }, (_, i) => i + 2)).pipe(
|
||||
mergeMap(page => ask({ ...pinned, page }).pipe(map(answer => ({ page, answer }))), CONCURRENCY),
|
||||
tap(({ page, answer }) => {
|
||||
if (answer.paginacion.page !== page || answer.paginacion.total_items !== total || answer.paginacion.total_pages !== pages
|
||||
|| answer.corte !== first.corte || !sameQuery(pinned, answer)) throw new ExportInconsistent('The list changed while it was being read');
|
||||
collected.set(page, answer.items);
|
||||
}),
|
||||
map((): TrackingExportEvent => ({ kind: 'progress', fetched: count(), total })),
|
||||
);
|
||||
return rest.pipe(
|
||||
startWith<TrackingExportEvent>({ kind: 'progress', fetched: first.items.length, total }),
|
||||
concatWith(defer(() => {
|
||||
const items = [...collected.entries()].sort(([a], [b]) => a - b).flatMap(([, rows]) => rows);
|
||||
// Every row has the identity the table shows, and no patient (or episode) appears on two pages.
|
||||
if (items.length !== total || !identidadesDe(items)) throw new ExportInconsistent('The pages do not add up to the announced total');
|
||||
return of<TrackingExportEvent>({
|
||||
kind: 'done',
|
||||
snapshot: { corte: first.corte, ventana: first.ventana, filtros: first.filtros, filtros_disponibles: first.filtros_disponibles, columnas: first.columnas, items },
|
||||
});
|
||||
})),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// Covers how a follow-up snapshot becomes table cells (shared by the spreadsheet and the PDF), the formula
|
||||
// neutraliser and the file name policy. Fixture: fixtures/cama_seguimiento.json.
|
||||
import fixtureData from '../fixtures/cama_seguimiento.json';
|
||||
import { seguimientoTablaResponse } from '../seguimiento-tabla.service';
|
||||
import { neutralizeFormula } from './cell-sanitizer';
|
||||
import { exportFilename } from './download-file';
|
||||
import { displayText, exportColumns, flatTable, UNAVAILABLE } from './tracking-export-table';
|
||||
import { TrackingSnapshot } from './tracking-export.models';
|
||||
|
||||
function snapshot(): TrackingSnapshot {
|
||||
const r = seguimientoTablaResponse(structuredClone(fixtureData));
|
||||
return { corte: r.corte, ventana: r.ventana, filtros: r.filtros, filtros_disponibles: r.filtros_disponibles, columnas: r.columnas, items: r.items };
|
||||
}
|
||||
|
||||
describe('Exportación: tabla plana', () => {
|
||||
// Fails if a detail column is dropped or reordered: the spreadsheet would lose the date next to its value.
|
||||
it('places each detail after its value, labelled with its column', () => {
|
||||
const { columns } = flatTable(snapshot());
|
||||
expect(columns.map(c => c.key)).toEqual(['id_seudonimo', 'grupo_edad', 'estatus', 'birads', 'mastografia_fecha', 'biopsia', 'biopsia_fecha', 'dias_mastografia_diagnostico', 'prioridad']);
|
||||
expect(columns.find(c => c.key === 'mastografia_fecha')!.label).toBe('Última mastografía: Fecha');
|
||||
});
|
||||
|
||||
// Fails if a number is exported as text (it could not be summed or sorted) or a text column as a number.
|
||||
it('marks as numeric only the columns whose present values are all numbers', () => {
|
||||
const { columns } = flatTable(snapshot());
|
||||
expect(columns.filter(c => c.numeric).map(c => c.key)).toEqual(['dias_mastografia_diagnostico']);
|
||||
});
|
||||
|
||||
// Fails if a missing value is invented (0, '') instead of kept as null, which would pass as clinical data.
|
||||
it('keeps a missing value as null and the rows in the snapshot order', () => {
|
||||
const s = snapshot();
|
||||
const { columns, rows } = flatTable(s);
|
||||
const at = columns.findIndex(c => c.key === 'biopsia');
|
||||
expect(rows).toHaveLength(s.items.length);
|
||||
expect(rows.map(r => r[0])).toEqual(s.items.map(i => i['id_seudonimo']));
|
||||
expect(rows.some(r => r[at] === null)).toBe(true);
|
||||
});
|
||||
|
||||
// Fails if the document and the screen stop agreeing on how a missing value reads.
|
||||
it('reads a missing value as the table does', () => {
|
||||
expect(displayText(null)).toBe(UNAVAILABLE);
|
||||
expect(displayText(undefined)).toBe(UNAVAILABLE);
|
||||
expect(displayText(12)).toBe('12');
|
||||
expect(exportColumns(snapshot()).find(c => c.key === 'birads')!.details).toEqual([{ key: 'mastografia_fecha', label: 'Fecha' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Exportación: texto de celdas y nombres de archivo', () => {
|
||||
// Fails if a value that starts like a formula is written as is: opening the file could run it.
|
||||
it.each(['=1+1', '+SUM(A1)', '-2+3', '@cmd', '\tx', '\rx'])('neutralises %j', text => {
|
||||
expect(neutralizeFormula(text)).toBe(`'${text}`);
|
||||
});
|
||||
|
||||
// Fails if ordinary labels are altered by the neutraliser.
|
||||
it('leaves ordinary text untouched', () => {
|
||||
for (const text of ['Pendiente de biopsia', 'BI-RADS 4A', '2026-10-20', '']) expect(neutralizeFormula(text)).toBe(text);
|
||||
});
|
||||
|
||||
// Fails if a file name carries a patient identifier or characters that are unsafe in a path.
|
||||
it('names files after the report and the cut-off, never a patient', () => {
|
||||
const name = exportFilename('seguimiento-cancer-de-mama', '2026-10-20', 'xlsx', new Date(2026, 10, 12, 15, 30));
|
||||
expect(name).toBe('seguimiento-cancer-de-mama_corte-2026-10-20_20261112-1530.xlsx');
|
||||
expect(exportFilename('ficha-cancer-de-mama', '../2026-10-20', 'pdf', new Date(2026, 0, 2, 3, 4))).toBe('ficha-cancer-de-mama_corte-2026-10-20_20260102-0304.pdf');
|
||||
expect(name).not.toMatch(/M-\d+/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { SeguimientoValor } from '../seguimiento-tabla.service';
|
||||
import { TrackingSnapshot } from './tracking-export.models';
|
||||
|
||||
export const UNAVAILABLE = 'No disponible';
|
||||
|
||||
/** A column as the follow-up table shows it: the value and, under it, its labelled details. */
|
||||
export interface ExportColumn { key: string; label: string; details: { key: string; label: string }[]; }
|
||||
|
||||
/** One flat column of a spreadsheet; a detail becomes a column of its own so it can be filtered and sorted. */
|
||||
export interface FlatColumn { key: string; label: string; numeric: boolean; }
|
||||
|
||||
export interface FlatTable { columns: FlatColumn[]; rows: SeguimientoValor[][]; }
|
||||
|
||||
/** The columns the answer announced, in its order. */
|
||||
export function exportColumns(snapshot: TrackingSnapshot): ExportColumn[] {
|
||||
return snapshot.columnas.map(c => ({ key: c.clave, label: c.etiqueta, details: (c.detalles ?? []).map(d => ({ key: d.clave, label: d.etiqueta })) }));
|
||||
}
|
||||
|
||||
/** Text of a value as the table shows it, `null` included. */
|
||||
export function displayText(value: SeguimientoValor | undefined): string {
|
||||
return value === null || value === undefined ? UNAVAILABLE : String(value);
|
||||
}
|
||||
|
||||
/** Every detail after its value, with a column numeric only when each present value is a number. */
|
||||
export function flatTable(snapshot: TrackingSnapshot): FlatTable {
|
||||
const columns: FlatColumn[] = [];
|
||||
for (const column of exportColumns(snapshot)) {
|
||||
columns.push({ key: column.key, label: column.label, numeric: false });
|
||||
for (const detail of column.details) columns.push({ key: detail.key, label: `${column.label}: ${detail.label}`, numeric: false });
|
||||
}
|
||||
for (const column of columns) {
|
||||
const present = snapshot.items.map(item => item[column.key]).filter(v => v !== null && v !== undefined);
|
||||
column.numeric = present.length > 0 && present.every(v => typeof v === 'number');
|
||||
}
|
||||
return { columns, rows: snapshot.items.map(item => columns.map(column => item[column.key] ?? null)) };
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { etiquetaVentana, SeguimientoTablaResponse, SeguimientoValor } from '../seguimiento-tabla.service';
|
||||
|
||||
/** Largest number of rows each format accepts. A query above the limit is refused, never truncated. */
|
||||
export const EXPORT_LIMITS = { xlsx: 5000, pdf: 1000 } as const;
|
||||
export type ExportFormat = keyof typeof EXPORT_LIMITS;
|
||||
|
||||
export type TrackingRow = Record<string, SeguimientoValor>;
|
||||
|
||||
/** Everything one export needs: the first answer (columns, filters, window) and all the rows it announced. */
|
||||
export interface TrackingSnapshot {
|
||||
/** How the analysis named the selection this list opens, when it does; the files carry it so they say where they come from. */
|
||||
seleccion?: string;
|
||||
corte: string;
|
||||
ventana: SeguimientoTablaResponse['ventana'];
|
||||
filtros: SeguimientoTablaResponse['filtros'];
|
||||
filtros_disponibles: SeguimientoTablaResponse['filtros_disponibles'];
|
||||
columnas: SeguimientoTablaResponse['columnas'];
|
||||
items: TrackingRow[];
|
||||
}
|
||||
|
||||
/** The window as the files state it: the whole cohort up to the cut-off, or the dates and months of the window. */
|
||||
export function ventanaConsultada(snapshot: Pick<TrackingSnapshot, 'ventana'>): string {
|
||||
const { meses, desde, hasta } = snapshot.ventana;
|
||||
return meses === 0 ? `Toda la cohorte, al ${hasta}` : `${desde} al ${hasta} (${etiquetaVentana(meses)})`;
|
||||
}
|
||||
|
||||
export type TrackingExportEvent =
|
||||
| { kind: 'progress'; fetched: number; total: number }
|
||||
| { kind: 'done'; snapshot: TrackingSnapshot };
|
||||
|
||||
export class ExportLimitExceeded extends Error {
|
||||
constructor(readonly total: number, readonly limit: number) {
|
||||
super(`The query has ${total} rows and the limit is ${limit}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** The pages did not describe one stable list (the total changed, a page repeated or a row was lost). */
|
||||
export class ExportInconsistent extends Error {}
|
||||
@@ -0,0 +1,112 @@
|
||||
// Covers the follow-up PDF: the institutional frame (logo, title, footer), the parameters it
|
||||
// prints, the table that repeats its header across pages, and that the document really renders to a PDF file.
|
||||
// Fixture: fixtures/cama_seguimiento.json. The logo is a 1x1 PNG data URL; the real logo is read in the browser.
|
||||
import fixtureData from '../fixtures/cama_seguimiento.json';
|
||||
import { seguimientoTablaResponse } from '../seguimiento-tabla.service';
|
||||
import { COLORS, PDF_CONFIDENTIAL } from './pdf-template';
|
||||
import { buildTrackingPdf, trackingDocument } from './tracking-pdf';
|
||||
import { TrackingSnapshot } from './tracking-export.models';
|
||||
|
||||
const PIXEL = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
|
||||
const NOW = new Date(Date.UTC(2026, 10, 12, 21, 30));
|
||||
|
||||
function snapshot(mutate: (s: TrackingSnapshot) => void = () => undefined): TrackingSnapshot {
|
||||
const r = seguimientoTablaResponse(structuredClone(fixtureData));
|
||||
const s: TrackingSnapshot = { corte: r.corte, ventana: r.ventana, filtros: { ...r.filtros, prioridad: 'ALTA' }, filtros_disponibles: r.filtros_disponibles, columnas: r.columnas, items: r.items };
|
||||
mutate(s);
|
||||
return s;
|
||||
}
|
||||
// Every string of a nested document definition, to look for text without depending on its structure.
|
||||
function texts(node: unknown, out: string[] = []): string[] {
|
||||
if (typeof node === 'string') out.push(node);
|
||||
else if (Array.isArray(node)) node.forEach(n => texts(n, out));
|
||||
else if (node && typeof node === 'object') Object.values(node).forEach(n => texts(n, out));
|
||||
return out;
|
||||
}
|
||||
|
||||
describe('Exportación: PDF de seguimiento', () => {
|
||||
const definition = (s = snapshot()) => trackingDocument(s, NOW, PIXEL) as Record<string, any>;
|
||||
|
||||
// Fails if the report stops being landscape letter, which the nine columns need.
|
||||
it('is a landscape letter document with generic properties', () => {
|
||||
const d = definition();
|
||||
expect(d['pageSize']).toBe('LETTER');
|
||||
expect(d['pageOrientation']).toBe('landscape');
|
||||
expect(d['info']).toMatchObject({ author: 'ISSSTELEON', creator: 'ISSSTELEON', producer: 'ISSSTELEON', title: 'Cáncer de mama' });
|
||||
});
|
||||
|
||||
// Fails if the logo or the title are missing from the header: every page must carry them.
|
||||
it('puts the logo and the title in the header of every page', () => {
|
||||
const d = definition();
|
||||
const header = d['header']();
|
||||
const found = texts(header);
|
||||
// The logo is named in the header and defined once, so it is embedded once however many pages there are.
|
||||
expect(JSON.stringify(header)).toContain('"image":"logo"');
|
||||
expect(d['images']).toEqual({ logo: PIXEL });
|
||||
expect(found).toContain('Cáncer de mama');
|
||||
});
|
||||
|
||||
// Fails if the header breaks when the logo cannot be read: the report must still be produced.
|
||||
it('falls back to the name as text when there is no logo', () => {
|
||||
const d = trackingDocument(snapshot(), NOW) as Record<string, any>;
|
||||
expect(JSON.stringify(d['header']())).not.toContain('"image"');
|
||||
expect(texts(d['header']())).toContain('ISSSTELEON');
|
||||
});
|
||||
|
||||
// Fails if the footer loses the page count, the confidentiality line or the generation time.
|
||||
it('has a footer with the generation time, the confidentiality line and "Página X de Y"', () => {
|
||||
const found = texts(definition()['footer'](2, 7));
|
||||
expect(found).toContain('Página 2 de 7');
|
||||
expect(found).toContain(PDF_CONFIDENTIAL);
|
||||
expect(found.some(t => t.startsWith('Generado: 12 nov 2026, 3:30 p.m.'))).toBe(true);
|
||||
});
|
||||
|
||||
// Fails if the parameters stop saying what query the report answers.
|
||||
it('prints the cut-off, the window, every filter with its option and the number of rows', () => {
|
||||
const s = snapshot();
|
||||
const found = texts(definition(s)['content']);
|
||||
for (const t of ['Fecha de corte', s.corte, `${s.ventana.desde} al ${s.ventana.hasta} (3 meses)`, 'Prioridad', 'Alta', 'Todos', 'Registros', String(s.items.length)]) expect(found).toContain(t);
|
||||
});
|
||||
|
||||
// Fails if the table stops repeating its header across pages or lets a row split between two pages.
|
||||
it('repeats the header row and keeps each row on one page', () => {
|
||||
const table = definition()['content'].find((n: any) => n.table?.headerRows)!.table;
|
||||
expect(table.headerRows).toBe(1);
|
||||
expect(table.dontBreakRows).toBe(true);
|
||||
expect(table.body).toHaveLength(snapshot().items.length + 1);
|
||||
expect(table.body[0].map((cell: { text: string }) => cell.text)).toEqual(['Identificador seudónimo', 'Grupo de edad', 'Estatus de seguimiento', 'Última mastografía', 'Resultado histopatológico', 'Días de mastografía a diagnóstico', 'Prioridad']);
|
||||
});
|
||||
|
||||
// Fails if details stop appearing under their value, or a missing value is drawn as something other than "No disponible".
|
||||
it('shows each detail under its value and a missing value as "No disponible"', () => {
|
||||
const s = snapshot();
|
||||
const found = texts(definition(s)['content']);
|
||||
expect(found).toContain(`Fecha: ${s.items.find(i => i['mastografia_fecha'])!['mastografia_fecha']}`);
|
||||
expect(found).toContain('No disponible');
|
||||
});
|
||||
|
||||
// Fails if the rows lose their alternating band, which keeps long rows readable across a page.
|
||||
it('bands every other row and leaves the header row to its own style', () => {
|
||||
const { layout } = definition()['content'].find((n: any) => n.table?.headerRows);
|
||||
expect([layout.fillColor(0), layout.fillColor(1), layout.fillColor(2)]).toEqual([undefined, undefined, COLORS.band]);
|
||||
});
|
||||
|
||||
// Fails if an empty query produces a table with only a header, which reads as a broken report.
|
||||
it('says so when there are no rows', () => {
|
||||
expect(texts(definition(snapshot(x => { x.items = []; }))['content'])).toContain('No hay registros para los filtros aplicados.');
|
||||
});
|
||||
|
||||
// Fails if pdfmake, its fonts or the document definition no longer produce a real, multipage PDF. The logo is left
|
||||
// out because the test browser (jsdom) has no `Worker`, which pdfmake needs to decode a PNG; the image path is
|
||||
// checked in a real browser.
|
||||
it('renders a multipage PDF file for a long list', async () => {
|
||||
const many = snapshot(x => { x.items = Array.from({ length: 120 }, (_, i) => ({ ...x.items[i % x.items.length], id_seudonimo: `M-${String(i).padStart(4, '0')}` })); });
|
||||
const blob = await buildTrackingPdf(many, NOW);
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
const text = new TextDecoder('latin1').decode(bytes);
|
||||
expect(blob.type === 'application/pdf' || blob.type === '').toBe(true);
|
||||
expect(text.startsWith('%PDF-')).toBe(true);
|
||||
expect(text.trimEnd().endsWith('%%EOF')).toBe(true);
|
||||
expect((text.match(/\/Type \/Page\b/g) ?? []).length).toBeGreaterThan(3);
|
||||
}, 30000);
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
import { renderPdf, PdfDefinition } from './pdf-engine';
|
||||
import { COLORS, institutionalDocument, loadLogo } from './pdf-template';
|
||||
import { displayText, exportColumns } from './tracking-export-table';
|
||||
import { TrackingSnapshot, ventanaConsultada } from './tracking-export.models';
|
||||
|
||||
export const TRACKING_TITLE = 'Cáncer de mama';
|
||||
|
||||
const rule = { hLineWidth: () => 0.5, vLineWidth: () => 0, hLineColor: () => COLORS.rule, paddingTop: () => 4, paddingBottom: () => 4 };
|
||||
const zebra = { ...rule, fillColor: (row: number) => (row === 0 ? undefined : row % 2 === 0 ? COLORS.band : undefined) };
|
||||
|
||||
/** What the query was: cut-off, window, each announced filter with its chosen option, and how many rows follow. */
|
||||
function parameters(snapshot: TrackingSnapshot) {
|
||||
const rows: unknown[][] = [
|
||||
...(snapshot.seleccion ? [['Selección del análisis', snapshot.seleccion]] : []),
|
||||
['Fecha de corte', snapshot.corte],
|
||||
['Ventana consultada', ventanaConsultada(snapshot)],
|
||||
...snapshot.filtros_disponibles.map(f => [f.etiqueta, f.opciones.find(o => o.codigo === snapshot.filtros[f.clave])?.etiqueta ?? 'Todos']),
|
||||
['Registros', String(snapshot.items.length)],
|
||||
];
|
||||
return { table: { widths: [130, '*'], body: rows.map(([k, v]) => [{ text: k, bold: true }, v]) }, layout: rule };
|
||||
}
|
||||
|
||||
/** The follow-up table: the columns the answer announced, each value with its labelled details under it. */
|
||||
function dataTable(snapshot: TrackingSnapshot) {
|
||||
const columns = exportColumns(snapshot);
|
||||
const cell = (column: (typeof columns)[number], item: Record<string, string | number | null>) => {
|
||||
const value = item[column.key];
|
||||
const parts: unknown[] = [value === null || value === undefined ? { text: displayText(value), italics: true, color: COLORS.muted } : { text: String(value) }];
|
||||
for (const detail of column.details) {
|
||||
const v = item[detail.key];
|
||||
if (v !== null && v !== undefined) parts.push({ text: `${detail.label}: ${v}`, style: 'small' });
|
||||
}
|
||||
return parts.length === 1 ? parts[0] : { stack: parts };
|
||||
};
|
||||
return {
|
||||
table: {
|
||||
headerRows: 1,
|
||||
dontBreakRows: true,
|
||||
widths: columns.map((_, i) => (i === 0 ? 62 : '*')),
|
||||
body: [
|
||||
columns.map(c => ({ text: c.label, style: 'th' })),
|
||||
...snapshot.items.map(item => columns.map(c => cell(c, item))),
|
||||
],
|
||||
},
|
||||
layout: zebra,
|
||||
};
|
||||
}
|
||||
|
||||
/** The document definition of a follow-up report. Exported so its content can be checked without rendering. */
|
||||
export function trackingDocument(snapshot: TrackingSnapshot, now: Date, logo?: string): PdfDefinition {
|
||||
return institutionalDocument({ title: TRACKING_TITLE, logo, now, orientation: 'landscape' }, [
|
||||
{ text: 'Resultados de seguimiento', style: 'h1' },
|
||||
parameters(snapshot),
|
||||
{ text: 'Pacientes', style: 'h2' },
|
||||
snapshot.items.length ? dataTable(snapshot) : { text: 'No hay registros para los filtros aplicados.', style: 'muted' },
|
||||
{ text: '“No disponible” indica dato no registrado, no ausencia clínica.', style: 'small', margin: [0, 10, 0, 0] },
|
||||
]);
|
||||
}
|
||||
|
||||
/** A PDF with the follow-up rows over several pages, repeating the header row. */
|
||||
export async function buildTrackingPdf(snapshot: TrackingSnapshot, now = new Date(), logo?: string): Promise<Blob> {
|
||||
return renderPdf(trackingDocument(snapshot, now, logo ?? await loadLogo()));
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// Covers the spreadsheet of a follow-up export by reading the generated file back: its sheets, native filter, frozen
|
||||
// header, the simulated-data notice, numbers, empty cells, neutralised text and the absence of author metadata.
|
||||
// The reader is `fflate`, the zip library `write-excel-file` itself uses. Fixture: fixtures/cama_seguimiento.json.
|
||||
import { strFromU8, unzipSync } from 'fflate';
|
||||
import fixtureData from '../fixtures/cama_seguimiento.json';
|
||||
import { seguimientoTablaResponse } from '../seguimiento-tabla.service';
|
||||
import { buildTrackingXlsx, columnLetter, DATA_SHEET, PARAMETERS_SHEET } from './tracking-xlsx';
|
||||
import { TrackingSnapshot } from './tracking-export.models';
|
||||
|
||||
function snapshot(mutate: (s: TrackingSnapshot) => void = () => undefined): TrackingSnapshot {
|
||||
const r = seguimientoTablaResponse(structuredClone(fixtureData));
|
||||
const s: TrackingSnapshot = { corte: r.corte, ventana: r.ventana, filtros: { ...r.filtros, estatus: 'BENIGNO' }, filtros_disponibles: r.filtros_disponibles, columnas: r.columnas, items: r.items };
|
||||
mutate(s);
|
||||
return s;
|
||||
}
|
||||
async function leer(s: TrackingSnapshot) {
|
||||
const blob = await buildTrackingXlsx(s, new Date(Date.UTC(2026, 10, 12, 21, 30)));
|
||||
const files = unzipSync(new Uint8Array(await blob.arrayBuffer()));
|
||||
const text = (name: string) => strFromU8(files[name]);
|
||||
return { files, text, sheet1: text('xl/worksheets/sheet1.xml'), sheet2: text('xl/worksheets/sheet2.xml'), workbook: text('xl/workbook.xml'), strings: text('xl/sharedStrings.xml') };
|
||||
}
|
||||
|
||||
describe('Exportación: archivo XLSX', () => {
|
||||
// Fails if the file stops being a spreadsheet of two sheets, the data first and the parameters second.
|
||||
it('has the data sheet first and the parameters sheet second', async () => {
|
||||
const { workbook } = await leer(snapshot());
|
||||
expect(workbook.indexOf(`name="${DATA_SHEET}"`)).toBeGreaterThan(-1);
|
||||
expect(workbook.indexOf(`name="${PARAMETERS_SHEET}"`)).toBeGreaterThan(workbook.indexOf(`name="${DATA_SHEET}"`));
|
||||
});
|
||||
|
||||
// Fails if the native filter is lost or placed outside the header row and the rows .
|
||||
it('adds a native filter over the header and every row, starting at the header row', async () => {
|
||||
const s = snapshot();
|
||||
const { sheet1, workbook } = await leer(s);
|
||||
const last = columnLetter(9);
|
||||
expect(sheet1).toContain(`<autoFilter ref="A1:${last}${s.items.length + 1}"/>`);
|
||||
// The schema orders the filter after the data: a wrong order makes Excel repair the file.
|
||||
expect(sheet1.indexOf('</sheetData>')).toBeLessThan(sheet1.indexOf('<autoFilter'));
|
||||
expect(workbook).toContain(`_xlnm._FilterDatabase`);
|
||||
expect(workbook).not.toContain('<definedNames/>');
|
||||
});
|
||||
|
||||
// Fails if the header row stops being frozen, which hides the column names while scrolling.
|
||||
it('freezes the header row', async () => {
|
||||
const { sheet1 } = await leer(snapshot());
|
||||
expect(sheet1).toContain('ySplit="1"');
|
||||
expect(sheet1).toContain('state="frozen"');
|
||||
});
|
||||
|
||||
// Fails if the file regains a note or banner row: the headers must be the first row of the data sheet.
|
||||
it('starts the data sheet with the column headers and has no note anywhere', async () => {
|
||||
const s = snapshot();
|
||||
const { strings, sheet1 } = await leer(s);
|
||||
const shared = [...strings.matchAll(/<si>(.*?)<\/si>/g)].map(m => m[1].replace(/<[^>]+>/g, ''));
|
||||
expect(sheet1).toMatch(new RegExp('<row r="1"><c r="A1"[^>]*t="s"><v>' + shared.indexOf('Identificador seudónimo') + '</v>'));
|
||||
expect(sheet1).not.toContain('<mergeCells');
|
||||
expect(shared.filter(x => /^Nota$|Documento de consulta|expediente/i.test(x))).toEqual([]);
|
||||
expect(shared).not.toContain('Tipo de datos');
|
||||
expect((sheet1.match(/<row /g) ?? []).length).toBe(s.items.length + 1);
|
||||
});
|
||||
|
||||
// Fails if the headers, the sheet of parameters or the filter labels lose what query the file answers.
|
||||
it('records the cut-off, the window, the filters applied and the total in the parameters sheet', async () => {
|
||||
const s = snapshot();
|
||||
const { strings, sheet2 } = await leer(s);
|
||||
for (const text of [s.corte, `${s.ventana.desde} al ${s.ventana.hasta}`, 'Estatus de seguimiento', 'Benigno, regresa a tamizaje', 'Todos', 'Cáncer de mama']) expect(strings).toContain(text);
|
||||
expect(sheet2).toContain(`<v>${s.items.length}</v>`);
|
||||
});
|
||||
|
||||
// Fails if the generation moment is written without the time zone it refers to.
|
||||
it('writes the generation time in Mexico City time', async () => {
|
||||
const { strings } = await leer(snapshot());
|
||||
expect(strings).toContain('hora de la Ciudad de México');
|
||||
// 21:30 UTC is 15:30 in Mexico City (UTC-6 in November).
|
||||
expect(strings).toContain('3:30 p.m.');
|
||||
});
|
||||
|
||||
// Fails if a number is stored as text, or if a missing value becomes a value of its own.
|
||||
it('stores days as numbers and leaves missing values as empty cells', async () => {
|
||||
const s = snapshot();
|
||||
const { sheet1, strings } = await leer(s);
|
||||
const days = s.items.filter(i => typeof i['dias_mastografia_diagnostico'] === 'number');
|
||||
expect(days.length).toBeGreaterThan(0);
|
||||
expect(sheet1).toMatch(new RegExp(`<c r="H\\d+"[^>]*><v>${days[0]['dias_mastografia_diagnostico']}</v></c>`));
|
||||
expect(strings).not.toContain('No disponible');
|
||||
});
|
||||
|
||||
// Fails if text that starts like a formula reaches the file as it is.
|
||||
it('neutralises a value that starts like a formula', async () => {
|
||||
const s = snapshot(x => { x.items[0] = { ...x.items[0], biopsia: '=HYPERLINK("http://example.test")' }; });
|
||||
const { strings } = await leer(s);
|
||||
expect(strings).toContain(`'=HYPERLINK`);
|
||||
expect(strings).not.toMatch(/<t[^>]*>=HYPERLINK/);
|
||||
});
|
||||
|
||||
// Fails if the library starts writing author or application properties, which would leak who made the file.
|
||||
it('carries no document properties that identify an author', async () => {
|
||||
const { files } = await leer(snapshot());
|
||||
expect(Object.keys(files).filter(name => name.startsWith('docProps'))).toEqual([]);
|
||||
});
|
||||
|
||||
// Fails if the sheet gains hidden sheets, external links or macros.
|
||||
it('has no hidden sheets, external links or macros', async () => {
|
||||
const { files, workbook } = await leer(snapshot());
|
||||
expect(workbook).not.toContain('state="hidden"');
|
||||
expect(Object.keys(files).filter(name => /externalLinks|vbaProject|activeX|embeddings/i.test(name))).toEqual([]);
|
||||
});
|
||||
|
||||
// Fails if no rows turns into an invalid filter range or a failure instead of a file with headers.
|
||||
it('produces a valid file when the query has no rows', async () => {
|
||||
const { sheet1 } = await leer(snapshot(x => { x.items = []; }));
|
||||
expect(sheet1).toContain('<autoFilter ref="A1:I1"/>');
|
||||
});
|
||||
|
||||
// Fails if column letters beyond Z are wrong, which would put the filter on the wrong columns.
|
||||
it('names columns past Z', () => {
|
||||
expect([1, 26, 27, 52, 53].map(columnLetter)).toEqual(['A', 'Z', 'AA', 'AZ', 'BA']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import type { Feature, SheetData } from 'write-excel-file/browser';
|
||||
import { neutralizeFormula } from './cell-sanitizer';
|
||||
import { flatTable } from './tracking-export-table';
|
||||
import { TrackingSnapshot, ventanaConsultada } from './tracking-export.models';
|
||||
|
||||
export const DATA_SHEET = 'Seguimiento';
|
||||
export const PARAMETERS_SHEET = 'Parámetros';
|
||||
|
||||
const INK = '#081839';
|
||||
const ACCENT = '#a8c243';
|
||||
const header = (value: string) => ({ value, fontWeight: 'bold' as const, textColor: INK, backgroundColor: ACCENT, wrap: true, alignVertical: 'center' as const });
|
||||
|
||||
/** Spreadsheet column letters: 1 is A, 27 is AA. */
|
||||
export function columnLetter(n: number): string {
|
||||
let letters = '';
|
||||
for (; n > 0; n = Math.floor((n - 1) / 26)) letters = String.fromCharCode(65 + ((n - 1) % 26)) + letters;
|
||||
return letters;
|
||||
}
|
||||
|
||||
/** `write-excel-file` has no filter option: this extension adds the sheet's native filter over the header row. */
|
||||
function nativeFilter(range: string): Feature<Blob | ArrayBuffer> {
|
||||
const [first, last] = range.split(':').map(cell => cell.replace(/([A-Z]+)(\d+)/, '$$$1$$$2'));
|
||||
return {
|
||||
files: {
|
||||
transform: {
|
||||
'xl/worksheets/sheet{id}.xml': {
|
||||
transform: (content, _options, { sheetIndex }) => sheetIndex === 0 ? content.replace('</sheetData>', `</sheetData><autoFilter ref="${range}"/>`) : content,
|
||||
},
|
||||
'xl/workbook.xml': {
|
||||
transform: content => content.replace('<definedNames/>',
|
||||
`<definedNames><definedName name="_xlnm._FilterDatabase" localSheetId="0" hidden="1">'${DATA_SHEET}'!${first}:${last}</definedName></definedNames>`),
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function generatedAt(now: Date): string {
|
||||
return new Intl.DateTimeFormat('es-MX', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'America/Mexico_City' }).format(now) + ' (hora de la Ciudad de México)';
|
||||
}
|
||||
|
||||
/** The rows of the parameters sheet: what query this file answers and what its empty cells mean. */
|
||||
export function parameterRows(snapshot: TrackingSnapshot, now: Date): SheetData {
|
||||
const row = (label: string, value: string | number) => [{ value: label, fontWeight: 'bold' as const }, typeof value === 'number' ? { value, type: Number } : { value: neutralizeFormula(value), type: String }];
|
||||
const filters = snapshot.filtros_disponibles.map(f => {
|
||||
const code = snapshot.filtros[f.clave];
|
||||
return row(f.etiqueta, f.opciones.find(o => o.codigo === code)?.etiqueta ?? 'Todos');
|
||||
});
|
||||
return [
|
||||
[header('Parámetro'), header('Valor')],
|
||||
row('Reporte', 'Cáncer de mama'),
|
||||
...(snapshot.seleccion ? [row('Selección del análisis', snapshot.seleccion)] : []),
|
||||
row('Fecha de corte', snapshot.corte),
|
||||
row('Ventana consultada', ventanaConsultada(snapshot)),
|
||||
...filters,
|
||||
row('Total de registros', snapshot.items.length),
|
||||
row('Generado', generatedAt(now)),
|
||||
row('Celdas vacías', 'Indican dato no registrado, no ausencia clínica.'),
|
||||
] as SheetData;
|
||||
}
|
||||
|
||||
function width(label: string, values: readonly unknown[]): number {
|
||||
const longest = values.reduce<number>((max, v) => Math.max(max, v === null || v === undefined ? 0 : String(v).length), Math.min(label.length, 28));
|
||||
return Math.min(40, Math.max(12, longest + 2));
|
||||
}
|
||||
|
||||
/** A spreadsheet with the follow-up rows (native filter, frozen header) and a sheet with the query's parameters. */
|
||||
export async function buildTrackingXlsx(snapshot: TrackingSnapshot, now = new Date()): Promise<Blob> {
|
||||
const { default: writeXlsxFile } = await import('write-excel-file/browser');
|
||||
const { columns, rows } = flatTable(snapshot);
|
||||
const data = [
|
||||
columns.map(c => header(c.label)),
|
||||
...rows.map(row => row.map((value, i) => {
|
||||
if (value === null) return null;
|
||||
return columns[i].numeric ? { value: value as number, type: Number } : { value: neutralizeFormula(String(value)), type: String };
|
||||
})),
|
||||
] as SheetData;
|
||||
const range = `A1:${columnLetter(columns.length)}${rows.length + 1}`;
|
||||
return writeXlsxFile([
|
||||
{
|
||||
sheet: DATA_SHEET, data, stickyRowsCount: 1,
|
||||
columns: columns.map((c, i) => ({ width: width(c.label, rows.map(r => r[i])) })),
|
||||
},
|
||||
{ sheet: PARAMETERS_SHEET, data: parameterRows(snapshot, now), columns: [{ width: 26 }, { width: 90 }] },
|
||||
], { features: [nativeFilter(range)] }).toBlob();
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// The parts of FHIR R4 the WebApi's `/<domain>/fhir/` endpoints serve, read loosely: every field is optional and the
|
||||
// readers below decide what a missing one means.
|
||||
|
||||
export interface Coding { system?: string; code?: string; display?: string }
|
||||
export interface Concept { coding?: Coding[]; text?: string }
|
||||
export interface Quantity { value?: number; unit?: string }
|
||||
export interface Extension {
|
||||
url: string;
|
||||
valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number;
|
||||
valueDate?: string; valueDateTime?: string; valueCoding?: Coding; valueReference?: { reference?: string };
|
||||
extension?: Extension[];
|
||||
}
|
||||
export interface Resource {
|
||||
resourceType: string;
|
||||
id?: string;
|
||||
meta?: { tag?: Coding[] };
|
||||
extension?: Extension[];
|
||||
[field: string]: unknown;
|
||||
}
|
||||
export interface Bundle extends Resource {
|
||||
total?: number;
|
||||
entry?: { fullUrl?: string; resource: Resource; search?: { mode?: string } }[];
|
||||
}
|
||||
|
||||
export const CODE_SYSTEM = 'https://isssteleon.org/fhir/CodeSystem/';
|
||||
|
||||
export function code(concept: Concept | undefined): string | undefined {
|
||||
return concept?.coding?.[0]?.code;
|
||||
}
|
||||
export function display(concept: Concept | undefined): string | undefined {
|
||||
return concept?.coding?.[0]?.display ?? concept?.text;
|
||||
}
|
||||
// The code of a concept from `system` (a name under the project's CodeSystem base, or a full URL).
|
||||
export function codeIn(concept: Concept | undefined, system: string): string | undefined {
|
||||
const url = system.includes('://') ? system : CODE_SYSTEM + system;
|
||||
return concept?.coding?.find(c => c.system === url)?.code;
|
||||
}
|
||||
// The extensions named `name` (the last segment of their URL).
|
||||
export function extensions(owner: { extension?: Extension[] } | undefined, name: string): Extension[] {
|
||||
return (owner?.extension ?? []).filter(e => e.url === name || e.url.endsWith('/' + name));
|
||||
}
|
||||
export function extension(owner: { extension?: Extension[] } | undefined, name: string): Extension | undefined {
|
||||
return extensions(owner, name)[0];
|
||||
}
|
||||
export function resources(bundle: Bundle | undefined, type?: string): Resource[] {
|
||||
return (bundle?.entry ?? []).map(e => e.resource).filter(r => !type || r.resourceType === type);
|
||||
}
|
||||
export function isSimulated(resource: Resource): boolean {
|
||||
return !!resource.meta?.tag?.some(t => t.code === 'simulado');
|
||||
}
|
||||
// `Patient/P-1` -> `P-1`.
|
||||
export function referenceId(reference: { reference?: string } | undefined): string | undefined {
|
||||
return reference?.reference?.split('/').pop();
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "dimensiones": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "medidas": [{"clave": "maligno", "etiqueta": "Carcinoma in situ o invasor"}, {"clave": "invasor", "etiqueta": "Carcinoma invasor"}], "horizontes_dias": [30, 90, 180, 365], "tipos_periodo": ["mes", "semestre"], "secciones": [{"clave": "resumen", "titulo": "Indicadores de la cohorte", "estado": "disponible", "motivo": null}, {"clave": "distribucion", "titulo": "Distribución de pacientes", "estado": "disponible", "motivo": null}, {"clave": "comparacion", "titulo": "Comparación entre grupos", "estado": "disponible", "motivo": null}, {"clave": "mapa", "titulo": "Mapa entre variables", "estado": "disponible", "motivo": null}, {"clave": "tendencia", "titulo": "Tendencia en el tiempo", "estado": "disponible", "motivo": null}], "no_disponibles": [{"clave": "supervivencia", "titulo": "Supervivencia", "motivo": "No hay estado vital ni fecha de defunción en las fuentes."}, {"clave": "recaida", "titulo": "Recaída", "motivo": "No hay registro de recurrencia ni de tratamiento en las fuentes."}, {"clave": "adherencia_tratamiento", "titulo": "Adherencia al tratamiento", "motivo": "No hay tabla de tratamientos ni de visitas de seguimiento."}, {"clave": "curvas_tiempo_a_evento", "titulo": "Curvas de incidencia acumulada y de supervivencia", "motivo": "El seguimiento de quien no tuvo el evento no está registrado: no hay censura verificable ni tiempo cero común, y la muerte como riesgo competitivo no existe."}, {"clave": "riesgos_proporcionales", "titulo": "Razones de riesgo (Cox), log-rank y tiempo medio restringido", "motivo": "Dependen de las curvas anteriores."}, {"clave": "brca_estadio_tamano", "titulo": "BRCA, estadio clínico y tamaño tumoral", "motivo": "No hay registros de estas variables en las fuentes."}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "birads", "medida": "maligno", "denominador": "pacientes con resultado de biopsia conocido", "grupos": [{"estado": "suprimido", "casos": null, "total": null, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4", "etiqueta": "BI-RADS 4", "seleccion": {"birads": "BIRADS_4"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A", "seleccion": {"birads": "BIRADS_4A"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B", "seleccion": {"birads": "BIRADS_4B"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C", "seleccion": {"birads": "BIRADS_4C"}}, {"estado": "suprimido", "casos": null, "total": null, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_5", "etiqueta": "BI-RADS 5", "seleccion": {"birads": "BIRADS_5"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_6", "etiqueta": "BI-RADS 6", "seleccion": {"birads": "BIRADS_6"}}], "prueba": {"valida": false, "motivo": "Hacen falta al menos dos grupos con datos publicados.", "nombre": "Chi cuadrada de homogeneidad"}}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "grupo_edad", "medida": "invasor", "denominador": "pacientes con resultado de biopsia conocido", "grupos": [{"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "<40", "etiqueta": "<40", "seleccion": {"grupo_edad": "<40"}}, {"estado": "disponible", "casos": 5, "total": 12, "valor": 41.67, "ic_bajo": 19.33, "ic_alto": 68.05, "codigo": "40-49", "etiqueta": "40-49", "seleccion": {"grupo_edad": "40-49"}}, {"estado": "disponible", "casos": 6, "total": 13, "valor": 46.15, "ic_bajo": 23.21, "ic_alto": 70.86, "codigo": "50-59", "etiqueta": "50-59", "seleccion": {"grupo_edad": "50-59"}}, {"estado": "disponible", "casos": 8, "total": 17, "valor": 47.06, "ic_bajo": 26.17, "ic_alto": 69.04, "codigo": "60-69", "etiqueta": "60-69", "seleccion": {"grupo_edad": "60-69"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "70+", "etiqueta": "70+", "seleccion": {"grupo_edad": "70+"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "SIN_DATO", "etiqueta": "Sin dato", "seleccion": {"grupo_edad": "SIN_DATO"}}], "prueba": {"valida": true, "estadistico": 0.0889, "gl": 2, "p": 0.9565070599102384, "nombre": "Chi cuadrada de homogeneidad"}}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "biopsia", "total": 61, "items": [{"codigo": "BENIGNO", "etiqueta": "Benigno", "suprimido": false, "n": 21, "porcentaje": 34.43, "ic_bajo": 23.75, "ic_alto": 46.95, "seleccion": {"biopsia": "BENIGNO"}}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"biopsia": "CARCINOMA_IN_SITU"}}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"biopsia": "CARCINOMA_INVASOR"}}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"biopsia": "SIN_DATO"}}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada", "suprimido": false, "n": 19, "porcentaje": 31.15, "ic_bajo": 20.94, "ic_alto": 43.59, "seleccion": {"biopsia": "SIN_BIOPSIA"}}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "birads", "total": 61, "items": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4", "suprimido": false, "n": 33, "porcentaje": 54.1, "ic_bajo": 41.72, "ic_alto": 65.99, "seleccion": {"birads": "BIRADS_4"}}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4A"}}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4B"}}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4C"}}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"birads": "BIRADS_5"}}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"birads": "BIRADS_6"}}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "grupo_edad", "total": 61, "items": [{"codigo": "<40", "etiqueta": "<40", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "<40"}}, {"codigo": "40-49", "etiqueta": "40-49", "suprimido": false, "n": 16, "porcentaje": 26.23, "ic_bajo": 16.84, "ic_alto": 38.44, "seleccion": {"grupo_edad": "40-49"}}, {"codigo": "50-59", "etiqueta": "50-59", "suprimido": false, "n": 19, "porcentaje": 31.15, "ic_bajo": 20.94, "ic_alto": 43.59, "seleccion": {"grupo_edad": "50-59"}}, {"codigo": "60-69", "etiqueta": "60-69", "suprimido": false, "n": 26, "porcentaje": 42.62, "ic_bajo": 31.02, "ic_alto": 55.1, "seleccion": {"grupo_edad": "60-69"}}, {"codigo": "70+", "etiqueta": "70+", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "70+"}}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "SIN_DATO"}}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"simulado": true, "cohorte": "cama_birads_v1", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "escenario": "diagnostico", "corte": "2026-11-16", "umbral_supresion": 5, "unidad": "paciente", "denominador": "pacientes elegibles con última mastografía reportada BI-RADS 4 a 6", "grupos": [{"codigo": "BIRADS_4", "n": 33, "suprimido": false}, {"codigo": "BIRADS_4A", "n": 0, "suprimido": false}, {"codigo": "BIRADS_4B", "n": 0, "suprimido": false}, {"codigo": "BIRADS_4C", "n": 0, "suprimido": false}, {"codigo": "BIRADS_5", "n": null, "suprimido": true}, {"codigo": "BIRADS_6", "n": null, "suprimido": true}], "horizonte_dias": 0, "indicadores": []}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
{"error": "la selección tiene menos de 5 pacientes: su lista no se publica.", "motivo": "supresion"}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "horizonte_dias": 90, "indicadores": [{"clave": "cohorte", "titulo": "Pacientes en la cohorte BI-RADS 4 a 6", "descripcion": "Pacientes cuya última mastografía reportada al corte es BI-RADS 4, 5 o 6.", "unidad": "pacientes", "estado": "disponible", "valor": 61, "ic_bajo": null, "ic_alto": null, "n": 61, "denominador": null, "q1": null, "q3": null, "motivo": null}, {"clave": "con_biopsia", "titulo": "Con biopsia reportada", "descripcion": "Pacientes de la cohorte con al menos un reporte de biopsia de esa mastografía, entre las de la cohorte.", "unidad": "%", "estado": "disponible", "valor": 68.85, "ic_bajo": 56.41, "ic_alto": 79.06, "n": 42, "denominador": 61, "q1": null, "q3": null, "motivo": null}, {"clave": "maligno_conocido", "titulo": "Resultado maligno entre las biopsias con resultado", "descripcion": "Carcinoma in situ o invasor entre las pacientes de la cohorte con resultado de biopsia conocido. No es incidencia: el denominador son pacientes ya biopsiadas.", "unidad": "%", "estado": "disponible", "valor": 50.0, "ic_bajo": 35.53, "ic_alto": 64.47, "n": 21, "denominador": 42, "q1": null, "q3": null, "motivo": null}, {"clave": "invasor_conocido", "titulo": "Carcinoma invasor entre las biopsias con resultado", "descripcion": "Carcinoma invasor entre las pacientes de la cohorte con resultado de biopsia conocido.", "unidad": "%", "estado": "disponible", "valor": 45.24, "ic_bajo": 31.22, "ic_alto": 60.05, "n": 19, "denominador": 42, "q1": null, "q3": null, "motivo": null}, {"clave": "biopsia_90d", "titulo": "Biopsia reportada en 90 días", "descripcion": "Pacientes cuya biopsia se reportó dentro de 90 días de la mastografía, entre las que ya cumplieron 90 días al corte.", "unidad": "%", "estado": "disponible", "valor": 75.56, "ic_bajo": 61.33, "ic_alto": 85.76, "n": 34, "denominador": 45, "q1": null, "q3": null, "motivo": null}, {"clave": "maligno_90d", "titulo": "Cáncer confirmado en 90 días", "descripcion": "Pacientes con un reporte de biopsia maligna dentro de 90 días de la mastografía, entre las que ya cumplieron 90 días al corte. No es incidencia acumulada: no hay seguimiento de quien no tuvo biopsia.", "unidad": "%", "estado": "disponible", "valor": 40.0, "ic_bajo": 27.02, "ic_alto": 54.55, "n": 18, "denominador": 45, "q1": null, "q3": null, "motivo": null}, {"clave": "dias_a_biopsia", "titulo": "Días de la mastografía al reporte de biopsia", "descripcion": "Mediana y cuartiles entre las pacientes con biopsia reportada.", "unidad": "días", "estado": "disponible", "valor": 27.5, "ic_bajo": null, "ic_alto": null, "n": 42, "denominador": null, "q1": 19.25, "q3": 30.75, "motivo": null}], "no_disponibles": [{"clave": "supervivencia", "titulo": "Supervivencia", "motivo": "No hay estado vital ni fecha de defunción en las fuentes."}, {"clave": "recaida", "titulo": "Recaída", "motivo": "No hay registro de recurrencia ni de tratamiento en las fuentes."}, {"clave": "adherencia_tratamiento", "titulo": "Adherencia al tratamiento", "motivo": "No hay tabla de tratamientos ni de visitas de seguimiento."}, {"clave": "curvas_tiempo_a_evento", "titulo": "Curvas de incidencia acumulada y de supervivencia", "motivo": "El seguimiento de quien no tuvo el evento no está registrado: no hay censura verificable ni tiempo cero común, y la muerte como riesgo competitivo no existe."}, {"clave": "riesgos_proporcionales", "titulo": "Razones de riesgo (Cox), log-rank y tiempo medio restringido", "motivo": "Dependen de las curvas anteriores."}, {"clave": "brca_estadio_tamano", "titulo": "BRCA, estadio clínico y tamaño tumoral", "motivo": "No hay registros de estas variables en las fuentes."}]}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
{"corte": "2026-11-16", "umbral_supresion": 5, "tipo_periodo": "semestre", "unidad": "reportes", "poblacion": "Reportes de mastografía con BI-RADS reportado y reportes de biopsia vinculados a una de esas mastografías, de todas las pacientes; no la cohorte de Seguimiento", "alcance_biopsias": "Solo biopsias que se pueden ligar a una mastografía con BI-RADS reportado (mastografía, orden, reporte); una biopsia sin mastografía ligada no se cuenta", "denominador": "reportes de biopsia con resultado conocido en el periodo", "periodos": [{"periodo": "2025-S1", "inicio": "2025-01-01", "fin": "2025-06-30", "incompleto": false, "reportes_mastografia": {"total": 96, "por_categoria": {"4_a_6": {"n": 31, "suprimido": false}, "otras": {"n": 65, "suprimido": false}}}, "reportes_biopsia": {"total": 24, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 15, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 16, "total": 24, "valor": 66.67, "ic_bajo": 46.71, "ic_alto": 82.03}}, {"periodo": "2025-S2", "inicio": "2025-07-01", "fin": "2025-12-31", "incompleto": false, "reportes_mastografia": {"total": 97, "por_categoria": {"4_a_6": {"n": 37, "suprimido": false}, "otras": {"n": 60, "suprimido": false}}}, "reportes_biopsia": {"total": 25, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 13, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 14, "total": 25, "valor": 56.0, "ic_bajo": 37.07, "ic_alto": 73.33}}, {"periodo": "2026-S1", "inicio": "2026-01-01", "fin": "2026-06-30", "incompleto": false, "reportes_mastografia": {"total": 97, "por_categoria": {"4_a_6": {"n": 25, "suprimido": false}, "otras": {"n": 72, "suprimido": false}}}, "reportes_biopsia": {"total": 18, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 11, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 13, "total": 18, "valor": 72.22, "ic_bajo": 49.13, "ic_alto": 87.5}}, {"periodo": "2026-S2", "inicio": "2026-07-01", "fin": "2026-12-31", "incompleto": true, "reportes_mastografia": {"total": 72, "por_categoria": {"4_a_6": {"n": 27, "suprimido": false}, "otras": {"n": 45, "suprimido": false}}}, "reportes_biopsia": {"total": 19, "por_grado": {"BENIGNO": {"n": 9, "suprimido": false}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": null, "suprimido": true}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 10, "total": 19, "valor": 52.63, "ic_bajo": 31.71, "ic_alto": 72.67}}]}
|
||||
@@ -0,0 +1,56 @@
|
||||
[
|
||||
{
|
||||
"id": "cama_dias_resultado_diagnostico",
|
||||
"titulo": "Tiempo de resultado a diagnóstico",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C3r",
|
||||
"unidad": "examen",
|
||||
"sentido": "decrease",
|
||||
"tipos_periodo": [
|
||||
"semestre",
|
||||
"mes"
|
||||
],
|
||||
"figuras": [
|
||||
"fig_c3r_caja"
|
||||
],
|
||||
"estratos": [],
|
||||
"filtros": []
|
||||
},
|
||||
{
|
||||
"id": "cama_histopatologia_birads",
|
||||
"titulo": "Histopatología por BI-RADS",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"sentido": null,
|
||||
"tipos_periodo": [
|
||||
"semestre",
|
||||
"mes"
|
||||
],
|
||||
"figuras": [
|
||||
"fig_c2_barras",
|
||||
"fig_c2_donas"
|
||||
],
|
||||
"estratos": [
|
||||
"birads"
|
||||
],
|
||||
"filtros": []
|
||||
},
|
||||
{
|
||||
"id": "cama_tasa_deteccion_histopatologica",
|
||||
"titulo": "Detección histopatológica",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C1",
|
||||
"unidad": "examen",
|
||||
"sentido": null,
|
||||
"tipos_periodo": [
|
||||
"semestre",
|
||||
"mes"
|
||||
],
|
||||
"figuras": [
|
||||
"fig_c1_puntos"
|
||||
],
|
||||
"estratos": [],
|
||||
"filtros": []
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"id": "cama_dias_resultado_diagnostico",
|
||||
"titulo": "Tiempo de resultado a diagnóstico",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C3r",
|
||||
"unidad": "examen",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S1"
|
||||
],
|
||||
"estrato": null,
|
||||
"valores_estrato": [],
|
||||
"etiquetas_estrato": {},
|
||||
"grupos": {
|
||||
"TOTAL": "Días de resultado a diagnóstico"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
"notas": [
|
||||
"Sin nota hasta el corte no hay observación. Convención provisional."
|
||||
],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"report_id": 71,
|
||||
"periodo_inicio": "2025-01-01",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"fecha_corte": "2026-11-12",
|
||||
"generado_en": "2026-11-12T17:00:26.219496+00:00",
|
||||
"kit_version": "0.8.0",
|
||||
"toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d",
|
||||
"parametros_sha": "5e4badce17afe0141e8296c9edd88ff1ce50a21c8c278d1aad5327069830d251",
|
||||
"parametros": {
|
||||
"sql": {
|
||||
"_catalogo": [],
|
||||
"_grupos": [
|
||||
"TOTAL"
|
||||
],
|
||||
"fecha_corte": "2026-11-12",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"periodo_inicio": "2025-01-01"
|
||||
},
|
||||
"umbral_supresion": 5
|
||||
}
|
||||
}
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"n": null,
|
||||
"mediana": null,
|
||||
"q1": null,
|
||||
"q3": null,
|
||||
"n_sin_evento": 0,
|
||||
"n_excluido": 0,
|
||||
"suprimido": 1,
|
||||
"unidad": "dias"
|
||||
}
|
||||
],
|
||||
"totales_estrato": []
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"id": "cama_dias_resultado_diagnostico",
|
||||
"titulo": "Tiempo de resultado a diagnóstico",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C3r",
|
||||
"unidad": "examen",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S1"
|
||||
],
|
||||
"estrato": null,
|
||||
"valores_estrato": [],
|
||||
"etiquetas_estrato": {},
|
||||
"grupos": {
|
||||
"TOTAL": "Días de resultado a diagnóstico"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
"notas": [
|
||||
"Sin nota hasta el corte no hay observación. Convención provisional."
|
||||
],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"report_id": 71,
|
||||
"periodo_inicio": "2025-01-01",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"fecha_corte": "2026-11-12",
|
||||
"generado_en": "2026-11-12T17:00:38.264922+00:00",
|
||||
"kit_version": "0.8.0",
|
||||
"toml_sha": "38b2efac7d70f9c0bf37b03b7abd21d48bff4c6d8f6786fccbccfa31a7fcd7e7",
|
||||
"parametros_sha": "f26ecdc2fcef0aa015f8997b7c1aa2053678cb86ca9cff9b1524efaf000971ad",
|
||||
"parametros": {
|
||||
"sql": {
|
||||
"_catalogo": [],
|
||||
"_grupos": [
|
||||
"TOTAL"
|
||||
],
|
||||
"fecha_corte": "2026-11-12",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"periodo_inicio": "2025-01-01"
|
||||
},
|
||||
"umbral_supresion": 1
|
||||
}
|
||||
}
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"n": 4,
|
||||
"mediana": 6.5,
|
||||
"q1": 2.25,
|
||||
"q3": 12.5,
|
||||
"n_sin_evento": 0,
|
||||
"n_excluido": 1,
|
||||
"suprimido": 0,
|
||||
"unidad": "dias"
|
||||
}
|
||||
],
|
||||
"totales_estrato": []
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,842 @@
|
||||
{
|
||||
"resourceType": "Bundle",
|
||||
"type": "searchset",
|
||||
"total": 8,
|
||||
"link": [
|
||||
{
|
||||
"relation": "self",
|
||||
"url": "http://127.0.0.1:28091/cama/fhir/Measure?_count=50&_offset=0"
|
||||
}
|
||||
],
|
||||
"entry": [
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIOPSIAS",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-BIOPSIAS",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIOPSIAS",
|
||||
"version": "0.2.0",
|
||||
"name": "cama_biopsias",
|
||||
"title": "Distribución de resultados de biopsia",
|
||||
"status": "active",
|
||||
"description": "Cuántas biopsias reportadas en el semestre caen en cada grado histológico. Se cuenta cada biopsia, no cada paciente. «Sin dato»: el reporte no trae grado.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C2"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "cohort"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_biopsias"
|
||||
}
|
||||
}
|
||||
],
|
||||
"stratifier": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "grado"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "examen"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-BIRADS",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS",
|
||||
"version": "0.2.0",
|
||||
"name": "cama_birads",
|
||||
"title": "Distribución de BI-RADS",
|
||||
"status": "active",
|
||||
"description": "Cuántas pacientes caen en cada categoría de BI-RADS en el semestre, cada una en la más grave de sus mastografías. «Sin dato»: ninguna de sus mastografías tiene reporte con BI-RADS.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C2"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "cohort"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_birads"
|
||||
}
|
||||
}
|
||||
],
|
||||
"stratifier": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "birads"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "paciente"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS-CANCER-INVASOR",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-BIRADS-CANCER-INVASOR",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS-CANCER-INVASOR",
|
||||
"version": "0.1.0",
|
||||
"name": "cama_birads_cancer_invasor",
|
||||
"title": "BI-RADS de los cánceres invasores",
|
||||
"status": "active",
|
||||
"description": "De las pacientes con una biopsia reportada en el periodo con carcinoma invasor, cuántas tenían cada BI-RADS en la mastografía que originó su biopsia más reciente, por edad y por las características del tumor: estadio clínico, etapa, subtipo molecular y tamaño. Las características vienen de los reportes leídos por texto y son provisionales. «Sin dato»: la biopsia no se ligó a una mastografía con BI-RADS.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C2"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "cohort"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_birads_cancer_invasor"
|
||||
}
|
||||
}
|
||||
],
|
||||
"stratifier": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "birads"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "grupo_edad"
|
||||
}
|
||||
],
|
||||
"text": "grupo_edad"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "estadio"
|
||||
}
|
||||
],
|
||||
"text": "Estadio clínico"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "etapa"
|
||||
}
|
||||
],
|
||||
"text": "Etapa"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "clasificacion"
|
||||
}
|
||||
],
|
||||
"text": "Subtipo molecular"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "tamano"
|
||||
}
|
||||
],
|
||||
"text": "Tamaño tumoral (T)"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "paciente"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS456-MASTOGRAFIA",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-BIRADS456-MASTOGRAFIA",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-MASTOGRAFIA",
|
||||
"version": "0.2.0",
|
||||
"name": "cama_birads_456_mastografia",
|
||||
"title": "Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6",
|
||||
"status": "active",
|
||||
"description": "Cuántas mastografías tomadas en el periodo tienen BI-RADS 4, 5 o 6, cada una con su categoría.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C2"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "cohort"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_birads_456_mastografia"
|
||||
}
|
||||
}
|
||||
],
|
||||
"stratifier": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "birads"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "examen"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS456-PACIENTE",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-BIRADS456-PACIENTE",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-PACIENTE",
|
||||
"version": "0.2.0",
|
||||
"name": "cama_birads_456_paciente",
|
||||
"title": "Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6",
|
||||
"status": "active",
|
||||
"description": "Cuántas pacientes tienen como BI-RADS más grave del periodo un 4, 5 o 6, cada una en la más grave de sus mastografías.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C2"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "cohort"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_birads_456_paciente"
|
||||
}
|
||||
}
|
||||
],
|
||||
"stratifier": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "birads"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "paciente"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-CONFIRMACION-BIRADS45",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-CONFIRMACION-BIRADS45",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-CONFIRMACION-BIRADS45",
|
||||
"version": "0.2.0",
|
||||
"name": "cama_confirmacion_birads45",
|
||||
"title": "Tasa de confirmación histopatológica",
|
||||
"status": "active",
|
||||
"description": "De las mastografías del semestre con BI-RADS de sospecha, las que tienen una biopsia reportada originada por esa mastografía. A la fecha de corte: sin un plazo máximo, el valor puede subir mientras lleguen reportes. No dice si la biopsia confirmó cáncer.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C1"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "proportion"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "principal"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_confirmacion_birads45_denominador"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "denominator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Denominador",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_confirmacion_birads45_denominador"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "numerator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Numerador",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_confirmacion_birads45_numerador"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "episodio"
|
||||
}
|
||||
]
|
||||
},
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "increase"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-DIAS-TOMA-DIAGNOSTICO",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-DIAS-TOMA-DIAGNOSTICO",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-DIAS-TOMA-DIAGNOSTICO",
|
||||
"version": "0.2.2",
|
||||
"name": "cama_dias_toma_diagnostico",
|
||||
"title": "Tiempo de tamizaje a diagnóstico",
|
||||
"status": "active",
|
||||
"description": "Días naturales de la toma de cada mastografía del semestre a la primera nota médica posterior que la resuelve: un diagnóstico CIE-10 de la lista (normal, benigno, lesión o cáncer), escrito por una de las especialidades que diagnostican, dentro del horizonte y a la fecha de corte. Entran todas las mastografías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de cáncer de mama anterior a la toma.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C3r"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "continuous-variable"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_dias_toma_diagnostico"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-observation"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades con valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_dias_toma_diagnostico"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-population-exclusion"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades sin valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_dias_toma_diagnostico"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "examen"
|
||||
}
|
||||
]
|
||||
},
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "decrease"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-EU38A",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-EU38A",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-EU38A",
|
||||
"version": "0.2.1",
|
||||
"name": "cama_eu38a",
|
||||
"title": "Días de la toma de la mastografía a su resultado",
|
||||
"status": "active",
|
||||
"description": "Días naturales de la toma de cada mastografía del semestre a su resultado, a la fecha de corte. Las que aún no tienen resultado y siguen dentro del horizonte no se miden; las que lo pasaron sin resultado cuentan en los excluidos.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C3r"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "continuous-variable"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_eu38a"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-observation"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades con valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_eu38a"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-population-exclusion"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades sin valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_eu38a"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "examen"
|
||||
}
|
||||
]
|
||||
},
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "decrease"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,477 @@
|
||||
{
|
||||
"id": "cama_histopatologia_birads",
|
||||
"titulo": "Histopatología por BI-RADS",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S1"
|
||||
],
|
||||
"estrato": "birads",
|
||||
"valores_estrato": [
|
||||
"BIRADS_4",
|
||||
"BIRADS_4A",
|
||||
"BIRADS_4B",
|
||||
"BIRADS_4C",
|
||||
"BIRADS_5",
|
||||
"BIRADS_6"
|
||||
],
|
||||
"etiquetas_estrato": {
|
||||
"BIRADS_4": "BI-RADS 4 sin subtipo",
|
||||
"BIRADS_4A": "BI-RADS 4A",
|
||||
"BIRADS_4B": "BI-RADS 4B",
|
||||
"BIRADS_4C": "BI-RADS 4C",
|
||||
"BIRADS_5": "BI-RADS 5",
|
||||
"BIRADS_6": "BI-RADS 6"
|
||||
},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {
|
||||
"BENIGNO": {
|
||||
"etiqueta": "Benigno",
|
||||
"color": "#9DBFE3",
|
||||
"grupo": "NO_MALIGNO",
|
||||
"gravedad": 1
|
||||
},
|
||||
"RIESGO_B3": {
|
||||
"etiqueta": "Lesión de riesgo (B3)",
|
||||
"color": "#2F6DB3",
|
||||
"grupo": "NO_MALIGNO",
|
||||
"gravedad": 2
|
||||
},
|
||||
"IN_SITU": {
|
||||
"etiqueta": "Carcinoma in situ",
|
||||
"color": "#D9822B",
|
||||
"grupo": "MALIGNO",
|
||||
"gravedad": 3
|
||||
},
|
||||
"INVASOR": {
|
||||
"etiqueta": "Carcinoma invasor",
|
||||
"color": "#B5482E",
|
||||
"grupo": "MALIGNO",
|
||||
"gravedad": 4
|
||||
},
|
||||
"SIN_BIOPSIA": {
|
||||
"etiqueta": "Sin biopsia reportada",
|
||||
"color": "#C9CDD2",
|
||||
"grupo": null,
|
||||
"gravedad": null
|
||||
},
|
||||
"SIN_DATO": {
|
||||
"etiqueta": "Sin dato",
|
||||
"color": "#C9CDD2",
|
||||
"grupo": "SIN_DATO",
|
||||
"gravedad": null
|
||||
}
|
||||
},
|
||||
"grupos_de_categoria": {
|
||||
"NO_MALIGNO": "No maligno",
|
||||
"MALIGNO": "Maligno",
|
||||
"SIN_DATO": "Sin dato"
|
||||
},
|
||||
"notas": [
|
||||
"Convención provisional; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado."
|
||||
],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"report_id": 141,
|
||||
"periodo_inicio": "2025-01-01",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"fecha_corte": "2025-12-31",
|
||||
"generado_en": "2026-11-12T16:33:37.621606+00:00",
|
||||
"kit_version": "0.8.0",
|
||||
"toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d",
|
||||
"parametros_sha": "75706ce35dbdd4440f22f71220400666e6a14eeb2922353960c1d66878bbf6fe",
|
||||
"parametros": {
|
||||
"sql": {
|
||||
"_catalogo": [
|
||||
"BENIGNO",
|
||||
"RIESGO_B3",
|
||||
"IN_SITU",
|
||||
"INVASOR"
|
||||
],
|
||||
"_grupos": [
|
||||
"TOTAL"
|
||||
],
|
||||
"fecha_corte": "2025-12-31",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"periodo_inicio": "2025-01-01"
|
||||
},
|
||||
"umbral_supresion": 5
|
||||
}
|
||||
}
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4",
|
||||
"categoria": "BENIGNO",
|
||||
"n": 2,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4",
|
||||
"categoria": "RIESGO_B3",
|
||||
"n": 0,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4",
|
||||
"categoria": "IN_SITU",
|
||||
"n": 1,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4",
|
||||
"categoria": "INVASOR",
|
||||
"n": 1,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4",
|
||||
"categoria": "SIN_BIOPSIA",
|
||||
"n": 1,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4A",
|
||||
"categoria": "BENIGNO",
|
||||
"n": 1,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4A",
|
||||
"categoria": "RIESGO_B3",
|
||||
"n": 1,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4A",
|
||||
"categoria": "IN_SITU",
|
||||
"n": 1,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4A",
|
||||
"categoria": "INVASOR",
|
||||
"n": 2,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4A",
|
||||
"categoria": "SIN_BIOPSIA",
|
||||
"n": 1,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4A",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4B",
|
||||
"categoria": "BENIGNO",
|
||||
"n": 1,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4B",
|
||||
"categoria": "RIESGO_B3",
|
||||
"n": 1,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4B",
|
||||
"categoria": "IN_SITU",
|
||||
"n": 1,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4B",
|
||||
"categoria": "INVASOR",
|
||||
"n": 1,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4B",
|
||||
"categoria": "SIN_BIOPSIA",
|
||||
"n": 1,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4B",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4C",
|
||||
"categoria": "BENIGNO",
|
||||
"n": 1,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4C",
|
||||
"categoria": "RIESGO_B3",
|
||||
"n": 1,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4C",
|
||||
"categoria": "IN_SITU",
|
||||
"n": 1,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4C",
|
||||
"categoria": "INVASOR",
|
||||
"n": 1,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4C",
|
||||
"categoria": "SIN_BIOPSIA",
|
||||
"n": 1,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4C",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_5",
|
||||
"categoria": "BENIGNO",
|
||||
"n": 1,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_5",
|
||||
"categoria": "RIESGO_B3",
|
||||
"n": 1,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_5",
|
||||
"categoria": "IN_SITU",
|
||||
"n": 1,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_5",
|
||||
"categoria": "INVASOR",
|
||||
"n": 1,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_5",
|
||||
"categoria": "SIN_BIOPSIA",
|
||||
"n": 1,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_5",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_6",
|
||||
"categoria": "BENIGNO",
|
||||
"n": 1,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_6",
|
||||
"categoria": "RIESGO_B3",
|
||||
"n": 1,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_6",
|
||||
"categoria": "IN_SITU",
|
||||
"n": 1,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_6",
|
||||
"categoria": "INVASOR",
|
||||
"n": 1,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_6",
|
||||
"categoria": "SIN_BIOPSIA",
|
||||
"n": 1,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_6",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
}
|
||||
],
|
||||
"totales_estrato": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4",
|
||||
"n": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4A",
|
||||
"n": 7,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4B",
|
||||
"n": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4C",
|
||||
"n": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_5",
|
||||
"n": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_6",
|
||||
"n": 6,
|
||||
"suprimido": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
{
|
||||
"id": "cama_histopatologia_birads",
|
||||
"titulo": "Histopatología por BI-RADS",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S1"
|
||||
],
|
||||
"estrato": null,
|
||||
"valores_estrato": [],
|
||||
"etiquetas_estrato": {},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {
|
||||
"BENIGNO": {
|
||||
"etiqueta": "Benigno",
|
||||
"color": "#9DBFE3",
|
||||
"grupo": "NO_MALIGNO",
|
||||
"gravedad": 1
|
||||
},
|
||||
"RIESGO_B3": {
|
||||
"etiqueta": "Lesión de riesgo (B3)",
|
||||
"color": "#2F6DB3",
|
||||
"grupo": "NO_MALIGNO",
|
||||
"gravedad": 2
|
||||
},
|
||||
"IN_SITU": {
|
||||
"etiqueta": "Carcinoma in situ",
|
||||
"color": "#D9822B",
|
||||
"grupo": "MALIGNO",
|
||||
"gravedad": 3
|
||||
},
|
||||
"INVASOR": {
|
||||
"etiqueta": "Carcinoma invasor",
|
||||
"color": "#B5482E",
|
||||
"grupo": "MALIGNO",
|
||||
"gravedad": 4
|
||||
},
|
||||
"SIN_BIOPSIA": {
|
||||
"etiqueta": "Sin biopsia reportada",
|
||||
"color": "#C9CDD2",
|
||||
"grupo": null,
|
||||
"gravedad": null
|
||||
},
|
||||
"SIN_DATO": {
|
||||
"etiqueta": "Sin dato",
|
||||
"color": "#C9CDD2",
|
||||
"grupo": "SIN_DATO",
|
||||
"gravedad": null
|
||||
}
|
||||
},
|
||||
"grupos_de_categoria": {
|
||||
"NO_MALIGNO": "No maligno",
|
||||
"MALIGNO": "Maligno",
|
||||
"SIN_DATO": "Sin dato"
|
||||
},
|
||||
"notas": [
|
||||
"Convención provisional; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado."
|
||||
],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"report_id": 141,
|
||||
"periodo_inicio": "2025-01-01",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"fecha_corte": "2025-12-31",
|
||||
"generado_en": "2026-11-12T16:33:37.621606+00:00",
|
||||
"kit_version": "0.8.0",
|
||||
"toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d",
|
||||
"parametros_sha": "75706ce35dbdd4440f22f71220400666e6a14eeb2922353960c1d66878bbf6fe",
|
||||
"parametros": {
|
||||
"sql": {
|
||||
"_catalogo": [
|
||||
"BENIGNO",
|
||||
"RIESGO_B3",
|
||||
"IN_SITU",
|
||||
"INVASOR"
|
||||
],
|
||||
"_grupos": [
|
||||
"TOTAL"
|
||||
],
|
||||
"fecha_corte": "2025-12-31",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"periodo_inicio": "2025-01-01"
|
||||
},
|
||||
"umbral_supresion": 5
|
||||
}
|
||||
}
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "BENIGNO",
|
||||
"n": 7,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "RIESGO_B3",
|
||||
"n": 5,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "IN_SITU",
|
||||
"n": 6,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "INVASOR",
|
||||
"n": 7,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "SIN_BIOPSIA",
|
||||
"n": 6,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 6,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
}
|
||||
],
|
||||
"totales_estrato": []
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
{
|
||||
"campo_ventana": "mastografia_fecha",
|
||||
"columnas": [
|
||||
{
|
||||
"clave": "id_seudonimo",
|
||||
"etiqueta": "Identificador seudónimo"
|
||||
},
|
||||
{
|
||||
"clave": "grupo_edad",
|
||||
"etiqueta": "Grupo de edad"
|
||||
},
|
||||
{
|
||||
"clave": "estatus",
|
||||
"etiqueta": "Estatus de seguimiento"
|
||||
},
|
||||
{
|
||||
"clave": "birads",
|
||||
"detalles": [
|
||||
{
|
||||
"clave": "mastografia_fecha",
|
||||
"etiqueta": "Fecha"
|
||||
}
|
||||
],
|
||||
"etiqueta": "Última mastografía"
|
||||
},
|
||||
{
|
||||
"clave": "biopsia",
|
||||
"detalles": [
|
||||
{
|
||||
"clave": "biopsia_fecha",
|
||||
"etiqueta": "Fecha de biopsia"
|
||||
}
|
||||
],
|
||||
"etiqueta": "Resultado histopatológico"
|
||||
},
|
||||
{
|
||||
"clave": "dias_mastografia_diagnostico",
|
||||
"etiqueta": "Días de mastografía a diagnóstico"
|
||||
},
|
||||
{
|
||||
"clave": "prioridad",
|
||||
"etiqueta": "Prioridad"
|
||||
}
|
||||
],
|
||||
"corte": "2026-10-20",
|
||||
"filtros": {
|
||||
"birads": null,
|
||||
"estatus": null,
|
||||
"grupo_edad": null,
|
||||
"prioridad": null
|
||||
},
|
||||
"filtros_disponibles": [
|
||||
{
|
||||
"clave": "estatus",
|
||||
"etiqueta": "Estatus de seguimiento",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "PENDIENTE_BIOPSIA",
|
||||
"etiqueta": "Pendiente de biopsia"
|
||||
},
|
||||
{
|
||||
"codigo": "BIOPSIA_SIN_RESULTADO",
|
||||
"etiqueta": "Biopsia sin resultado"
|
||||
},
|
||||
{
|
||||
"codigo": "CANCER_CONFIRMADO",
|
||||
"etiqueta": "Cáncer confirmado"
|
||||
},
|
||||
{
|
||||
"codigo": "BENIGNO",
|
||||
"etiqueta": "Benigno, regresa a tamizaje"
|
||||
},
|
||||
{
|
||||
"codigo": "INFO_INSUFICIENTE",
|
||||
"etiqueta": "Información insuficiente"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "birads",
|
||||
"etiqueta": "Categoría BI-RADS",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "BIRADS_4A",
|
||||
"etiqueta": "BI-RADS 4A"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_4B",
|
||||
"etiqueta": "BI-RADS 4B"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_4C",
|
||||
"etiqueta": "BI-RADS 4C"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_5",
|
||||
"etiqueta": "BI-RADS 5"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_6",
|
||||
"etiqueta": "BI-RADS 6"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "grupo_edad",
|
||||
"etiqueta": "Grupo de edad",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "40-49",
|
||||
"etiqueta": "40-49"
|
||||
},
|
||||
{
|
||||
"codigo": "50-59",
|
||||
"etiqueta": "50-59"
|
||||
},
|
||||
{
|
||||
"codigo": "60-69",
|
||||
"etiqueta": "60-69"
|
||||
},
|
||||
{
|
||||
"codigo": "70+",
|
||||
"etiqueta": "70+"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "prioridad",
|
||||
"etiqueta": "Prioridad",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "ALTA",
|
||||
"etiqueta": "Alta"
|
||||
},
|
||||
{
|
||||
"codigo": "MEDIA",
|
||||
"etiqueta": "Media"
|
||||
},
|
||||
{
|
||||
"codigo": "BAJA",
|
||||
"etiqueta": "Baja"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"items": [
|
||||
{
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"birads": "BI-RADS 5",
|
||||
"birads_codigo": "BIRADS_5",
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"estatus": "Pendiente de biopsia",
|
||||
"estatus_codigo": "PENDIENTE_BIOPSIA",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"id_seudonimo": "M-0001",
|
||||
"mastografia_fecha": "2026-10-15",
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": "2026-10-18",
|
||||
"birads": "BI-RADS 4A",
|
||||
"birads_codigo": "BIRADS_4A",
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"estatus": "Biopsia sin resultado",
|
||||
"estatus_codigo": "BIOPSIA_SIN_RESULTADO",
|
||||
"grupo_edad": "40-49",
|
||||
"grupo_edad_codigo": "40-49",
|
||||
"id_seudonimo": "M-0002",
|
||||
"mastografia_fecha": "2026-10-15",
|
||||
"prioridad": "Media",
|
||||
"prioridad_codigo": "MEDIA"
|
||||
},
|
||||
{
|
||||
"biopsia": "Benigno",
|
||||
"biopsia_fecha": "2026-09-10",
|
||||
"birads": "BI-RADS 4B",
|
||||
"birads_codigo": "BIRADS_4B",
|
||||
"dias_mastografia_diagnostico": 16,
|
||||
"estatus": "Benigno, regresa a tamizaje",
|
||||
"estatus_codigo": "BENIGNO",
|
||||
"grupo_edad": "60-69",
|
||||
"grupo_edad_codigo": "60-69",
|
||||
"id_seudonimo": "M-0003",
|
||||
"mastografia_fecha": "2026-09-01",
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"biopsia": "Carcinoma invasor",
|
||||
"biopsia_fecha": "2026-08-22",
|
||||
"birads": "BI-RADS 4C",
|
||||
"birads_codigo": "BIRADS_4C",
|
||||
"dias_mastografia_diagnostico": 20,
|
||||
"estatus": "Cáncer confirmado",
|
||||
"estatus_codigo": "CANCER_CONFIRMADO",
|
||||
"grupo_edad": "70+",
|
||||
"grupo_edad_codigo": "70+",
|
||||
"id_seudonimo": "M-0004",
|
||||
"mastografia_fecha": "2026-08-15",
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"birads": "BI-RADS 6",
|
||||
"birads_codigo": "BIRADS_6",
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"estatus": "Información insuficiente",
|
||||
"estatus_codigo": "INFO_INSUFICIENTE",
|
||||
"grupo_edad": "40-49",
|
||||
"grupo_edad_codigo": "40-49",
|
||||
"id_seudonimo": "M-0005",
|
||||
"mastografia_fecha": "2026-07-21",
|
||||
"prioridad": "Media",
|
||||
"prioridad_codigo": "MEDIA"
|
||||
}
|
||||
],
|
||||
"paginacion": {
|
||||
"page": 1,
|
||||
"page_size": 50,
|
||||
"total_items": 5,
|
||||
"total_pages": 1
|
||||
},
|
||||
"simulado": true,
|
||||
"ventana": {
|
||||
"desde": "2026-07-21",
|
||||
"hasta": "2026-10-20",
|
||||
"meses": 3
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
{
|
||||
"campo_ventana": "mastografia_fecha",
|
||||
"columnas": [
|
||||
{
|
||||
"clave": "id_seudonimo",
|
||||
"etiqueta": "Identificador seudónimo"
|
||||
},
|
||||
{
|
||||
"clave": "grupo_edad",
|
||||
"etiqueta": "Grupo de edad"
|
||||
},
|
||||
{
|
||||
"clave": "estatus",
|
||||
"etiqueta": "Estatus de seguimiento"
|
||||
},
|
||||
{
|
||||
"clave": "birads",
|
||||
"detalles": [
|
||||
{
|
||||
"clave": "mastografia_fecha",
|
||||
"etiqueta": "Fecha"
|
||||
}
|
||||
],
|
||||
"etiqueta": "Última mastografía"
|
||||
},
|
||||
{
|
||||
"clave": "biopsia",
|
||||
"detalles": [
|
||||
{
|
||||
"clave": "biopsia_fecha",
|
||||
"etiqueta": "Fecha de biopsia"
|
||||
}
|
||||
],
|
||||
"etiqueta": "Resultado histopatológico"
|
||||
},
|
||||
{
|
||||
"clave": "dias_mastografia_diagnostico",
|
||||
"etiqueta": "Días de mastografía a diagnóstico"
|
||||
},
|
||||
{
|
||||
"clave": "prioridad",
|
||||
"etiqueta": "Prioridad"
|
||||
}
|
||||
],
|
||||
"corte": "2026-10-20",
|
||||
"filtros": {
|
||||
"birads": null,
|
||||
"estatus": null,
|
||||
"grupo_edad": null,
|
||||
"prioridad": "ALTA"
|
||||
},
|
||||
"filtros_disponibles": [
|
||||
{
|
||||
"clave": "estatus",
|
||||
"etiqueta": "Estatus de seguimiento",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "PENDIENTE_BIOPSIA",
|
||||
"etiqueta": "Pendiente de biopsia"
|
||||
},
|
||||
{
|
||||
"codigo": "BIOPSIA_SIN_RESULTADO",
|
||||
"etiqueta": "Biopsia sin resultado"
|
||||
},
|
||||
{
|
||||
"codigo": "CANCER_CONFIRMADO",
|
||||
"etiqueta": "Cáncer confirmado"
|
||||
},
|
||||
{
|
||||
"codigo": "BENIGNO",
|
||||
"etiqueta": "Benigno, regresa a tamizaje"
|
||||
},
|
||||
{
|
||||
"codigo": "INFO_INSUFICIENTE",
|
||||
"etiqueta": "Información insuficiente"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "birads",
|
||||
"etiqueta": "Categoría BI-RADS",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "BIRADS_4A",
|
||||
"etiqueta": "BI-RADS 4A"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_4B",
|
||||
"etiqueta": "BI-RADS 4B"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_4C",
|
||||
"etiqueta": "BI-RADS 4C"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_5",
|
||||
"etiqueta": "BI-RADS 5"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_6",
|
||||
"etiqueta": "BI-RADS 6"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "grupo_edad",
|
||||
"etiqueta": "Grupo de edad",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "40-49",
|
||||
"etiqueta": "40-49"
|
||||
},
|
||||
{
|
||||
"codigo": "50-59",
|
||||
"etiqueta": "50-59"
|
||||
},
|
||||
{
|
||||
"codigo": "60-69",
|
||||
"etiqueta": "60-69"
|
||||
},
|
||||
{
|
||||
"codigo": "70+",
|
||||
"etiqueta": "70+"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "prioridad",
|
||||
"etiqueta": "Prioridad",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "ALTA",
|
||||
"etiqueta": "Alta"
|
||||
},
|
||||
{
|
||||
"codigo": "MEDIA",
|
||||
"etiqueta": "Media"
|
||||
},
|
||||
{
|
||||
"codigo": "BAJA",
|
||||
"etiqueta": "Baja"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"items": [],
|
||||
"paginacion": {
|
||||
"page": 4,
|
||||
"page_size": 1,
|
||||
"total_items": 3,
|
||||
"total_pages": 3
|
||||
},
|
||||
"simulado": true,
|
||||
"ventana": {
|
||||
"desde": "2025-10-21",
|
||||
"hasta": "2026-10-20",
|
||||
"meses": 12
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,565 @@
|
||||
{
|
||||
"simulado": true,
|
||||
"corte": "2026-10-20",
|
||||
"ventana": {
|
||||
"meses": 3,
|
||||
"desde": "2026-07-21",
|
||||
"hasta": "2026-10-20"
|
||||
},
|
||||
"campo_ventana": "mastografia_fecha",
|
||||
"filtros": {
|
||||
"estatus": null,
|
||||
"birads": null,
|
||||
"grupo_edad": null,
|
||||
"prioridad": null
|
||||
},
|
||||
"filtros_disponibles": [
|
||||
{
|
||||
"clave": "estatus",
|
||||
"etiqueta": "Estatus de seguimiento",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "PENDIENTE_BIOPSIA",
|
||||
"etiqueta": "Pendiente de biopsia"
|
||||
},
|
||||
{
|
||||
"codigo": "BIOPSIA_SIN_RESULTADO",
|
||||
"etiqueta": "Biopsia sin resultado"
|
||||
},
|
||||
{
|
||||
"codigo": "CANCER_CONFIRMADO",
|
||||
"etiqueta": "Cáncer confirmado"
|
||||
},
|
||||
{
|
||||
"codigo": "BENIGNO",
|
||||
"etiqueta": "Benigno, regresa a tamizaje"
|
||||
},
|
||||
{
|
||||
"codigo": "INFO_INSUFICIENTE",
|
||||
"etiqueta": "Información insuficiente"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "birads",
|
||||
"etiqueta": "Categoría BI-RADS",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "BIRADS_4A",
|
||||
"etiqueta": "BI-RADS 4A"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_4B",
|
||||
"etiqueta": "BI-RADS 4B"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_4C",
|
||||
"etiqueta": "BI-RADS 4C"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_5",
|
||||
"etiqueta": "BI-RADS 5"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_6",
|
||||
"etiqueta": "BI-RADS 6"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "grupo_edad",
|
||||
"etiqueta": "Grupo de edad",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "40-49",
|
||||
"etiqueta": "40-49"
|
||||
},
|
||||
{
|
||||
"codigo": "50-59",
|
||||
"etiqueta": "50-59"
|
||||
},
|
||||
{
|
||||
"codigo": "60-69",
|
||||
"etiqueta": "60-69"
|
||||
},
|
||||
{
|
||||
"codigo": "70+",
|
||||
"etiqueta": "70+"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "prioridad",
|
||||
"etiqueta": "Prioridad",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "ALTA",
|
||||
"etiqueta": "Alta"
|
||||
},
|
||||
{
|
||||
"codigo": "MEDIA",
|
||||
"etiqueta": "Media"
|
||||
},
|
||||
{
|
||||
"codigo": "BAJA",
|
||||
"etiqueta": "Baja"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"columnas": [
|
||||
{
|
||||
"clave": "id_seudonimo",
|
||||
"etiqueta": "Identificador seudónimo"
|
||||
},
|
||||
{
|
||||
"clave": "grupo_edad",
|
||||
"etiqueta": "Grupo de edad"
|
||||
},
|
||||
{
|
||||
"clave": "estatus",
|
||||
"etiqueta": "Estatus de seguimiento"
|
||||
},
|
||||
{
|
||||
"clave": "birads",
|
||||
"etiqueta": "Última mastografía",
|
||||
"detalles": [
|
||||
{
|
||||
"clave": "mastografia_fecha",
|
||||
"etiqueta": "Fecha"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "biopsia",
|
||||
"etiqueta": "Resultado histopatológico",
|
||||
"detalles": [
|
||||
{
|
||||
"clave": "biopsia_fecha",
|
||||
"etiqueta": "Fecha de biopsia"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "dias_mastografia_diagnostico",
|
||||
"etiqueta": "Días de mastografía a diagnóstico"
|
||||
},
|
||||
{
|
||||
"clave": "prioridad",
|
||||
"etiqueta": "Prioridad"
|
||||
}
|
||||
],
|
||||
"paginacion": {
|
||||
"page": 1,
|
||||
"page_size": 50,
|
||||
"total_items": 27,
|
||||
"total_pages": 1
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id_seudonimo": "M-0081",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Pendiente de biopsia",
|
||||
"estatus_codigo": "PENDIENTE_BIOPSIA",
|
||||
"birads": "BI-RADS 4A",
|
||||
"birads_codigo": "BIRADS_4A",
|
||||
"mastografia_fecha": "2026-07-25",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0020",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Información insuficiente",
|
||||
"estatus_codigo": "INFO_INSUFICIENTE",
|
||||
"birads": "BI-RADS 4C",
|
||||
"birads_codigo": "BIRADS_4C",
|
||||
"mastografia_fecha": "2026-07-31",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0051",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Pendiente de biopsia",
|
||||
"estatus_codigo": "PENDIENTE_BIOPSIA",
|
||||
"birads": "BI-RADS 5",
|
||||
"birads_codigo": "BIRADS_5",
|
||||
"mastografia_fecha": "2026-08-01",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0022",
|
||||
"grupo_edad": "60-69",
|
||||
"grupo_edad_codigo": "60-69",
|
||||
"estatus": "Pendiente de biopsia",
|
||||
"estatus_codigo": "PENDIENTE_BIOPSIA",
|
||||
"birads": "BI-RADS 6",
|
||||
"birads_codigo": "BIRADS_6",
|
||||
"mastografia_fecha": "2026-08-03",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0029",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Biopsia sin resultado",
|
||||
"estatus_codigo": "BIOPSIA_SIN_RESULTADO",
|
||||
"birads": "BI-RADS 4C",
|
||||
"birads_codigo": "BIRADS_4C",
|
||||
"mastografia_fecha": "2026-08-13",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": "2026-09-11",
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0019",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Pendiente de biopsia",
|
||||
"estatus_codigo": "PENDIENTE_BIOPSIA",
|
||||
"birads": "BI-RADS 4C",
|
||||
"birads_codigo": "BIRADS_4C",
|
||||
"mastografia_fecha": "2026-08-21",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0064",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Información insuficiente",
|
||||
"estatus_codigo": "INFO_INSUFICIENTE",
|
||||
"birads": "BI-RADS 5",
|
||||
"birads_codigo": "BIRADS_5",
|
||||
"mastografia_fecha": "2026-08-22",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0048",
|
||||
"grupo_edad": "60-69",
|
||||
"grupo_edad_codigo": "60-69",
|
||||
"estatus": "Biopsia sin resultado",
|
||||
"estatus_codigo": "BIOPSIA_SIN_RESULTADO",
|
||||
"birads": "BI-RADS 4C",
|
||||
"birads_codigo": "BIRADS_4C",
|
||||
"mastografia_fecha": "2026-09-01",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": "2026-10-07",
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0059",
|
||||
"grupo_edad": "40-49",
|
||||
"grupo_edad_codigo": "40-49",
|
||||
"estatus": "Pendiente de biopsia",
|
||||
"estatus_codigo": "PENDIENTE_BIOPSIA",
|
||||
"birads": "BI-RADS 4C",
|
||||
"birads_codigo": "BIRADS_4C",
|
||||
"mastografia_fecha": "2026-09-05",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0050",
|
||||
"grupo_edad": "60-69",
|
||||
"grupo_edad_codigo": "60-69",
|
||||
"estatus": "Información insuficiente",
|
||||
"estatus_codigo": "INFO_INSUFICIENTE",
|
||||
"birads": "BI-RADS 5",
|
||||
"birads_codigo": "BIRADS_5",
|
||||
"mastografia_fecha": "2026-09-06",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0084",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Biopsia sin resultado",
|
||||
"estatus_codigo": "BIOPSIA_SIN_RESULTADO",
|
||||
"birads": "BI-RADS 4C",
|
||||
"birads_codigo": "BIRADS_4C",
|
||||
"mastografia_fecha": "2026-09-08",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": "2026-09-18",
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0054",
|
||||
"grupo_edad": "60-69",
|
||||
"grupo_edad_codigo": "60-69",
|
||||
"estatus": "Pendiente de biopsia",
|
||||
"estatus_codigo": "PENDIENTE_BIOPSIA",
|
||||
"birads": "BI-RADS 4C",
|
||||
"birads_codigo": "BIRADS_4C",
|
||||
"mastografia_fecha": "2026-10-04",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0035",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Biopsia sin resultado",
|
||||
"estatus_codigo": "BIOPSIA_SIN_RESULTADO",
|
||||
"birads": "BI-RADS 4B",
|
||||
"birads_codigo": "BIRADS_4B",
|
||||
"mastografia_fecha": "2026-08-21",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": "2026-08-31",
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Media",
|
||||
"prioridad_codigo": "MEDIA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0052",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Información insuficiente",
|
||||
"estatus_codigo": "INFO_INSUFICIENTE",
|
||||
"birads": "BI-RADS 4A",
|
||||
"birads_codigo": "BIRADS_4A",
|
||||
"mastografia_fecha": "2026-10-01",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Media",
|
||||
"prioridad_codigo": "MEDIA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0033",
|
||||
"grupo_edad": "40-49",
|
||||
"grupo_edad_codigo": "40-49",
|
||||
"estatus": "Cáncer confirmado",
|
||||
"estatus_codigo": "CANCER_CONFIRMADO",
|
||||
"birads": "BI-RADS 5",
|
||||
"birads_codigo": "BIRADS_5",
|
||||
"mastografia_fecha": "2026-07-25",
|
||||
"biopsia": "Carcinoma invasor",
|
||||
"biopsia_fecha": "2026-09-03",
|
||||
"dias_mastografia_diagnostico": 15,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0040",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Benigno, regresa a tamizaje",
|
||||
"estatus_codigo": "BENIGNO",
|
||||
"birads": "BI-RADS 4A",
|
||||
"birads_codigo": "BIRADS_4A",
|
||||
"mastografia_fecha": "2026-07-25",
|
||||
"biopsia": "Benigno",
|
||||
"biopsia_fecha": "2026-08-16",
|
||||
"dias_mastografia_diagnostico": 71,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0011",
|
||||
"grupo_edad": "40-49",
|
||||
"grupo_edad_codigo": "40-49",
|
||||
"estatus": "Benigno, regresa a tamizaje",
|
||||
"estatus_codigo": "BENIGNO",
|
||||
"birads": "BI-RADS 4B",
|
||||
"birads_codigo": "BIRADS_4B",
|
||||
"mastografia_fecha": "2026-08-08",
|
||||
"biopsia": "Benigno",
|
||||
"biopsia_fecha": "2026-08-16",
|
||||
"dias_mastografia_diagnostico": 46,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0047",
|
||||
"grupo_edad": "60-69",
|
||||
"grupo_edad_codigo": "60-69",
|
||||
"estatus": "Cáncer confirmado",
|
||||
"estatus_codigo": "CANCER_CONFIRMADO",
|
||||
"birads": "BI-RADS 5",
|
||||
"birads_codigo": "BIRADS_5",
|
||||
"mastografia_fecha": "2026-08-28",
|
||||
"biopsia": "Carcinoma invasor",
|
||||
"biopsia_fecha": "2026-09-28",
|
||||
"dias_mastografia_diagnostico": 36,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0038",
|
||||
"grupo_edad": "60-69",
|
||||
"grupo_edad_codigo": "60-69",
|
||||
"estatus": "Cáncer confirmado",
|
||||
"estatus_codigo": "CANCER_CONFIRMADO",
|
||||
"birads": "BI-RADS 4A",
|
||||
"birads_codigo": "BIRADS_4A",
|
||||
"mastografia_fecha": "2026-08-29",
|
||||
"biopsia": "Carcinoma invasor",
|
||||
"biopsia_fecha": "2026-10-08",
|
||||
"dias_mastografia_diagnostico": 42,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0072",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Benigno, regresa a tamizaje",
|
||||
"estatus_codigo": "BENIGNO",
|
||||
"birads": "BI-RADS 4A",
|
||||
"birads_codigo": "BIRADS_4A",
|
||||
"mastografia_fecha": "2026-09-03",
|
||||
"biopsia": "Benigno",
|
||||
"biopsia_fecha": "2026-09-26",
|
||||
"dias_mastografia_diagnostico": 49,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0021",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Cáncer confirmado",
|
||||
"estatus_codigo": "CANCER_CONFIRMADO",
|
||||
"birads": "BI-RADS 5",
|
||||
"birads_codigo": "BIRADS_5",
|
||||
"mastografia_fecha": "2026-09-07",
|
||||
"biopsia": "Carcinoma invasor",
|
||||
"biopsia_fecha": "2026-09-27",
|
||||
"dias_mastografia_diagnostico": 56,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0039",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Benigno, regresa a tamizaje",
|
||||
"estatus_codigo": "BENIGNO",
|
||||
"birads": "BI-RADS 4C",
|
||||
"birads_codigo": "BIRADS_4C",
|
||||
"mastografia_fecha": "2026-09-08",
|
||||
"biopsia": "Benigno",
|
||||
"biopsia_fecha": "2026-09-17",
|
||||
"dias_mastografia_diagnostico": 27,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0083",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Cáncer confirmado",
|
||||
"estatus_codigo": "CANCER_CONFIRMADO",
|
||||
"birads": "BI-RADS 5",
|
||||
"birads_codigo": "BIRADS_5",
|
||||
"mastografia_fecha": "2026-09-20",
|
||||
"biopsia": "Carcinoma invasor",
|
||||
"biopsia_fecha": "2026-09-27",
|
||||
"dias_mastografia_diagnostico": 25,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0062",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Benigno, regresa a tamizaje",
|
||||
"estatus_codigo": "BENIGNO",
|
||||
"birads": "BI-RADS 4A",
|
||||
"birads_codigo": "BIRADS_4A",
|
||||
"mastografia_fecha": "2026-09-26",
|
||||
"biopsia": "Benigno",
|
||||
"biopsia_fecha": "2026-10-14",
|
||||
"dias_mastografia_diagnostico": 19,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0032",
|
||||
"grupo_edad": "40-49",
|
||||
"grupo_edad_codigo": "40-49",
|
||||
"estatus": "Benigno, regresa a tamizaje",
|
||||
"estatus_codigo": "BENIGNO",
|
||||
"birads": "BI-RADS 4B",
|
||||
"birads_codigo": "BIRADS_4B",
|
||||
"mastografia_fecha": "2026-10-07",
|
||||
"biopsia": "Benigno",
|
||||
"biopsia_fecha": "2026-10-20",
|
||||
"dias_mastografia_diagnostico": 61,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0077",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Benigno, regresa a tamizaje",
|
||||
"estatus_codigo": "BENIGNO",
|
||||
"birads": "BI-RADS 4B",
|
||||
"birads_codigo": "BIRADS_4B",
|
||||
"mastografia_fecha": "2026-10-14",
|
||||
"biopsia": "Lesión de riesgo (B3)",
|
||||
"biopsia_fecha": "2026-10-20",
|
||||
"dias_mastografia_diagnostico": 60,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0027",
|
||||
"grupo_edad": "70+",
|
||||
"grupo_edad_codigo": "70+",
|
||||
"estatus": "Cáncer confirmado",
|
||||
"estatus_codigo": "CANCER_CONFIRMADO",
|
||||
"birads": "BI-RADS 4B",
|
||||
"birads_codigo": "BIRADS_4B",
|
||||
"mastografia_fecha": "2026-10-16",
|
||||
"biopsia": "Carcinoma invasor",
|
||||
"biopsia_fecha": "2026-10-20",
|
||||
"dias_mastografia_diagnostico": 36,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
{"error": "la selección tiene menos de 5 pacientes: su lista no se publica.", "motivo": "supresion"}
|
||||
@@ -0,0 +1 @@
|
||||
{"simulado": true, "cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "a2c95b755ba3ccab288c148153e14be1e958aadff1f5a320a4d54e84b3cae745", "corte": "2026-11-17", "ventana": {"meses": 6, "desde": "2026-05-18", "hasta": "2026-11-17"}, "filtros": {"birads": "BIRADS_5", "grupo_edad": null, "biopsia": null}, "filtros_disponibles": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "columnas": [{"clave": "pac_id", "etiqueta": "Identificador de paciente"}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad"}, {"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]}, {"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]}], "paginacion": {"page": 1, "page_size": 50, "total_items": 16, "total_pages": 1}, "items": [{"pac_id": "251", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-11-05", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "185", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "95", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-15", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-11-14"}, {"pac_id": "188", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-04", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-20"}, {"pac_id": "126", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-27", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-04"}, {"pac_id": "52", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "220", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-19", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}, {"pac_id": "254", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-11", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-09-16"}, {"pac_id": "129", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-22", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-08-20"}, {"pac_id": "117", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-21", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-08-09"}, {"pac_id": "101", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-03", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-07-31"}, {"pac_id": "225", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-02", "biopsia": "CARCINOMA_IN_SITU", "biopsia_fecha": "2026-07-31"}, {"pac_id": "287", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-14", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-07-13"}, {"pac_id": "55", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-09", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-06-30"}, {"pac_id": "7", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-02", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "260", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-05-21", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-06-07"}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"simulado": true, "cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "a2c95b755ba3ccab288c148153e14be1e958aadff1f5a320a4d54e84b3cae745", "corte": "2026-11-17", "ventana": {"meses": 3, "desde": "2026-08-18", "hasta": "2026-11-17"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "filtros_disponibles": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "columnas": [{"clave": "pac_id", "etiqueta": "Identificador de paciente"}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad"}, {"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]}, {"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]}], "paginacion": {"page": 1, "page_size": 50, "total_items": 16, "total_pages": 1}, "items": [{"pac_id": "251", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-11-05", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "54", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "185", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "255", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-21", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "95", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-15", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-11-14"}, {"pac_id": "4", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-10", "biopsia": "BENIGNO", "biopsia_fecha": "2026-11-06"}, {"pac_id": "256", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-08", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "188", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-04", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-20"}, {"pac_id": "239", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-09-14", "biopsia": "BENIGNO", "biopsia_fecha": "2026-10-06"}, {"pac_id": "245", "grupo_edad": "40-49", "birads": "BIRADS_4", "mastografia_fecha": "2026-09-09", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "186", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-31", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}, {"pac_id": "282", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-29", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-10"}, {"pac_id": "126", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-27", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-04"}, {"pac_id": "31", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "52", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "220", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-19", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}]}
|
||||
@@ -0,0 +1,59 @@
|
||||
{
|
||||
"id": "cama_tasa_deteccion_histopatologica",
|
||||
"titulo": "Detección histopatológica",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C1",
|
||||
"unidad": "examen",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S1"
|
||||
],
|
||||
"estrato": null,
|
||||
"valores_estrato": [],
|
||||
"etiquetas_estrato": {},
|
||||
"grupos": {
|
||||
"total": "Total"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
"notas": [
|
||||
"Detección histopatológica"
|
||||
],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"report_id": 127,
|
||||
"periodo_inicio": "2025-01-01",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"fecha_corte": "2026-11-12",
|
||||
"generado_en": "2026-11-12T17:00:31.282549+00:00",
|
||||
"kit_version": "0.8.0",
|
||||
"toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d",
|
||||
"parametros_sha": "d909bc4a153b244533acde1f26ce8c4cfaaedf0d277239dd9b1ce9e9f65b23a9",
|
||||
"parametros": {
|
||||
"sql": {
|
||||
"fecha_corte": "2026-11-12",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"periodo_inicio": "2025-01-01"
|
||||
},
|
||||
"umbral_supresion": 5
|
||||
}
|
||||
}
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "total",
|
||||
"estrato": null,
|
||||
"numerador": null,
|
||||
"denominador": null,
|
||||
"valor": null,
|
||||
"ic_bajo": null,
|
||||
"ic_alto": null,
|
||||
"suprimido": 1,
|
||||
"n_sin_evento": 0,
|
||||
"n_excluido": 0
|
||||
}
|
||||
],
|
||||
"totales_estrato": []
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
{
|
||||
"id": "cama_tasa_deteccion_histopatologica",
|
||||
"titulo": "Detección histopatológica",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C1",
|
||||
"unidad": "examen",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S1"
|
||||
],
|
||||
"estrato": null,
|
||||
"valores_estrato": [],
|
||||
"etiquetas_estrato": {},
|
||||
"grupos": {
|
||||
"total": "Total"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
"notas": [
|
||||
"Detección histopatológica"
|
||||
],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"report_id": 127,
|
||||
"periodo_inicio": "2025-01-01",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"fecha_corte": "2026-11-12",
|
||||
"generado_en": "2026-11-12T17:00:42.857591+00:00",
|
||||
"kit_version": "0.8.0",
|
||||
"toml_sha": "38b2efac7d70f9c0bf37b03b7abd21d48bff4c6d8f6786fccbccfa31a7fcd7e7",
|
||||
"parametros_sha": "7202a2779ae47c29a7659dd6fdfb77e8895d4d778a772ff13cc2ce93c5a6e871",
|
||||
"parametros": {
|
||||
"sql": {
|
||||
"fecha_corte": "2026-11-12",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"periodo_inicio": "2025-01-01"
|
||||
},
|
||||
"umbral_supresion": 1
|
||||
}
|
||||
}
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "total",
|
||||
"estrato": null,
|
||||
"numerador": 0,
|
||||
"denominador": 1,
|
||||
"valor": 0.0,
|
||||
"ic_bajo": 0.0,
|
||||
"ic_alto": 79.3450688208,
|
||||
"suprimido": 0,
|
||||
"n_sin_evento": 1,
|
||||
"n_excluido": 0
|
||||
}
|
||||
],
|
||||
"totales_estrato": []
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
@@ -3,7 +3,6 @@ import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { MatSelect } from '@angular/material/select';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
@@ -28,7 +27,6 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
fixture.componentRef.setInput('indicador', { id: 'i', titulo: 'I', contrato: 'C2', figuras, tipos_periodo: ['semestre'] });
|
||||
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges();
|
||||
}
|
||||
function select() { return fixture.debugElement.query(By.directive(MatSelect)).componentInstance as MatSelect; }
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).filter(e => e.componentInstance.result().status !== 'deferred'); }
|
||||
function request(id: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + id)); }
|
||||
function open() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); }
|
||||
@@ -47,13 +45,9 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
expect(fixture.componentInstance.indicador.contrato).toBe(contrato);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para selector, consulta y memoria', () => {
|
||||
it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para consulta y memoria', () => {
|
||||
fixture.destroy(); create(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c2_barras', 'fig_c2_donas', 'fig_c9_futura']);
|
||||
fixture.componentRef.setInput('indicador', { ...fixture.componentInstance.indicador, contrato: 'C1' }); fixture.detectChanges();
|
||||
expect(select().options.map(option => [option.value, option.viewValue])).toEqual([
|
||||
['fig_c1_grupos', 'Grupos'], ['fig_c2_apiladas', 'Barras apiladas'],
|
||||
['fig_c2_barras', 'Barras'], ['fig_c2_donas', 'Donas'], ['fig_c9_futura', 'Representación 5'],
|
||||
]);
|
||||
http.expectNone(() => true);
|
||||
open(); request('fig_c1_grupos').flush({ data: [], layout: {} });
|
||||
for (const [id, label] of [
|
||||
@@ -62,7 +56,7 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
['fig_c2_donas', 'Donas'],
|
||||
['fig_c9_futura', 'Representación 5'],
|
||||
]) {
|
||||
select().selectionChange.emit({ source: select(), value: id }); fixture.detectChanges();
|
||||
fixture.componentInstance.selectFigure(id); fixture.detectChanges();
|
||||
const pending = request(id);
|
||||
expect(pending.request.url).toBe('/cacu/indicadores/i/figuras/' + id);
|
||||
expect(pending.request.params.get('tema')).toBe('claro');
|
||||
@@ -74,9 +68,9 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
}
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('una opción publicada está deshabilitada y sólo consulta esa figura', () => {
|
||||
fixture.destroy(); create(['f']); open(); expect(select().disabled).toBe(true);
|
||||
expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
|
||||
it('no ofrece selector de representación y sólo consulta la figura mostrada', () => {
|
||||
fixture.destroy(); create(['f', 'g']); open(); expect(fixture.nativeElement.querySelector('mat-select')).toBeNull();
|
||||
request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
|
||||
});
|
||||
it('comparte una sola solicitud de metadatos entre las dos figuras y asocia por ID exacto', () => {
|
||||
fixture.componentRef.setInput('indicador', { id: 'cacu_eu13', titulo: 'EU13', contrato: 'C2',
|
||||
@@ -98,9 +92,8 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
expect(cards.every(card => card.interpretation.every(line => line !== 'No debe asignarse.'))).toBe(true);
|
||||
});
|
||||
it('múltiples opciones habilitan el selector, mantienen una representación y cancelan cambios rápidos', () => {
|
||||
open(); const first = request('f'); expect(select().disabled).toBe(false);
|
||||
expect(select().options.map(o => o.value)).toEqual(['f', 'g']); expect(panels()).toHaveLength(1);
|
||||
select().selectionChange.emit({ source: select(), value: 'g' }); fixture.detectChanges();
|
||||
open(); const first = request('f'); expect(panels()).toHaveLength(1);
|
||||
fixture.componentInstance.selectFigure('g'); fixture.detectChanges();
|
||||
const next = request('g'); expect(first.cancelled).toBe(true); expect(panels()).toHaveLength(1);
|
||||
expect(next.request.params.get('periodos')).toBe('2025-S1');
|
||||
fixture.componentInstance.selectFigure('f'); fixture.detectChanges(); expect(next.cancelled).toBe(true);
|
||||
|
||||
@@ -2,8 +2,6 @@ import { ChangeDetectorRef, Component, effect, ElementRef, inject, Input, OnChan
|
||||
import { catchError, of, Subscription } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models';
|
||||
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
|
||||
@@ -20,12 +18,16 @@ import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
||||
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
|
||||
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
||||
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
|
||||
import { IndicadorHistopatologiaCama } from './indicador-histopatologia-cama';
|
||||
import { ID_HISTOPATOLOGIA } from './indicadores-histopatologia-cama';
|
||||
import { parTiempos } from './indicadores-tiempos-pareados';
|
||||
import { IndicadorConteosPareados } from './indicador-conteos-pareados';
|
||||
import { parConteos } from './indicadores-conteos-pareados';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-catalog-card',
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || !!tiempos' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia],
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
|
||||
template: `
|
||||
<mat-card>
|
||||
<header>
|
||||
@@ -33,13 +35,15 @@ import { parTiempos } from './indicadores-tiempos-pareados';
|
||||
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
|
||||
</div>
|
||||
</header>
|
||||
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
|
||||
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + indicador.titulo"
|
||||
(click)="pinChanged.emit()">
|
||||
<mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }}
|
||||
</button>
|
||||
@if (!sobrio) {
|
||||
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
|
||||
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + indicador.titulo"
|
||||
(click)="pinChanged.emit()">
|
||||
<mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }}
|
||||
</button>
|
||||
}
|
||||
<div class="catalog-content" [id]="contentId" [attr.aria-labelledby]="titleId">
|
||||
<p class="catalog-metadata">{{ indicador.figuras.length }} figuras publicadas</p>
|
||||
@if (!sobrio) { <p class="catalog-metadata">{{ indicador.figuras.length }} figuras publicadas</p> }
|
||||
@if (isEu7) {
|
||||
<div #visibilityRegion class="eu7-region">
|
||||
<app-indicador-eu7-escenario [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
@@ -48,21 +52,19 @@ import { parTiempos } from './indicadores-tiempos-pareados';
|
||||
<div #visibilityRegion class="confirmacion-region">
|
||||
<app-indicador-confirmacion-citologia [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (isHistopatologia) {
|
||||
<div #visibilityRegion class="confirmacion-region">
|
||||
<app-indicador-histopatologia-cama [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (tiempos; as par) {
|
||||
<div #visibilityRegion class="tiempos-region">
|
||||
<app-indicador-tiempos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (conteos; as par) {
|
||||
<div #visibilityRegion class="conteos-region">
|
||||
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (selectedFigure) {
|
||||
@if (!pair.length || otherFigures.length) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Representación gráfica</mat-label>
|
||||
<mat-select [value]="selectedFigure" [disabled]="indicador.figuras.length === 1"
|
||||
[attr.aria-label]="'Representación gráfica de ' + indicador.titulo" (selectionChange)="selectFigure($event.value)">
|
||||
@if (pair.length) { <mat-option [value]="pair[0]">Dona y barras</mat-option> }
|
||||
@for (figure of (pair.length ? otherFigures : indicador.figuras); track figure) { <mat-option [value]="figure">{{ figureDisplayName(figure, indicador.figuras) }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
|
||||
@for (figure of displayFigures; track panelIdentity(figure)) {
|
||||
<div class="representation-panel">
|
||||
@@ -103,7 +105,7 @@ import { parTiempos } from './indicadores-tiempos-pareados';
|
||||
}
|
||||
.card-identity { min-width: 0; }
|
||||
h2, p { overflow-wrap: anywhere; }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 700; font-size: 1.5rem; line-height: 1.25; }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; }
|
||||
.pin-toggle { align-self: start; margin-top: var(--issste-space-1); max-width: 100%; height: auto;
|
||||
min-width: 48px; min-height: 48px; color: var(--issste-text); }
|
||||
.pin-toggle mat-icon { flex-shrink: 0; }
|
||||
@@ -131,12 +133,17 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
if (this.indicador && this.applied) untracked(() => this.updateNumeric());
|
||||
});
|
||||
}
|
||||
// CaMa's cards carry no pin, representation selector or figure count, as in the mockup.
|
||||
get sobrio() { return this.dominio === 'cama'; }
|
||||
get pair() { return dualFigures(this.indicador); }
|
||||
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
|
||||
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
|
||||
// CaMa's histopathology by BI-RADS has its own coordinated view, as the cytology confirmation has in CaCu.
|
||||
get isHistopatologia() { return this.dominio === 'cama' && this.indicador.id === ID_HISTOPATOLOGIA; }
|
||||
// Connected time pairs replace the diagnosis card with one coordinated box plot.
|
||||
get tiempos() { return parTiempos(this.dominio, this.indicador.id); }
|
||||
get otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); }
|
||||
// Exams and patients of the same finding, drawn together on the exams' card.
|
||||
get conteos() { return parConteos(this.dominio, this.indicador.id); }
|
||||
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
|
||||
get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; }
|
||||
private updateNumeric() {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
<section class="conteos" [attr.aria-label]="indicador.titulo + ', por ' + par.unidades.pacientes.slice(0, -1) + ' y por ' + par.unidades.examenes.slice(0, -1)">
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||
@if (helpOpen) {
|
||||
<div class="methodology">
|
||||
<section class="reading-guide" aria-label="Cómo leer: dona por categoría">
|
||||
<h3>Dona por categoría</h3>
|
||||
@if (donutGuide; as guide) {
|
||||
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
|
||||
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
||||
} @else if (!metadata) { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
||||
@else { <p>El servicio no publica instrucciones de lectura para esta figura.</p> }
|
||||
</section>
|
||||
<section class="reading-guide" aria-label="Cómo leer: pacientes y mastografías">
|
||||
<h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}</h3>
|
||||
<p>Cada paciente cuenta una vez en el periodo, en la categoría más grave de sus mastografías. Cada mastografía cuenta en su propia categoría. Las barras comparan ambos conteos por familia de BI-RADS; no se calcula cuántas mastografías tiene cada paciente, porque no son las mismas poblaciones.</p>
|
||||
</section>
|
||||
</div>
|
||||
}
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando {{ par.unidades.examenes }} y {{ par.unidades.pacientes }} del mismo periodo…</p> }
|
||||
@case ('empty') { <p role="status">No hay periodos publicados por los dos conteos.</p> }
|
||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (status() === 'ready' && model; as m) {
|
||||
@if (pages.length > 1) {
|
||||
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
|
||||
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||
<span role="status">{{ m.periodo }}, {{ periodIndex + 1 }} de {{ pages.length }}</span>
|
||||
<button type="button" aria-label="Periodo siguiente" [disabled]="periodIndex === pages.length - 1" (click)="changePeriod(1)">›</button>
|
||||
</nav>
|
||||
}
|
||||
<div class="figures">
|
||||
<section class="figure"><h3>{{ par.unidades.examenes | titlecase }} por categoría, {{ m.periodo }}</h3>
|
||||
@if (total) {
|
||||
<app-plotly-chart [figure]="donutFigure!" class="donut-chart" (widthChanged)="ajustarAnchoDona($event)" [showNotes]="false" [label]="indicador.titulo + ', dona, ' + m.periodo" />
|
||||
} @else { <p role="status">{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}</p> }
|
||||
@if (m.sinDato) { <p class="note">Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.</p> }
|
||||
</section>
|
||||
<section class="figure"><h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}</h3>
|
||||
<app-plotly-chart [figure]="barsFigure!" [showNotes]="false" [label]="indicador.titulo + ', barras por familia de BI-RADS, ' + m.periodo" />
|
||||
@if (!m.pacientesVerificados) { <p class="note" role="status">Pacientes pendientes: la versión publicada del indicador de pacientes no es una cuya definición se haya verificado para sumar sus categorías.</p> }
|
||||
</section>
|
||||
</div>
|
||||
<p class="note">Cada paciente cuenta una vez, en la categoría más grave de sus mastografías del periodo; cada mastografía cuenta en su categoría. Por eso no se calcula la razón de mastografías por paciente.</p>
|
||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
|
||||
<table><caption>{{ par.unidades.pacientes | titlecase }} (su categoría más grave) y {{ par.unidades.examenes }}, {{ m.periodo }}</caption>
|
||||
<thead><tr><th scope="col">Familia de BI-RADS</th><th scope="col">{{ par.unidades.pacientes | titlecase }}</th><th scope="col">{{ par.unidades.examenes | titlecase }}</th></tr></thead>
|
||||
<tbody>@for (f of m.filas; track f.id) { <tr><th scope="row">{{ f.etiqueta }}</th><td>{{ textoPacientes(f.pacientes) }}</td><td>{{ texto(f.examenes) }}</td></tr> }</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,24 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
.conteos { min-width: 0; padding-top: var(--issste-space-3); }
|
||||
p, h3, summary { overflow-wrap: anywhere; }
|
||||
.applied-summary, .note { color: var(--issste-text-secondary); }
|
||||
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.reading-guide h3 { margin: 0 0 .25rem; }
|
||||
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
|
||||
h3 { font-size: 1rem; font-weight: 500; line-height: 1.5; }
|
||||
.periods { display: flex; align-items: center; gap: var(--issste-space-3); }
|
||||
.periods button { min-width: 44px; min-height: 44px; font-size: 1.25rem; color: var(--issste-text); background: var(--issste-surface);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); cursor: pointer; }
|
||||
.periods button:disabled { opacity: .5; cursor: default; }
|
||||
// The two figures share the card in equal halves; one above the other on a narrow card.
|
||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||
@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
app-plotly-chart { --plot-height: 400px; }
|
||||
// Keep space for the outside labels and let the existing plot viewport scroll on very narrow cards.
|
||||
.donut-chart { --plot-min-width: 230px; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.table-scroll { overflow: auto; }
|
||||
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||
caption { text-align: start; font-weight: 600; }
|
||||
@@ -0,0 +1,122 @@
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { TitleCasePipe } from '@angular/common';
|
||||
import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { barrasConteos, ConteosIncompatibles, donaConteos, ModeloConteos, modelosConteos, ParConteos, totalExamenes } from './indicadores-conteos-pareados';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-conteos-pareados',
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart, TitleCasePipe],
|
||||
templateUrl: './indicador-conteos-pareados.html',
|
||||
styleUrl: './indicador-conteos-pareados.scss',
|
||||
})
|
||||
export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) par!: ParConteos;
|
||||
// The card's indicator (the exams); its partner (the patients) has no card and is requested by id.
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() visible = true;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
readonly metadataRequested = output<void>();
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
message = '';
|
||||
periodIndex = 0;
|
||||
pages: ModeloConteos[] = [];
|
||||
donutFigure?: PlotlyFigure;
|
||||
barsFigure?: PlotlyFigure;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
private anchoDona = 390;
|
||||
|
||||
get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; }
|
||||
get total() { return this.model ? totalExamenes(this.model) : null; }
|
||||
texto(n: number | null) { return n === null ? 'Sin dato' : n.toLocaleString('es-MX'); }
|
||||
textoPacientes(n: number | null) { return n === null && this.model && !this.model.pacientesVerificados ? 'Pendiente' : this.texto(n); }
|
||||
helpOpen = false;
|
||||
// "Cómo leer": what the kit publishes for the exams' donut. The bars combine two indicators, so the kit's
|
||||
// description of its own bars does not apply to them and is not used.
|
||||
get donutGuide() {
|
||||
const detail = this.metadata?.figuras_detalle?.find(item => item.figura === 'fig_c2_donas');
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
return descripcion || como_leer.length ? { descripcion, como_leer } : undefined;
|
||||
}
|
||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.par.examenes, this.par.pacientes, this.indicador.tipos_periodo]);
|
||||
if (key !== this.key) {
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.clear();
|
||||
if (!this.visible) { this.status.set('deferred'); return; }
|
||||
this.load();
|
||||
} else if (this.visible && !this.loaded) this.load();
|
||||
else if (this.model && changes['tema']) this.draw();
|
||||
}
|
||||
retry() { if (this.visible) this.load(); }
|
||||
private clear() { this.pages = []; this.periodIndex = 0; this.donutFigure = undefined; this.barsFigure = undefined; }
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.clear();
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
if (this.indicador.id !== this.par.examenes || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
|
||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica el conteo necesario para esta vista.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
const key = this.key;
|
||||
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
|
||||
this.status.set('loading');
|
||||
this.subscription = combineLatest([
|
||||
this.snapshots.datos(this.dominio, this.par.examenes, this.applied.tipo, periods, this.indicador.version),
|
||||
this.snapshots.datos(this.dominio, this.par.pacientes, this.applied.tipo, periods),
|
||||
]).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: ([examenes, pacientes]) => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.pages = modelosConteos(this.par, examenes, pacientes, this.applied.tipo);
|
||||
// The most recent period first; navigation goes back.
|
||||
this.periodIndex = Math.max(0, this.pages.length - 1);
|
||||
this.draw(); this.status.set(this.model ? 'ready' : 'empty');
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
error: error => { if (key === this.key) this.failure(error); },
|
||||
});
|
||||
}
|
||||
private failure(error: unknown) {
|
||||
this.clear();
|
||||
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||
: error instanceof ConteosIncompatibles ? error.message : httpMessage(error);
|
||||
this.status.set(error instanceof ConteosIncompatibles || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
|
||||
? 'incompatible' : 'error');
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
changePeriod(step: number) {
|
||||
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
|
||||
this.periodIndex += step; this.draw();
|
||||
}
|
||||
ajustarAnchoDona(ancho: number) {
|
||||
if (ancho === this.anchoDona) return;
|
||||
this.anchoDona = ancho;
|
||||
const m = this.model;
|
||||
if (m) this.donutFigure = donaConteos(m, this.par, this.tema, ancho);
|
||||
}
|
||||
private draw() {
|
||||
const m = this.model;
|
||||
if (!m) return;
|
||||
this.donutFigure = donaConteos(m, this.par, this.tema, this.anchoDona);
|
||||
this.barsFigure = barrasConteos(m, this.par, this.tema);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||
}
|
||||
@@ -83,7 +83,23 @@
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (state.status === 'ready' && state.donutLegend?.length) {
|
||||
@if (state.status === 'ready' && state.highlight; as h) {
|
||||
<div class="highlight-legend" role="group" aria-label="Resaltar partes de la figura">
|
||||
<p class="highlight-status" role="status" aria-live="polite">Selección: {{ highlightStatus }}</p>
|
||||
<button type="button" class="highlight-back" (click)="highlightBack()" [disabled]="!highlightSelection.group && !highlightSelection.item">Volver</button>
|
||||
@for (row of highlightRows(h); track row.group?.id ?? '') {
|
||||
<div class="highlight-keys" role="group" [attr.aria-label]="row.group ? row.group.label + ' y sus categorías' : 'Categorías'">
|
||||
@if (row.group; as g) {
|
||||
<button type="button" class="highlight-group" [attr.aria-pressed]="highlightSelection.group === g.id" (click)="highlight('group', g.id)"><span class="legend-swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.label }}</button>
|
||||
}
|
||||
@for (c of row.items; track c.id) {
|
||||
<button type="button" [attr.aria-pressed]="highlightSelection.item === c.id" [disabled]="!!highlightSelection.group && c.group !== highlightSelection.group"
|
||||
[attr.aria-label]="c.short ? c.label : null" (click)="highlight('item', c.id)"><span class="legend-swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.short ?? c.label }}</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
} @else if (state.status === 'ready' && state.donutLegend?.length) {
|
||||
<div class="donut-static-legend" role="list" aria-label="Leyenda de la dona">
|
||||
@for (entry of state.donutLegend; track entry.label) {
|
||||
<span class="donut-static-legend__item" role="listitem">
|
||||
@@ -94,7 +110,7 @@
|
||||
}
|
||||
</div>
|
||||
<div class="plot-slot" [hidden]="state.status !== 'ready'">
|
||||
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ', ' + selected?.id + ', ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
||||
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend || state.highlight ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ', ' + selected?.id + ', ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
||||
</div>
|
||||
}
|
||||
<div class="figure-footer" [hidden]="state.status !== 'ready'">
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
:host(.methodology-expanded) .figure-card { grid-row: auto; }
|
||||
.figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); font-family: var(--issste-font-heading); overflow-wrap: anywhere; }
|
||||
.state { padding: 1.25rem; margin: 0; overflow-wrap: anywhere; }
|
||||
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; }
|
||||
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b7d251; --mat-sys-outline: #a1aabd; }
|
||||
.figure-id { padding: .25rem 1rem 0; margin: 0; font: var(--mat-sys-body-small); opacity: .8; overflow-wrap: anywhere; }
|
||||
@media (max-width: 550px) { .methodology-detail { padding: var(--issste-space-3); } }
|
||||
|
||||
@@ -113,3 +113,16 @@
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.donut-children-region, .donut-children-region.expanded { transition: none; transform: none; }
|
||||
}
|
||||
// Highlight buttons, as in CaCu's «Distribución de resultados citológicos».
|
||||
.highlight-legend { display: grid; gap: .5rem; padding: .5rem .75rem .75rem; color: var(--issste-text); }
|
||||
.dark .highlight-legend { color: #eef1f7; }
|
||||
.highlight-status { margin: 0; font-weight: 600; }
|
||||
.highlight-back { justify-self: start; }
|
||||
.highlight-keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.highlight-legend button { display: inline-flex; align-items: center; gap: .4rem; min-height: 36px; padding: .3rem .75rem; text-align: start;
|
||||
overflow-wrap: anywhere; color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 999px; font: inherit; cursor: pointer; }
|
||||
.highlight-legend button:disabled { opacity: .45; cursor: default; }
|
||||
.highlight-legend button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
|
||||
.highlight-legend button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
.highlight-legend .legend-swatch { border-radius: 50%; }
|
||||
.highlight-legend .highlight-group { font-weight: 600; }
|
||||
|
||||
@@ -12,6 +12,7 @@ import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, HighlightSelection, toggleHighlight } from './indicadores-highlight';
|
||||
|
||||
// The panel owns requests; the card receives the original and its presentation copy.
|
||||
export interface FigureState {
|
||||
@@ -22,6 +23,10 @@ export interface FigureState {
|
||||
categoryLabels?: readonly CategoryLabel[];
|
||||
minimumPlotWidth?: number;
|
||||
donutLegend?: readonly DonutLegendEntry[];
|
||||
// The figure already lays out its own rings (C1 double donut): show the legend, keep the figure as is.
|
||||
ownLayout?: boolean;
|
||||
// Legend buttons that highlight one part of the figure (CaCu style).
|
||||
highlight?: FigureHighlight;
|
||||
plotWidth?: number;
|
||||
plotHeight?: number;
|
||||
message?: string;
|
||||
@@ -64,7 +69,7 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
}
|
||||
@Input({ required: true }) set state(value: FigureState) {
|
||||
if (value.status !== 'ready' || value.figure !== this.currentState?.figure
|
||||
|| JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; }
|
||||
|| JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; this.highlightSelection = {}; }
|
||||
this.currentState = value;
|
||||
if (value.status === 'ready') {
|
||||
this.updateDonut();
|
||||
@@ -87,7 +92,8 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
? { ...presentationFigure, layout: { ...presentationFigure.layout, height: this.state.plotHeight } } : presentationFigure;
|
||||
this.chartFigure = source && hierarchy
|
||||
? donutView(source, hierarchy, this.activeParent, this.state.plotWidth)
|
||||
: source && this.state.donutLegend ? donutSimpleView(source) : source;
|
||||
: source && this.state.highlight ? highlightFigure(source, this.state.highlight, this.highlightSelection)
|
||||
: source && this.state.donutLegend && !this.state.ownLayout ? donutSimpleView(source) : source;
|
||||
}
|
||||
expandParent(parent: string) {
|
||||
if (this.state.status !== 'ready' || !this.state.hierarchy?.parents.includes(parent)
|
||||
@@ -109,9 +115,28 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
target?.focus();
|
||||
}
|
||||
}
|
||||
highlightSelection: HighlightSelection = {};
|
||||
readonly highlightRows = highlightRows;
|
||||
get highlightStatus() { return this.state.highlight ? highlightLabel(this.state.highlight, this.highlightSelection) : ''; }
|
||||
highlight(kind: 'group' | 'item', id: string) {
|
||||
if (!this.state.highlight) return;
|
||||
this.highlightSelection = toggleHighlight(this.state.highlight, this.highlightSelection, kind, id);
|
||||
this.updateDonut();
|
||||
}
|
||||
highlightBack() {
|
||||
const sel = this.highlightSelection;
|
||||
this.highlightSelection = sel.item && sel.group ? { group: sel.group } : {};
|
||||
this.updateDonut();
|
||||
}
|
||||
plotClicked(event: unknown) {
|
||||
if (!event || typeof event !== 'object' || !('points' in event) || !Array.isArray(event.points)) return;
|
||||
const point = event.points[0];
|
||||
if (this.state.highlight) {
|
||||
const hit = typeof point?.curveNumber === 'number' && typeof point.pointNumber === 'number'
|
||||
? highlightAt(this.state.highlight, { trace: point.curveNumber, index: point.pointNumber }) : undefined;
|
||||
if (hit) this.highlight(hit.kind, hit.id);
|
||||
return;
|
||||
}
|
||||
if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label);
|
||||
else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label);
|
||||
}
|
||||
|
||||
@@ -215,10 +215,10 @@ describe('IndicadorFigurePanel', () => {
|
||||
expect(JSON.stringify(page.result().figure)).toBe(original);
|
||||
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno');
|
||||
});
|
||||
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita o Todos', () => {
|
||||
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters();
|
||||
control.changeMode('manual');
|
||||
control.select([]);
|
||||
expect(control.canApply).toBe(false);
|
||||
apply();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
@@ -228,18 +228,13 @@ describe('IndicadorFigurePanel', () => {
|
||||
expect(state?.applied?.selection.mode).toBe('todos');
|
||||
apply();
|
||||
const manual = figure();
|
||||
expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
expect(manual.request.params.get('periodos')).toBe('2025-S2');
|
||||
control.select([]);
|
||||
expect(manual.cancelled).toBe(false);
|
||||
expect(control.canApply).toBe(false);
|
||||
apply();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
control.changeMode('todos');
|
||||
apply();
|
||||
expect(manual.cancelled).toBe(true);
|
||||
const all = figure();
|
||||
expect(all.request.params.has('periodos')).toBe(false);
|
||||
all.flush({ data: [], layout: {} });
|
||||
manual.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('UX-07B cambia perfil y restaura desde el original sin HTTP ni pérdida de host o revisión', () => {
|
||||
load(); const received = { data: [{ y: [0, null], marker: { color: 'gray' } }], layout: { paper_bgcolor: 'white' }, future: 42 };
|
||||
@@ -300,7 +295,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
});
|
||||
it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => {
|
||||
load(); figure().flush({ data: [{ y: [0, null] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual');
|
||||
const control = filters(); control.select([]);
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
fixture.detectChanges();
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([0, null]);
|
||||
@@ -308,9 +303,9 @@ describe('IndicadorFigurePanel', () => {
|
||||
expect(fixture.nativeElement.textContent).toContain('Filtro general aplicado: Todos con reporte');
|
||||
http.expectNone(r => r.url.includes('/figuras/'));
|
||||
});
|
||||
it.each([{ periodos: ['2025-S1'] }, { periodos: ['2025-S1', '2025-S2'] }])('404 de conjunto conserva borrador y reintenta la última aplicación', ({ periodos }) => {
|
||||
it.each([{ periodos: ['2025-S1'] }])('404 de un periodo conserva borrador y reintenta la última aplicación', ({ periodos }) => {
|
||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025';
|
||||
const control = filters(); control.select([]); control.year = '2025';
|
||||
for (const period of periodos) { control.unit = period.slice(-2); control.add(); }
|
||||
apply();
|
||||
const req = figure();
|
||||
@@ -320,7 +315,6 @@ describe('IndicadorFigurePanel', () => {
|
||||
expect(page.result().figure).toBeUndefined();
|
||||
expect(page.result().message).toContain('esta selección');
|
||||
expect(page.result().message).not.toContain('2025');
|
||||
if (periodos.length > 1) expect(page.result().message).toContain('conjunto de periodos');
|
||||
expect(control.selectedPeriods).toEqual(periodos);
|
||||
control.select([]);
|
||||
page.requestFigure();
|
||||
@@ -333,7 +327,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
});
|
||||
it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
apply(); figure().flush({ data: [{ y: [20] }], layout: {} });
|
||||
control.unit = 'S2'; control.add();
|
||||
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
||||
@@ -344,17 +338,17 @@ describe('IndicadorFigurePanel', () => {
|
||||
page.requestFigure();
|
||||
const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1');
|
||||
retry.flush({ data: [], layout: {} });
|
||||
expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
||||
expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
});
|
||||
it('descarta respuestas obsoletas de aplicaciones sucesivas', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
apply(); const old = figure();
|
||||
control.unit = 'S2'; control.add();
|
||||
expect(old.cancelled).toBe(false);
|
||||
apply(); const current = figure();
|
||||
expect(old.cancelled).toBe(true);
|
||||
expect(current.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
expect(current.request.params.get('periodos')).toBe('2025-S2');
|
||||
current.flush({ data: [{ y: [12] }], layout: {} });
|
||||
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([12]);
|
||||
@@ -362,7 +356,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
|
||||
it('UX-06E.B1 alterna ayuda sin HTTP y conserva filtros, borrador, memoria y panel', () => {
|
||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
fixture.detectChanges();
|
||||
const result = page.result(), filterState = state, snapshot = JSON.stringify(filterState);
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance;
|
||||
|
||||
@@ -13,6 +13,9 @@ import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { DonutHierarchy, DonutSelection, donutHierarchy, donutLegend, donutPeriod } from './indicadores-donut-drilldown';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
import { c2Capability, c2Figure } from './indicadores-c2-adapter';
|
||||
import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2';
|
||||
import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut';
|
||||
import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones';
|
||||
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
|
||||
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
|
||||
import { c2GeneralSelection } from './indicadores-c2-general-selection';
|
||||
@@ -245,6 +248,26 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
const state = this.presentStratified(data); this.stratifiedData = data; return state;
|
||||
}));
|
||||
}
|
||||
if (c1DonutCapability(this.indicador.contrato, selection.figura)) {
|
||||
if (selection.tipoPeriodo !== 'semestre' || selection.periodos?.length !== 1)
|
||||
return of({ status: 'incompatible', message: 'Esta figura muestra un solo semestre. Elige el intervalo semestral y un periodo.' } as FigureState);
|
||||
return this.snapshots.datos(selection.dominio!, selection.indicador, 'semestre', selection.periodos, this.indicador.version, { estrato: C1_DONUT_ESTRATO }).pipe(map(data => {
|
||||
const adapted = c1DonutFigure(data, selection);
|
||||
if (adapted.status !== 'supported') return { status: 'incompatible', message: adapted.reason } as FigureState;
|
||||
return { ...this.present(adapted.figure, selection), source: 'datos' as const, footnotes: adapted.notes,
|
||||
highlight: adapted.highlight, ownLayout: true, plotHeight: selection.figura === C1_AGE_BARS ? 400 : undefined,
|
||||
emptyMessage: adapted.total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined };
|
||||
}));
|
||||
}
|
||||
if (c1AlterationCapability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) {
|
||||
return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, selection.periodos, this.indicador.version).pipe(map(data => {
|
||||
const adapted = c1AlterationFigure(data, selection);
|
||||
if (adapted.status !== 'supported') return { status: 'incompatible', message: adapted.reason } as FigureState;
|
||||
return { ...this.present(adapted.figure, selection), source: 'datos' as const, footnotes: adapted.notes,
|
||||
highlight: adapted.highlight, ownLayout: true, plotHeight: 400,
|
||||
emptyMessage: adapted.total === 0 ? 'Ningún niño tiene su primer EEG de buena calidad en la selección; no hay un porcentaje que representar.' : undefined };
|
||||
}));
|
||||
}
|
||||
if (c2Capability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) {
|
||||
// Both panels, KPI and numeric table share the exact same transport key.
|
||||
// Do not catch /datos errors here: a backend failure is a real error state.
|
||||
@@ -265,6 +288,13 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
return this.publishedFigure(selection, 'Partición multiperiodo no verificable', data);
|
||||
}
|
||||
const adapted = c2Figure(data, selection);
|
||||
if (adapted.status === 'supported' && selection.dominio === 'tea') {
|
||||
const base = { source: 'datos' as const, footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage };
|
||||
if (selection.figura === 'fig_c2_donas') {
|
||||
const tea = teaC2Donut(adapted.model, selection.tema, adapted.figure.layout['title']);
|
||||
if (tea) return of({ ...this.present(tea.figure, selection), ...base, highlight: tea.highlight, ownLayout: true });
|
||||
} else return of({ ...this.present(adapted.figure, selection), ...base, highlight: c2BarsHighlight(adapted.model) });
|
||||
}
|
||||
return adapted.status === 'supported'
|
||||
? of({ ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const,
|
||||
footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage })
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
<section class="confirmacion" aria-label="Resultado histopatológico por categoría BI-RADS">
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||
@if (helpOpen) {
|
||||
<div class="methodology">
|
||||
<p>Cada punto es el porcentaje de pacientes de esa categoría BI-RADS cuyo resultado de biopsia pertenece a la selección, entre las que tienen resultado; la línea es su intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» no entran en el denominador y se muestran aparte, en la tabla de valores publicados.</p>
|
||||
@if (metadata) {
|
||||
@for (guide of readingGuide; track guide.figura) {
|
||||
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
||||
<h3>{{ guide.nombre }}</h3>
|
||||
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
|
||||
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
||||
</section>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando la histopatología por BI-RADS" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
|
||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (status() === 'ready' || status() === 'empty') {
|
||||
@if (periods.length > 1) {
|
||||
<nav class="periods" aria-label="Periodos de la histopatología por BI-RADS">
|
||||
<button type="button" aria-label="Periodo anterior de la histopatología" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||
<span role="status">{{ periods[periodIndex] }}, {{ periodIndex + 1 }} de {{ periods.length }}</span>
|
||||
<button type="button" aria-label="Periodo siguiente de la histopatología" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
|
||||
</nav>
|
||||
}
|
||||
@if (model; as m) {
|
||||
@if (status() === 'empty') { <p role="status">No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.</p> }
|
||||
@else {
|
||||
<div class="figures">
|
||||
<section class="figure rates"><h3>Por categoría BI-RADS, {{ m.periodo }}</h3>
|
||||
@if (ratesFigure) {
|
||||
<app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Histopatología, tasas por categoría BI-RADS, ' + m.periodo + ', ' + selectionLabel" />
|
||||
}
|
||||
<ul class="rate-states">
|
||||
@for (t of rates; track t.fila.id) { @if (t.k === null) { <li>{{ t.fila.etiqueta }}: {{ estadoTasa(t) }}</li> } }
|
||||
</ul>
|
||||
</section>
|
||||
<section class="figure donut"><h3>Resultado de la biopsia, {{ m.periodo }}</h3>
|
||||
@if (m.conResultado !== null && m.conResultado > 0 && donutFigure) {
|
||||
<app-plotly-chart [figure]="donutFigure" [showNotes]="false" [label]="'Histopatología, dona de resultados de la biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||
} @else { <p role="status">{{ m.conResultado === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado de biopsia en el periodo.' }}</p> }
|
||||
</section>
|
||||
</div>
|
||||
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
|
||||
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista general de la histopatología">Volver</button>
|
||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
||||
@for (g of m.grupos; track g.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
|
||||
@for (c of m.categorias; track c.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}</p>
|
||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de pacientes por categoría BI-RADS y resultado de biopsia" tabindex="0">
|
||||
<table><caption>Pacientes por categoría BI-RADS y resultado de la biopsia, {{ m.periodo }}</caption>
|
||||
<thead><tr><th scope="col">Categoría BI-RADS</th>@for (c of m.categorias; track c.id) { <th scope="col">{{ c.etiqueta }}</th> }<th scope="col">Con resultado</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }<th scope="col">Total de pacientes</th></tr></thead>
|
||||
<tbody>@for (fila of m.filas; track fila.id) {
|
||||
<tr><th scope="row">{{ fila.etiqueta }}</th>@for (c of m.categorias; track c.id) { <td>{{ cellText(fila.celdas[c.id]) }}</td> }<td>{{ denText(fila.den, fila.estado) }}</td>@for (a of m.aparte; track a.id) { <td>{{ cellText(fila.aparte[a.id]) }}</td> }<td>{{ cellText(fila.total) }}</td></tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,149 @@
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { Celda } from './indicadores-confirmacion-citologia';
|
||||
import { clicHistopatologia, donaHistopatologia, ESTRATO_BIRADS, estadoTasa, figuraTasas, HistopatologiaIncompatible, ID_HISTOPATOLOGIA,
|
||||
lectura, ModeloHistopatologia, modeloHistopatologia, periodosHistopatologia, SeleccionHistopatologia, seleccionBase, seleccionEtiqueta, tasas } from './indicadores-histopatologia-cama';
|
||||
|
||||
// Figures of the kit whose "Cómo leer" describes this coordinated view.
|
||||
const FIGURAS = [['fig_c2_donas', 'Dona de resultados de la biopsia'], ['fig_c2_barras', 'Tasas por categoría BI-RADS']] as const;
|
||||
|
||||
/**
|
||||
* CaMa's histopathological result by BI-RADS: rates with their interval per category, and a two-ring donut of the
|
||||
* result of the biopsy, drawn from one stratified C2 response. Data in, figures out: it asks the snapshot service
|
||||
* for the matrix and hands it to the pure adapter in `indicadores-histopatologia-cama`.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-indicador-histopatologia-cama',
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
|
||||
templateUrl: './indicador-histopatologia-cama.html',
|
||||
styleUrl: './indicador-confirmacion-citologia.scss',
|
||||
})
|
||||
export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() visible = true;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
readonly metadataRequested = output<void>();
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
message = '';
|
||||
selection?: SeleccionHistopatologia;
|
||||
periods: string[] = [];
|
||||
periodIndex = 0;
|
||||
model?: ModeloHistopatologia;
|
||||
donutFigure?: PlotlyFigure;
|
||||
ratesFigure?: PlotlyFigure;
|
||||
helpOpen = false;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
private pages: ModeloHistopatologia[] = [];
|
||||
// The rates figure has a phone-width variant; it is redrawn when the window crosses that width.
|
||||
private readonly estrecho = typeof matchMedia === 'function' ? matchMedia('(max-width: 600px)') : undefined;
|
||||
private readonly alCambiarAncho = () => this.draw();
|
||||
constructor() { this.estrecho?.addEventListener('change', this.alCambiarAncho); }
|
||||
|
||||
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||
get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; }
|
||||
get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; }
|
||||
get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; }
|
||||
get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; }
|
||||
readonly estadoTasa = estadoTasa;
|
||||
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
|
||||
denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); }
|
||||
get readingGuide() {
|
||||
const details = this.metadata?.figuras_detalle ?? [];
|
||||
return FIGURAS.flatMap(([figura, nombre]) => {
|
||||
const detail = details.find(item => item.figura === figura);
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
|
||||
});
|
||||
}
|
||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_BIRADS })
|
||||
+ JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras]);
|
||||
if (key !== this.key) {
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
|
||||
this.clear();
|
||||
if (!this.visible) { this.status.set('deferred'); return; }
|
||||
this.load();
|
||||
} else if (this.visible && !this.loaded) this.load();
|
||||
else if (this.model && changes['tema']) this.draw();
|
||||
}
|
||||
retry() { if (this.visible) this.load(); }
|
||||
private clear() {
|
||||
this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined;
|
||||
this.donutFigure = undefined; this.ratesFigure = undefined;
|
||||
}
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.clear();
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
if (this.dominio !== 'cama' || this.indicador.id !== ID_HISTOPATOLOGIA || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
|
||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
const key = this.key;
|
||||
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
|
||||
this.status.set('loading');
|
||||
this.subscription = this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version,
|
||||
{ estrato: ESTRATO_BIRADS }).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: datos => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.periods = periodosHistopatologia(datos, this.applied.tipo, periods);
|
||||
this.pages = this.periods.map(p => modeloHistopatologia(datos, p));
|
||||
// The most recent period first; navigation goes back.
|
||||
this.periodIndex = Math.max(0, this.periods.length - 1); this.activatePeriod();
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
error: error => { if (key === this.key) this.failure(error); },
|
||||
});
|
||||
}
|
||||
private failure(error: unknown) {
|
||||
this.clear();
|
||||
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||
: error instanceof HistopatologiaIncompatible ? error.message : httpMessage(error);
|
||||
this.status.set(error instanceof HistopatologiaIncompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
|
||||
? 'incompatible' : 'error');
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
private activatePeriod() {
|
||||
this.model = this.pages[this.periodIndex];
|
||||
this.selection = this.model ? seleccionBase(this.model) : undefined;
|
||||
this.draw(); this.status.set(this.model && !this.model.vacio ? 'ready' : 'empty');
|
||||
}
|
||||
changePeriod(step: number) {
|
||||
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
|
||||
this.periodIndex += step; this.activatePeriod();
|
||||
}
|
||||
select(trace: string, index = 0) {
|
||||
if (!this.model || !this.selection || this.status() !== 'ready') return;
|
||||
this.selection = clicHistopatologia(this.model, this.selection, trace, index); this.draw();
|
||||
}
|
||||
plotClicked(event: unknown) {
|
||||
const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0];
|
||||
if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber);
|
||||
}
|
||||
private draw() {
|
||||
if (!this.model || !this.selection) return;
|
||||
this.donutFigure = donaHistopatologia(this.model, this.selection, this.tema);
|
||||
this.ratesFigure = figuraTasas(this.model, this.selection, this.tema, !!this.estrecho?.matches);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecho?.removeEventListener('change', this.alCambiarAncho); }
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Component, signal } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
|
||||
/**
|
||||
* CaMa's histopathological result by BI-RADS category, while the catalog does not publish its indicator
|
||||
* (`cama_histopatologia_birads`). It keeps the card's place and structure, with no figure and no number.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-indicador-histopatologia-pendiente',
|
||||
host: { class: 'dual-card' },
|
||||
imports: [MatButtonModule, MatCardModule],
|
||||
template: `
|
||||
<mat-card>
|
||||
<h2>Resultado histopatológico por categoría BI-RADS</h2>
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="ayuda()" (click)="ayuda.set(!ayuda())">Cómo leer</button>
|
||||
@if (ayuda()) {
|
||||
<div class="methodology">
|
||||
<p>Cuando el catálogo publique el indicador, esta tarjeta mostrará, por categoría BI-RADS, el porcentaje de biopsias con resultado maligno y su intervalo de confianza, y la distribución del resultado de la biopsia en una dona que se puede recorrer por grupo y por resultado.</p>
|
||||
</div>
|
||||
}
|
||||
<p class="estado" role="status"><strong>Integración pendiente.</strong> Este indicador aún no está publicado por el catálogo institucional.</p>
|
||||
<div class="figures">
|
||||
<section class="figure"><h3>Por categoría BI-RADS</h3><div class="vacio">Sin datos publicados</div></section>
|
||||
<section class="figure"><h3>Resultado de la biopsia</h3><div class="vacio">Sin datos publicados</div></section>
|
||||
</div>
|
||||
</mat-card>
|
||||
`,
|
||||
styles: `
|
||||
:host { display: flex; min-width: 0; margin: 0; grid-column: 1 / -1; }
|
||||
mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface); color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; overflow-wrap: anywhere; }
|
||||
h3 { margin: 0; font-size: 1rem; font-weight: 500; line-height: 1.5; }
|
||||
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
|
||||
.estado { color: var(--issste-text-secondary); }
|
||||
.methodology { margin-top: var(--issste-space-3); padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.methodology p { margin: 0; }
|
||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); margin-top: var(--issste-space-3); }
|
||||
@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
.vacio { display: grid; place-items: center; min-height: 12rem; margin-top: var(--issste-space-3); color: var(--issste-text-secondary);
|
||||
border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); }
|
||||
button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorHistopatologiaPendiente {
|
||||
readonly ayuda = signal(false);
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import { MatCardModule } from '@angular/material/card';
|
||||
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
|
||||
}
|
||||
@if (temporalReference) { <p>{{ temporalReference }}</p> }
|
||||
<p class="kpi-state" role="status">{{ state }}</p>
|
||||
<p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p>
|
||||
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
|
||||
</mat-card>
|
||||
`,
|
||||
@@ -22,12 +22,17 @@ import { MatCardModule } from '@angular/material/card';
|
||||
mat-card { box-sizing: border-box; height: 100%; padding: var(--issste-space-6);
|
||||
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border);
|
||||
border-radius: var(--issste-radius); box-shadow: none; }
|
||||
h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; }
|
||||
h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
|
||||
h3, p { overflow-wrap: anywhere; }
|
||||
p { margin: var(--issste-space-3) 0 0; }
|
||||
.kpi-state, .additional-info { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.value { font: var(--mat-sys-headline-medium); }
|
||||
.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
||||
.value { font-size: 1.75rem; font-weight: 500; line-height: 1.2; }
|
||||
.value span { margin-inline-start: .3em; }
|
||||
// CaMa's cards are as tall as their grid row.
|
||||
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
|
||||
:host-context(.kpi-section[data-domain='cama']) mat-card { flex: 1 1 auto; height: auto; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorKpiCard {
|
||||
@@ -38,6 +43,8 @@ export class IndicadorKpiCard {
|
||||
@Input() loading = false;
|
||||
@Input() notes: string[] = [];
|
||||
@Input() state = 'Pendiente de definición';
|
||||
// A card that shows its value needs no "Disponible" line.
|
||||
@Input() quietWhenAvailable = false;
|
||||
@Input() additionalInfo?: string;
|
||||
get informationLine(): string | undefined {
|
||||
const lines = [this.additionalInfo, ...this.notes].map(value => value?.trim()).filter((value): value is string => !!value);
|
||||
|
||||
@@ -27,9 +27,14 @@ describe('KPI integración con autoridad global', () => {
|
||||
if (!initial) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
|
||||
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
|
||||
http.expectOne('/' + domain + '/indicadores').flush(KPI_BY_DOMAIN[domain].slice(missing ? 1 : 0).map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })));
|
||||
for (const request of http.match(r => r.url.endsWith('/periodos'))) request.flush({ id: request.request.url.split('/').at(-2), periodos: periods.map(periodo => ({ tipo: 'semestre', periodo })) });
|
||||
flushPeriodos(() => periods.map(periodo => ({ tipo: 'semestre', periodo })));
|
||||
fixture.detectChanges();
|
||||
}
|
||||
// Availability runs four requests at a time; flushing one batch starts the next.
|
||||
function flushPeriodos(periodos: () => unknown[]) {
|
||||
for (let pending = http.match(r => r.url.endsWith('/periodos')); pending.length; pending = http.match(r => r.url.endsWith('/periodos')))
|
||||
pending.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: periodos() }));
|
||||
}
|
||||
// Regression assertions below target the original KPI contracts. The added lab
|
||||
// consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts.
|
||||
// Satisfy its independent request with an explicit empty response, never diagnosis data.
|
||||
@@ -56,7 +61,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
expect(panels().map(p => p.definition.id)).toEqual([]);
|
||||
expect(panels().every(p => p.result().state === 'Esperando filtro aplicado')).toBe(true); http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
it('TEA consulta sus tres destacados y muestra conteo, porcentaje y mediana', () => {
|
||||
it('TEA consulta sus cinco destacados y muestra conteo, porcentajes y mediana', () => {
|
||||
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush([]);
|
||||
load('tea'); const initial = requests();
|
||||
expect(initial.map(r => r.request.url)).toEqual(['/tea/indicadores/' + KPI_BY_DOMAIN.tea[0].id + '/datos']);
|
||||
@@ -64,8 +69,10 @@ describe('KPI integración con autoridad global', () => {
|
||||
const req = requests();
|
||||
expect(req.map(r => r.request.url)).toEqual(KPI_BY_DOMAIN.tea.slice(1).map(d => '/tea/indicadores/' + d.id + '/datos'));
|
||||
req.forEach((r, i) => r.flush(response(i + 1, 'tea'))); fixture.detectChanges();
|
||||
expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7]]);
|
||||
expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7], ['Disponible', '40.0'], ['Disponible', '40.0']]);
|
||||
expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.');
|
||||
expect(panels()[3].result().info).toBe('2 de 5 pacientes con diagnóstico confirmado tienen un EEG de buena calidad.');
|
||||
expect(panels()[4].result().info).toBe('2 de 5 pacientes con diagnóstico confirmado no tienen todavía un EEG de buena calidad.');
|
||||
});
|
||||
it('dos KPI reales y un placeholder manejan 404, error y éxito sin cifras anteriores', () => {
|
||||
load('cacu'); const req = requests(); expect(req).toHaveLength(2); expect(panels().every(p => p.result().loading)).toBe(true);
|
||||
@@ -80,7 +87,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
it('borrador no consulta; aplicar equivalente tampoco; revisión distinta cancela las tres anteriores', () => {
|
||||
load('cacu'); const initial = requests(); initial.forEach((r,i) => r.flush(response(i)));
|
||||
const editor = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
editor.changeMode('manual'); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
editor.select([]); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(0);
|
||||
expect(panels().map(p => p.result().value)).toEqual([5, 7]);
|
||||
expect(single.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
||||
@@ -164,28 +171,29 @@ describe('KPI integración con autoridad global', () => {
|
||||
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu');
|
||||
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges();
|
||||
http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] })));
|
||||
http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [] })); fixture.detectChanges();
|
||||
flushPeriodos(() => []); fixture.detectChanges();
|
||||
expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true);
|
||||
http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
it('las seis tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => {
|
||||
it('las tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => {
|
||||
for (const domain of ['cacu', 'cama'] as const) {
|
||||
load(domain);
|
||||
const req = requests(); expect(req).toHaveLength(KPI_BY_DOMAIN[domain].length);
|
||||
req.forEach((r, i) => r.flush({ ...response(i, domain), notas: ['Nota del pie de la figura.'] }));
|
||||
// CaMa draws its cards in a different order than KPI_BY_DOMAIN: answer each request by its indicator.
|
||||
req.forEach(r => r.flush({ ...response(KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')), domain), notas: ['Nota del pie de la figura.'] }));
|
||||
fixture.detectChanges();
|
||||
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
|
||||
expect(cards).toHaveLength(domain === 'cacu' ? 5 : 3);
|
||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', '40.0', '7']);
|
||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined] : ['pacientes', '%', 'días (mediana)']);
|
||||
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible'] : ['Disponible', 'Disponible', 'Disponible']);
|
||||
expect(cards).toHaveLength(domain === 'cacu' ? 5 : 4);
|
||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', undefined, '7', undefined]);
|
||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined] : ['pacientes', undefined, 'días (mediana)', undefined]);
|
||||
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible'] : ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente']);
|
||||
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('2025-S1'),
|
||||
expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'),
|
||||
]));
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
||||
// CaCu cards say only their own line; the kit notes are the figure footer.
|
||||
expect(fixture.nativeElement.textContent.includes('Nota del pie de la figura.')).toBe(domain !== 'cacu');
|
||||
// CaCu and CaMa cards say only their own line, as in the reference; the kit notes are the figure footer and the definitions.
|
||||
expect(fixture.nativeElement.textContent.includes('Nota del pie de la figura.')).toBe(false);
|
||||
}
|
||||
});
|
||||
it('Aplicar Todos después del periodo compartido conserva supresión del último sin retroceder', () => {
|
||||
|
||||
@@ -19,11 +19,15 @@ interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; ver
|
||||
imports: [IndicadorKpiCard, MatButtonModule],
|
||||
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
|
||||
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
|
||||
[loading]="result().loading ?? false" [notes]="dominio === 'cacu' ? [] : result().notes ?? []" />
|
||||
[loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="dominio === 'cama'" />
|
||||
@if (result().state === 'Error de consulta') {
|
||||
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
|
||||
}`,
|
||||
styles: ':host { display: block; min-width: 0; }',
|
||||
styles: `
|
||||
:host { display: block; min-width: 0; }
|
||||
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
|
||||
:host-context(.kpi-section[data-domain='cama']) app-indicador-kpi-card { flex: 1 1 auto; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorKpiPanel implements OnChanges {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
|
||||
@@ -1,45 +1,81 @@
|
||||
@if (compact) {
|
||||
<section aria-label="Editor de filtros generales del proyecto">
|
||||
@if (state.tipo === 'mes') { <p class="filter-help">Para consultar meses debes elegir periodos explícitos. Todos con reporte utiliza semestres.</p> }
|
||||
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de tiempo del borrador ya no está publicado para este proyecto. Elige un intervalo de tiempo disponible.</p> }
|
||||
<div class="fields">
|
||||
@if (types.length > 1 || !types.includes(state.tipo)) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de tiempo</mat-label>
|
||||
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mes' : 'Semestre' }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
@if (state.tipo === 'semestre' && state.tipo === types[0]) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Modalidad</mat-label>
|
||||
<mat-select [ngModel]="entry.draft.mode === 'todos' ? 'todos' : 'manual'" (ngModelChange)="changeMode($event)">
|
||||
<mat-select-trigger><span class="select-value">{{ entry.draft.mode === 'todos' ? 'Todos con reporte' : 'Elegir periodos' }}</span></mat-select-trigger>
|
||||
<mat-option value="todos">Todos con reporte</mat-option>
|
||||
<mat-option value="manual">Elegir periodos</mat-option>
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
@if (entry.draft.mode !== 'todos') {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodos seleccionados</mat-label>
|
||||
<mat-select multiple [ngModel]="selectedPeriods" (ngModelChange)="select($event)">
|
||||
<mat-select-trigger><span class="select-value">{{ selectedPeriods.join(', ') }}</span></mat-select-trigger>
|
||||
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
|
||||
@if (availability) {
|
||||
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }}, disponibilidad no confirmada</mat-option> }
|
||||
}
|
||||
</mat-select>
|
||||
<mat-hint>{{ availability ? 'Existe reporte en al menos un indicador del dominio; la cobertura puede variar.' : 'Disponibilidad desconocida hasta consultar.' }}</mat-hint>
|
||||
</mat-form-field>
|
||||
}
|
||||
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
|
||||
<div class="fields compact">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label>
|
||||
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
|
||||
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
|
||||
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
|
||||
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
|
||||
@if (availability) {
|
||||
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }}, disponibilidad no confirmada</mat-option> }
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || (!hasPending && !initialPresentation)" (click)="apply.emit()">Aplicar</button>
|
||||
@if (hasPending) { <span class="pending" role="status">Hay cambios sin aplicar.</span> }
|
||||
</div>
|
||||
@if (availability) {
|
||||
@if (availability.status === 'loading') { <p role="status">Consultando periodos disponibles…</p> }
|
||||
@else if (availability.status === 'error') {
|
||||
<p role="alert">No se pudo completar la consulta de periodos disponibles.</p>
|
||||
<button type="button" mat-stroked-button (click)="retryAvailability.emit()">Reintentar disponibilidad</button>
|
||||
} @else if (!options.length) { <p role="status">Sin reportes disponibles para este intervalo de tiempo.</p> }
|
||||
} @else if (!options.length) { <p role="status">Sin reportes disponibles para este intervalo de análisis.</p> }
|
||||
@if (entry.draft.mode === 'explicit' && unavailableSelection.length) { <p role="status">La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.</p> }
|
||||
}
|
||||
@if (!availability && entry.draft.mode !== 'todos') {
|
||||
@if (!availability) {
|
||||
<p class="filter-help">Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.</p>
|
||||
<div class="fields period-builder">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Año</mat-label><input matInput [(ngModel)]="year" inputmode="numeric" maxlength="4" /></mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>{{ state.tipo === 'mes' ? 'Mes' : 'Semestre' }}</mat-label>
|
||||
<mat-select [(ngModel)]="unit">
|
||||
@for (value of state.tipo === 'mes' ? months : ['S1', 'S2']; track value) { <mat-option [value]="value">{{ value }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<button type="button" mat-stroked-button (click)="add()">Agregar periodo</button>
|
||||
</div>
|
||||
<div class="remove" aria-label="Eliminar periodos agregados">
|
||||
@for (period of entry.added; track period) {
|
||||
<button type="button" mat-button (click)="remove(period)" [attr.aria-label]="'Eliminar periodo ' + period">Eliminar {{ period }}</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@if (error) { <p class="error" role="alert">{{ error }}</p> }
|
||||
@if (!canApply) { <p role="status">Selecciona un periodo válido para aplicar.</p> }
|
||||
</section>
|
||||
} @else {
|
||||
<section aria-label="Editor de filtros generales del proyecto">
|
||||
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
|
||||
<div class="fields">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label>
|
||||
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
|
||||
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
|
||||
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
|
||||
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
|
||||
@if (availability) {
|
||||
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }}, disponibilidad no confirmada</mat-option> }
|
||||
}
|
||||
</mat-select>
|
||||
<mat-hint>{{ availability ? 'Existe reporte en al menos un indicador del dominio; la cobertura puede variar.' : 'Disponibilidad desconocida hasta consultar.' }}</mat-hint>
|
||||
</mat-form-field>
|
||||
</div>
|
||||
@if (availability) {
|
||||
@if (availability.status === 'loading') { <p role="status">Consultando periodos disponibles…</p> }
|
||||
@else if (availability.status === 'error') {
|
||||
<p role="alert">No se pudo completar la consulta de periodos disponibles.</p>
|
||||
<button type="button" mat-stroked-button (click)="retryAvailability.emit()">Reintentar disponibilidad</button>
|
||||
} @else if (!options.length) { <p role="status">Sin reportes disponibles para este intervalo de análisis.</p> }
|
||||
@if (entry.draft.mode === 'explicit' && unavailableSelection.length) { <p role="status">La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.</p> }
|
||||
}
|
||||
@if (!availability) {
|
||||
<p class="filter-help">Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.</p>
|
||||
<div class="fields period-builder">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Año</mat-label><input matInput [(ngModel)]="year" inputmode="numeric" maxlength="4" /></mat-form-field>
|
||||
@@ -58,9 +94,10 @@
|
||||
}
|
||||
@if (error) { <p class="error" role="alert">{{ error }}</p> }
|
||||
<p class="draft-summary">Selección en edición: {{ summary }}</p>
|
||||
@if (!canApply) { <p role="status">Selecciona al menos un periodo válido para aplicar.</p> }
|
||||
@if (!canApply) { <p role="status">Selecciona un periodo válido para aplicar.</p> }
|
||||
@if (!hasPending) { <p class="pending">Sin cambios pendientes.</p> }
|
||||
@if (hasPending) { <p class="pending" role="status">Hay cambios sin aplicar.</p> }
|
||||
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || (!hasPending && !initialPresentation)" (click)="apply.emit()">Aplicar</button>
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
</section>
|
||||
}
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
@use '@angular/material' as mat;
|
||||
|
||||
:host { display: block; min-width: 0; margin: var(--issste-space-4) 0; }
|
||||
// CaMa's compact row: tighter fields and buttons, one line of text under it.
|
||||
:host(.compacto) { margin: 0; @include mat.theme((density: -4)); }
|
||||
:host(.compacto) p { line-height: 1.4; margin: var(--issste-space-2) 0 0; font: var(--mat-sys-body-small); }
|
||||
:host(.compacto) .pending { color: var(--issste-text); border-left-color: var(--issste-accent); padding-left: var(--issste-space-2); }
|
||||
:host(.compacto) .apply-button { min-height: 40px; }
|
||||
:host(.compacto) .period-builder button { min-height: 40px; }
|
||||
section { min-width: 0; }
|
||||
.fields { display: flex; flex-wrap: wrap; align-items: start; gap: var(--issste-space-3); }
|
||||
mat-form-field { flex: 1 1 14rem; min-width: 0; max-width: 24rem; }
|
||||
@@ -13,6 +21,9 @@ p { overflow-wrap: anywhere; line-height: 1.5; margin: var(--issste-space-3) 0;
|
||||
.remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); }
|
||||
.remove button { min-height: 44px; }
|
||||
.apply-button { min-height: 44px; margin-top: var(--issste-space-2); }
|
||||
.fields.compact { align-items: center; }
|
||||
.fields.compact mat-form-field { flex: 0 1 14rem; }
|
||||
.fields.compact .apply-button { margin-top: 0; }
|
||||
@media (max-width: 550px) {
|
||||
mat-form-field, .period-builder mat-form-field { flex: 1 1 100%; max-width: none; }
|
||||
.period-builder button { margin-top: 0; }
|
||||
|
||||
@@ -18,18 +18,26 @@ describe('UX-04 control asistido', () => {
|
||||
control = fixture.componentInstance;
|
||||
});
|
||||
afterEach(() => fixture.destroy());
|
||||
it('UX-06C: valores largos del trigger preservan Todos, selección explícita y borrador vacío', async () => {
|
||||
await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.select-value')?.textContent).toContain('Todos con reporte');
|
||||
function periodSelect() {
|
||||
return fixture.debugElement.queryAll(By.css('mat-form-field'))
|
||||
.find(f => f.nativeElement.textContent.includes('Periodo seleccionado'))!.query(By.directive(MatSelect));
|
||||
}
|
||||
it('en modo compacto agregar otro periodo sustituye la selección anterior', () => {
|
||||
fixture.componentRef.setInput('compact', true); fixture.detectChanges();
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.unit = 'S2'; control.add();
|
||||
expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
|
||||
});
|
||||
it('UX-06C: el trigger muestra el periodo explícito y el borrador vacío no se aplica', async () => {
|
||||
fixture.componentRef.setInput('state', {
|
||||
...control.state, editors: { ...control.state.editors, semestre: {
|
||||
added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] },
|
||||
added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S2'] },
|
||||
} },
|
||||
});
|
||||
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
||||
const values = Array.from(fixture.nativeElement.querySelectorAll('.select-value') as NodeListOf<HTMLElement>);
|
||||
expect(values.map(e => e.textContent)).toContain('2025-S1, 2025-S2');
|
||||
expect(values.map(e => e.textContent)).toContain('Elegir periodos');
|
||||
expect(values.map(e => e.textContent)).toContain('2025-S2');
|
||||
fixture.componentRef.setInput('state', {
|
||||
...control.state, editors: { ...control.state.editors, semestre: {
|
||||
added: ['2025-S1', '2025-S2'], draft: { mode: 'empty' },
|
||||
@@ -43,10 +51,11 @@ describe('UX-04 control asistido', () => {
|
||||
it('UX-04A: el selector vacío no reescribe el FormControl en cada detección', async () => {
|
||||
// Bound the pre-fix reproduction: do not wait for an unstable fixture forever.
|
||||
fixture.changeDetectorRef.detach();
|
||||
control.changeMode('manual');
|
||||
control.select([]);
|
||||
fixture.detectChanges();
|
||||
await Promise.resolve();
|
||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
||||
const select = periodSelect();
|
||||
expect(select.componentInstance.multiple).toBe(false);
|
||||
const model = select.injector.get(NgModel);
|
||||
const writes = vi.spyOn(model.control, 'setValue');
|
||||
const edits = vi.spyOn(control.edited, 'emit');
|
||||
@@ -54,16 +63,16 @@ describe('UX-04 control asistido', () => {
|
||||
fixture.detectChanges();
|
||||
await Promise.resolve();
|
||||
}
|
||||
expect(model.control.value).toEqual([]);
|
||||
expect(model.control.value).toBeNull();
|
||||
expect(writes).not.toHaveBeenCalled();
|
||||
expect(edits).not.toHaveBeenCalled();
|
||||
expect(control.state.applied?.selection.mode).toBe('todos');
|
||||
});
|
||||
it('UX-04A: meses vacíos se estabilizan al abrir y cerrar selección múltiple', async () => {
|
||||
it('UX-04A: meses vacíos se estabilizan al abrir y cerrar el selector', async () => {
|
||||
control.changeTipo('mes');
|
||||
control.year = '2025'; control.unit = '01'; control.add(); control.select([]);
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
||||
const select = periodSelect();
|
||||
const model = select.injector.get(NgModel);
|
||||
const writes = vi.spyOn(model.control, 'setValue');
|
||||
for (let i = 0; i < 3; i++) {
|
||||
@@ -78,7 +87,7 @@ describe('UX-04 control asistido', () => {
|
||||
expect(control.canApply).toBe(false);
|
||||
});
|
||||
it('normaliza el año y rechaza agregar duplicados', () => {
|
||||
control.changeMode('manual');
|
||||
control.select([]);
|
||||
control.year = '1'; control.unit = 'S1'; control.add();
|
||||
expect(control.selectedPeriods).toEqual(['0001-S1']);
|
||||
control.add();
|
||||
@@ -86,7 +95,7 @@ describe('UX-04 control asistido', () => {
|
||||
expect(control.entry.added).toEqual(['0001-S1']);
|
||||
});
|
||||
it.each([['0', 'S1'], ['10000', 'S1'], ['2025', 'S3'], ['abc', 'S1'], ['', 'S1']])('rechaza año/unidad %s %s', (year, unit) => {
|
||||
control.changeMode('manual'); control.year = year; control.unit = unit; control.add();
|
||||
control.select([]); control.year = year; control.unit = unit; control.add();
|
||||
expect(control.error).toContain('unidad válida'); expect(control.canApply).toBe(false);
|
||||
});
|
||||
it.each(['00', '13', 'S1'])('rechaza unidad mensual %s', unit => {
|
||||
@@ -94,21 +103,22 @@ describe('UX-04 control asistido', () => {
|
||||
expect(control.entry.added).toEqual([]); expect(control.canApply).toBe(false);
|
||||
});
|
||||
it('conserva borradores independientes sin convertir periodos', () => {
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.changeTipo('mes'); control.year = '2026'; control.unit = '12'; control.add();
|
||||
control.changeTipo('semestre'); expect(control.selectedPeriods).toEqual(['2025-S1']);
|
||||
control.changeTipo('mes'); expect(control.selectedPeriods).toEqual(['2026-12']);
|
||||
expect(control.state.applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' } });
|
||||
});
|
||||
it('deselecciona sin eliminar opciones y elimina sin botones dentro de opciones', () => {
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
it('un solo periodo: agregar otro lo reemplaza y varios se rechazan; elimina sin botones dentro de opciones', () => {
|
||||
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.unit = 'S2'; control.add();
|
||||
control.select(['2025-S2']);
|
||||
expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
control.select(['2025-S1', '2025-S2']); expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
|
||||
control.remove('2025-S1'); expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
fixture.detectChanges();
|
||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
||||
expect(select).toBeTruthy();
|
||||
const select = periodSelect();
|
||||
expect(select.componentInstance.multiple).toBe(false);
|
||||
expect(select.nativeElement.querySelector('button')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).toContain('Eliminar 2025-S2');
|
||||
fixture.nativeElement.querySelector('.remove button').click();
|
||||
@@ -119,7 +129,7 @@ describe('UX-04 control asistido', () => {
|
||||
it('emite edición y aplicación por separado y explica la disponibilidad desconocida', () => {
|
||||
const edited = vi.spyOn(control.edited, 'emit');
|
||||
const apply = vi.spyOn(control.apply, 'emit');
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
expect(edited).toHaveBeenCalledTimes(2); expect(apply).not.toHaveBeenCalled();
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar');
|
||||
@@ -128,11 +138,25 @@ describe('UX-04 control asistido', () => {
|
||||
fixture.nativeElement.querySelector('button[mat-flat-button]').click();
|
||||
expect(apply).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it('no ofrece Todos en meses cuando el primero es semestre', () => {
|
||||
control.changeTipo('mes'); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses');
|
||||
control.changeMode('todos'); expect(control.entry.draft.mode).toBe('empty');
|
||||
control.changeTipo('semestre'); control.changeTipo('mes');
|
||||
expect(control.entry.draft.mode).toBe('empty');
|
||||
it('ofrece el intervalo de análisis mensual o semestral, sin Modalidad', async () => {
|
||||
const labels = Array.from(fixture.nativeElement.querySelectorAll('mat-label') as NodeListOf<HTMLElement>).map(l => l.textContent);
|
||||
expect(labels).toContain('Intervalo de análisis');
|
||||
expect(labels).not.toContain('Modalidad');
|
||||
const select = fixture.debugElement.queryAll(By.css('mat-form-field'))
|
||||
.find(f => f.nativeElement.textContent.includes('Intervalo de análisis'))!.query(By.directive(MatSelect));
|
||||
select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable();
|
||||
const options = Array.from(document.querySelectorAll('mat-option')).map(o => o.textContent?.trim());
|
||||
expect(options).toEqual(['Semestral', 'Mensual']);
|
||||
select.componentInstance.close();
|
||||
});
|
||||
it('al cambiar de intervalo elige el periodo más reciente con reporte', () => {
|
||||
fixture.componentRef.setInput('availability', { status: 'ready', byIndicator: {}, errors: {},
|
||||
options: { semestre: ['2025-S2', '2025-S1'], mes: ['2025-12', '2025-11'] } });
|
||||
fixture.detectChanges();
|
||||
control.changeTipo('mes');
|
||||
expect(control.selectedPeriods).toEqual(['2025-12']);
|
||||
control.select(['2025-11']); control.changeTipo('semestre'); control.changeTipo('mes');
|
||||
// A period already chosen for that interval is kept.
|
||||
expect(control.selectedPeriods).toEqual(['2025-11']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,6 +11,7 @@ import { describePeriods, newEditor, FilterState, pending, validDraft } from './
|
||||
@Component({
|
||||
selector: 'app-indicador-period-filters',
|
||||
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule],
|
||||
host: { '[class.compacto]': 'compact' },
|
||||
templateUrl: './indicador-period-filters.html',
|
||||
styleUrl: './indicador-period-filters.scss',
|
||||
})
|
||||
@@ -19,6 +20,8 @@ export class IndicadorPeriodFilters implements OnChanges {
|
||||
@Input({ required: true }) types!: TipoPeriodo[];
|
||||
@Input() availability?: PeriodAvailability;
|
||||
@Input() initialPresentation = false;
|
||||
// One period at a time, with the interval and Aplicar on one row.
|
||||
@Input() compact = false;
|
||||
@Output() retryAvailability = new EventEmitter<void>();
|
||||
@Output() edited = new EventEmitter<void>();
|
||||
@Output() apply = new EventEmitter<void>();
|
||||
@@ -29,7 +32,7 @@ export class IndicadorPeriodFilters implements OnChanges {
|
||||
ngOnChanges() { this.year = this.unit = this.error = ''; }
|
||||
get entry() { return this.state.editors[this.state.tipo]!; }
|
||||
// NgModel schedules a microtask and markForCheck when its input reference changes.
|
||||
// Keep the empty multiple-select value stable so an unchanged draft can settle.
|
||||
// Keep the empty selection stable so an unchanged draft can settle.
|
||||
private readonly emptyPeriods: string[] = [];
|
||||
get selectedPeriods() { return this.entry.draft.mode === 'explicit' ? this.entry.draft.periodos : this.emptyPeriods; }
|
||||
get options() { return this.availability ? this.availability.options[this.state.tipo] : this.entry.added; }
|
||||
@@ -42,21 +45,21 @@ export class IndicadorPeriodFilters implements OnChanges {
|
||||
get hasPending() { return pending(this.state); }
|
||||
get summary() { return describePeriods(this.state.tipo, this.entry.draft); }
|
||||
get appliedSummary() { return this.state.applied ? describePeriods(this.state.applied.tipo, this.state.applied.selection) : 'Todavía no hay selección aplicada'; }
|
||||
// There is no "every period" choice in the editor: a new interval starts on its most recent
|
||||
// period with a report (options are sorted newest first).
|
||||
changeTipo(tipo: TipoPeriodo) {
|
||||
if (!this.types.includes(tipo)) return;
|
||||
this.state.tipo = tipo;
|
||||
this.state.editors[tipo] ??= newEditor(tipo, this.types[0]);
|
||||
this.year = this.unit = this.error = '';
|
||||
if (this.entry.draft.mode !== 'explicit' && this.availability?.status === 'ready' && this.options.length)
|
||||
this.entry.draft = { mode: 'explicit', periodos: [this.options[0]] };
|
||||
this.edited.emit();
|
||||
}
|
||||
changeMode(mode: 'todos' | 'manual') {
|
||||
if (mode === 'todos' && (this.state.tipo !== 'semestre' || this.state.tipo !== this.types[0])) return;
|
||||
this.entry.draft = mode === 'todos' ? { mode: 'todos' } : { mode: 'empty' };
|
||||
this.error = '';
|
||||
this.edited.emit();
|
||||
}
|
||||
// Only one period can be chosen: cards and figures never combine periods.
|
||||
select(values: string[]) {
|
||||
const unique = [...new Set(values)];
|
||||
const unique = [...new Set(this.compact ? values.slice(-1) : values)];
|
||||
if (unique.length > 1) return;
|
||||
if (unique.some(p => !this.options.includes(p) || parsePeriodos(p, this.state.tipo)?.[0] !== p)) return;
|
||||
this.entry.draft = unique.length ? { mode: 'explicit', periodos: unique as [string, ...string[]] } : { mode: 'empty' };
|
||||
this.edited.emit();
|
||||
@@ -70,13 +73,11 @@ export class IndicadorPeriodFilters implements OnChanges {
|
||||
return;
|
||||
}
|
||||
if (this.entry.added.includes(period)) { this.error = 'Este periodo ya está agregado.'; return; }
|
||||
const selected = this.selectedPeriods;
|
||||
this.entry.added.push(period);
|
||||
this.select([...selected, period]);
|
||||
this.select([period]);
|
||||
}
|
||||
remove(period: string) {
|
||||
this.entry.added = this.entry.added.filter(p => p !== period);
|
||||
// Removing an unselected option must not change the Todos mode.
|
||||
if (this.entry.draft.mode === 'explicit') this.select(this.selectedPeriods.filter(p => p !== period));
|
||||
else this.edited.emit();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
|
||||
import { CeldaMapa, ComparacionAnalisis, DistribucionAnalisis, MapaAnalisis, TendenciaAnalisis } from './indicadores-analisis.service';
|
||||
|
||||
// The figures of the descriptive analysis. They draw what the answer publishes and nothing else: a suppressed or missing
|
||||
// value is left out of the drawing (a gap, never a zero) and named in the table beside it.
|
||||
const miles = (v: number) => v.toLocaleString('es-MX');
|
||||
const pct = (v: number) => v.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 }) + ' %';
|
||||
const base = (tema: Tema, alto: number, margen: Record<string, number>) => {
|
||||
const t = c2Theme(tema);
|
||||
return { autosize: true, height: alto, paper_bgcolor: t.background, plot_bgcolor: t.background, font: { color: t.text }, margin: margen, showlegend: false };
|
||||
};
|
||||
const config = { displayModeBar: false };
|
||||
|
||||
/** Share of the selection by category, with the Wilson interval of each published share as a horizontal bar. */
|
||||
export function distribucionFigura(d: DistribucionAnalisis, tema: Tema): PlotlyFigure {
|
||||
const t = c2Theme(tema);
|
||||
const items = d.items.filter(i => !i.suprimido && (i.n ?? 0) > 0 && i.porcentaje !== null);
|
||||
return {
|
||||
data: [{
|
||||
type: 'bar', orientation: 'h', y: items.map(i => i.etiqueta), x: items.map(i => i.porcentaje), customdata: items.map(i => i.codigo),
|
||||
marker: { color: C2_PALETTE.series[0] },
|
||||
error_x: { type: 'data', symmetric: false, array: items.map(i => i.ic_alto! - i.porcentaje!), arrayminus: items.map(i => i.porcentaje! - i.ic_bajo!), color: t.text },
|
||||
text: items.map(i => `${miles(i.n!)} (${pct(i.porcentaje!)})`), textposition: 'inside', insidetextanchor: 'start', textfont: { color: '#081839' }, cliponaxis: false,
|
||||
hovertemplate: items.map(i => `<b>${i.etiqueta}</b><br>${miles(i.n!)} pacientes<br>${pct(i.porcentaje!)} (IC 95 %: ${pct(i.ic_bajo!)} a ${pct(i.ic_alto!)})<extra></extra>`),
|
||||
}],
|
||||
layout: { ...base(tema, Math.max(220, 60 + 44 * items.length), { t: 24, l: 150, r: 90, b: 52 }),
|
||||
xaxis: { title: { text: 'Porcentaje de la selección' }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true },
|
||||
yaxis: { autorange: 'reversed', automargin: true, fixedrange: true } },
|
||||
config,
|
||||
};
|
||||
}
|
||||
|
||||
/** The share of cases per group as a point with its interval: groups that aren't published have no point. */
|
||||
export function comparacionFigura(c: ComparacionAnalisis, tema: Tema, medida: string): PlotlyFigure {
|
||||
const t = c2Theme(tema);
|
||||
const grupos = c.grupos.filter(g => g.estado === 'disponible');
|
||||
return {
|
||||
data: [{
|
||||
type: 'scatter', mode: 'markers', y: grupos.map(g => g.etiqueta), x: grupos.map(g => g.valor), customdata: grupos.map(g => g.codigo),
|
||||
marker: { color: C2_PALETTE.series[1], size: 11 },
|
||||
error_x: { type: 'data', symmetric: false, array: grupos.map(g => g.ic_alto! - g.valor!), arrayminus: grupos.map(g => g.valor! - g.ic_bajo!), color: t.text, thickness: 2, width: 6 },
|
||||
hovertemplate: grupos.map(g => `<b>${g.etiqueta}</b><br>${g.casos} de ${g.total} pacientes con resultado<br>${pct(g.valor!)} (IC 95 %: ${pct(g.ic_bajo!)} a ${pct(g.ic_alto!)})<extra></extra>`),
|
||||
}],
|
||||
layout: { ...base(tema, Math.max(220, 80 + 46 * grupos.length), { t: 24, l: 150, r: 28, b: 56 }),
|
||||
xaxis: { title: { text: `${medida} entre pacientes con resultado de biopsia` }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true },
|
||||
yaxis: { autorange: 'reversed', type: 'category', automargin: true, fixedrange: true } },
|
||||
config,
|
||||
};
|
||||
}
|
||||
|
||||
const textoCelda = (c: CeldaMapa, medida: string) => c.suprimido ? 'No publicado'
|
||||
: medida === 'pacientes' ? `${miles(c.n!)} pacientes` : c.resultado.estado === 'disponible' ? `${pct(c.resultado.valor!)}<br>${c.resultado.casos} de ${c.resultado.total}` : c.resultado.estado === 'suprimido' ? 'No publicado' : 'Sin pacientes con resultado';
|
||||
|
||||
/** BI-RADS by age group: the number of patients or the share of cases in each cell; hidden cells are blank. */
|
||||
export function mapaFigura(m: MapaAnalisis, tema: Tema, medida: 'pacientes' | 'resultado'): PlotlyFigure {
|
||||
const t = c2Theme(tema);
|
||||
const celdas = new Map(m.celdas.map(c => [c.fila + '\u0000' + c.columna, c]));
|
||||
const valor = (c: CeldaMapa | undefined) => !c || c.suprimido ? null : medida === 'pacientes' ? c.n : c.resultado.estado === 'disponible' ? c.resultado.valor : null;
|
||||
const z = m.filas.categorias.map(f => m.columnas.categorias.map(c => valor(celdas.get(f.codigo + '\u0000' + c.codigo))));
|
||||
return {
|
||||
data: [{
|
||||
type: 'heatmap', x: m.columnas.categorias.map(c => c.etiqueta), y: m.filas.categorias.map(f => f.etiqueta), z,
|
||||
customdata: m.filas.categorias.map(f => m.columnas.categorias.map(c => [f.codigo, c.codigo])),
|
||||
text: m.filas.categorias.map(f => m.columnas.categorias.map(c => textoCelda(celdas.get(f.codigo + '\u0000' + c.codigo)!, medida === 'pacientes' ? 'pacientes' : 'resultado'))),
|
||||
hovertemplate: '%{y}, %{x}<br>%{text}<extra></extra>', hoverongaps: false, xgap: 2, ygap: 2,
|
||||
colorscale: [[0, '#E4EEC0'], [1, '#6A8000']], zmin: 0, zmax: medida === 'resultado' ? 100 : undefined,
|
||||
colorbar: { title: { text: medida === 'resultado' ? '% de casos' : 'Pacientes' } },
|
||||
}],
|
||||
layout: { ...base(tema, Math.max(280, 90 + 40 * m.filas.categorias.length), { t: 24, l: 130, r: 28, b: 60 }),
|
||||
xaxis: { automargin: true, fixedrange: true, type: 'category' }, yaxis: { autorange: 'reversed', automargin: true, fixedrange: true, type: 'category' },
|
||||
plot_bgcolor: t.grid },
|
||||
config,
|
||||
};
|
||||
}
|
||||
|
||||
export interface FigurasTendencia { actividad: PlotlyFigure; proporcion: PlotlyFigure; }
|
||||
|
||||
/** Reports per period (bars; a hidden total is a gap) and the share of malignant results with its interval. */
|
||||
export function tendenciaFiguras(r: TendenciaAnalisis, tema: Tema, medida: string): FigurasTendencia {
|
||||
const t = c2Theme(tema);
|
||||
const x = r.periodos.map(p => p.periodo + (p.incompleto ? ' (en curso)' : ''));
|
||||
const disponibles = r.periodos.map((p, i) => ({ p, x: x[i] })).filter(({ p }) => p.maligno.estado === 'disponible');
|
||||
return {
|
||||
actividad: {
|
||||
data: [
|
||||
{ type: 'bar', name: 'Reportes de mastografía', x, y: r.periodos.map(p => p.reportes_mastografia.total), marker: { color: C2_PALETTE.series[2] },
|
||||
hovertemplate: '%{x}<br>%{y} reportes de mastografía<extra></extra>' },
|
||||
{ type: 'bar', name: 'Reportes de biopsia', x, y: r.periodos.map(p => p.reportes_biopsia.total), marker: { color: C2_PALETTE.series[3] },
|
||||
hovertemplate: '%{x}<br>%{y} reportes de biopsia<extra></extra>' },
|
||||
],
|
||||
layout: { ...base(tema, 340, { t: 24, l: 56, r: 16, b: 80 }), showlegend: true, legend: { orientation: 'h', y: -0.28 }, barmode: 'group',
|
||||
xaxis: { type: 'category', automargin: true, fixedrange: true }, yaxis: { title: { text: 'Reportes' }, gridcolor: t.grid, rangemode: 'tozero', fixedrange: true } },
|
||||
config,
|
||||
},
|
||||
proporcion: {
|
||||
data: [{
|
||||
type: 'scatter', mode: 'lines+markers', x: disponibles.map(d => d.x), y: disponibles.map(d => d.p.maligno.valor), connectgaps: false,
|
||||
line: { color: C2_PALETTE.series[1] }, marker: { color: C2_PALETTE.series[1], size: 9 },
|
||||
error_y: { type: 'data', symmetric: false, array: disponibles.map(d => d.p.maligno.ic_alto! - d.p.maligno.valor!), arrayminus: disponibles.map(d => d.p.maligno.valor! - d.p.maligno.ic_bajo!), color: t.text },
|
||||
hovertemplate: disponibles.map(d => `${d.x}<br>${d.p.maligno.casos} de ${d.p.maligno.total} reportes de biopsia con resultado<br>${pct(d.p.maligno.valor!)} (IC 95 %: ${pct(d.p.maligno.ic_bajo!)} a ${pct(d.p.maligno.ic_alto!)})<extra></extra>`),
|
||||
}],
|
||||
layout: { ...base(tema, 340, { t: 24, l: 64, r: 16, b: 64 }),
|
||||
xaxis: { type: 'category', categoryorder: 'array', categoryarray: x, automargin: true, fixedrange: true },
|
||||
yaxis: { title: { text: medida }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true } },
|
||||
config,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
// What this module covers: CaMa's descriptive analysis in the Analysis tab: the answers' validation, the cards, the
|
||||
// figures built from them, the sections the component draws, the way from a figure to Seguimiento and the states
|
||||
// without data, suppressed or not published.
|
||||
// Fixtures (`fixtures/cama_analisis_real_*.json`): answers of the WebApi's `/cama/analisis` endpoints over the local
|
||||
// installation's synthetic CaMa data at 2026-11-16, whole cohort: catalog, indicators (90 days), distribution by BI-RADS, by
|
||||
// age group and by biopsy result, comparison by age group, map, trend by semester and by month, and the 403 body.
|
||||
import { TestBed, ComponentFixture } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { IndicadoresAnalisisDescriptivo, detalleTarjeta, valorTarjeta } from './indicadores-analisis-descriptivo';
|
||||
import {
|
||||
catalogoDescriptivo, comparacionDescriptiva, distribucionDescriptiva, mapaDescriptivo, resumenDescriptivo, tendenciaDescriptiva,
|
||||
} from './indicadores-analisis.service';
|
||||
import { comparacionFigura, distribucionFigura, mapaFigura, tendenciaFiguras } from './indicadores-analisis-descriptivo-figuras';
|
||||
import catalogoData from './fixtures/cama_analisis_real_catalogo.json';
|
||||
import resumenData from './fixtures/cama_analisis_real_resumen90.json';
|
||||
import distBirads from './fixtures/cama_analisis_real_dist_birads.json';
|
||||
import distEdad from './fixtures/cama_analisis_real_dist_edad.json';
|
||||
import distBiopsia from './fixtures/cama_analisis_real_dist_biopsia.json';
|
||||
import compBirads from './fixtures/cama_analisis_real_comp_birads.json';
|
||||
import compEdad from './fixtures/cama_analisis_real_comp_edad.json';
|
||||
import mapaData from './fixtures/cama_analisis_real_mapa.json';
|
||||
import tendSem from './fixtures/cama_analisis_real_tend_sem.json';
|
||||
import tendMes from './fixtures/cama_analisis_real_tend_mes.json';
|
||||
import pequenoData from './fixtures/cama_analisis_real_pequeno.json';
|
||||
|
||||
const copia = (v: unknown) => structuredClone(v) as unknown as Record<string, any>;
|
||||
const CORTE = '2026-11-16';
|
||||
|
||||
describe('Respuestas del análisis descriptivo', () => {
|
||||
it('las respuestas reales cumplen su contrato y nombran la cohorte que describen', () => {
|
||||
// Pins down: every answer is accepted as the server sends it, names the cohort, scenario, revision and cut-off, and
|
||||
// carries no `simulado` field. Fails if the contract drifts from what the client validates.
|
||||
const todas = [catalogoDescriptivo(copia(catalogoData)), resumenDescriptivo(copia(resumenData)), distribucionDescriptiva(copia(distBirads)),
|
||||
comparacionDescriptiva(copia(compEdad)), mapaDescriptivo(copia(mapaData))];
|
||||
for (const r of todas) { expect(r.cohorte).toBe('cama_birads_v1'); expect(r.revision).toMatch(/^[0-9a-f]{64}$/); expect(r.corte).toBe(CORTE); expect('simulado' in r).toBe(false); }
|
||||
expect(new Set(todas.map(r => r.revision)).size).toBe(1);
|
||||
// The trend is activity, not the cohort: it names its cut-off, unit, population and biopsy scope, and no cohort, filters or test.
|
||||
for (const t of [tendenciaDescriptiva(copia(tendSem)), tendenciaDescriptiva(copia(tendMes))]) {
|
||||
expect(t.corte).toBe(CORTE); expect(t.unidad).toBe('reportes'); expect(t.poblacion).toBeTruthy(); expect(t.alcance_biopsias).toBeTruthy();
|
||||
expect(Object.keys(t)).not.toEqual(expect.arrayContaining(['cohorte']));
|
||||
for (const k of ['cohorte', 'revision', 'ventana', 'filtros', 'prueba', 'simulado']) expect(k in t).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('una respuesta con un conteo publicado y suprimido a la vez, o sin cohorte, se rechaza', () => {
|
||||
// Pins down: a suppressed item can't carry a count and a published one must; an answer without cohort context isn't read.
|
||||
// Fails if the client draws figures from an answer that contradicts itself.
|
||||
const d = copia(distBirads); d['items'][0].suprimido = true;
|
||||
expect(() => distribucionDescriptiva(d)).toThrow();
|
||||
const sin = copia(distBirads); delete sin['revision'];
|
||||
expect(() => distribucionDescriptiva(sin)).toThrow();
|
||||
const r = copia(resumenData); r['indicadores'][1].estado = 'suprimido';
|
||||
expect(() => resumenDescriptivo(r)).toThrow();
|
||||
});
|
||||
|
||||
it('las tarjetas escriben el valor, su intervalo y su denominador, o dicen por qué no hay cifra', () => {
|
||||
// Pins down: a proportion reads «68.9»-style with its Wilson interval and `k de n pacientes`; a median reads its quartiles;
|
||||
// a suppressed card has no value and says why. Fails if a card shows a number the answer doesn't publish.
|
||||
const r = resumenDescriptivo(copia(resumenData));
|
||||
const t = Object.fromEntries(r.indicadores.map(i => [i.clave, i]));
|
||||
expect(valorTarjeta(t['cohorte'])).toBe('61');
|
||||
expect(valorTarjeta(t['con_biopsia'])).toBe('68.9');
|
||||
expect(detalleTarjeta(t['con_biopsia'])).toContain('IC 95 %: 56.4 a 79.1 %. 42 de 61 pacientes.');
|
||||
expect(detalleTarjeta(t['dias_a_biopsia'])).toContain('Q1 a Q3: 19.3 a 30.8 días. 42 pacientes.');
|
||||
const oculta = { ...t['con_biopsia'], estado: 'suprimido' as const, valor: null, ic_bajo: null, ic_alto: null };
|
||||
expect(valorTarjeta(oculta)).toBeNull();
|
||||
expect(detalleTarjeta(oculta)).toContain('Muy pocos pacientes');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Figuras del análisis descriptivo', () => {
|
||||
it('la distribución dibuja solo las categorías publicadas, con su intervalo, y deja las suprimidas fuera', () => {
|
||||
// Pins down: BI-RADS 5 and 6 are suppressed in the real answer, so only BI-RADS 4 is drawn, at its share with its Wilson
|
||||
// interval as asymmetric error bars; a hidden category is a gap, not a zero bar. Fails if a suppressed group is drawn.
|
||||
const d = distribucionDescriptiva(copia(distBirads));
|
||||
const [traza] = distribucionFigura(d, 'claro').data as Record<string, any>[];
|
||||
expect(traza['y']).toEqual(['BI-RADS 4']);
|
||||
expect(traza['x']).toEqual([54.1]);
|
||||
expect(traza['error_x']['array'][0] + traza['x'][0]).toBeCloseTo(d.items[0].ic_alto!, 5);
|
||||
});
|
||||
|
||||
it('la comparación dibuja un punto por grupo publicado con su intervalo', () => {
|
||||
// Pins down: by age group three groups have enough patients with a result; each point is its share and the interval is
|
||||
// asymmetric. Fails if a group without data or a hidden one gets a point.
|
||||
const c = comparacionDescriptiva(copia(compEdad));
|
||||
const [traza] = comparacionFigura(c, 'claro', 'Carcinoma invasor').data as Record<string, any>[];
|
||||
expect(traza['y']).toEqual(['40 a 49 años', '50 a 59 años', '60 a 69 años'].map(e => expect.stringContaining(e.split(' ')[0])));
|
||||
expect(traza['x']).toHaveLength(3);
|
||||
expect(c.grupos.filter(g => g.estado === 'disponible').map(g => g.casos)).toEqual([5, 6, 8]);
|
||||
});
|
||||
|
||||
it('el mapa deja en blanco las celdas que no se publican y conserva la posición de cada celda publicada', () => {
|
||||
// Pins down: a hidden cell is `null` in the matrix (blank), never zero; published cells keep their row and column and carry
|
||||
// the key that opens their patients. Fails if suppression turns into a zero or shifts a cell.
|
||||
const m = mapaDescriptivo(copia(mapaData));
|
||||
const [traza] = mapaFigura(m, 'claro', 'pacientes').data as Record<string, any>[];
|
||||
const iFila = m.filas.categorias.findIndex(f => f.codigo === 'BIRADS_4'), iCol = m.columnas.categorias.findIndex(c => c.codigo === '50-59');
|
||||
expect(traza['z'][iFila][iCol]).toBeNull();
|
||||
const publicada = m.celdas.find(c => !c.suprimido && (c.n ?? 0) > 0)!;
|
||||
const f = m.filas.categorias.findIndex(x => x.codigo === publicada.fila), c = m.columnas.categorias.findIndex(x => x.codigo === publicada.columna);
|
||||
expect(traza['z'][f][c]).toBe(publicada.n);
|
||||
expect(traza['customdata'][f][c]).toEqual([publicada.fila, publicada.columna]);
|
||||
});
|
||||
|
||||
it('la tendencia dibuja los periodos y el porcentaje solo donde se publica, y marca el periodo en curso', () => {
|
||||
// Pins down: by semester four periods carry a share with an interval; by month the months with fewer than five biopsies
|
||||
// have no point; the period the cut-off cuts is labelled. Fails if an unpublished period gets a point.
|
||||
const sem = tendenciaFiguras(tendenciaDescriptiva(copia(tendSem)), 'claro', 'x');
|
||||
expect((sem.proporcion.data[0] as Record<string, any>)['x']).toHaveLength(4);
|
||||
const mes = tendenciaDescriptiva(copia(tendMes));
|
||||
const figuras = tendenciaFiguras(mes, 'claro', 'x');
|
||||
const publicados = mes.periodos.filter(p => p.maligno.estado === 'disponible').length;
|
||||
expect((figuras.proporcion.data[0] as Record<string, any>)['x']).toHaveLength(publicados);
|
||||
expect((figuras.actividad.data[0] as Record<string, any>)['x'].at(-1)).toContain('(en curso)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Análisis descriptivo de CaMa (componente)', () => {
|
||||
let fixture: ComponentFixture<IndicadoresAnalisisDescriptivo>, http: HttpTestingController;
|
||||
let emitidas: { seleccion: any; origen: HTMLElement | null }[];
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresAnalisisDescriptivo], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
fixture = TestBed.createComponent(IndicadoresAnalisisDescriptivo); http = TestBed.inject(HttpTestingController);
|
||||
emitidas = []; fixture.componentInstance.verPacientes.subscribe(e => emitidas.push(e));
|
||||
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('corte', CORTE);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
const pide = (ruta: string) => http.expectOne(r => r.url === `/cama/analisis${ruta}`);
|
||||
async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); }
|
||||
async function abrir() {
|
||||
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||
pide('').flush(catalogoData); pide('/resumen').flush(resumenData); pide('/distribucion').flush(distBirads);
|
||||
pide('/comparacion').flush(compBirads); pide('/mapa').flush(mapaData); pide('/tendencia').flush(tendSem);
|
||||
await asentar();
|
||||
}
|
||||
const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement;
|
||||
|
||||
it('no pide nada hasta que la pestaña se abre y entonces pide sus seis respuestas con el corte y la selección', async () => {
|
||||
// Pins down: nothing before the tab is open; then the catalog, indicators (90-day horizon), distribution by BI-RADS,
|
||||
// comparison by age group, map and semester trend, all at the cut-off and the whole cohort. Fails if a section is
|
||||
// asked early or without the selection.
|
||||
http.expectNone(() => true);
|
||||
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||
const parametros = (ruta: string) => { const r = pide(ruta); const p = Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)])); r.flush({}, { status: 404, statusText: 'x' }); return p; };
|
||||
expect(parametros('')).toEqual({ corte: CORTE, meses: '0' });
|
||||
expect(parametros('/resumen')).toEqual({ corte: CORTE, meses: '0', horizonte: '90' });
|
||||
expect(parametros('/distribucion')).toEqual({ corte: CORTE, meses: '0', por: 'birads' });
|
||||
expect(parametros('/comparacion')).toEqual({ corte: CORTE, meses: '0', por: 'grupo_edad', medida: 'maligno' });
|
||||
expect(parametros('/mapa')).toEqual({ corte: CORTE, meses: '0', filas: 'birads', columnas: 'grupo_edad', medida: 'maligno' });
|
||||
expect(parametros('/tendencia')).toEqual({ corte: CORTE, tipo: 'semestre', periodos: '6' });
|
||||
});
|
||||
|
||||
it('dibuja las tarjetas, las tablas y la lista de lo que no se puede calcular, con las mismas 61 pacientes en todas partes', async () => {
|
||||
// Pins down: the cohort card, the distribution's total and its caption agree on 61 patients; the unavailable analyses
|
||||
// are listed with their reasons; nothing says the data is simulated, provisional or a test. Fails if two parts of the tab
|
||||
// count different patients or a banner of that kind appears.
|
||||
await abrir();
|
||||
const texto = root().textContent!;
|
||||
expect(root().querySelectorAll('app-indicador-kpi-card')).toHaveLength(7);
|
||||
expect(root().querySelector('app-indicador-kpi-card .value')?.textContent).toContain('61');
|
||||
expect(root().querySelector('#desc-dist ~ div table caption, section[aria-labelledby="desc-dist"] caption')?.textContent).toContain('61 pacientes');
|
||||
expect(texto).toContain('No disponible con las fuentes actuales');
|
||||
for (const titulo of ['Supervivencia', 'Recaída', 'Adherencia al tratamiento']) expect(texto).toContain(titulo);
|
||||
expect(texto).toContain('No hay estado vital');
|
||||
expect(texto).not.toMatch(/simulad|demostraci|provisional|prueba de concepto|modo de desarrollo|datos de prueba/i);
|
||||
});
|
||||
|
||||
it('una categoría suprimida dice «No publicado» sin botón y una publicada abre sus pacientes con la selección completa', async () => {
|
||||
// Pins down: BI-RADS 5 (suppressed) has no «Ver pacientes» button; BI-RADS 4 has one and its click emits the filter, the
|
||||
// label, the cut-off, the patients counted and the cohort context to quote back. Fails if a hidden group can be opened or
|
||||
// the list would open another selection.
|
||||
await abrir();
|
||||
const fila = (codigo: string) => root().querySelector<HTMLElement>(`tr[data-codigo="${codigo}"]`)!;
|
||||
expect(fila('BIRADS_5').textContent).toContain('No publicado'); expect(fila('BIRADS_5').querySelector('button')).toBeNull();
|
||||
fila('BIRADS_4').querySelector<HTMLButtonElement>('button.ver')!.click();
|
||||
expect(emitidas).toHaveLength(1);
|
||||
expect(emitidas[0].seleccion).toMatchObject({ filtros: { birads: 'BIRADS_4' }, etiqueta: 'BI-RADS 4', corte: CORTE, esperados: 33,
|
||||
contexto: { cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: (distBirads as any).revision } });
|
||||
});
|
||||
|
||||
it('cambiar la dimensión de la distribución vuelve a pedir solo esa sección', async () => {
|
||||
// Pins down: choosing «Grupo de edad» asks `distribucion?por=grupo_edad` and nothing else, and its answer replaces the
|
||||
// table. Fails if a choice in one section reloads the rest.
|
||||
await abrir();
|
||||
boton('Grupo de edad').click(); fixture.detectChanges();
|
||||
const r = pide('/distribucion'); expect(r.request.params.get('por')).toBe('grupo_edad'); r.flush(distEdad); await asentar();
|
||||
expect([...root().querySelectorAll('tr[data-codigo]')].map(tr => tr.getAttribute('data-codigo'))).toEqual(['<40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO']);
|
||||
http.expectNone(() => true);
|
||||
boton('Resultado de la biopsia').click(); fixture.detectChanges(); pide('/distribucion').flush(distBiopsia); await asentar();
|
||||
expect(root().querySelector('tr[data-codigo="SIN_BIOPSIA"]')?.textContent).toContain('19');
|
||||
});
|
||||
|
||||
it('un grupo sin suficientes pacientes dice por qué, un 503 lo dice y un 404 queda pendiente, sin pantalla vacía', async () => {
|
||||
// Pins down: a 403 on the distribution shows the fixed message; the indicators' 503 says the cohort isn't available and
|
||||
// offers a retry; a 404 is «pendiente», not an error. Fails if a failure leaves the section empty or shows the body.
|
||||
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||
pide('').flush(catalogoData);
|
||||
pide('/resumen').flush({}, { status: 503, statusText: 'x' });
|
||||
pide('/distribucion').flush(pequenoData, { status: 403, statusText: 'x' });
|
||||
pide('/comparacion').flush({}, { status: 404, statusText: 'x' });
|
||||
pide('/mapa').flush(mapaData); pide('/tendencia').flush(tendSem);
|
||||
await asentar();
|
||||
expect(root().textContent).toContain('La cohorte no está disponible en este momento.');
|
||||
expect(root().querySelector('#desc-dist')!.parentElement!.querySelector('[role=alert]')?.textContent).toContain('muy pocos pacientes');
|
||||
expect(root().querySelector('#desc-dist')!.parentElement!.textContent).not.toContain('menos de 5 pacientes: su lista');
|
||||
expect(root().querySelector('[aria-labelledby="desc-comp"] table')).toBeNull();
|
||||
});
|
||||
|
||||
it('la comparación sin prueba válida lo dice; con prueba válida da el estadístico y su p', async () => {
|
||||
// Pins down: by BI-RADS no table supports the test and the page says «No disponible» with the reason; by age group it
|
||||
// gives chi-square, degrees of freedom and p. Fails if a p-value appears on a table the server called invalid.
|
||||
await abrir();
|
||||
expect(root().querySelector('[aria-labelledby="desc-comp"] .nota[role=status]')?.textContent).toContain('No disponible. Hacen falta al menos dos grupos');
|
||||
const c = fixture.componentInstance;
|
||||
c.cambiarComparacion('grupo_edad', 'invasor'); fixture.detectChanges();
|
||||
pide('/comparacion').flush(compEdad); await asentar();
|
||||
expect(root().querySelector('[aria-labelledby="desc-comp"] .nota[role=status]')?.textContent).toMatch(/χ² 0.089, 2 gl, p 0.957/);
|
||||
});
|
||||
|
||||
it('la tendencia marca el periodo en curso y deja sin cifra el porcentaje que no se publica', async () => {
|
||||
// Pins down: by month the table says «No publicado» where a month has too few biopsies and labels the current month.
|
||||
// Fails if a hidden share is written as a number or the partial period looks whole.
|
||||
await abrir();
|
||||
fixture.componentInstance.cambiarTendencia('mes', 12); fixture.detectChanges(); pide('/tendencia').flush(tendMes); await asentar();
|
||||
const tabla = root().querySelector('[aria-labelledby="desc-tend"] table')!;
|
||||
expect(tabla.textContent).toContain('(en curso)');
|
||||
expect(tabla.textContent).toContain('No publicado');
|
||||
expect(new Set([...tabla.querySelectorAll('tbody tr')].map(tr => tr.children[3].textContent!.trim())).has('No publicado')).toBe(true);
|
||||
});
|
||||
|
||||
it('la actividad de reportes conserva su definición: solo cambia con el corte, nunca con la ventana ni los filtros', async () => {
|
||||
// Pins down: «Aplicar» with another window and filters reloads the cohort sections with them but not the trend, and a new
|
||||
// cut-off reloads the trend with only that cut-off, the period type and the count. Fails if the trend takes a filter or
|
||||
// window it doesn't apply, or isn't refreshed when the cut-off changes.
|
||||
await abrir();
|
||||
const c = fixture.componentInstance;
|
||||
c.meses = 3; c.filtros = { grupo_edad: '50-59' }; c.aplicar(); fixture.detectChanges();
|
||||
const d = pide('/distribucion'); expect(d.request.params.get('meses')).toBe('3'); expect(d.request.params.get('grupo_edad')).toBe('50-59');
|
||||
d.flush({}, { status: 404, statusText: 'x' });
|
||||
for (const ruta of ['', '/resumen', '/comparacion', '/mapa']) pide(ruta).flush({}, { status: 404, statusText: 'x' });
|
||||
http.expectNone(r => r.url.endsWith('/tendencia'));
|
||||
fixture.componentRef.setInput('corte', '2026-10-31'); await asentar();
|
||||
const t = http.expectOne(r => r.url === '/cama/analisis/tendencia');
|
||||
expect(Object.fromEntries(t.request.params.keys().map(k => [k, t.request.params.get(k)]))).toEqual({ corte: '2026-10-31', tipo: 'semestre', periodos: '6' });
|
||||
t.flush({}, { status: 404, statusText: 'x' });
|
||||
for (const ruta of ['', '/resumen', '/distribucion', '/comparacion', '/mapa']) pide(ruta).flush({}, { status: 404, statusText: 'x' });
|
||||
});
|
||||
|
||||
it('la actividad de reportes se presenta con su población, la unidad y el alcance de las biopsias, y sin prueba estadística', async () => {
|
||||
// Pins down: the section names what it counts (reports, not patients), over whom, the scope of the biopsies and that the
|
||||
// cohort selection doesn't apply; it has no chi-square paragraph. Fails if the text attributes the filters or implies a test.
|
||||
await abrir();
|
||||
const seccion = root().querySelector('[aria-labelledby="desc-tend"]')!.textContent!;
|
||||
expect(seccion).toContain('Actividad de reportes en el tiempo');
|
||||
expect(seccion).toContain('no depende de la cohorte, la ventana ni los filtros');
|
||||
expect(seccion).toContain('Cuenta reportes, no pacientes');
|
||||
expect(seccion).toContain((tendSem as any).alcance_biopsias);
|
||||
expect(seccion).toContain('Reportes de biopsia');
|
||||
expect(seccion).not.toMatch(/χ²|p-valor|prueba de homogeneidad/i);
|
||||
});
|
||||
|
||||
it.each([0, 1, 3, 6, 12])('una barra de la distribución con la ventana de %i meses y filtros abre la lista con esa misma ventana', async (m) => {
|
||||
// Pins down: the selection a published bar emits carries the window the analysis was computed over, the filters applied,
|
||||
// the cut-off and the cohort context. Fails if a window turns into the whole cohort when the patients are opened.
|
||||
await abrir();
|
||||
const c = fixture.componentInstance;
|
||||
c.meses = m; c.filtros = { grupo_edad: '50-59' }; c.aplicar(); fixture.detectChanges();
|
||||
pide('').flush({}, { status: 404, statusText: 'x' }); pide('/resumen').flush({}, { status: 404, statusText: 'x' });
|
||||
pide('/distribucion').flush({ ...(distBirads as any), ventana: { ...(distBirads as any).ventana, meses: m }, filtros: { birads: null, grupo_edad: '50-59', biopsia: null } });
|
||||
pide('/comparacion').flush({}, { status: 404, statusText: 'x' }); pide('/mapa').flush({}, { status: 404, statusText: 'x' });
|
||||
await asentar();
|
||||
root().querySelector<HTMLButtonElement>('tr[data-codigo="BIRADS_4"] button.ver')!.click();
|
||||
expect(emitidas.at(-1)!.seleccion).toMatchObject({ filtros: { grupo_edad: '50-59', birads: 'BIRADS_4' }, corte: CORTE, meses: m, esperados: 33,
|
||||
contexto: { cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: (distBirads as any).revision } });
|
||||
});
|
||||
|
||||
it('«No disponible con las fuentes actuales» es una sección plegable, cerrada al inicio, con todo su contenido al abrirla', async () => {
|
||||
// Pins down: the unavailable analyses sit in a native disclosure (keyboard and screen reader for free), closed at first,
|
||||
// with its heading as the summary and every title and reason in the list inside it; opening it shows the same text as
|
||||
// before. Fails if it starts open, loses an entry or stops being reachable from the keyboard.
|
||||
await abrir();
|
||||
const plegable = root().querySelector<HTMLDetailsElement>('details[data-plegable="no-disponibles"]')!;
|
||||
const resumen = plegable.querySelector('summary')!;
|
||||
expect(plegable.open).toBe(false);
|
||||
expect(resumen.querySelector('h2')!.textContent).toBe('No disponible con las fuentes actuales');
|
||||
expect(root().querySelector('section[aria-labelledby="desc-no"] h2')!.id).toBe('desc-no');
|
||||
expect(resumen.tabIndex).toBeGreaterThanOrEqual(0);
|
||||
const entradas = [...plegable.querySelectorAll('li')].map(li => li.textContent);
|
||||
expect(entradas.length).toBe((resumenData as any).no_disponibles.length);
|
||||
for (const n of (resumenData as any).no_disponibles) expect(entradas.some(t => t!.includes(n.titulo) && t!.includes('No disponible. ' + n.motivo))).toBe(true);
|
||||
resumen.dispatchEvent(new MouseEvent('click', { bubbles: true })); fixture.detectChanges();
|
||||
expect(plegable.open).toBe(true);
|
||||
resumen.dispatchEvent(new MouseEvent('click', { bubbles: true })); fixture.detectChanges();
|
||||
expect(plegable.open).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,368 @@
|
||||
import { Component, DestroyRef, effect, inject, input, output, signal, untracked, WritableSignal } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { Observable, Subscription } from 'rxjs';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import {
|
||||
AnalisisCatalogoDescriptivo, AnalisisDescriptivoService, AnalisisSeleccion, CeldaMapa, ComparacionAnalisis, DistribucionAnalisis, MapaAnalisis,
|
||||
PedidoDescriptivo, ResumenAnalisis, TarjetaAnalisis, TendenciaAnalisis,
|
||||
} from './indicadores-analisis.service';
|
||||
import { comparacionFigura, distribucionFigura, FigurasTendencia, mapaFigura, tendenciaFiguras } from './indicadores-analisis-descriptivo-figuras';
|
||||
import { Dominio, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import type { SeleccionPacientes } from './indicadores-analisis';
|
||||
|
||||
type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' } | { estado: 'no-disponible' };
|
||||
const VACIA = { data: [], layout: {} } as PlotlyFigure;
|
||||
const miles = (v: number) => v.toLocaleString('es-MX');
|
||||
const decimal = (v: number) => v.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 });
|
||||
|
||||
/** The card's value as the page writes it: a share with its interval, a median with its quartiles, or a count. */
|
||||
export function valorTarjeta(t: TarjetaAnalisis): string | null {
|
||||
if (t.estado !== 'disponible' || t.valor === null) return null;
|
||||
return t.unidad === '%' ? decimal(t.valor) : t.unidad === 'días' ? decimal(t.valor) : miles(t.valor);
|
||||
}
|
||||
export function detalleTarjeta(t: TarjetaAnalisis): string {
|
||||
if (t.estado === 'suprimido') return 'Muy pocos pacientes para publicar esta cifra. ' + t.descripcion;
|
||||
if (t.estado === 'sin_datos') return 'No hay pacientes en esta base para calcularla. ' + t.descripcion;
|
||||
const partes: string[] = [];
|
||||
if (t.unidad === '%' && t.ic_bajo !== null && t.ic_alto !== null) partes.push(`IC 95 %: ${decimal(t.ic_bajo)} a ${decimal(t.ic_alto)} %. ${miles(t.n ?? 0)} de ${miles(t.denominador ?? 0)} pacientes.`);
|
||||
if (t.unidad === 'días' && t.q1 !== null && t.q3 !== null) partes.push(`Q1 a Q3: ${decimal(t.q1)} a ${decimal(t.q3)} días. ${miles(t.n ?? 0)} pacientes.`);
|
||||
partes.push(t.descripcion);
|
||||
return partes.join(' ');
|
||||
}
|
||||
|
||||
// Descriptive analysis of the BI-RADS cohort: its indicators, its distribution, a comparison between groups, the map
|
||||
// between two variables and the trend over time. Every figure is drawn from the endpoint's answer; what the data cannot
|
||||
// hold is listed as not available, with its reason. Nothing is requested until the tab is first opened.
|
||||
@Component({
|
||||
selector: 'app-indicadores-analisis-descriptivo',
|
||||
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard],
|
||||
template: `
|
||||
<section class="bloque" aria-labelledby="desc-resumen">
|
||||
<h2 id="desc-resumen">Indicadores de la cohorte</h2>
|
||||
<p class="nota">Pacientes cuya última mastografía reportada al corte es BI-RADS 4, 5 o 6. Descriptivos: describen a estas pacientes, no la incidencia en una población.</p>
|
||||
<form class="controles" (ngSubmit)="aplicar()">
|
||||
<label>Ventana
|
||||
<select name="meses" [(ngModel)]="meses">
|
||||
<option [ngValue]="0">Toda la cohorte</option><option [ngValue]="1">Último mes</option><option [ngValue]="3">Últimos 3 meses</option>
|
||||
<option [ngValue]="6">Últimos 6 meses</option><option [ngValue]="12">Últimos 12 meses</option>
|
||||
</select></label>
|
||||
<label>Categoría BI-RADS
|
||||
<select name="birads" [(ngModel)]="filtros['birads']"><option [ngValue]="undefined">Todas</option>
|
||||
@for (o of opciones('birads'); track o.codigo) { <option [ngValue]="o.codigo">{{ o.etiqueta }}</option> }</select></label>
|
||||
<label>Grupo de edad
|
||||
<select name="grupo_edad" [(ngModel)]="filtros['grupo_edad']"><option [ngValue]="undefined">Todos</option>
|
||||
@for (o of opciones('grupo_edad'); track o.codigo) { <option [ngValue]="o.codigo">{{ o.etiqueta }}</option> }</select></label>
|
||||
<label>Horizonte del seguimiento diagnóstico
|
||||
<select name="horizonte" [(ngModel)]="horizonte">
|
||||
@for (h of horizontes(); track h) { <option [ngValue]="h">{{ h }} días</option> }</select></label>
|
||||
<button type="submit" mat-stroked-button [disabled]="cargando()">Aplicar</button>
|
||||
</form>
|
||||
@switch (resumen().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando los indicadores" /> }
|
||||
@case ('pendiente') { <p role="status">Funcionalidad pendiente de publicación.</p> }
|
||||
@case ('no-disponible') { <p role="status">La cohorte no está disponible en este momento.</p><button type="button" mat-stroked-button (click)="aplicar()">Reintentar consulta</button> }
|
||||
@case ('error') { <div role="alert"><p>{{ $any(resumen()).mensaje }}</p><button type="button" mat-stroked-button (click)="aplicar()">Reintentar consulta</button></div> }
|
||||
}
|
||||
@if (r(); as res) {
|
||||
<p class="contexto">Fecha de corte: {{ res.corte }}. Ventana: {{ res.ventana.meses === 0 ? 'toda la cohorte' : res.ventana.desde + ' al ' + res.ventana.hasta }}.</p>
|
||||
<div class="tarjetas">
|
||||
@for (t of res.indicadores; track t.clave) {
|
||||
<app-indicador-kpi-card [title]="t.titulo" [value]="valor(t)" [unit]="t.unidad === 'pacientes' ? '' : t.unidad === 'días' ? 'días (mediana)' : '%'"
|
||||
[state]="t.estado === 'disponible' ? 'Disponible' : t.estado === 'suprimido' ? 'Dato oculto por tamaño' : 'Sin valor disponible'"
|
||||
[quietWhenAvailable]="true" [additionalInfo]="detalle(t)" />
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="bloque" aria-labelledby="desc-dist">
|
||||
<h2 id="desc-dist">Distribución de pacientes</h2>
|
||||
<div class="selector" role="group" aria-label="Distribuir por">
|
||||
@for (d of dimensionesDist; track d.clave) {
|
||||
<button type="button" mat-stroked-button [class.activo]="por() === d.clave" [attr.aria-pressed]="por() === d.clave" (click)="cambiarPor(d.clave)">{{ d.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
@switch (distribucion().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la distribución" /> }
|
||||
@case ('error') { <div role="alert"><p>{{ $any(distribucion()).mensaje }}</p></div> }
|
||||
}
|
||||
@if (dist(); as d) {
|
||||
@if (d.total === 0) { <p role="status">No hay pacientes en esta cohorte para el corte seleccionado.</p> }
|
||||
@else {
|
||||
<app-plotly-chart [style.--plot-height]="'auto'" [showNotes]="false" [figure]="figuraDist()" label="Distribución de pacientes" (plotClick)="clicDist($event)" />
|
||||
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Distribución de pacientes, tabla">
|
||||
<table><caption>{{ miles(d.total) }} pacientes en la selección</caption>
|
||||
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col">Porcentaje (IC 95 %)</th><th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
|
||||
<tbody>@for (i of d.items; track i.codigo) {
|
||||
<tr [attr.data-codigo]="i.codigo"><th scope="row">{{ i.etiqueta }}</th>
|
||||
<td>{{ i.suprimido ? 'No publicado' : miles(i.n!) }}</td>
|
||||
<td>{{ i.suprimido || i.porcentaje === null ? 'No disponible' : decimal(i.porcentaje) + ' % (' + decimal(i.ic_bajo!) + ' a ' + decimal(i.ic_alto!) + ')' }}</td>
|
||||
<td>@if (!i.suprimido && i.n) { <button type="button" class="ver" (click)="abrir(i.seleccion, i.etiqueta, i.n, d, $event.currentTarget)"
|
||||
[attr.aria-label]="'Ver pacientes de ' + i.etiqueta + ' en Seguimiento'">Ver pacientes</button> }</td></tr>
|
||||
}</tbody></table>
|
||||
</div>
|
||||
@if (d.items.some(i => i.suprimido)) { <p class="nota">Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica; para que su cifra no se pueda deducir, otra categoría puede quedar sin publicar.</p> }
|
||||
}
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="bloque" aria-labelledby="desc-comp">
|
||||
<h2 id="desc-comp">Comparación entre grupos</h2>
|
||||
<p class="nota">Porcentaje de pacientes con el resultado elegido entre las que tienen resultado de biopsia conocido, por grupo. Es una comparación descriptiva dentro de la cohorte.</p>
|
||||
<div class="controles">
|
||||
<label>Comparar por
|
||||
<select name="comp-por" [ngModel]="compPor()" (ngModelChange)="cambiarComparacion($event, compMedida())">
|
||||
<option value="birads">Categoría BI-RADS</option><option value="grupo_edad">Grupo de edad</option></select></label>
|
||||
<label>Resultado
|
||||
<select name="comp-medida" [ngModel]="compMedida()" (ngModelChange)="cambiarComparacion(compPor(), $event)">
|
||||
<option value="maligno">Carcinoma in situ o invasor</option><option value="invasor">Carcinoma invasor</option></select></label>
|
||||
</div>
|
||||
@switch (comparacion().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la comparación" /> }
|
||||
@case ('error') { <div role="alert"><p>{{ $any(comparacion()).mensaje }}</p></div> }
|
||||
}
|
||||
@if (comp(); as c) {
|
||||
@if (hayComparables()) { <app-plotly-chart [showNotes]="false" [figure]="figuraComp()" label="Comparación entre grupos" /> }
|
||||
@else { <p role="status">Ningún grupo tiene suficientes pacientes con resultado de biopsia para publicar su porcentaje.</p> }
|
||||
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Comparación entre grupos, tabla">
|
||||
<table><caption>{{ c.denominador }}</caption>
|
||||
<thead><tr><th scope="col">Grupo</th><th scope="col">Con el resultado</th><th scope="col">Con resultado conocido</th><th scope="col">Porcentaje (IC 95 %)</th></tr></thead>
|
||||
<tbody>@for (g of c.grupos; track g.codigo) {
|
||||
<tr><th scope="row">{{ g.etiqueta }}</th>
|
||||
<td>{{ g.estado === 'disponible' ? miles(g.casos!) : g.estado === 'suprimido' ? 'No publicado' : '0' }}</td>
|
||||
<td>{{ g.estado === 'disponible' ? miles(g.total!) : g.estado === 'suprimido' ? 'No publicado' : '0' }}</td>
|
||||
<td>{{ g.estado === 'disponible' ? decimal(g.valor!) + ' % (' + decimal(g.ic_bajo!) + ' a ' + decimal(g.ic_alto!) + ')' : 'No disponible' }}</td></tr>
|
||||
}</tbody></table>
|
||||
</div>
|
||||
<p class="nota" role="status">{{ textoPrueba(c.prueba) }}</p>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="bloque" aria-labelledby="desc-mapa">
|
||||
<h2 id="desc-mapa">Mapa entre variables: categoría BI-RADS y grupo de edad</h2>
|
||||
<div class="selector" role="group" aria-label="Medida del mapa">
|
||||
<button type="button" mat-stroked-button [class.activo]="mapaMedida() === 'pacientes'" [attr.aria-pressed]="mapaMedida() === 'pacientes'" (click)="cambiarMapa('pacientes')">Pacientes</button>
|
||||
<button type="button" mat-stroked-button [class.activo]="mapaMedida() === 'resultado'" [attr.aria-pressed]="mapaMedida() === 'resultado'" (click)="cambiarMapa('resultado')">Porcentaje con carcinoma</button>
|
||||
</div>
|
||||
@switch (mapa().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando el mapa" /> }
|
||||
@case ('error') { <div role="alert"><p>{{ $any(mapa()).mensaje }}</p></div> }
|
||||
}
|
||||
@if (m(); as mm) {
|
||||
<app-plotly-chart [showNotes]="false" [figure]="figuraMapa()" label="Mapa entre variables" (plotClick)="clicMapa($event)" />
|
||||
<p class="nota">Las celdas en blanco no se publican (menos de {{ mm.umbral_supresion }} pacientes, o se ocultan para que otra no se pueda deducir). Una celda publicada abre sus pacientes en Seguimiento.</p>
|
||||
<details><summary>Valores publicados</summary>
|
||||
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Mapa entre variables, tabla">
|
||||
<table><thead><tr><th scope="col">BI-RADS</th><th scope="col">Grupo de edad</th><th scope="col">Pacientes</th><th scope="col">Con carcinoma entre los de resultado conocido</th></tr></thead>
|
||||
<tbody>@for (c of celdasPublicadas(mm); track c.fila + c.columna) {
|
||||
<tr><th scope="row">{{ etiqueta(mm.filas.categorias, c.fila) }}</th><td>{{ etiqueta(mm.columnas.categorias, c.columna) }}</td><td>{{ miles(c.n!) }}</td>
|
||||
<td>{{ c.resultado.estado === 'disponible' ? c.resultado.casos + ' de ' + c.resultado.total + ' (' + decimal(c.resultado.valor!) + ' %)' : 'No disponible' }}</td></tr>
|
||||
}</tbody></table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="bloque" aria-labelledby="desc-tend">
|
||||
<h2 id="desc-tend">Actividad de reportes en el tiempo</h2>
|
||||
<p class="nota">Reportes de mastografía con BI-RADS y de biopsia ligada a esas mastografías en cada periodo, de todas las pacientes, y el porcentaje de resultados con carcinoma entre los reportes de biopsia con resultado. Es la actividad general: no depende de la cohorte, la ventana ni los filtros de arriba. Cuenta reportes, no pacientes; una paciente con varios reportes se cuenta varias veces.</p>
|
||||
<div class="controles">
|
||||
<label>Periodo
|
||||
<select name="tend-tipo" [ngModel]="tendTipo()" (ngModelChange)="cambiarTendencia($event, tendPeriodos())"><option value="semestre">Semestral</option><option value="mes">Mensual</option></select></label>
|
||||
<label>Periodos a mostrar
|
||||
<select name="tend-n" [ngModel]="tendPeriodos()" (ngModelChange)="cambiarTendencia(tendTipo(), $event)"><option [ngValue]="4">4</option><option [ngValue]="6">6</option><option [ngValue]="12">12</option><option [ngValue]="24">24</option></select></label>
|
||||
</div>
|
||||
@switch (tendencia().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la tendencia" /> }
|
||||
@case ('error') { <div role="alert"><p>{{ $any(tendencia()).mensaje }}</p></div> }
|
||||
}
|
||||
@if (t(); as tt) {
|
||||
<div class="par">
|
||||
<app-plotly-chart [showNotes]="false" [figure]="figurasTend().actividad" label="Reportes de mastografía y de biopsia por periodo" />
|
||||
<app-plotly-chart [showNotes]="false" [figure]="figurasTend().proporcion" label="Porcentaje de resultados con carcinoma por periodo" />
|
||||
</div>
|
||||
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Tendencia, tabla">
|
||||
<table><thead><tr><th scope="col">Periodo</th><th scope="col">Reportes de mastografía</th><th scope="col">Reportes de biopsia</th><th scope="col">Con carcinoma (IC 95 %)</th></tr></thead>
|
||||
<tbody>@for (p of tt.periodos; track p.periodo) {
|
||||
<tr><th scope="row">{{ p.periodo }}@if (p.incompleto) { <span class="nota"> (en curso)</span> }</th>
|
||||
<td>{{ p.reportes_mastografia.total === null ? 'No publicado' : miles(p.reportes_mastografia.total) }}</td>
|
||||
<td>{{ p.reportes_biopsia.total === null ? 'No publicado' : miles(p.reportes_biopsia.total) }}</td>
|
||||
<td>{{ p.maligno.estado === 'disponible' ? p.maligno.casos + ' de ' + p.maligno.total + ' (' + decimal(p.maligno.valor!) + ' %; ' + decimal(p.maligno.ic_bajo!) + ' a ' + decimal(p.maligno.ic_alto!) + ')' : p.maligno.estado === 'suprimido' ? 'No publicado' : 'Sin reportes de biopsia con resultado' }}</td></tr>
|
||||
}</tbody></table>
|
||||
</div>
|
||||
<p class="nota" role="status">{{ tt.alcance_biopsias }}. Los periodos en curso están incompletos y se marcan.</p>
|
||||
}
|
||||
</section>
|
||||
|
||||
@if (r(); as res) {
|
||||
<section class="bloque" aria-labelledby="desc-no">
|
||||
<!-- Closed at first; the native disclosure gives the keyboard (Enter and Space) and the screen reader its state. -->
|
||||
<details class="plegable" data-plegable="no-disponibles">
|
||||
<summary><h2 id="desc-no">No disponible con las fuentes actuales</h2></summary>
|
||||
<ul class="no-disponibles">
|
||||
@for (n of res.no_disponibles; track n.clave) { <li><strong>{{ n.titulo }}</strong>: No disponible. {{ n.motivo }}</li> }
|
||||
</ul>
|
||||
</details>
|
||||
</section>
|
||||
}
|
||||
`,
|
||||
styles: `
|
||||
:host { display: flex; flex-direction: column; gap: var(--issste-space-4); min-width: 0; }
|
||||
.bloque { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
|
||||
p, ul { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
|
||||
.nota, .contexto { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.tarjetas { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-4); }
|
||||
@media (min-width: 700px) { .tarjetas { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
@media (min-width: 1100px) { .tarjetas { grid-template-columns: repeat(4, minmax(0, 1fr)); } .par { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
.par { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
|
||||
.controles { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); margin-top: var(--issste-space-3); }
|
||||
.selector { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); margin-top: var(--issste-space-3); }
|
||||
.selector .activo { background: var(--issste-accent, #A8C243); color: #081839; }
|
||||
label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; }
|
||||
select { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px; padding: .6rem; min-height: 44px; font: inherit; }
|
||||
select:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
app-plotly-chart { margin-top: var(--issste-space-3); }
|
||||
.tabla-scroll { overflow-x: auto; margin-top: var(--issste-space-4); }
|
||||
table { width: 100%; min-width: 28rem; border-collapse: collapse; font: var(--mat-sys-body-medium); }
|
||||
caption { text-align: left; font: var(--mat-sys-title-small); padding-bottom: var(--issste-space-2); }
|
||||
th, td { padding: var(--issste-space-2) var(--issste-space-3); border-bottom: 1px solid var(--issste-border); text-align: left; vertical-align: top; }
|
||||
td { font-variant-numeric: tabular-nums; }
|
||||
.ver { min-height: 44px; padding: 0 .5rem; border: 0; background: none; color: inherit; text-decoration: underline; cursor: pointer; font: inherit; }
|
||||
.ver:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
details { margin-top: var(--issste-space-3); } summary { cursor: pointer; }
|
||||
.no-disponibles { padding-left: 1.2rem; color: var(--issste-text-secondary); }
|
||||
.plegable > summary { display: list-item; list-style-position: inside; cursor: pointer; border-radius: var(--issste-radius); }
|
||||
.plegable > summary h2 { display: inline; }
|
||||
.plegable > summary:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
||||
`,
|
||||
})
|
||||
export class IndicadoresAnalisisDescriptivo {
|
||||
readonly dominio = input.required<Dominio>();
|
||||
readonly tema = input.required<Tema>();
|
||||
readonly corte = input.required<string>();
|
||||
readonly active = input(false);
|
||||
readonly verPacientes = output<{ seleccion: SeleccionPacientes; origen: HTMLElement | null }>();
|
||||
readonly miles = miles; readonly decimal = decimal;
|
||||
readonly valor = valorTarjeta; readonly detalle = detalleTarjeta;
|
||||
readonly dimensionesDist = [{ clave: 'birads', etiqueta: 'Categoría BI-RADS' }, { clave: 'grupo_edad', etiqueta: 'Grupo de edad' }, { clave: 'biopsia', etiqueta: 'Resultado de la biopsia' }];
|
||||
|
||||
meses = 0; horizonte = 90; filtros: Record<string, string | undefined> = {};
|
||||
readonly por = signal('birads');
|
||||
readonly compPor = signal('grupo_edad'); readonly compMedida = signal('maligno');
|
||||
readonly mapaMedida = signal<'pacientes' | 'resultado'>('pacientes');
|
||||
readonly tendTipo = signal('semestre'); readonly tendPeriodos = signal(6);
|
||||
|
||||
readonly catalogo = signal<Carga<AnalisisCatalogoDescriptivo>>({ estado: 'cargando' });
|
||||
readonly resumen = signal<Carga<ResumenAnalisis>>({ estado: 'cargando' });
|
||||
readonly distribucion = signal<Carga<DistribucionAnalisis>>({ estado: 'cargando' });
|
||||
readonly comparacion = signal<Carga<ComparacionAnalisis>>({ estado: 'cargando' });
|
||||
readonly mapa = signal<Carga<MapaAnalisis>>({ estado: 'cargando' });
|
||||
readonly tendencia = signal<Carga<TendenciaAnalisis>>({ estado: 'cargando' });
|
||||
readonly figuraDist = signal<PlotlyFigure>(VACIA); readonly figuraComp = signal<PlotlyFigure>(VACIA);
|
||||
readonly figuraMapa = signal<PlotlyFigure>(VACIA);
|
||||
readonly figurasTend = signal<FigurasTendencia>({ actividad: VACIA, proporcion: VACIA });
|
||||
private readonly service = inject(AnalisisDescriptivoService);
|
||||
private readonly destroy = inject(DestroyRef);
|
||||
private readonly suscripciones = new Map<string, Subscription>();
|
||||
private abierto = false; private corteCargado = ''; private tendCorte = '';
|
||||
// The filters and window the sections were last asked with: one selection for all of them.
|
||||
private pedidoVigente: PedidoDescriptivo = { corte: '', meses: 0, filtros: {} };
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const activa = this.active(), corte = this.corte();
|
||||
if (!activa) return;
|
||||
untracked(() => { if (!this.abierto || corte !== this.corteCargado) { this.abierto = true; this.corteCargado = corte; this.aplicar(); } });
|
||||
});
|
||||
}
|
||||
|
||||
// Each accessor gives the loaded data or nothing: the template draws only what the endpoint answered.
|
||||
r() { const c = this.resumen(); return c.estado === 'listo' ? c.datos : undefined; }
|
||||
dist() { const c = this.distribucion(); return c.estado === 'listo' ? c.datos : undefined; }
|
||||
comp() { const c = this.comparacion(); return c.estado === 'listo' ? c.datos : undefined; }
|
||||
m() { const c = this.mapa(); return c.estado === 'listo' ? c.datos : undefined; }
|
||||
t() { const c = this.tendencia(); return c.estado === 'listo' ? c.datos : undefined; }
|
||||
cargando() { return [this.resumen(), this.distribucion(), this.comparacion(), this.mapa(), this.tendencia()].some(c => c.estado === 'cargando'); }
|
||||
opciones(clave: string) { const c = this.catalogo(); return c.estado === 'listo' ? c.datos.dimensiones.find(d => d.clave === clave)?.opciones ?? [] : []; }
|
||||
horizontes() { const c = this.catalogo(); return c.estado === 'listo' ? c.datos.horizontes_dias : [90]; }
|
||||
hayComparables() { return !!this.comp()?.grupos.some(g => g.estado === 'disponible'); }
|
||||
celdasPublicadas(m: MapaAnalisis): CeldaMapa[] { return m.celdas.filter(c => !c.suprimido && (c.n ?? 0) > 0); }
|
||||
etiqueta(categorias: { codigo: string; etiqueta: string }[], codigo: string) { return categorias.find(c => c.codigo === codigo)?.etiqueta ?? codigo; }
|
||||
textoPrueba(p: { valida: boolean; motivo?: string; estadistico?: number; gl?: number; p?: number; nombre: string }) {
|
||||
if (!p.valida) return `${p.nombre}: No disponible. ${p.motivo ?? ''}`.trim();
|
||||
const valor = p.p! < 0.001 ? '< 0.001' : p.p!.toLocaleString('es-MX', { minimumFractionDigits: 3, maximumFractionDigits: 3 });
|
||||
return `${p.nombre}: χ² ${p.estadistico!.toLocaleString('es-MX')}, ${p.gl} gl, p ${valor}. Describe diferencias en estas pacientes; no es una estimación causal.`;
|
||||
}
|
||||
|
||||
private pedido(): PedidoDescriptivo {
|
||||
return { corte: this.corte(), meses: this.meses, filtros: { ...this.filtros } };
|
||||
}
|
||||
/** Asks every section for the selection in the form: the first time, on a new cut-off and on «Aplicar». */
|
||||
aplicar() {
|
||||
this.pedidoVigente = this.pedido();
|
||||
const p = this.pedidoVigente;
|
||||
this.cargar('catalogo', this.catalogo, this.service.catalogo(this.dominio(), p));
|
||||
this.cargar('resumen', this.resumen, this.service.resumen(this.dominio(), p, this.horizonte));
|
||||
this.recargarDist(); this.recargarComp(); this.recargarMapa();
|
||||
// The trend depends only on the cut-off: «Aplicar» with other filters or window leaves it as it is.
|
||||
if (this.corte() !== this.tendCorte) { this.tendCorte = this.corte(); this.recargarTend(); }
|
||||
}
|
||||
private recargarDist() { this.cargar('dist', this.distribucion, this.service.distribucion(this.dominio(), this.pedidoVigente, this.por()), d => this.figuraDist.set(distribucionFigura(d, this.tema()))); }
|
||||
private recargarComp() { this.cargar('comp', this.comparacion, this.service.comparacion(this.dominio(), this.pedidoVigente, this.compPor(), this.compMedida()), c => this.figuraComp.set(comparacionFigura(c, this.tema(), this.compMedida() === 'invasor' ? 'Carcinoma invasor' : 'Carcinoma in situ o invasor'))); }
|
||||
private recargarMapa() { this.cargar('mapa', this.mapa, this.service.mapa(this.dominio(), this.pedidoVigente, 'birads', 'grupo_edad', 'maligno'), m => this.figuraMapa.set(mapaFigura(m, this.tema(), this.mapaMedida()))); }
|
||||
private recargarTend() { this.cargar('tend', this.tendencia, this.service.tendencia(this.dominio(), this.corte(), this.tendTipo(), this.tendPeriodos()), t => this.figurasTend.set(tendenciaFiguras(t, this.tema(), 'Con carcinoma entre biopsias con resultado'))); }
|
||||
cambiarPor(clave: string) { this.por.set(clave); this.recargarDist(); }
|
||||
cambiarComparacion(por: string, medida: string) { this.compPor.set(por); this.compMedida.set(medida); this.recargarComp(); }
|
||||
cambiarMapa(medida: 'pacientes' | 'resultado') { this.mapaMedida.set(medida); const m = this.m(); if (m) this.figuraMapa.set(mapaFigura(m, this.tema(), medida)); }
|
||||
cambiarTendencia(tipo: string, periodos: number) { this.tendTipo.set(tipo); this.tendPeriodos.set(periodos); this.recargarTend(); }
|
||||
|
||||
private cargar<T>(clave: string, destino: WritableSignal<Carga<T>>, fuente: Observable<T>, alListo?: (d: T) => void) {
|
||||
this.suscripciones.get(clave)?.unsubscribe();
|
||||
destino.set({ estado: 'cargando' });
|
||||
this.suscripciones.set(clave, fuente.pipe(takeUntilDestroyed(this.destroy)).subscribe({
|
||||
next: datos => { destino.set({ estado: 'listo', datos }); alListo?.(datos); },
|
||||
error: error => destino.set(this.fallo(error)),
|
||||
}));
|
||||
}
|
||||
private fallo(error: unknown): Carga<never> {
|
||||
if (error instanceof HttpErrorResponse) {
|
||||
if (error.status === 404) return { estado: 'pendiente' };
|
||||
if (error.status === 503) return { estado: 'no-disponible' };
|
||||
if (error.status === 403) return { estado: 'error', mensaje: 'La selección tiene muy pocos pacientes para publicar sus resultados.' };
|
||||
if (error.status === 409) return { estado: 'error', mensaje: 'La cohorte cambió. Consulta de nuevo.' };
|
||||
if (error.status === 400) return { estado: 'error', mensaje: 'El servicio rechazó la selección. Revisa la ventana y los filtros.' };
|
||||
if (error.status === 0) return { estado: 'error', mensaje: 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.' };
|
||||
if (error.status >= 500) return { estado: 'error', mensaje: 'El servicio encontró un error interno. Intenta nuevamente más tarde.' };
|
||||
}
|
||||
return { estado: 'error', mensaje: 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.' };
|
||||
}
|
||||
|
||||
/** The patients of a published group or cell, for the page to open them in Seguimiento. */
|
||||
abrir(seleccion: Record<string, string>, etiqueta: string, n: number | null, base: AnalisisSeleccion, origen?: EventTarget | null) {
|
||||
if (!n) return;
|
||||
const activos = Object.fromEntries(Object.entries(base.filtros).filter(([, v]) => v !== null)) as Record<string, string>;
|
||||
this.verPacientes.emit({
|
||||
origen: origen instanceof HTMLElement ? origen : null,
|
||||
seleccion: { filtros: { ...activos, ...seleccion }, etiqueta, corte: base.corte, meses: base.ventana.meses, esperados: n, contexto: { cohorte: base.cohorte, escenario: base.escenario, revision: base.revision } },
|
||||
});
|
||||
}
|
||||
clicDist(evento: unknown) {
|
||||
const codigo = (evento as { points?: { customdata?: unknown }[] } | undefined)?.points?.[0]?.customdata;
|
||||
const d = this.dist(), item = d?.items.find(i => i.codigo === codigo && !i.suprimido);
|
||||
if (d && item) this.abrir(item.seleccion, item.etiqueta, item.n, d);
|
||||
}
|
||||
clicMapa(evento: unknown) {
|
||||
const c = (evento as { points?: { customdata?: unknown; z?: unknown }[] } | undefined)?.points?.[0];
|
||||
const [fila, columna] = Array.isArray(c?.customdata) ? c.customdata as string[] : [];
|
||||
const mm = this.m(), celda = mm?.celdas.find(x => x.fila === fila && x.columna === columna && !x.suprimido);
|
||||
if (mm && celda) this.abrir(celda.seleccion, `${this.etiqueta(mm.filas.categorias, celda.fila)}, ${this.etiqueta(mm.columnas.categorias, celda.columna)}`, celda.n, mm);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
|
||||
import { AnalisisAgregado } from './indicadores-analisis.service';
|
||||
import { etiquetaBirads } from './etiquetas-cohorte';
|
||||
|
||||
export { etiquetaBirads };
|
||||
const miles = (v: number) => v.toLocaleString('es-MX');
|
||||
|
||||
/** The code of the published bar that was clicked, from its `customdata`; a suppressed bar or an empty click gives nothing. */
|
||||
export function grupoDelClic(evento: unknown, agregado: AnalisisAgregado | undefined): string | undefined {
|
||||
const punto = (evento as { points?: { customdata?: unknown }[] } | undefined)?.points?.[0];
|
||||
const codigo = punto?.customdata;
|
||||
return typeof codigo === 'string' && agregado?.grupos.some(g => g.codigo === codigo && !g.suprimido) ? codigo : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Patients per BI-RADS category. A suppressed category is drawn as an empty grey bar that says it is not published,
|
||||
* never as a zero; each bar carries its code, so a click can only change the filters of the list, never read rows.
|
||||
*/
|
||||
export function gruposFigura(d: AnalisisAgregado, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema), s = C2_PALETTE.states;
|
||||
return {
|
||||
data: [{
|
||||
type: 'bar', x: d.grupos.map(g => etiquetaBirads(g.codigo)), y: d.grupos.map(g => g.suprimido ? 0 : g.n),
|
||||
customdata: d.grupos.map(g => g.codigo),
|
||||
marker: { color: d.grupos.map(g => g.suprimido ? s.noData : C2_PALETTE.series[0]) },
|
||||
text: d.grupos.map(g => g.suprimido ? 'No publicado' : miles(g.n!)), textposition: 'outside', cliponaxis: false,
|
||||
hovertemplate: d.grupos.map(g => g.suprimido
|
||||
? `<b>${etiquetaBirads(g.codigo)}</b><br>Menos de ${d.umbral_supresion} pacientes: no se publica<extra></extra>`
|
||||
: `<b>${etiquetaBirads(g.codigo)}</b><br>${miles(g.n!)} pacientes<extra></extra>`),
|
||||
}],
|
||||
layout: {
|
||||
autosize: true, height: 360, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { t: 32, l: 56, r: 16, b: 56 }, showlegend: false,
|
||||
xaxis: { title: { text: 'Categoría BI-RADS' }, fixedrange: true, automargin: true },
|
||||
yaxis: { title: { text: 'Pacientes' }, gridcolor: p.grid, zeroline: false, fixedrange: true, rangemode: 'tozero' },
|
||||
},
|
||||
config: { displayModeBar: false },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { isoDate } from './cacu-seguimiento.models';
|
||||
import { Dominio, requireDominio } from './indicadores.models';
|
||||
|
||||
// The epidemiological analysis of a domain's cohort. What the server publishes today is one aggregate: how many
|
||||
// patients of the cohort fall in each BI-RADS category at a cut-off (`GET /<dominio>/analisis/indicadores?corte=`).
|
||||
// It is a descriptive count, not an incidence or a survival estimate, and it never carries patient rows. The answer
|
||||
// names the cohort, the scenario and a `revision` of the cohort that the patients' list must quote back: a list asked
|
||||
// for with another revision is refused, so a group opened from this count is always the group that was counted.
|
||||
export interface GrupoAnalisis { codigo: string; n: number | null; suprimido: boolean; }
|
||||
export interface AnalisisAgregado {
|
||||
simulado: true; cohorte: string; revision: string; escenario: string; corte: string; umbral_supresion: number;
|
||||
unidad: string; denominador: string; grupos: GrupoAnalisis[];
|
||||
}
|
||||
/** What a patients' list must quote back to open a group of the aggregate. */
|
||||
export interface ContextoCohorte { cohorte: string; escenario: string; revision: string; }
|
||||
|
||||
/** Today as the date input writes it, in the user's own calendar day. */
|
||||
export function hoyIso(ahora = new Date()) {
|
||||
const dos = (n: number) => String(n).padStart(2, '0');
|
||||
return `${ahora.getFullYear()}-${dos(ahora.getMonth() + 1)}-${dos(ahora.getDate())}`;
|
||||
}
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
|
||||
// Keys that only patient-level data would carry: the answer is rejected if any appears, at any depth.
|
||||
const DE_PACIENTE = new Set(['id_seudonimo', 'pac_id', 'paciente', 'pacientes', 'items', 'fecha_nacimiento', 'curp', 'nss']);
|
||||
function sinFilasDePaciente(v: unknown): boolean {
|
||||
if (Array.isArray(v)) return v.every(sinFilasDePaciente);
|
||||
if (!record(v)) return true;
|
||||
return Object.entries(v).every(([k, x]) => !DE_PACIENTE.has(k) && sinFilasDePaciente(x));
|
||||
}
|
||||
|
||||
/** Validates the aggregate before anything is drawn: aggregates only, and nothing published under the threshold. */
|
||||
export function analisisAgregado(v: unknown): AnalisisAgregado {
|
||||
const invalido = (): never => { throw new Error('Respuesta de análisis inválida'); };
|
||||
if (!record(v) || v['simulado'] !== true) return invalido();
|
||||
const umbral = v['umbral_supresion'], grupos = v['grupos'];
|
||||
if (!sinFilasDePaciente(v) || !text(v['cohorte']) || !text(v['escenario']) || !isoDate(v['corte']) || !text(v['unidad']) || !text(v['denominador'])
|
||||
|| !text(v['revision']) || !/^[0-9a-f]{64}$/.test(v['revision']) || typeof umbral !== 'number' || !Number.isFinite(umbral) || umbral < 1
|
||||
|| !Array.isArray(grupos) || !grupos.length
|
||||
|| !grupos.every(g => record(g) && text(g['codigo']) && typeof g['suprimido'] === 'boolean'
|
||||
&& (g['suprimido'] ? g['n'] === null : typeof g['n'] === 'number' && Number.isInteger(g['n']) && g['n'] >= umbral))
|
||||
|| new Set(grupos.map(g => (g as GrupoAnalisis).codigo)).size !== grupos.length) return invalido();
|
||||
return v as unknown as AnalisisAgregado;
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AnalisisService {
|
||||
private readonly http = inject(HttpClient);
|
||||
agregado(dominio: Dominio, corte: string) {
|
||||
if (!isoDate(corte)) throw new Error('Fecha de corte inválida');
|
||||
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/indicadores`, { params: new HttpParams().set('corte', corte) }).pipe(map(analisisAgregado));
|
||||
}
|
||||
}
|
||||
|
||||
// The descriptive analysis (`/<dominio>/analisis/...`): counts and proportions of the cohort at a cut-off, with the
|
||||
// window and filters of the follow-up list. Every answer names the cohort it describes, so a figure can open its patients.
|
||||
export interface AnalisisSeleccion {
|
||||
cohorte: string; escenario: string; revision: string; corte: string; umbral_supresion: number;
|
||||
ventana: { meses: number; desde: string; hasta: string };
|
||||
filtros: Record<string, string | null>;
|
||||
}
|
||||
export type EstadoDato = 'disponible' | 'suprimido' | 'sin_datos';
|
||||
export interface Proporcion { estado: EstadoDato; casos: number | null; total: number | null; valor: number | null; ic_bajo: number | null; ic_alto: number | null; }
|
||||
export interface DimensionAnalisis { clave: string; etiqueta: string; opciones: { codigo: string; etiqueta: string }[]; }
|
||||
export interface NoDisponible { clave: string; titulo: string; motivo: string; }
|
||||
export interface AnalisisCatalogoDescriptivo extends AnalisisSeleccion {
|
||||
dimensiones: DimensionAnalisis[]; medidas: { clave: string; etiqueta: string }[]; horizontes_dias: number[]; tipos_periodo: string[];
|
||||
secciones: { clave: string; titulo: string; estado: string; motivo: string | null }[]; no_disponibles: NoDisponible[];
|
||||
}
|
||||
export interface TarjetaAnalisis {
|
||||
clave: string; titulo: string; descripcion: string; unidad: string; estado: EstadoDato; valor: number | null; ic_bajo: number | null; ic_alto: number | null;
|
||||
n: number | null; denominador: number | null; q1: number | null; q3: number | null; motivo: string | null;
|
||||
}
|
||||
export interface ResumenAnalisis extends AnalisisSeleccion { horizonte_dias: number; indicadores: TarjetaAnalisis[]; no_disponibles: NoDisponible[]; }
|
||||
export interface ItemDistribucion { codigo: string; etiqueta: string; suprimido: boolean; n: number | null; porcentaje: number | null; ic_bajo: number | null; ic_alto: number | null; seleccion: Record<string, string>; }
|
||||
export interface DistribucionAnalisis extends AnalisisSeleccion { por: string; total: number; items: ItemDistribucion[]; }
|
||||
export interface Prueba { nombre: string; valida: boolean; motivo?: string; estadistico?: number; gl?: number; p?: number; }
|
||||
export interface GrupoComparacion extends Proporcion { codigo: string; etiqueta: string; seleccion: Record<string, string>; }
|
||||
export interface ComparacionAnalisis extends AnalisisSeleccion { por: string; medida: string; denominador: string; grupos: GrupoComparacion[]; prueba: Prueba; }
|
||||
export interface CeldaMapa { fila: string; columna: string; suprimido: boolean; n: number | null; seleccion: Record<string, string>; resultado: Proporcion; }
|
||||
export interface EjeMapa { por: string; categorias: { codigo: string; etiqueta: string }[]; }
|
||||
export interface MapaAnalisis extends AnalisisSeleccion { filas: EjeMapa; columnas: EjeMapa; medida: string; celdas: CeldaMapa[]; }
|
||||
export interface ConteoPeriodo { n: number | null; suprimido: boolean; }
|
||||
export interface PeriodoTendencia {
|
||||
periodo: string; inicio: string; fin: string; incompleto: boolean;
|
||||
reportes_mastografia: { total: number | null; por_categoria: Record<string, ConteoPeriodo> };
|
||||
reportes_biopsia: { total: number | null; por_grado: Record<string, ConteoPeriodo> };
|
||||
maligno: Proporcion;
|
||||
}
|
||||
// The trend is general activity, not the cohort: it carries no cohort, window or filters, only what it counts and over whom.
|
||||
export interface TendenciaAnalisis {
|
||||
corte: string; umbral_supresion: number; tipo_periodo: string; unidad: string; poblacion: string; alcance_biopsias: string;
|
||||
denominador: string; periodos: PeriodoTendencia[];
|
||||
}
|
||||
export interface PedidoDescriptivo { corte: string; meses: number; filtros: Record<string, string | undefined>; contexto?: { cohorte: string; escenario: string; revision: string }; }
|
||||
|
||||
const numOnulo = (v: unknown) => v === null || (typeof v === 'number' && Number.isFinite(v));
|
||||
const estadoOk = (v: unknown) => v === 'disponible' || v === 'suprimido' || v === 'sin_datos';
|
||||
const proporcionOk = (v: unknown) => record(v) && estadoOk(v['estado']) && numOnulo(v['valor']) && numOnulo(v['ic_bajo']) && numOnulo(v['ic_alto'])
|
||||
&& numOnulo(v['casos']) && numOnulo(v['total']) && (v['estado'] === 'disponible' ? v['valor'] !== null && v['casos'] !== null : v['valor'] === null);
|
||||
const seleccionOk = (v: unknown): v is Record<string, unknown> => record(v) && text(v['cohorte']) && text(v['escenario']) && text(v['revision']) && text(v['corte'])
|
||||
&& typeof v['umbral_supresion'] === 'number' && record(v['ventana']) && record(v['filtros']);
|
||||
const invalidoDescriptivo = (): never => { throw new Error('Respuesta de análisis inválida'); };
|
||||
|
||||
export function catalogoDescriptivo(v: unknown): AnalisisCatalogoDescriptivo {
|
||||
if (!seleccionOk(v) || !Array.isArray(v['dimensiones']) || !v['dimensiones'].every(d => record(d) && text(d['clave']) && Array.isArray(d['opciones']))
|
||||
|| !Array.isArray(v['no_disponibles']) || !Array.isArray(v['horizontes_dias']) || !Array.isArray(v['tipos_periodo'])) invalidoDescriptivo();
|
||||
return v as unknown as AnalisisCatalogoDescriptivo;
|
||||
}
|
||||
export function resumenDescriptivo(v: unknown): ResumenAnalisis {
|
||||
if (!seleccionOk(v) || !Array.isArray(v['indicadores']) || !v['indicadores'].every(t => record(t) && text(t['clave']) && text(t['titulo']) && estadoOk(t['estado'])
|
||||
&& numOnulo(t['valor']) && (t['estado'] === 'disponible' ? t['valor'] !== null : t['valor'] === null))) invalidoDescriptivo();
|
||||
return v as unknown as ResumenAnalisis;
|
||||
}
|
||||
export function distribucionDescriptiva(v: unknown): DistribucionAnalisis {
|
||||
if (!seleccionOk(v) || typeof v['total'] !== 'number' || !Array.isArray(v['items'])
|
||||
|| !v['items'].every(i => record(i) && text(i['codigo']) && typeof i['suprimido'] === 'boolean' && numOnulo(i['n']) && (i['suprimido'] ? i['n'] === null : i['n'] !== null)
|
||||
&& record(i['seleccion']))) invalidoDescriptivo();
|
||||
return v as unknown as DistribucionAnalisis;
|
||||
}
|
||||
export function comparacionDescriptiva(v: unknown): ComparacionAnalisis {
|
||||
if (!seleccionOk(v) || !Array.isArray(v['grupos']) || !v['grupos'].every(g => record(g) && text(g['codigo']) && proporcionOk(g))
|
||||
|| !record(v['prueba']) || typeof v['prueba']['valida'] !== 'boolean') invalidoDescriptivo();
|
||||
return v as unknown as ComparacionAnalisis;
|
||||
}
|
||||
export function mapaDescriptivo(v: unknown): MapaAnalisis {
|
||||
if (!seleccionOk(v) || !record(v['filas']) || !record(v['columnas']) || !Array.isArray(v['celdas'])
|
||||
|| !v['celdas'].every(c => record(c) && text(c['fila']) && text(c['columna']) && typeof c['suprimido'] === 'boolean' && numOnulo(c['n'])
|
||||
&& (c['suprimido'] ? c['n'] === null : c['n'] !== null) && record(c['resultado']) && estadoOk(c['resultado']['estado']))) invalidoDescriptivo();
|
||||
return v as unknown as MapaAnalisis;
|
||||
}
|
||||
export function tendenciaDescriptiva(v: unknown): TendenciaAnalisis {
|
||||
if (!record(v) || !text(v['corte']) || v['unidad'] !== 'reportes' || !text(v['poblacion']) || !text(v['alcance_biopsias']) || !text(v['tipo_periodo'])
|
||||
|| !Array.isArray(v['periodos']) || !v['periodos'].every(p => record(p) && text(p['periodo']) && typeof p['incompleto'] === 'boolean'
|
||||
&& record(p['reportes_mastografia']) && record(p['reportes_biopsia']) && proporcionOk(p['maligno']))) invalidoDescriptivo();
|
||||
return v as unknown as TendenciaAnalisis;
|
||||
}
|
||||
|
||||
function paramsDe(pedido: PedidoDescriptivo, extra: Record<string, string | number | undefined> = {}) {
|
||||
let params = new HttpParams().set('corte', pedido.corte).set('meses', pedido.meses);
|
||||
for (const [k, v] of Object.entries(pedido.filtros)) if (v) params = params.set(k, v);
|
||||
if (pedido.contexto) for (const [k, v] of Object.entries(pedido.contexto)) params = params.set(k, v);
|
||||
for (const [k, v] of Object.entries(extra)) if (v !== undefined) params = params.set(k, v);
|
||||
return params;
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AnalisisDescriptivoService {
|
||||
private readonly http = inject(HttpClient);
|
||||
private url(dominio: Dominio, ruta: string) { return `/${requireDominio(dominio)}/analisis${ruta}`; }
|
||||
catalogo(d: Dominio, p: PedidoDescriptivo) { return this.http.get<unknown>(this.url(d, ''), { params: paramsDe(p) }).pipe(map(catalogoDescriptivo)); }
|
||||
resumen(d: Dominio, p: PedidoDescriptivo, horizonte: number) {
|
||||
return this.http.get<unknown>(this.url(d, '/resumen'), { params: paramsDe(p, { horizonte }) }).pipe(map(resumenDescriptivo));
|
||||
}
|
||||
distribucion(d: Dominio, p: PedidoDescriptivo, por: string) {
|
||||
return this.http.get<unknown>(this.url(d, '/distribucion'), { params: paramsDe(p, { por }) }).pipe(map(distribucionDescriptiva));
|
||||
}
|
||||
comparacion(d: Dominio, p: PedidoDescriptivo, por: string, medida: string) {
|
||||
return this.http.get<unknown>(this.url(d, '/comparacion'), { params: paramsDe(p, { por, medida }) }).pipe(map(comparacionDescriptiva));
|
||||
}
|
||||
mapa(d: Dominio, p: PedidoDescriptivo, filas: string, columnas: string, medida: string) {
|
||||
return this.http.get<unknown>(this.url(d, '/mapa'), { params: paramsDe(p, { filas, columnas, medida }) }).pipe(map(mapaDescriptivo));
|
||||
}
|
||||
/** The trend takes only the cut-off, the period type and the number of periods: never the window, filters or context. */
|
||||
tendencia(d: Dominio, corte: string, tipo: string, periodos: number) {
|
||||
const params = new HttpParams().set('corte', corte).set('tipo', tipo).set('periodos', periodos);
|
||||
return this.http.get<unknown>(this.url(d, '/tendencia'), { params }).pipe(map(tendenciaDescriptiva));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
import { Component, output } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient, withInterceptors } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadoresAnalisis, MOTIVO_GRUPO_SUPRIMIDO, SeleccionPacientes, hoyIso, motivoSinLista, seleccionDeGrupo } from './indicadores-analisis';
|
||||
import { etiquetaBirads, grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
|
||||
import { analisisAgregado } from './indicadores-analisis.service';
|
||||
import { agregado, agregadoJson, CONTEXTO, CORTE, sinAnalisisDescriptivo } from './indicadores-analisis.testing';
|
||||
|
||||
// Covers the «Análisis epidemiológico» tab of breast cancer as the cohort API publishes it today: the guard of its answer
|
||||
// (an aggregate, never patient rows, nothing published under the threshold), the figure, the selection a published group
|
||||
// sends to Seguimiento, and the tab's requests and states. The fixtures are in indicadores-analisis.testing.ts.
|
||||
|
||||
describe('Respuesta del análisis', () => {
|
||||
it('admite el agregado de la cohorte, con la extensión de grupos y el arreglo de indicadores vacío', () => {
|
||||
// Fails if the real answer (with the fields the prototype leaves empty) stops being accepted.
|
||||
expect(analisisAgregado(agregadoJson()).grupos).toHaveLength(6);
|
||||
});
|
||||
it('rechaza lo que no es un agregado: filas de paciente, un grupo suprimido con conteo o un grupo publicado bajo el umbral', () => {
|
||||
// Fails if a guard stops rejecting patient rows at any depth, or a count that should be hidden.
|
||||
expect(() => analisisAgregado({ ...agregadoJson(), simulado: false })).toThrow();
|
||||
expect(() => analisisAgregado({ ...agregadoJson(), pacientes: [] })).toThrow();
|
||||
expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_5', n: 6, suprimido: false, items: [{ id_seudonimo: 'M-1' }] }] })).toThrow();
|
||||
expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_4', n: 3, suprimido: true }] })).toThrow();
|
||||
expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_5', n: 4, suprimido: false }] })).toThrow();
|
||||
expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_5', n: 6, suprimido: false }, { codigo: 'BIRADS_5', n: 7, suprimido: false }] })).toThrow();
|
||||
expect(() => analisisAgregado({ ...agregadoJson(), revision: 'abc' })).toThrow();
|
||||
expect(() => analisisAgregado({ ...agregadoJson(), corte: '2026-13-40' })).toThrow();
|
||||
expect(() => analisisAgregado({ ...agregadoJson(), grupos: [] })).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Figura del análisis', () => {
|
||||
it('dibuja una barra por categoría con sus pacientes y la suprimida vacía, gris y sin cifra', () => {
|
||||
// Fails if a suppressed category is drawn as a zero count, or loses its explanation.
|
||||
const fig = gruposFigura(agregado(), 'claro');
|
||||
const barra = fig.data[0];
|
||||
expect(barra['x']).toEqual(['BI-RADS 4', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']);
|
||||
expect(barra['y']).toEqual([0, 0, 0, 0, 6, 0]);
|
||||
expect((barra['text'] as string[]).filter(t => t === 'No publicado')).toHaveLength(5);
|
||||
expect((barra['hovertemplate'] as string[])[0]).toContain('Menos de 5 pacientes: no se publica');
|
||||
expect((fig.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Pacientes');
|
||||
});
|
||||
it('un clic solo da el código de una barra publicada', () => {
|
||||
// Fails if a click on a suppressed or unknown bar could open its list.
|
||||
expect(grupoDelClic({ points: [{ customdata: 'BIRADS_5' }] }, agregado())).toBe('BIRADS_5');
|
||||
expect(grupoDelClic({ points: [{ customdata: 'BIRADS_4' }] }, agregado())).toBeUndefined();
|
||||
expect(grupoDelClic({ points: [{ customdata: 'OTRO' }] }, agregado())).toBeUndefined();
|
||||
expect(grupoDelClic({ points: [{}] }, agregado())).toBeUndefined();
|
||||
expect(grupoDelClic(undefined, agregado())).toBeUndefined();
|
||||
});
|
||||
it('escribe los códigos como en la clínica', () => {
|
||||
expect(etiquetaBirads('BIRADS_4A')).toBe('BI-RADS 4A');
|
||||
expect(etiquetaBirads('OTRO')).toBe('OTRO');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Selección que va a Seguimiento', () => {
|
||||
it('un grupo publicado lleva su filtro, el corte, el nombre, cuántas pacientes cuenta y la cohorte con su revisión', () => {
|
||||
// Fails if the list is opened without the cohort's revision, at another cut-off, or on another group.
|
||||
expect(seleccionDeGrupo(agregado(), 'BIRADS_5')).toEqual({
|
||||
filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE, esperados: 6, contexto: CONTEXTO });
|
||||
});
|
||||
it('un grupo suprimido o desconocido no abre nada y dice por qué', () => {
|
||||
// Fails if the list of a group the answer hid could be opened.
|
||||
expect(motivoSinLista(agregado(), 'BIRADS_4')).toBe(MOTIVO_GRUPO_SUPRIMIDO);
|
||||
expect(seleccionDeGrupo(agregado(), 'BIRADS_4')).toBeUndefined();
|
||||
expect(seleccionDeGrupo(agregado(), 'OTRO')).toBeUndefined();
|
||||
expect(motivoSinLista(agregado(), 'BIRADS_5')).toBeUndefined();
|
||||
});
|
||||
it('hoy se escribe como la fecha de un campo de fecha, en el día del usuario', () => {
|
||||
expect(hoyIso(new Date(2026, 10, 3, 23, 59))).toBe('2026-11-03');
|
||||
});
|
||||
});
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub { readonly plotClick = output<unknown>(); }
|
||||
|
||||
describe('Pestaña Análisis epidemiológico', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresAnalisis>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(withInterceptors([sinAnalisisDescriptivo])), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadoresAnalisis); http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('tema', 'claro');
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
const text = () => root().textContent as string;
|
||||
const pedido = (corte = hoyIso()) => http.expectOne(r => r.url === '/cama/analisis/indicadores' && r.params.get('corte') === corte);
|
||||
const abrir = () => { fixture.componentRef.setInput('active', true); fixture.detectChanges(); };
|
||||
const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement | undefined;
|
||||
// The date goes in as the user would type it; ngModel writes its value in a microtask.
|
||||
async function escribirCorte(valor: string) {
|
||||
// A form control is registered in a microtask after its first render: it is only ready to be typed into after that.
|
||||
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
||||
const c = root().querySelector('input[name="corte"]') as HTMLInputElement;
|
||||
c.value = valor; c.dispatchEvent(new Event('input', { bubbles: true })); c.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(c.value, 'el campo conserva lo escrito').toBe(valor === '2026-02-31' ? '' : valor);
|
||||
}
|
||||
|
||||
it('no pide nada hasta abrirse; luego pide el agregado al corte de hoy y lo dibuja con su tabla', () => {
|
||||
// Fails if the tab loads while hidden, or its first request stops carrying a cut-off.
|
||||
fixture.detectChanges();
|
||||
http.expectNone(() => true);
|
||||
abrir();
|
||||
expect(text()).toContain('Pacientes por categoría BI-RADS');
|
||||
pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
|
||||
expect(text()).toContain('Denominador: pacientes elegibles con última mastografía reportada BI-RADS 4 a 6.');
|
||||
expect(text()).toContain('No estima incidencia, recurrencia ni supervivencia.');
|
||||
const filas = Array.from(root().querySelectorAll('tbody tr')) as HTMLElement[];
|
||||
expect(filas.map(f => f.querySelector('th')!.textContent!.trim())).toEqual(['BI-RADS 4', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']);
|
||||
expect(filas.map(f => f.children[1].textContent!.trim())).toEqual(['No publicado', 'No publicado', 'No publicado', 'No publicado', '6', 'No publicado']);
|
||||
});
|
||||
it('encabeza la vista y deriva las dos tarjetas de los estados de los grupos, sin sumar pacientes', () => {
|
||||
// Fails if the cards count patients instead of categories, appear before an answer, or the heading and denominator are lost.
|
||||
abrir();
|
||||
expect(root().querySelector('h2')!.textContent).toBe('Análisis epidemiológico');
|
||||
expect(root().querySelector('app-indicador-kpi-card')).toBeNull();
|
||||
pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
|
||||
const tarjetas = Array.from(root().querySelectorAll('app-indicador-kpi-card')) as HTMLElement[];
|
||||
expect(tarjetas.map(t => t.querySelector('h3')!.textContent)).toEqual(['Categorías publicadas', 'Categorías no publicadas']);
|
||||
expect(tarjetas.map(t => t.querySelector('.value')!.textContent!.trim())).toEqual(['1', '5']);
|
||||
expect(tarjetas[0].textContent).toContain('de 6 categorías BI-RADS');
|
||||
expect(tarjetas[0].textContent).not.toContain('6 pacientes');
|
||||
expect(root().querySelector('h3#birads-titulo')!.textContent).toBe('Pacientes por categoría BI-RADS');
|
||||
expect(text()).toContain('Denominador: pacientes elegibles con última mastografía reportada BI-RADS 4 a 6.');
|
||||
expect(text()).toContain('abrir la lista en Seguimiento');
|
||||
});
|
||||
it('las tarjetas cuentan 0 publicadas cuando todas se suprimen y desaparecen en carga, pendiente y error', () => {
|
||||
// Fails if the cards stay on screen without an answer with categories.
|
||||
abrir();
|
||||
const grupos = agregado().grupos.map(g => ({ codigo: g.codigo, n: null, suprimido: true }));
|
||||
pedido().flush(agregadoJson({ corte: hoyIso(), grupos })); fixture.detectChanges();
|
||||
expect(Array.from(root().querySelectorAll('app-indicador-kpi-card .value')).map(v => v.textContent!.trim())).toEqual(['0', '6']);
|
||||
fixture.componentInstance.consultar(); fixture.detectChanges();
|
||||
expect(root().querySelector('app-indicador-kpi-card')).toBeNull();
|
||||
pedido().flush({}, { status: 404, statusText: 'Not found' }); fixture.detectChanges();
|
||||
expect(root().querySelector('app-indicador-kpi-card')).toBeNull();
|
||||
});
|
||||
it('«Consultar» pide el agregado a la fecha elegida y la respuesta tardía de una consulta anterior no se dibuja', async () => {
|
||||
// Fails if a slow answer replaces the aggregate of a later cut-off.
|
||||
abrir();
|
||||
const primera = pedido(); primera.flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
|
||||
await escribirCorte('2026-09-01');
|
||||
expect(fixture.componentInstance.corte).toBe('2026-09-01');
|
||||
boton('Consultar')!.click(); fixture.detectChanges();
|
||||
const lenta = pedido('2026-09-01');
|
||||
// The button is disabled while a query runs, so the later query comes from the code (a retry, a programmatic refresh).
|
||||
expect(boton('Consultar')!.disabled).toBe(true);
|
||||
await escribirCorte('2026-08-01'); fixture.componentInstance.consultar(); fixture.detectChanges();
|
||||
expect(lenta.cancelled).toBe(true);
|
||||
pedido('2026-08-01').flush(agregadoJson({ corte: '2026-08-01' })); fixture.detectChanges();
|
||||
expect(text()).toContain('Fecha de corte: 2026-08-01.');
|
||||
});
|
||||
it('una fecha que no es de calendario no sale del navegador', async () => {
|
||||
// Fails if an invalid cut-off is sent to the server.
|
||||
abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
|
||||
await escribirCorte('2026-02-31'); boton('Consultar')!.click(); fixture.detectChanges();
|
||||
http.expectNone(() => true);
|
||||
expect(root().querySelector('[role=alert]')?.textContent).toContain('Revisa la fecha de corte');
|
||||
});
|
||||
it('si ninguna categoría se publica, lo dice y conserva «No publicado»: la respuesta no distingue una cohorte vacía de grupos pequeños', () => {
|
||||
// Fails if an empty cohort is announced when the answer cannot tell it, or the explanation of the suppression is lost.
|
||||
abrir();
|
||||
const grupos = agregado().grupos.map(g => ({ codigo: g.codigo, n: null, suprimido: true }));
|
||||
pedido().flush(agregadoJson({ corte: hoyIso(), grupos })); fixture.detectChanges();
|
||||
expect(text()).toContain('Ninguna categoría alcanza el mínimo de 5 pacientes para publicarse a esta fecha de corte.');
|
||||
expect(text()).not.toContain('Sin pacientes');
|
||||
expect(Array.from(root().querySelectorAll('tbody tr')).every(f => f.children[1].textContent!.trim() === 'No publicado' && !f.querySelector('button'))).toBe(true);
|
||||
});
|
||||
it('un grupo suprimido no tiene botón y dice por qué; el publicado tiene su botón accesible', () => {
|
||||
// Fails if the table offers the patients of a hidden group.
|
||||
abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
|
||||
const filas = Array.from(root().querySelectorAll('tbody tr')) as HTMLElement[];
|
||||
expect(filas.map(f => !!f.querySelector('button.ver'))).toEqual([false, false, false, false, true, false]);
|
||||
expect(filas[0].textContent).toContain(MOTIVO_GRUPO_SUPRIMIDO);
|
||||
expect(filas[4].querySelector('button')!.getAttribute('aria-label')).toBe('Ver pacientes de BI-RADS 5 en Seguimiento');
|
||||
});
|
||||
it('el botón de la tabla y la barra emiten la misma selección; la barra suprimida no emite nada', () => {
|
||||
// Fails if a click stops reaching Seguimiento, sends another group, or a hidden bar emits.
|
||||
const emitidas: SeleccionPacientes[] = [];
|
||||
fixture.componentInstance.verPacientes.subscribe(s => emitidas.push(s));
|
||||
abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
|
||||
(root().querySelector('tr[data-grupo="BIRADS_5"] button.ver') as HTMLButtonElement).click();
|
||||
fixture.componentInstance.clicGrupo({ points: [{ customdata: 'BIRADS_5' }] });
|
||||
fixture.componentInstance.clicGrupo({ points: [{ customdata: 'BIRADS_4' }] });
|
||||
expect(emitidas).toHaveLength(2);
|
||||
expect(emitidas[0]).toEqual(emitidas[1]);
|
||||
expect(emitidas[0]).toMatchObject({ filtros: { birads: 'BIRADS_5' }, corte: hoyIso(), esperados: 6, contexto: { ...CONTEXTO } });
|
||||
});
|
||||
it('al volver restaura el foco en el control de origen y no repite ninguna consulta', () => {
|
||||
// Fails if coming back from Seguimiento loses the focus or the answer already loaded.
|
||||
fixture.componentInstance.verPacientes.subscribe(() => undefined);
|
||||
abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
|
||||
const origen = root().querySelector('tr[data-grupo="BIRADS_5"] button.ver') as HTMLButtonElement;
|
||||
origen.focus(); origen.click();
|
||||
(document.activeElement as HTMLElement | null)?.blur();
|
||||
fixture.componentInstance.restaurar();
|
||||
http.expectNone(() => true);
|
||||
expect(document.activeElement).toBe(origen);
|
||||
expect(fixture.componentInstance.datos()?.grupos).toHaveLength(6);
|
||||
});
|
||||
|
||||
it('sin endpoint publicado queda pendiente, sin mostrarse como un error', () => {
|
||||
// Fails if a 404 is shown as a broken page instead of a feature not yet published.
|
||||
abrir(); pedido().flush({}, { status: 404, statusText: 'Not found' }); fixture.detectChanges();
|
||||
expect(text()).toContain('Funcionalidad pendiente de publicación');
|
||||
expect(root().querySelector('[role=alert]')).toBeNull();
|
||||
});
|
||||
it('con la cohorte no disponible (503) lo dice y deja reintentar; el reintento repite la misma consulta', () => {
|
||||
// Fails if a cohort that is not configured is hidden, or the retry asks for another date.
|
||||
abrir(); pedido().flush({ error: 'Cohorte no disponible' }, { status: 503, statusText: 'Unavailable' }); fixture.detectChanges();
|
||||
expect(text()).toContain('La cohorte no está disponible en este momento.');
|
||||
boton('Reintentar consulta')!.click(); fixture.detectChanges();
|
||||
pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
|
||||
expect(root().querySelector('tbody')).not.toBeNull();
|
||||
});
|
||||
it('un error del servicio se muestra con su reintento y con el mensaje fijo, nunca con el cuerpo', () => {
|
||||
// Fails if a real failure is swallowed or the server's own text reaches the page.
|
||||
abrir(); pedido().flush('detalle interno', { status: 500, statusText: 'Error' }); fixture.detectChanges();
|
||||
expect(root().querySelector('[role=alert]')?.textContent).toContain('El servicio encontró un error interno');
|
||||
expect(text()).not.toContain('detalle interno');
|
||||
expect(boton('Reintentar consulta')).toBeDefined();
|
||||
});
|
||||
it('una respuesta fuera de contrato no se dibuja', () => {
|
||||
// Fails if an answer with patient rows or counts under the threshold reaches the page.
|
||||
abrir(); pedido().flush({ ...agregadoJson({ corte: hoyIso() }), pacientes: [{ id_seudonimo: 'M-0001' }] }); fixture.detectChanges();
|
||||
expect(root().querySelector('[role=alert]')?.textContent).toContain('no tiene el formato esperado');
|
||||
expect(root().querySelector('tbody')).toBeNull();
|
||||
expect(text()).not.toContain('M-0001');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
// Fixtures of the analysis tab and of its journey to Seguimiento, shaped like the answers of the cohort API
|
||||
// (`GET /cama/analisis/indicadores?corte=` and the list `GET /cama/seguimiento` of a cohort).
|
||||
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
|
||||
import { throwError } from 'rxjs';
|
||||
import { AnalisisAgregado } from './indicadores-analisis.service';
|
||||
|
||||
export const REVISION = 'dae23030398f86a24e8ad910471d27ce02502ac6b174063c98e5163dea0ce7a7';
|
||||
export const CORTE = '2026-10-20';
|
||||
export const CONTEXTO = { cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: REVISION };
|
||||
|
||||
/** One published category (BI-RADS 5, six patients) and five suppressed ones. */
|
||||
export const agregado = (extra: Partial<AnalisisAgregado> = {}): AnalisisAgregado => ({
|
||||
simulado: true, ...CONTEXTO, corte: CORTE, umbral_supresion: 5, unidad: 'paciente',
|
||||
denominador: 'pacientes elegibles con última mastografía reportada BI-RADS 4 a 6',
|
||||
grupos: [
|
||||
{ codigo: 'BIRADS_4', n: null, suprimido: true }, { codigo: 'BIRADS_4A', n: null, suprimido: true }, { codigo: 'BIRADS_4B', n: null, suprimido: true },
|
||||
{ codigo: 'BIRADS_4C', n: null, suprimido: true }, { codigo: 'BIRADS_5', n: 6, suprimido: false }, { codigo: 'BIRADS_6', n: null, suprimido: true },
|
||||
],
|
||||
...extra,
|
||||
});
|
||||
/**
|
||||
* The answer of the cohort's list as the API sends it: only the two filters it announces, with the code as their label,
|
||||
* the codes as the values of the rows, the biopsy date being the date of the report (the result can still be unknown),
|
||||
* and the cohort quoted back. `n` rows M-0001…; the third row has a reported biopsy whose result is not known at the cut-off.
|
||||
*/
|
||||
export function listaCohorte(o: { corte?: string; filtros?: Record<string, string>; page?: number; size?: number; n?: number; meses?: number; revision?: string } = {}): Record<string, any> {
|
||||
const { corte = CORTE, filtros = {}, page = 1, size = 50, n = 6, meses = 0, revision = REVISION } = o;
|
||||
const todos = Array.from({ length: n }, (_, i) => ({
|
||||
id_seudonimo: `M-${String(i + 1).padStart(4, '0')}`, grupo_edad: i % 2 ? '60-69' : '50-59', birads: 'BIRADS_5', mastografia_fecha: '2025-02-01',
|
||||
biopsia: i === 0 ? 'BENIGNO' : null, biopsia_fecha: i === 0 || i === 2 ? '2025-02-15' : null,
|
||||
}));
|
||||
const opciones = (codigos: string[]) => codigos.map(c => ({ codigo: c, etiqueta: c }));
|
||||
return {
|
||||
simulado: true, ...CONTEXTO, revision, corte, ventana: { meses, desde: '2025-02-01', hasta: corte }, campo_ventana: 'mastografia_fecha',
|
||||
filtros: { birads: null, grupo_edad: null, ...filtros },
|
||||
filtros_disponibles: [
|
||||
{ clave: 'birads', etiqueta: 'Categoría BI-RADS', opciones: opciones(['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6']) },
|
||||
{ clave: 'grupo_edad', etiqueta: 'Grupo de edad', opciones: opciones(['MENOR_40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO']) }],
|
||||
columnas: [
|
||||
{ clave: 'id_seudonimo', etiqueta: 'Identificador seudónimo' }, { clave: 'grupo_edad', etiqueta: 'Grupo de edad' },
|
||||
{ clave: 'birads', etiqueta: 'Última mastografía', detalles: [{ clave: 'mastografia_fecha', etiqueta: 'Fecha' }] },
|
||||
{ clave: 'biopsia', etiqueta: 'Resultado histopatológico', detalles: [{ clave: 'biopsia_fecha', etiqueta: 'Fecha de reporte' }] }],
|
||||
paginacion: { page, page_size: size, total_items: n, total_pages: Math.max(1, Math.ceil(n / size)) },
|
||||
items: todos.slice((page - 1) * size, page * size),
|
||||
};
|
||||
}
|
||||
|
||||
/** What the API sends on the wire: the aggregate plus the fields of the prototype it leaves empty. */
|
||||
export const agregadoJson = (extra: Record<string, unknown> = {}) => ({ ...agregado(), horizonte_dias: 0, indicadores: [], ...extra });
|
||||
|
||||
/**
|
||||
* For specs of the analysis tab that are about its BI-RADS aggregate and its way to Seguimiento: the descriptive sections
|
||||
* below it (catalog, indicators, distribution, comparison, map, trend) answer «not published» and never reach the test
|
||||
* backend, so those specs keep counting only the requests they are about.
|
||||
*/
|
||||
export const sinAnalisisDescriptivo: HttpInterceptorFn = (req, next) =>
|
||||
/^\/[a-z]+\/analisis(\/(resumen|distribucion|comparacion|mapa|tendencia))?$/.test(req.url)
|
||||
? throwError(() => new HttpErrorResponse({ status: 404, url: req.url })) : next(req);
|
||||
@@ -0,0 +1,251 @@
|
||||
import { Component, computed, DestroyRef, effect, ElementRef, inject, input, output, signal, untracked } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import { IndicadoresAnalisisDescriptivo } from './indicadores-analisis-descriptivo';
|
||||
import { isoDate } from './cacu-seguimiento.models';
|
||||
import { grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
|
||||
import { etiquetaBirads } from './etiquetas-cohorte';
|
||||
import { AnalisisAgregado, AnalisisService, ContextoCohorte, hoyIso } from './indicadores-analisis.service';
|
||||
import { Dominio, Tema } from './indicadores.models';
|
||||
|
||||
type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' } | { estado: 'no-disponible' };
|
||||
|
||||
/**
|
||||
* The patients behind a group of the aggregate, for the page to open them in Seguimiento: the list's filters, how to
|
||||
* name the selection, the cut-off and the cohort the group was counted in (the list quotes it back), and how many
|
||||
* patients the analysis counts there.
|
||||
*/
|
||||
export interface SeleccionPacientes { filtros: Record<string, string>; etiqueta: string; corte: string; meses?: number; esperados: number | null; contexto: ContextoCohorte; }
|
||||
|
||||
export const MOTIVO_GRUPO_SUPRIMIDO = 'El grupo tiene muy pocos pacientes: su lista no se publica.';
|
||||
|
||||
export { hoyIso };
|
||||
|
||||
/** Why a group cannot open its patients, or nothing when it can: only a published group does. */
|
||||
export function motivoSinLista(agregado: AnalisisAgregado, codigo: string): string | undefined {
|
||||
const g = agregado.grupos.find(x => x.codigo === codigo);
|
||||
return !g || g.suprimido ? MOTIVO_GRUPO_SUPRIMIDO : undefined;
|
||||
}
|
||||
|
||||
/** The selection of a published group: the whole group of the cohort at the cut-off it was counted at, nothing else. */
|
||||
export function seleccionDeGrupo(agregado: AnalisisAgregado, codigo: string): SeleccionPacientes | undefined {
|
||||
const g = agregado.grupos.find(x => x.codigo === codigo);
|
||||
if (!g || motivoSinLista(agregado, codigo)) return undefined;
|
||||
return { filtros: { birads: codigo }, etiqueta: `Categoría BI-RADS: ${etiquetaBirads(codigo)}`, corte: agregado.corte, esperados: g.n,
|
||||
contexto: { cohorte: agregado.cohorte, escenario: agregado.escenario, revision: agregado.revision } };
|
||||
}
|
||||
|
||||
/** The scrolling ancestor of an element, or the document's own scroller. */
|
||||
function contenedorDeScroll(el: HTMLElement): HTMLElement {
|
||||
for (let n = el.parentElement; n; n = n.parentElement) {
|
||||
const overflow = getComputedStyle(n).overflowY;
|
||||
if ((overflow === 'auto' || overflow === 'scroll') && n.scrollHeight > n.clientHeight) return n;
|
||||
}
|
||||
return (el.ownerDocument.scrollingElement ?? el.ownerDocument.documentElement) as HTMLElement;
|
||||
}
|
||||
|
||||
// Epidemiological analysis of the breast cohort. For now: how many patients of the cohort are in each BI-RADS category at
|
||||
// a cut-off, as a count (not an incidence or a survival estimate). A published category opens its patients in Seguimiento;
|
||||
// a suppressed one says why it does not. Nothing is requested until the tab is first opened.
|
||||
@Component({
|
||||
selector: 'app-indicadores-analisis',
|
||||
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard, IndicadoresAnalisisDescriptivo],
|
||||
template: `
|
||||
<section class="analisis" aria-labelledby="analisis-titulo">
|
||||
<h2 id="analisis-titulo">Análisis epidemiológico</h2>
|
||||
<p class="nota">Conteo de pacientes de la cohorte por categoría BI-RADS a la fecha de corte. No estima incidencia, recurrencia ni supervivencia.</p>
|
||||
@if (datos(); as d) {
|
||||
<p class="contexto">Fecha de corte: {{ d.corte }}. Denominador: {{ d.denominador }}.</p>
|
||||
<div class="tarjetas">
|
||||
<app-indicador-kpi-card title="Categorías publicadas" [value]="publicadas()" state="Disponible" [quietWhenAvailable]="true"
|
||||
[additionalInfo]="'de ' + d.grupos.length + ' categorías BI-RADS.'" />
|
||||
<app-indicador-kpi-card title="Categorías no publicadas" [value]="d.grupos.length - publicadas()" state="Disponible" [quietWhenAvailable]="true"
|
||||
[additionalInfo]="'Con menos de ' + d.umbral_supresion + ' pacientes: su conteo y su lista no se publican.'" />
|
||||
</div>
|
||||
}
|
||||
<form class="controles" (ngSubmit)="consultar()">
|
||||
<label>Fecha de corte <input name="corte" type="date" required [(ngModel)]="corte" [max]="hoy" /></label>
|
||||
<button type="submit" mat-stroked-button [disabled]="carga().estado === 'cargando'">Consultar</button>
|
||||
</form>
|
||||
<article class="panel" aria-labelledby="birads-titulo">
|
||||
<h3 id="birads-titulo">Pacientes por categoría BI-RADS</h3>
|
||||
@switch (carga().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Consultando el análisis" /> }
|
||||
@case ('pendiente') { <p role="status">Funcionalidad pendiente de publicación.</p> }
|
||||
@case ('no-disponible') {
|
||||
<p role="status">La cohorte no está disponible en este momento.</p>
|
||||
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button>
|
||||
}
|
||||
@case ('error') {
|
||||
<div role="alert"><p>{{ $any(carga()).mensaje }}</p><button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div>
|
||||
}
|
||||
}
|
||||
@if (datos(); as d) {
|
||||
@if (todasSuprimidas()) {
|
||||
<p class="nota">Ninguna categoría alcanza el mínimo de {{ d.umbral_supresion }} pacientes para publicarse a esta fecha de corte.</p>
|
||||
}
|
||||
<p class="aviso" role="status">{{ aviso() }}</p>
|
||||
<app-plotly-chart [style.--plot-height]="'360px'" [style.--plot-min-width]="'480px'" [showNotes]="false" [figure]="figura()" (plotClick)="clicGrupo($event)"
|
||||
label="Pacientes por categoría BI-RADS" />
|
||||
<p class="nota">Haga clic en una barra o use «Ver pacientes» para abrir la lista en Seguimiento. Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica.</p>
|
||||
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Pacientes por categoría BI-RADS, tabla">
|
||||
<table>
|
||||
<caption>Pacientes por categoría BI-RADS a la fecha de corte {{ d.corte }}</caption>
|
||||
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
|
||||
<tbody>
|
||||
@for (g of d.grupos; track g.codigo) {
|
||||
<tr [attr.data-grupo]="g.codigo">
|
||||
<th scope="row">{{ etiqueta(g.codigo) }}</th>
|
||||
<td>{{ g.suprimido ? 'No publicado' : miles(g.n!) }}</td>
|
||||
<td>@if (g.suprimido) { <span class="sin-lista">{{ motivo }}</span> }
|
||||
@else { <button type="button" class="ver" (click)="verGrupo(g.codigo, $event.currentTarget)" [attr.aria-label]="'Ver pacientes de ' + etiqueta(g.codigo) + ' en Seguimiento'">Ver pacientes</button> }</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</article>
|
||||
</section>
|
||||
<app-indicadores-analisis-descriptivo [dominio]="dominio()" [tema]="tema()" [corte]="corteConsultado()" [active]="active()" (verPacientes)="abrirDescriptivo($event)" />
|
||||
`,
|
||||
styles: `
|
||||
:host { display: block; min-width: 0; }
|
||||
/* Positioned so the absolutely placed visually-hidden labels belong to this view: otherwise they are laid out against the document and give it a vertical scroll of its own. */
|
||||
.analisis { position: relative; display: flex; flex-direction: column; gap: var(--issste-space-4); min-width: 0; }
|
||||
.analisis > * { margin: 0; }
|
||||
/* The dark theme paints the panel's own surfaces, not the page: the loose heading and notes get the dark background so their light text stays legible. */
|
||||
:host-context(.dark-theme) .analisis { padding: var(--issste-space-4); background: var(--issste-background); color: var(--issste-text); border-radius: var(--issste-radius); }
|
||||
.tarjetas { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); }
|
||||
@media (min-width: 700px) { .tarjetas { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
.panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
h2, h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
|
||||
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
|
||||
.nota, .contexto, .sin-lista { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.controles { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); padding: var(--issste-space-3) var(--issste-space-4); background: var(--issste-surface);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; }
|
||||
input { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px; padding: .6rem; min-height: 44px; box-sizing: border-box; font: inherit; max-width: 100%; }
|
||||
input:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
/* The live region stays in the page, so what is written into it is announced; empty, it takes no room. */
|
||||
.aviso { padding: var(--issste-space-2) var(--issste-space-3); border-left: 4px solid var(--issste-accent); font: var(--mat-sys-body-medium); }
|
||||
.aviso:empty { padding: 0; border: 0; margin: 0; }
|
||||
app-plotly-chart { margin-top: var(--issste-space-3); }
|
||||
.tabla-scroll { overflow-x: auto; margin-top: var(--issste-space-4); }
|
||||
.tabla-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||
table { width: 100%; min-width: 28rem; border-collapse: collapse; font: var(--mat-sys-body-medium); }
|
||||
caption { text-align: left; font: var(--mat-sys-title-small); padding-bottom: var(--issste-space-2); }
|
||||
th, td { padding: var(--issste-space-2) var(--issste-space-3); border-bottom: 1px solid var(--issste-border); text-align: left; vertical-align: top; }
|
||||
td:nth-child(2) { font-variant-numeric: tabular-nums; }
|
||||
td:last-child { min-width: 11rem; }
|
||||
.ver { min-height: 44px; padding: 0 .5rem; border: 0; background: none; color: inherit; text-decoration: underline; cursor: pointer; font: inherit; }
|
||||
.ver:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||
.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
||||
@media (max-width: 600px) { .panel { padding: var(--issste-space-4); } .controles label, .controles input { width: 100%; } }
|
||||
`,
|
||||
})
|
||||
export class IndicadoresAnalisis {
|
||||
readonly dominio = input.required<Dominio>();
|
||||
readonly tema = input.required<Tema>();
|
||||
readonly active = input(false);
|
||||
// The patients of a group, for the page to open them in Seguimiento.
|
||||
readonly verPacientes = output<SeleccionPacientes>();
|
||||
readonly miles = (v: number) => v.toLocaleString('es-MX');
|
||||
readonly etiqueta = etiquetaBirads;
|
||||
readonly motivo = MOTIVO_GRUPO_SUPRIMIDO;
|
||||
readonly hoy = hoyIso();
|
||||
private readonly service = inject(AnalisisService);
|
||||
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
private readonly pedidos = new Subject<string>();
|
||||
private abierto = false;
|
||||
private ultimo?: string;
|
||||
private retorno?: { origen: HTMLElement | null; area: HTMLElement; arriba: number };
|
||||
corte = this.hoy;
|
||||
// The cut-off of the last query: the descriptive sections follow it.
|
||||
readonly corteConsultado = signal(this.hoy);
|
||||
readonly carga = signal<Carga<AnalisisAgregado>>({ estado: 'cargando' });
|
||||
// Why the last click on a bar opened nothing.
|
||||
readonly aviso = signal('');
|
||||
readonly datos = computed(() => { const c = this.carga(); return c.estado === 'listo' ? c.datos : undefined; });
|
||||
// How many categories the answer publishes; the rest are suppressed. Counts categories only, never patients.
|
||||
readonly publicadas = computed(() => this.datos()?.grupos.filter(g => !g.suprimido).length ?? 0);
|
||||
// The answer cannot tell an empty cohort from categories that are all under the threshold: it only says none is published.
|
||||
readonly todasSuprimidas = computed(() => !!this.datos()?.grupos.every(g => g.suprimido));
|
||||
readonly figura = computed(() => { const d = this.datos(); return d ? gruposFigura(d, this.tema()) : { data: [], layout: {} }; });
|
||||
|
||||
constructor() {
|
||||
const destroy = inject(DestroyRef);
|
||||
const cargar = (corte: string): Observable<Carga<AnalisisAgregado>> => {
|
||||
let fuente: Observable<AnalisisAgregado>;
|
||||
try { fuente = this.service.agregado(this.dominio(), corte); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); }
|
||||
return fuente.pipe(
|
||||
map((datos): Carga<AnalisisAgregado> => ({ estado: 'listo', datos })),
|
||||
catchError(error => of(this.fallo(error))),
|
||||
startWith<Carga<AnalisisAgregado>>({ estado: 'cargando' }));
|
||||
};
|
||||
this.pedidos.pipe(switchMap(cargar), takeUntilDestroyed(destroy)).subscribe(c => { this.aviso.set(''); this.carga.set(c); });
|
||||
effect(() => {
|
||||
if (!this.active() || this.abierto) return;
|
||||
untracked(() => { this.abierto = true; this.consultar(); });
|
||||
});
|
||||
}
|
||||
|
||||
private fallo(error: unknown): Carga<AnalisisAgregado> {
|
||||
if (error instanceof HttpErrorResponse) {
|
||||
if (error.status === 404) return { estado: 'pendiente' };
|
||||
if (error.status === 503) return { estado: 'no-disponible' };
|
||||
if (error.status === 0) return { estado: 'error', mensaje: 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.' };
|
||||
if (error.status === 400) return { estado: 'error', mensaje: 'El servicio rechazó la fecha de corte. Revisa la fecha.' };
|
||||
if (error.status >= 500) return { estado: 'error', mensaje: 'El servicio encontró un error interno. Intenta nuevamente más tarde.' };
|
||||
}
|
||||
return { estado: 'error', mensaje: 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.' };
|
||||
}
|
||||
consultar() {
|
||||
if (!isoDate(this.corte)) { this.carga.set({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); return; }
|
||||
this.ultimo = this.corte;
|
||||
this.corteConsultado.set(this.corte);
|
||||
this.pedidos.next(this.corte);
|
||||
}
|
||||
reintentar() { this.pedidos.next(this.ultimo ?? this.corte); }
|
||||
|
||||
// A click on a published bar is the same as its «Ver pacientes» button; a suppressed bar does nothing.
|
||||
clicGrupo(evento: unknown) {
|
||||
const codigo = grupoDelClic(evento, this.datos());
|
||||
if (!codigo) return;
|
||||
const fila = Array.from(this.host.nativeElement.querySelectorAll<HTMLElement>('tr[data-grupo]')).find(tr => tr.getAttribute('data-grupo') === codigo);
|
||||
this.verGrupo(codigo, fila?.querySelector<HTMLElement>('button.ver') ?? this.host.nativeElement.querySelector<HTMLElement>('.plot-viewport'));
|
||||
}
|
||||
// The patients of a published group: the page opens them in Seguimiento. Where the user was is kept for the way back.
|
||||
verGrupo(codigo: string, origen?: EventTarget | null) {
|
||||
const d = this.datos();
|
||||
if (!d) return;
|
||||
this.aviso.set(motivoSinLista(d, codigo) ?? '');
|
||||
const seleccion = seleccionDeGrupo(d, codigo);
|
||||
if (!seleccion) return;
|
||||
const el = origen instanceof HTMLElement ? origen : null;
|
||||
const area = contenedorDeScroll(this.host.nativeElement);
|
||||
this.retorno = { origen: el, area, arriba: area.scrollTop };
|
||||
this.verPacientes.emit(seleccion);
|
||||
}
|
||||
// The patients of a figure of the descriptive sections: the same way back as a bar of the BI-RADS table.
|
||||
abrirDescriptivo(evento: { seleccion: SeleccionPacientes; origen: HTMLElement | null }) {
|
||||
const area = contenedorDeScroll(this.host.nativeElement);
|
||||
this.retorno = { origen: evento.origen, area, arriba: area.scrollTop };
|
||||
this.verPacientes.emit(evento.seleccion);
|
||||
}
|
||||
/** Back from Seguimiento: the scroll where it was and the focus on the control that opened the list. */
|
||||
restaurar() {
|
||||
const r = this.retorno;
|
||||
if (!r) return;
|
||||
if (r.area.isConnected) r.area.scrollTop = r.arriba;
|
||||
(r.origen?.isConnected ? r.origen : this.host.nativeElement.querySelector<HTMLElement>('input[name="corte"]'))?.focus({ preventScroll: true });
|
||||
this.retorno = undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones';
|
||||
import { FigureSelection, IndicadorDatos } from './indicadores.models';
|
||||
|
||||
const fila = (grupo: string, numerador: number, denominador: number, extra: object = {}) => ({
|
||||
periodo: '2025-S2', grupo, estrato: null, suprimido: 0, numerador, denominador, valor: 0, ic_bajo: null, ic_alto: null,
|
||||
n_sin_evento: denominador - numerador, n_excluido: 0, ...extra,
|
||||
});
|
||||
const datos = (filas: Record<string, unknown>[] = [fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20), fila('picos_paroxisticos', 0, 20)]): IndicadorDatos => ({
|
||||
id: 'M30_resultado_eeg', titulo: 'Porcentaje de EEG normal y anormal', contrato: 'C1', unidad: 'paciente',
|
||||
tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: null, valores_estrato: [],
|
||||
grupos: { TOTAL: 'Total', ritmo_posterior: 'Ritmo posterior', picos_paroxisticos: 'Picos paroxísticos' },
|
||||
grupos_de_categoria: {}, notas: ['Datos ficticios.'], filas,
|
||||
});
|
||||
const selection: FigureSelection = { dominio: 'tea', indicador: 'M30_resultado_eeg', figura: 'fig_c1_barras_alteracion', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] };
|
||||
|
||||
describe('Barras por alteración para C1', () => {
|
||||
it('solo aplica a C1 con la figura por alteración', () => {
|
||||
expect(c1AlterationCapability('C1', 'fig_c1_barras_alteracion')).toBe(true);
|
||||
expect(c1AlterationCapability('C2', 'fig_c1_barras_alteracion')).toBe(false);
|
||||
expect(c1AlterationCapability('C1', 'fig_c1_barras_edad')).toBe(false);
|
||||
});
|
||||
it('una barra por alteración tras la de alguna alteración, con su porcentaje y sus conteos', () => {
|
||||
const result = c1AlterationFigure(datos(), selection);
|
||||
if (result.status !== 'supported') throw new Error(result.reason);
|
||||
const [trace] = result.figure.data as Record<string, unknown>[];
|
||||
expect(result.figure.data.length).toBe(1);
|
||||
expect(trace['x']).toEqual(['Alguna alteración', 'Ritmo posterior', 'Picos paroxísticos']);
|
||||
expect(trace['y']).toEqual([55, 25, 0]);
|
||||
expect(trace['text']).toEqual(['55.0 %', '25.0 %', '0.0 %']);
|
||||
expect(trace['customdata']).toEqual([[11, 20], [5, 20], [0, 20]]);
|
||||
expect(result.total).toBe(20);
|
||||
expect(result.notes).toEqual(['Datos ficticios.']);
|
||||
expect(result.highlight.items.map(i => i.id)).toEqual(['TOTAL', 'ritmo_posterior', 'picos_paroxisticos']);
|
||||
expect((result.figure.layout['title'] as { text: string }).text).toBe('Porcentaje de EEG normal y anormal, 2025-S2');
|
||||
});
|
||||
it('varios periodos se dibujan lado a lado, uno por serie', () => {
|
||||
const otro = (grupo: string, n: number, d: number) => fila(grupo, n, d, { periodo: '2025-S1' });
|
||||
const data = { ...datos([otro('TOTAL', 2, 8), otro('ritmo_posterior', 1, 8), otro('picos_paroxisticos', 1, 8), ...datos().filas]), periodos: ['2025-S1', '2025-S2'] };
|
||||
const result = c1AlterationFigure(data, { ...selection, periodos: ['2025-S1', '2025-S2'] });
|
||||
if (result.status !== 'supported') throw new Error(result.reason);
|
||||
const traces = result.figure.data as Record<string, unknown>[];
|
||||
expect(traces.map(t => t['name'])).toEqual(['2025-S1', '2025-S2']);
|
||||
expect(traces[0]['y']).toEqual([25, 12.5, 12.5]);
|
||||
expect(result.figure.layout['showlegend']).toBe(true);
|
||||
expect(result.total).toBe(28);
|
||||
expect(result.highlight.items[1].points).toEqual([{ trace: 0, index: 1 }, { trace: 1, index: 1 }]);
|
||||
});
|
||||
it('un periodo sin niños con EEG bueno no dibuja ceros', () => {
|
||||
const result = c1AlterationFigure(datos([fila('TOTAL', 0, 0), fila('ritmo_posterior', 0, 0), fila('picos_paroxisticos', 0, 0)]), selection);
|
||||
if (result.status !== 'supported') throw new Error(result.reason);
|
||||
expect((result.figure.data[0] as Record<string, unknown>)['y']).toEqual([null, null, null]);
|
||||
expect(result.total).toBe(0);
|
||||
});
|
||||
it('rechaza datos que no son los grupos por alteración de la selección', () => {
|
||||
expect(c1AlterationFigure({ ...datos(), grupos: { TOTAL: 'Total' } }, selection).status).toBe('unsupported');
|
||||
expect(c1AlterationFigure({ ...datos(), estrato: 'grupo_edad' }, selection).status).toBe('unsupported');
|
||||
expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20)]), selection).status).toBe('unsupported');
|
||||
expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 25, 20), fila('picos_paroxisticos', 0, 20)]), selection).status).toBe('unsupported');
|
||||
expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20, { suprimido: 1 }), fila('picos_paroxisticos', 0, 20)]), selection).status).toBe('unsupported');
|
||||
expect(c1AlterationFigure(datos(), { ...selection, periodos: ['2025-S1'] }).status).toBe('unsupported');
|
||||
expect(c1AlterationFigure(datos(), { ...selection, figura: 'fig_c1_barras_edad' }).status).toBe('unsupported');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { percentNumber } from './indicadores-format';
|
||||
import { FigureHighlight } from './indicadores-highlight';
|
||||
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
|
||||
import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models';
|
||||
|
||||
// fig_c1_barras_alteracion: a C1 proportion whose groups are the alterations of the EEG. One bar per alteration with
|
||||
// the share of the period's children that have it, after a first bar for the children with any of them (the TOTAL
|
||||
// group). A child counts in every alteration it has, so the bars don't add up. Several periods draw side by side.
|
||||
export const C1_ALTERATION_BARS = 'fig_c1_barras_alteracion';
|
||||
const TOTAL = 'TOTAL';
|
||||
const ANY_LABEL = 'Alguna alteración';
|
||||
|
||||
export type C1AlterationResult = { status: 'unsupported'; reason: string }
|
||||
| { status: 'supported'; figure: PlotlyFigure; highlight: FigureHighlight; total: number; notes: string[] };
|
||||
export function c1AlterationCapability(contract: string, representation: string): boolean {
|
||||
return contract === 'C1' && representation === C1_ALTERATION_BARS;
|
||||
}
|
||||
|
||||
const count = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
|
||||
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
// The any-alteration bar uses the second series colour; each alteration takes its own colour.
|
||||
const COLORS = [C2_PALETTE.series[1], ...C2_PALETTE.edades, C2_PALETTE.series[2], C2_PALETTE.series[3], C2_PALETTE.series[0]];
|
||||
const color = (i: number) => COLORS[i % COLORS.length];
|
||||
|
||||
export function c1AlterationFigure(data: IndicadorDatos, selection: FigureSelection): C1AlterationResult {
|
||||
const unsupported = (reason: string): C1AlterationResult => ({ status: 'unsupported', reason });
|
||||
if (!c1AlterationCapability(data.contrato, selection.figura)) return unsupported('Representación no soportada');
|
||||
if (data['estrato'] != null) return unsupported('Esta figura no admite una dimensión');
|
||||
const periods = selection.periodos ? data.periodos.filter(p => selection.periodos!.includes(p)) : data.periodos;
|
||||
if (!periods.length) return unsupported('No hay periodos publicados para esta selección');
|
||||
const published = data['grupos'];
|
||||
const groups = Object.entries(published && typeof published === 'object' ? published : {}).filter(([id]) => id !== TOTAL);
|
||||
if (!groups.length) return unsupported('El indicador no publica grupos por alteración');
|
||||
const bars = [{ id: TOTAL, label: ANY_LABEL }, ...groups.map(([id, label]) => ({ id, label: String(label) }))];
|
||||
|
||||
const cells = periods.map(period => bars.map(bar =>
|
||||
data.filas.filter(r => r['periodo'] === period && r['grupo'] === bar.id && r['estrato'] == null)));
|
||||
if (cells.some(row => row.some(found => found.length !== 1))) return unsupported('Grupos por alteración incompletos');
|
||||
const rows = cells.map(row => row.map(([r]) => r));
|
||||
if (rows.some(row => row.some(r => (r['suprimido'] !== 0 && r['suprimido'] !== false)
|
||||
|| !count(r['numerador']) || !count(r['denominador']) || r['numerador'] > r['denominador'])))
|
||||
return unsupported('Conteos por alteración suprimidos o no verificables');
|
||||
|
||||
const theme = c2Theme(selection.tema);
|
||||
const x = bars.map(b => escape(b.label));
|
||||
const single = periods.length === 1;
|
||||
const traces = rows.map((row, p) => {
|
||||
const y = row.map(r => (r['denominador'] as number) ? 100 * (r['numerador'] as number) / (r['denominador'] as number) : null);
|
||||
return { type: 'bar', name: periods[p], x, y,
|
||||
marker: { color: single ? bars.map((_, i) => color(i)) : color(p), line: { color: theme.background, width: 1 } },
|
||||
text: y.map(v => v === null ? '' : percentNumber(v) + ' %'), textposition: 'outside', cliponaxis: false,
|
||||
customdata: row.map(r => [r['numerador'], r['denominador']]),
|
||||
hovertemplate: '%{x}' + (single ? '' : ', %{fullData.name}') + '<br>%{y:.1f} % (%{customdata[0]} de %{customdata[1]} niños)<extra></extra>' };
|
||||
});
|
||||
const figure: PlotlyFigure = {
|
||||
data: traces,
|
||||
layout: { autosize: true, height: 400, barmode: 'group', margin: { t: 56, l: 72, r: 24, b: single ? 64 : 96 }, showlegend: !single,
|
||||
legend: { orientation: 'h', y: -0.3, itemclick: false, itemdoubleclick: false },
|
||||
title: { text: escape(String(data['titulo'] ?? data.id)) + (single ? ', ' + periods[0] : '') },
|
||||
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
|
||||
xaxis: { type: 'category', title: { text: 'Alteración del EEG' }, automargin: true },
|
||||
yaxis: { title: { text: '% de niños con EEG de buena calidad' }, range: [0, 100], ticksuffix: ' %', gridcolor: theme.grid, zeroline: false } },
|
||||
config: { displayModeBar: false },
|
||||
};
|
||||
const highlight: FigureHighlight = { groups: [], traces: traces.map((_, t) => t), allLabel: 'Todas las alteraciones',
|
||||
items: bars.map((b, i) => ({ id: b.id, label: b.label, color: single ? color(i) : theme.line,
|
||||
points: traces.map((_, t) => ({ trace: t, index: i })) })) };
|
||||
// Children with a first good EEG over the periods drawn: zero means there is nothing to draw a share of.
|
||||
const total = rows.reduce((sum, row) => sum + (row[0]['denominador'] as number), 0);
|
||||
return { status: 'supported', figure, highlight, total, notes: Array.isArray(data.notas) ? [...data.notas] : [] };
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { c1DonutCapability, c1DonutFigure, c1DonutLabels } from './indicadores-c1-donut';
|
||||
import { FigureSelection, IndicadorDatos } from './indicadores.models';
|
||||
|
||||
const fila = (estrato: string, numerador: number, denominador: number, extra: object = {}) => ({
|
||||
periodo: '2025-S2', grupo: 'TOTAL', estrato, suprimido: 0, numerador, denominador, valor: 0, ic_bajo: null, ic_alto: null,
|
||||
n_sin_evento: denominador - numerador, n_excluido: 0, ...extra,
|
||||
});
|
||||
const datos = (filas = [fila('16-23', 16, 24), fila('24-29', 13, 18), fila('30-36', 17, 22)]): IndicadorDatos => ({
|
||||
id: 'M21_diagnosticados_con_eeg', titulo: 'Porcentaje de pacientes con diagnóstico de TEA con EEG', contrato: 'C1', unidad: 'paciente',
|
||||
tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: 'grupo_edad', valores_estrato: ['16-23', '24-29', '30-36'],
|
||||
etiquetas_estrato: { '16-23': '16 a 23 meses', '24-29': '24 a 29 meses', '30-36': '30 a 36 meses' },
|
||||
grupos: { TOTAL: 'Total' }, grupos_de_categoria: {}, notas: ['Datos ficticios.'], filas,
|
||||
});
|
||||
const selection: FigureSelection = { dominio: 'tea', indicador: 'M21_diagnosticados_con_eeg', figura: 'fig_c1_donas', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] };
|
||||
|
||||
describe('Dona de dos anillos para C1', () => {
|
||||
it('solo aplica a C1 con las figuras por grupo de edad', () => {
|
||||
expect(c1DonutCapability('C1', 'fig_c1_donas')).toBe(true);
|
||||
expect(c1DonutCapability('C1', 'fig_c1_dona_edad')).toBe(true);
|
||||
expect(c1DonutCapability('C1', 'fig_c1_barras_edad')).toBe(true);
|
||||
expect(c1DonutCapability('C2', 'fig_c1_donas')).toBe(false);
|
||||
expect(c1DonutCapability('C1', 'fig_c1_grupos')).toBe(false);
|
||||
});
|
||||
it('anillo interior con y sin el evento; exterior por grupo de edad, con el total al centro', () => {
|
||||
const result = c1DonutFigure(datos(), selection);
|
||||
expect(result.status).toBe('supported');
|
||||
if (result.status !== 'supported') return;
|
||||
const [center, inner, outer] = result.figure.data as { labels: string[]; values: number[]; text: string[] }[];
|
||||
expect(center.text[0]).toContain('<b>64</b>');
|
||||
expect(inner.labels).toEqual(['Con EEG', 'Sin EEG']);
|
||||
expect(inner.values).toEqual([46, 18]);
|
||||
expect(inner.text).toEqual(['Con EEG<br>71.9 %', 'Sin EEG<br>28.1 %']);
|
||||
expect(outer.labels).toEqual(['Con EEG · 16 a 23 meses', 'Con EEG · 24 a 29 meses', 'Con EEG · 30 a 36 meses',
|
||||
'Sin EEG · 16 a 23 meses', 'Sin EEG · 24 a 29 meses', 'Sin EEG · 30 a 36 meses']);
|
||||
expect(outer.values).toEqual([16, 13, 17, 8, 5, 5]);
|
||||
// Inside the outer ring only the age group; slices under 5 % stay unlabeled.
|
||||
expect(outer.text[0]).toMatch(/^16 a 23 meses<br>/);
|
||||
expect(outer.text[4]).toMatch(/^24 a 29 meses<br>7.8/);
|
||||
const small = c1DonutFigure(datos([fila('16-23', 16, 24), fila('24-29', 13, 14), fila('30-36', 17, 40)]), selection);
|
||||
if (small.status === 'supported') expect((small.figure.data[2] as { text: string[] }).text[4]).toBe('');
|
||||
expect(result.total).toBe(64);
|
||||
expect(result.notes).toEqual(['Datos ficticios.']);
|
||||
expect(result.highlight.groups.map(g => g.label)).toEqual(['Con EEG', 'Sin EEG']);
|
||||
expect(result.highlight.items.map(i => i.short)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses', '16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||
expect(result.highlight.groups[1].center).toBe('<b>18</b><br>Sin EEG');
|
||||
expect(result.figure.layout['title']).toEqual({ text: 'Porcentaje de pacientes con diagnóstico de TEA con EEG, 2025-S2' });
|
||||
});
|
||||
it('dona por grupo de edad: solo los pacientes con el evento, con el porcentaje total al centro', () => {
|
||||
const result = c1DonutFigure(datos(), { ...selection, figura: 'fig_c1_dona_edad' });
|
||||
if (result.status !== 'supported') throw new Error(result.reason);
|
||||
expect(result.figure.data).toHaveLength(1);
|
||||
// Only the patients with EEG, by age group; each slice is its share of those 46 patients.
|
||||
const [ring] = result.figure.data as { labels: string[]; values: number[]; text: string[] }[];
|
||||
expect(ring.labels).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||
expect(ring.values).toEqual([16, 13, 17]);
|
||||
expect(ring.text[0]).toMatch(/^16 a 23 meses<br>34.8/);
|
||||
expect((result.figure.layout['annotations'] as { text: string }[])[0].text).toBe('<b>71.9 %</b>');
|
||||
expect(result.highlight.groups).toEqual([]);
|
||||
expect(result.highlight.items.map(i => i.label)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||
expect(result.highlight.items[0].center).toBe('<b>34.8 %</b><br>16 a 23 meses');
|
||||
});
|
||||
it('cada grupo de edad tiene el mismo color en la dona de M21 y las barras de M22, sin verde ni rojo', () => {
|
||||
const colores = ['#2F6DB3', '#E0A526', '#A23E8C'];
|
||||
const dona = c1DonutFigure(datos(), { ...selection, figura: 'fig_c1_dona_edad' });
|
||||
if (dona.status !== 'supported') throw new Error('sin figura');
|
||||
expect((dona.figure.data[0] as { marker: { colors: string[] } }).marker.colors).toEqual(colores);
|
||||
expect(dona.highlight.items.map(i => i.color)).toEqual(colores);
|
||||
const barras = c1DonutFigure({ ...datos(), id: 'M22_diagnosticados_sin_eeg' }, { ...selection, indicador: 'M22_diagnosticados_sin_eeg', figura: 'fig_c1_barras_edad' });
|
||||
if (barras.status !== 'supported') throw new Error('sin figura');
|
||||
expect((barras.figure.data[0] as { marker: { color: string[] } }).marker.color).toEqual(colores);
|
||||
expect(barras.highlight.items.map(i => i.color)).toEqual(colores);
|
||||
});
|
||||
it('barras apiladas por grupo de edad: confirmados y en proceso, con un botón por estado', () => {
|
||||
const result = c1DonutFigure({ ...datos(), id: 'M24_confirmacion_diagnostico' }, { ...selection, indicador: 'M24_confirmacion_diagnostico', figura: 'fig_c1_barras_apiladas_edad' });
|
||||
if (result.status !== 'supported') throw new Error('sin figura');
|
||||
expect(result.figure.layout['barmode']).toBe('stack');
|
||||
expect(result.figure.data.map(t => [t['name'], t['y']])).toEqual([['Diagnóstico confirmado', [16, 13, 17]], ['En proceso', [8, 5, 5]]]);
|
||||
expect(result.figure.data[1]['text']).toEqual(['8 (33.3 %)', '5 (27.8 %)', '5 (22.7 %)']);
|
||||
expect(result.highlight.items.map(i => i.label)).toEqual(['Diagnóstico confirmado', 'En proceso']);
|
||||
});
|
||||
it('barras por grupo de edad: una barra por grupo con su porcentaje', () => {
|
||||
const result = c1DonutFigure({ ...datos([fila('16-23', 8, 24), fila('24-29', 5, 18), fila('30-36', 5, 22)]), id: 'M22_diagnosticados_sin_eeg' },
|
||||
{ ...selection, indicador: 'M22_diagnosticados_sin_eeg', figura: 'fig_c1_barras_edad' });
|
||||
if (result.status !== 'supported') throw new Error(result.reason);
|
||||
const [bars] = result.figure.data as { type: string; x: string[]; y: number[]; text: string[] }[];
|
||||
expect(bars.type).toBe('bar');
|
||||
expect(bars.x).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||
expect(bars.text).toEqual(['33.3 %', '27.8 %', '22.7 %']);
|
||||
expect(JSON.stringify(result.figure.layout['yaxis'])).toContain('% de pacientes sin EEG');
|
||||
expect(result.highlight.items.map(i => i.points)).toEqual([[{ trace: 0, index: 0 }], [{ trace: 0, index: 1 }], [{ trace: 0, index: 2 }]]);
|
||||
});
|
||||
it('usa etiquetas propias por indicador y neutrales para otros', () => {
|
||||
expect(c1DonutLabels('M24_confirmacion_diagnostico')).toEqual(['Diagnóstico confirmado', 'En proceso']);
|
||||
expect(c1DonutLabels('M22_diagnosticados_sin_eeg')).toEqual(['Sin EEG', 'Con EEG']);
|
||||
expect(c1DonutLabels('otro')).toEqual(['Con el evento', 'Sin el evento']);
|
||||
});
|
||||
it('solo un semestre', () => {
|
||||
expect(c1DonutFigure({ ...datos(), tipo_periodo: 'mes', periodos: ['2025-12'] }, { ...selection, tipoPeriodo: 'mes', periodos: ['2025-12'] }))
|
||||
.toEqual({ status: 'unsupported', reason: 'Esta figura solo está disponible para un semestre.' });
|
||||
expect(c1DonutFigure({ ...datos(), periodos: ['2025-S1', '2025-S2'] }, { ...selection, periodos: ['2025-S1', '2025-S2'] }).status).toBe('unsupported');
|
||||
expect(c1DonutFigure(datos(), { ...selection, periodos: ['2025-S1'] }).status).toBe('unsupported');
|
||||
});
|
||||
it('rechaza estratos incompletos, suprimidos o imposibles', () => {
|
||||
expect(c1DonutFigure({ ...datos(), estrato: null }, selection).status).toBe('unsupported');
|
||||
expect(c1DonutFigure(datos([fila('16-23', 16, 24), fila('24-29', 13, 18)]), selection).status).toBe('unsupported');
|
||||
expect(c1DonutFigure(datos([fila('16-23', 16, 24), fila('24-29', 13, 18), fila('30-36', null as unknown as number, 22, { suprimido: 1 })]), selection).status).toBe('unsupported');
|
||||
expect(c1DonutFigure(datos([fila('16-23', 30, 24), fila('24-29', 13, 18), fila('30-36', 17, 22)]), selection).status).toBe('unsupported');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,161 @@
|
||||
import { Categoria, dona, Grupo, Modelo } from './indicadores-eu7-escenario';
|
||||
import { percentNumber, shareText } from './indicadores-format';
|
||||
import { donaHighlight, FigureHighlight } from './indicadores-highlight';
|
||||
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
|
||||
import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models';
|
||||
|
||||
// Figures by age group for a C1 proportion over one semester, built from the age-stratified C1 rows:
|
||||
// - fig_c1_donas: double donut drawn like CaCu's «Distribución de resultados citológicos»; the inner ring
|
||||
// splits the denominator into patients with and without the event, the outer ring each of them by age group.
|
||||
// - fig_c1_dona_edad: only the patients with the event, by age group, with the overall percentage in the centre.
|
||||
// - fig_c1_barras_edad: one bar per age group with its percentage.
|
||||
export const C1_DONUT = 'fig_c1_donas';
|
||||
export const C1_RING = 'fig_c1_dona_edad';
|
||||
export const C1_AGE_BARS = 'fig_c1_barras_edad';
|
||||
export const C1_AGE_STACK = 'fig_c1_barras_apiladas_edad';
|
||||
const C1_AGE_FIGURES = [C1_DONUT, C1_RING, C1_AGE_BARS, C1_AGE_STACK];
|
||||
export const C1_DONUT_ESTRATO = 'grupo_edad';
|
||||
// Mock (TEA): ring labels per indicator; any other C1 indicator falls back to a neutral wording.
|
||||
const EVENT_LABELS: Readonly<Record<string, readonly [string, string]>> = {
|
||||
M21_diagnosticados_con_eeg: ['Con EEG', 'Sin EEG'],
|
||||
M22_diagnosticados_sin_eeg: ['Sin EEG', 'Con EEG'],
|
||||
M24_confirmacion_diagnostico: ['Diagnóstico confirmado', 'En proceso'],
|
||||
};
|
||||
// Olive for the event, the next series colour for its complement; age groups keep their own colours.
|
||||
const RING_COLORS = [C2_PALETTE.series[0], C2_PALETTE.series[1]] as const;
|
||||
// One colour per age group, the same in the donut (M21) and the bars (M22).
|
||||
const ageColor = (i: number) => C2_PALETTE.edades[i % C2_PALETTE.edades.length];
|
||||
|
||||
export type C1DonutResult = { status: 'unsupported'; reason: string }
|
||||
| { status: 'supported'; figure: PlotlyFigure; highlight: FigureHighlight; total: number; notes: string[] };
|
||||
export function c1DonutCapability(contract: string, representation: string): boolean {
|
||||
return contract === 'C1' && C1_AGE_FIGURES.includes(representation);
|
||||
}
|
||||
export function c1DonutLabels(indicador: string): readonly [string, string] {
|
||||
return EVENT_LABELS[indicador] ?? ['Con el evento', 'Sin el evento'];
|
||||
}
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const count = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
|
||||
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
function shade(hex: string, step: number, steps: number): string {
|
||||
const t = steps > 1 ? 0.65 * step / (steps - 1) : 0;
|
||||
const rgb = [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16)).map(c => Math.round(c + (255 - c) * t));
|
||||
return '#' + rgb.map(c => c.toString(16).padStart(2, '0')).join('').toUpperCase();
|
||||
}
|
||||
|
||||
export function c1DonutFigure(data: IndicadorDatos, selection: FigureSelection): C1DonutResult {
|
||||
const unsupported = (reason: string): C1DonutResult => ({ status: 'unsupported', reason });
|
||||
if (!c1DonutCapability(data.contrato, selection.figura)) return unsupported('Representación no soportada');
|
||||
if (selection.tipoPeriodo !== 'semestre' || data.tipo_periodo !== 'semestre') return unsupported('Esta figura solo está disponible para un semestre.');
|
||||
if (data.periodos.length !== 1 || (selection.periodos && (selection.periodos.length !== 1 || selection.periodos[0] !== data.periodos[0])))
|
||||
return unsupported('Se requiere un semestre único concordante');
|
||||
const values = data['valores_estrato'], names = data['etiquetas_estrato'];
|
||||
if (data['estrato'] !== C1_DONUT_ESTRATO || !Array.isArray(values) || !values.length || !values.every(v => typeof v === 'string')
|
||||
|| new Set(values).size !== values.length || (names != null && !record(names))) return unsupported('Estratificación por grupo de edad no verificable');
|
||||
const period = data.periodos[0];
|
||||
const rows = values.map(v => data.filas.filter(r => r['periodo'] === period && r['estrato'] === v));
|
||||
if (rows.some(r => r.length !== 1) || data.filas.length !== values.length) return unsupported('Partición por grupo de edad incompleta');
|
||||
const strata = rows.map(([r], i) => ({ id: values[i] as string, label: typeof names?.[values[i]] === 'string' ? names[values[i]] as string : values[i] as string,
|
||||
numerador: r['numerador'], denominador: r['denominador'], suprimido: r['suprimido'], grupo: r['grupo'] }));
|
||||
if (strata.some(s => s.grupo !== 'TOTAL' || (s.suprimido !== 0 && s.suprimido !== false)
|
||||
|| !count(s.numerador) || !count(s.denominador) || s.numerador > s.denominador)) return unsupported('Conteos por grupo de edad suprimidos o no verificables');
|
||||
|
||||
const labels = c1DonutLabels(data.id);
|
||||
const notes = Array.isArray(data.notas) ? [...data.notas] : [];
|
||||
const title = { text: escape(String(data['titulo'] ?? data.id)) + ', ' + period };
|
||||
const total = strata.reduce((sum, s) => sum + (s.denominador as number), 0);
|
||||
if (selection.figura === C1_AGE_STACK) {
|
||||
const figure = ageStack(strata, labels, selection);
|
||||
figure.layout = { ...figure.layout, title };
|
||||
const highlight: FigureHighlight = { groups: [], traces: [0, 1], allLabel: 'Todos los pacientes',
|
||||
items: labels.map((label, g) => ({ id: g ? 'SIN' : 'CON', label, color: RING_COLORS[g], points: strata.map((_, i) => ({ trace: g, index: i })) })) };
|
||||
return { status: 'supported', figure, highlight, total, notes };
|
||||
}
|
||||
if (selection.figura === C1_AGE_BARS) {
|
||||
const figure = ageBars(strata, labels[0], selection);
|
||||
figure.layout = { ...figure.layout, title };
|
||||
const highlight: FigureHighlight = { groups: [], traces: [0], allLabel: 'Todos los grupos de edad',
|
||||
items: strata.map((s, i) => ({ id: s.id, label: s.label, color: ageColor(i), points: [{ trace: 0, index: i }] })) };
|
||||
return { status: 'supported', figure, highlight, total, notes };
|
||||
}
|
||||
|
||||
const grupos: Grupo[] = labels.map((etiqueta, g) => ({ id: g ? 'SIN' : 'CON', etiqueta, color: RING_COLORS[g] }));
|
||||
const categorias: Categoria[] = [], celdas: Modelo['celdas'] = {};
|
||||
grupos.forEach((g, gi) => strata.forEach((s, i) => {
|
||||
const id = g.id + ':' + s.id, n = gi ? (s.denominador as number) - (s.numerador as number) : s.numerador as number;
|
||||
// Unique labels: Plotly merges pie slices that share one.
|
||||
categorias.push({ id, etiqueta: g.etiqueta + ' · ' + s.label, color: shade(g.color, i, strata.length), grupo: g.id });
|
||||
celdas[id] = { n, estado: 'Publicado' };
|
||||
}));
|
||||
const modelo: Modelo = { periodo: period, categorias, grupos, celdas, total, sinDato: { n: 0, estado: 'Publicado' },
|
||||
escenarios: [], vacio: total === 0, notas: notes, sinDatoEtiqueta: '' };
|
||||
const figure = dona(modelo, {}, selection.tema);
|
||||
if (figure.data.length === 3) {
|
||||
const [, inner, outer] = figure.data as Record<string, unknown>[];
|
||||
const hover = '%{label}<br>%{customdata[0]} pacientes, %{customdata[1]} % de ' + total + '<extra></extra>';
|
||||
inner['hovertemplate'] = outer['hovertemplate'] = hover;
|
||||
// Inside the outer ring the colour already tells the group: show only the age group and its share.
|
||||
const outerValues = outer['values'] as number[];
|
||||
outer['text'] = categorias.map((c, i) => outerValues[i] / total < .05 ? ''
|
||||
: escape(strata[i % strata.length].label) + '<br>' + shareText(outerValues[i], total));
|
||||
inner['text'] = grupos.map((g, i) => {
|
||||
const n = (inner['values'] as number[])[i];
|
||||
return n / total < .05 ? '' : escape(g.etiqueta) + '<br>' + percentNumber(100 * n / total) + ' %';
|
||||
});
|
||||
if (selection.figura === C1_RING) {
|
||||
// Only the patients with the event, by age group, around the overall percentage of the event.
|
||||
// Each slice is its age group's share of those patients.
|
||||
const numerador = strata.reduce((sum, s) => sum + (s.numerador as number), 0);
|
||||
const values = strata.map(s => s.numerador as number);
|
||||
figure.data = [{ ...outer, hole: .6, values, labels: strata.map(s => escape(s.label)),
|
||||
marker: { ...(outer['marker'] as object), colors: strata.map((_, i) => ageColor(i)) },
|
||||
text: values.map((n, i) => !numerador || n / numerador < .05 ? '' : escape(strata[i].label) + '<br>' + shareText(n, numerador)),
|
||||
customdata: values.map(n => [n, numerador ? percentNumber(100 * n / numerador) : '0']),
|
||||
hovertemplate: '%{label}<br>%{customdata[0]} pacientes, %{customdata[1]} % de los ' + numerador + ' ' + escape(what(labels[0])) + '<extra></extra>' }];
|
||||
figure.layout = { ...figure.layout, title, annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false,
|
||||
text: '<b>' + percentNumber(100 * numerador / total) + ' %</b>', font: { size: 26, color: c2Theme(selection.tema).text } }] };
|
||||
const highlight: FigureHighlight = { groups: [], traces: [0], center: { annotation: 0 }, allLabel: labels[0],
|
||||
items: strata.map((s, i) => ({ id: s.id, label: s.label, color: ageColor(i), points: [{ trace: 0, index: i }],
|
||||
center: '<b>' + (numerador ? percentNumber(100 * values[i] / numerador) : '0') + ' %</b><br>' + escape(s.label) })) };
|
||||
return { status: 'supported', figure, highlight, total, notes };
|
||||
}
|
||||
}
|
||||
figure.layout = { ...figure.layout, title };
|
||||
// Next to its group's button, a category only needs its age group.
|
||||
const highlight = donaHighlight(modelo, id => strata.find(s => id.endsWith(':' + s.id))?.label);
|
||||
return { status: 'supported', figure, highlight, total, notes };
|
||||
}
|
||||
|
||||
// "Con EEG" -> "con EEG", to follow «pacientes».
|
||||
const what = (label: string) => label.charAt(0).toLowerCase() + label.slice(1);
|
||||
// One stacked bar per age group: how many of its patients have the event and how many don't.
|
||||
function ageStack(strata: readonly { label: string; numerador: unknown; denominador: unknown }[], labels: readonly [string, string], selection: FigureSelection): PlotlyFigure {
|
||||
const theme = c2Theme(selection.tema);
|
||||
const x = strata.map(s => escape(s.label));
|
||||
const conEvento = strata.map(s => s.numerador as number), sinEvento = strata.map(s => (s.denominador as number) - (s.numerador as number));
|
||||
return { data: [conEvento, sinEvento].map((y, g) => ({ type: 'bar', name: escape(labels[g]), x, y, marker: { color: RING_COLORS[g], line: { color: theme.background, width: 1 } },
|
||||
text: y.map((n, i) => (strata[i].denominador as number) ? n + ' (' + percentNumber(100 * n / (strata[i].denominador as number)) + ' %)' : ''),
|
||||
textposition: 'inside', insidetextanchor: 'middle', hovertemplate: '%{x}<br>%{fullData.name}: %{y} pacientes<extra></extra>' })),
|
||||
layout: { autosize: true, height: 400, barmode: 'stack', margin: { t: 24, l: 72, r: 24, b: 80 }, showlegend: true,
|
||||
legend: { orientation: 'h', y: -0.28, itemclick: false, itemdoubleclick: false },
|
||||
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
|
||||
xaxis: { type: 'category', title: { text: 'Grupo de edad' }, automargin: true },
|
||||
yaxis: { title: { text: 'Pacientes' }, rangemode: 'tozero', gridcolor: theme.grid, zeroline: false } },
|
||||
config: { displayModeBar: false } };
|
||||
}
|
||||
// One bar per age group: the share of its patients with the event.
|
||||
function ageBars(strata: readonly { label: string; numerador: unknown; denominador: unknown }[], event: string, selection: FigureSelection): PlotlyFigure {
|
||||
const theme = c2Theme(selection.tema);
|
||||
const x = strata.map(s => escape(s.label));
|
||||
const y = strata.map(s => (s.denominador as number) ? 100 * (s.numerador as number) / (s.denominador as number) : null);
|
||||
return { data: [{ type: 'bar', x, y, marker: { color: strata.map((_, i) => ageColor(i)), line: { color: theme.background, width: 1 } },
|
||||
text: y.map(v => v === null ? '' : percentNumber(v) + ' %'), textposition: 'outside', cliponaxis: false,
|
||||
customdata: strata.map(s => [s.numerador, s.denominador]),
|
||||
hovertemplate: '%{x}<br>%{y:.1f} % (%{customdata[0]} de %{customdata[1]} pacientes)<extra></extra>' }],
|
||||
layout: { autosize: true, height: 400, margin: { t: 24, l: 72, r: 24, b: 64 }, showlegend: false,
|
||||
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
|
||||
xaxis: { type: 'category', title: { text: 'Grupo de edad' }, automargin: true },
|
||||
yaxis: { title: { text: '% de pacientes ' + escape(what(event)) }, range: [0, 100], ticksuffix: ' %', gridcolor: theme.grid, zeroline: false } },
|
||||
config: { displayModeBar: false } };
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { c2Capability, c2Descendants, c2Figure } from './indicadores-c2-adapter';
|
||||
import { c2Color, C2_PALETTE } from './indicadores-c2-palette';
|
||||
import { c2Color, C2_PALETTE, seriesColors } from './indicadores-c2-palette';
|
||||
import { c2Fixture } from './indicadores-c2-adapter.testing';
|
||||
import { FigureSelection } from './indicadores.models';
|
||||
import { donutFixture } from './indicadores-donut-drilldown.testing';
|
||||
@@ -43,7 +43,7 @@ describe('C2: datos publicados a Plotly', () => {
|
||||
const final = figurePresentation(result.figure, selection).figure, before = structuredClone(final);
|
||||
const legend = donutLegend(final), view = donutSimpleView(final);
|
||||
expect(legend).toEqual([
|
||||
{ label: 'A', color: '#7184A2' }, { label: 'B', color: '#A4B88A' }, { label: 'C', color: '#D0B778' },
|
||||
{ label: 'A', color: C2_PALETTE.series[0] }, { label: 'B', color: C2_PALETTE.series[1] }, { label: 'C', color: C2_PALETTE.series[2] },
|
||||
]);
|
||||
expect(view.layout).toMatchObject({ showlegend: false, height: 440, margin: { l: 16, r: 16, t: 16, b: 16, pad: 0 } });
|
||||
expect(view.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] });
|
||||
@@ -158,15 +158,18 @@ describe('C2: datos publicados a Plotly', () => {
|
||||
});
|
||||
|
||||
describe('paleta C2 institucional y semántica', () => {
|
||||
it.each(['claro','oscuro'] as const)('conserva colores publicados en %s y separa interfaz, series y estados', tema => {
|
||||
it.each(['claro','oscuro'] as const)('sustituye tonos ajenos al logo en %s y separa interfaz, series y estados', tema => {
|
||||
const data = c2Fixture(); (data['categorias'] as Record<string, Record<string, unknown>>)['A']['color'] = '#D98E4A';
|
||||
const figure = supported(data, { ...selection, tema }).figure;
|
||||
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', '#A4B88A', '#D0B778']);
|
||||
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', C2_PALETTE.series[1], C2_PALETTE.series[2]]);
|
||||
expect(seriesColors(['#D98E4A', undefined, undefined])).toEqual(['#D98E4A', C2_PALETTE.series[1], C2_PALETTE.series[2]]);
|
||||
expect(figure.layout['paper_bgcolor']).toBe(C2_PALETTE[tema].background);
|
||||
expect(figure.layout['font']).toMatchObject({ color: C2_PALETTE[tema].text });
|
||||
expect(C2_PALETTE.states.noData).toBe('#C9CDD2'); expect(c2Color('#C9CDD2',0)).toBe('#C9CDD2');
|
||||
expect(c2Color(undefined, 0)).toBe('#7184A2'); expect(c2Color(undefined, 1)).toBe('#A4B88A');
|
||||
expect(c2Color(undefined, 2)).toBe('#D0B778'); expect(c2Color(undefined, 3)).toBe('#B78B8E');
|
||||
expect(c2Color(undefined, 0)).toBe(C2_PALETTE.series[0]); expect(c2Color(undefined, 1)).toBe(C2_PALETTE.series[1]);
|
||||
expect(c2Color(undefined, 2)).toBe(C2_PALETTE.series[2]); expect(c2Color(undefined, 3)).toBe(C2_PALETTE.series[3]);
|
||||
expect(c2Color('#D98E4A', 0)).toBe('#D98E4A');
|
||||
expect(c2Color(C2_PALETTE.edades[0], 0)).toBe(C2_PALETTE.edades[0]);
|
||||
expect(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined();
|
||||
});
|
||||
it('mantiene contraste de texto legible y separadores suaves en ambos temas', () => {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user