From d9245fe9b7225f39a7b363cc57ba5a35eafc51d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Trevi=C3=B1o=20Cervantes?= Date: Fri, 23 Oct 2026 00:00:14 -0600 Subject: [PATCH] integration layer; merge work on indicators from forks with existing ingestion pipeline --- Dockerfile | 17 +- angular.json | 7 +- nginx.conf | 23 + package-lock.json | 7 + package.json | 1 + proxy.conf.json | 10 + src/_theme-colors.scss | 137 + src/app/app.config.ts | 4 +- src/app/app.html | 23 +- src/app/app.routes.ts | 29 +- src/app/app.scss | 23 +- src/app/app.spec.ts | 190 +- src/app/app.ts | 29 +- src/app/connect/api/api.types.ts | 247 + src/app/connect/api/connectors.api.ts | 18 + src/app/connect/api/data.api.ts | 15 + src/app/connect/api/document-source.api.ts | 25 + src/app/connect/api/file-encoding.ts | 10 + src/app/connect/api/file-source.api.ts | 24 + src/app/connect/api/imports.api.ts | 19 + src/app/connect/api/pdf-source.api.ts | 48 + src/app/connect/api/source-gateway.ts | 18 + src/app/connect/api/sql-source.api.ts | 42 + src/app/connect/api/targets.api.ts | 20 + .../column-mapper/column-mapper.html | 191 + .../column-mapper/column-mapper.scss | 340 ++ .../column-mapper/column-mapper.spec.ts | 54 + .../components/column-mapper/column-mapper.ts | 152 + .../components/connect-page/connect-page.html | 87 + .../components/connect-page/connect-page.scss | 115 + .../components/connect-page/connect-page.ts | 157 + .../connections-panel/connections-panel.html | 154 + .../connections-panel/connections-panel.scss | 217 + .../connections-panel/connections-panel.ts | 86 + .../connector-gallery-dialog.html | 138 + .../connector-gallery-dialog.scss | 120 + .../connector-gallery-dialog.ts | 172 + .../components/data-grid/data-grid.html | 82 + .../components/data-grid/data-grid.scss | 146 + .../connect/components/data-grid/data-grid.ts | 118 + .../database-explorer-dialog.html | 61 + .../database-explorer-dialog.scss | 76 + .../database-explorer-dialog.ts | 96 + .../document-review-dialog.html | 184 + .../document-review-dialog.scss | 228 + .../document-review-dialog.ts | 208 + .../file-dropzone/file-dropzone.html | 37 + .../file-dropzone/file-dropzone.scss | 157 + .../file-dropzone/file-dropzone.spec.ts | 104 + .../file-dropzone/file-dropzone.ts} | 56 +- .../components/flow-canvas/flow-canvas.html | 102 + .../components/flow-canvas/flow-canvas.scss | 167 + .../components/flow-canvas/flow-canvas.ts | 56 + .../components/flow-editor/flow-editor.html | 73 + .../components/flow-editor/flow-editor.scss | 101 + .../components/flow-editor/flow-editor.ts | 72 + .../components/load-dialog/load-dialog.html | 115 + .../components/load-dialog/load-dialog.scss | 60 + .../components/load-dialog/load-dialog.ts | 106 + .../new-flow-dialog/new-flow-dialog.ts | 74 + .../pdf-page-viewer/pdf-page-viewer.html | 56 + .../pdf-page-viewer/pdf-page-viewer.scss | 92 + .../pdf-page-viewer/pdf-page-viewer.spec.ts | 116 + .../pdf-page-viewer/pdf-page-viewer.ts | 105 + .../region-draw-overlay.directive.spec.ts | 136 + .../region-draw-overlay.directive.ts | 97 + .../pdf-regions-dialog.html | 74 + .../pdf-regions-dialog.scss | 72 + .../pdf-regions-dialog/pdf-regions-dialog.ts | 106 + .../components/shared/autofocus.directive.ts | 13 + .../connect/components/shared/flow-status.ts | 47 + .../shared/spanish-paginator-intl.ts | 18 + .../components/shared/type-icon.pipe.ts | 41 + .../sql-query-dialog/sql-query-dialog.ts | 116 + .../validation-report/validation-report.html | 99 + .../validation-report/validation-report.scss | 120 + .../validation-report/validation-report.ts | 100 + .../domain/connection-registry.spec.ts | 52 + src/app/connect/domain/connection-registry.ts | 52 + .../connect/domain/connector-catalog.spec.ts | 24 + src/app/connect/domain/connector-catalog.ts | 62 + src/app/connect/domain/data-source.ts | 121 + .../connect/domain/document-source.spec.ts | 60 + src/app/connect/domain/document-source.ts | 110 + src/app/connect/domain/eeg-source.ts | 52 + src/app/connect/domain/file-source.spec.ts | 47 + src/app/connect/domain/file-source.ts | 69 + src/app/connect/domain/import-flow.spec.ts | 95 + src/app/connect/domain/import-flow.ts | 264 + src/app/connect/domain/mapping-set.spec.ts | 44 + src/app/connect/domain/mapping-set.ts | 79 + src/app/connect/domain/pdf-source.ts | 117 + src/app/connect/domain/sql-source.spec.ts | 16 + src/app/connect/domain/sql-source.ts | 109 + src/app/connect/domain/sql-url.spec.ts | 12 + src/app/connect/domain/sql-url.ts | 24 + .../connect/domain/target-suggester.spec.ts | 29 + src/app/connect/domain/target-suggester.ts | 49 + .../state/connect-workspace.store.spec.ts | 122 + .../connect/state/connect-workspace.store.ts | 235 + src/app/connect/testing/fakes.ts | 84 + .../indicador-catalog-card.spec.ts | 123 + .../indicadores/indicador-catalog-card.ts | 108 + .../indicadores/indicador-figure-card.html | 58 + .../indicadores/indicador-figure-card.scss | 52 + .../indicadores/indicador-figure-card.spec.ts | 373 ++ .../indicadores/indicador-figure-card.ts | 120 + .../indicador-figure-panel.spec.ts | 333 ++ .../indicadores/indicador-figure-panel.ts | 136 + .../indicadores/indicador-kpi-card.spec.ts | 50 + .../indicadores/indicador-kpi-card.ts | 46 + .../indicadores/indicador-kpi-initial.spec.ts | 121 + .../indicadores/indicador-kpi-panel.spec.ts | 208 + .../indicadores/indicador-kpi-panel.ts | 100 + .../indicadores/indicador-period-filters.html | 66 + .../indicadores/indicador-period-filters.scss | 19 + .../indicador-period-filters.spec.ts | 138 + .../indicadores/indicador-period-filters.ts | 83 + .../indicadores-axis-labels.spec.ts | 230 + .../indicadores/indicadores-axis-labels.ts | 191 + .../indicadores-catalog-contract.spec.ts | 22 + .../indicadores-figure-labels.spec.ts | 28 + .../indicadores/indicadores-figure-labels.ts | 17 + .../indicadores-global-filters.spec.ts | 166 + .../features/indicadores/indicadores-http.ts | 10 + .../indicadores-identities.spec.ts | 9 + .../indicadores/indicadores-identities.ts | 12 + .../indicadores-kpi-cama-real.spec.ts | 145 + .../indicadores/indicadores-kpi-queries.ts | 23 + .../indicadores/indicadores-kpi.spec.ts | 62 + .../features/indicadores/indicadores-kpi.ts | 80 + .../indicadores/indicadores-memory.spec.ts | 103 + .../indicadores/indicadores-memory.ts | 103 + .../indicadores-navigation.spec.ts | 112 + .../indicadores/indicadores-page.html | 82 + .../indicadores/indicadores-page.scss | 60 + .../indicadores/indicadores-page.spec.ts | 328 ++ .../features/indicadores/indicadores-page.ts | 274 + .../indicadores-periodos-integration.spec.ts | 124 + .../indicadores/indicadores-periodos.spec.ts | 83 + .../indicadores-periodos.testing.ts | 23 + .../indicadores/indicadores-periodos.ts | 79 + .../indicadores/indicadores-pinning.spec.ts | 131 + .../indicadores-plotly-lifecycle.spec.ts | 102 + .../indicadores/indicadores-requests.ts | 35 + .../indicadores/indicadores-search.spec.ts | 224 + .../indicadores-visibility.spec.ts | 221 + .../indicadores-visual-profile.spec.ts | 228 + .../indicadores/indicadores-visual-profile.ts | 31 + .../indicadores/indicadores.models.spec.ts | 59 + .../indicadores/indicadores.models.ts | 60 + .../indicadores.presentation.spec.ts | 45 + .../indicadores/indicadores.presentation.ts | 161 + .../indicadores/indicadores.service.spec.ts | 120 + .../indicadores/indicadores.service.ts | 66 + .../indicadores.synthetic-fixtures.ts | 4654 +++++++++++++++++ src/app/governance/api/governance.api.ts | 108 + src/app/governance/api/governance.types.ts | 119 + .../cohort-exclusions-dialog.html | 61 + .../cohort-exclusions-dialog.scss | 32 + .../cohort-exclusions-dialog.ts | 51 + .../cohort-versions-panel.html | 79 + .../cohort-versions-panel.scss | 45 + .../cohort-versions-panel.ts | 110 + .../governance-page/governance-page.html | 26 + .../governance-page/governance-page.scss | 59 + .../governance-page/governance-page.ts | 19 + .../model-status-chip/model-status-chip.ts | 50 + .../model-version-dialog.html | 149 + .../model-version-dialog.scss | 113 + .../model-version-dialog.ts | 167 + .../model-versions-panel.html | 79 + .../model-versions-panel.scss | 72 + .../model-versions-panel.ts | 97 + .../ocr-correction-dialog.html | 43 + .../ocr-correction-dialog.scss | 57 + .../ocr-correction-dialog.ts | 116 + .../ocr-review-panel/ocr-review-panel.html | 89 + .../ocr-review-panel/ocr-review-panel.scss | 69 + .../ocr-review-panel/ocr-review-panel.ts | 182 + src/app/home.html | 20 +- src/app/home.scss | 18 + src/app/home.ts | 24 +- src/app/information-upload-dialog.html | 105 - src/app/information-upload-dialog.scss | 494 -- src/app/shared/plotly/plotly-chart.spec.ts | 67 + src/app/shared/plotly/plotly-chart.ts | 76 + .../shared/plotly/plotly-controller.spec.ts | 198 + src/app/shared/plotly/plotly-controller.ts | 87 + src/app/shared/plotly/plotly-runtime.spec.ts | 23 + src/app/shared/plotly/plotly-runtime.ts | 20 + src/app/shared/plotly/plotly.d.ts | 1 + src/index.html | 2 +- src/styles.scss | 73 +- 194 files changed, 21773 insertions(+), 848 deletions(-) create mode 100644 nginx.conf create mode 100644 proxy.conf.json create mode 100644 src/_theme-colors.scss create mode 100644 src/app/connect/api/api.types.ts create mode 100644 src/app/connect/api/connectors.api.ts create mode 100644 src/app/connect/api/data.api.ts create mode 100644 src/app/connect/api/document-source.api.ts create mode 100644 src/app/connect/api/file-encoding.ts create mode 100644 src/app/connect/api/file-source.api.ts create mode 100644 src/app/connect/api/imports.api.ts create mode 100644 src/app/connect/api/pdf-source.api.ts create mode 100644 src/app/connect/api/source-gateway.ts create mode 100644 src/app/connect/api/sql-source.api.ts create mode 100644 src/app/connect/api/targets.api.ts create mode 100644 src/app/connect/components/column-mapper/column-mapper.html create mode 100644 src/app/connect/components/column-mapper/column-mapper.scss create mode 100644 src/app/connect/components/column-mapper/column-mapper.spec.ts create mode 100644 src/app/connect/components/column-mapper/column-mapper.ts create mode 100644 src/app/connect/components/connect-page/connect-page.html create mode 100644 src/app/connect/components/connect-page/connect-page.scss create mode 100644 src/app/connect/components/connect-page/connect-page.ts create mode 100644 src/app/connect/components/connections-panel/connections-panel.html create mode 100644 src/app/connect/components/connections-panel/connections-panel.scss create mode 100644 src/app/connect/components/connections-panel/connections-panel.ts create mode 100644 src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.html create mode 100644 src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.scss create mode 100644 src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.ts create mode 100644 src/app/connect/components/data-grid/data-grid.html create mode 100644 src/app/connect/components/data-grid/data-grid.scss create mode 100644 src/app/connect/components/data-grid/data-grid.ts create mode 100644 src/app/connect/components/database-explorer-dialog/database-explorer-dialog.html create mode 100644 src/app/connect/components/database-explorer-dialog/database-explorer-dialog.scss create mode 100644 src/app/connect/components/database-explorer-dialog/database-explorer-dialog.ts create mode 100644 src/app/connect/components/document-review-dialog/document-review-dialog.html create mode 100644 src/app/connect/components/document-review-dialog/document-review-dialog.scss create mode 100644 src/app/connect/components/document-review-dialog/document-review-dialog.ts create mode 100644 src/app/connect/components/file-dropzone/file-dropzone.html create mode 100644 src/app/connect/components/file-dropzone/file-dropzone.scss create mode 100644 src/app/connect/components/file-dropzone/file-dropzone.spec.ts rename src/app/{information-upload-dialog.ts => connect/components/file-dropzone/file-dropzone.ts} (67%) create mode 100644 src/app/connect/components/flow-canvas/flow-canvas.html create mode 100644 src/app/connect/components/flow-canvas/flow-canvas.scss create mode 100644 src/app/connect/components/flow-canvas/flow-canvas.ts create mode 100644 src/app/connect/components/flow-editor/flow-editor.html create mode 100644 src/app/connect/components/flow-editor/flow-editor.scss create mode 100644 src/app/connect/components/flow-editor/flow-editor.ts create mode 100644 src/app/connect/components/load-dialog/load-dialog.html create mode 100644 src/app/connect/components/load-dialog/load-dialog.scss create mode 100644 src/app/connect/components/load-dialog/load-dialog.ts create mode 100644 src/app/connect/components/new-flow-dialog/new-flow-dialog.ts create mode 100644 src/app/connect/components/pdf-page-viewer/pdf-page-viewer.html create mode 100644 src/app/connect/components/pdf-page-viewer/pdf-page-viewer.scss create mode 100644 src/app/connect/components/pdf-page-viewer/pdf-page-viewer.spec.ts create mode 100644 src/app/connect/components/pdf-page-viewer/pdf-page-viewer.ts create mode 100644 src/app/connect/components/pdf-page-viewer/region-draw-overlay.directive.spec.ts create mode 100644 src/app/connect/components/pdf-page-viewer/region-draw-overlay.directive.ts create mode 100644 src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.html create mode 100644 src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.scss create mode 100644 src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.ts create mode 100644 src/app/connect/components/shared/autofocus.directive.ts create mode 100644 src/app/connect/components/shared/flow-status.ts create mode 100644 src/app/connect/components/shared/spanish-paginator-intl.ts create mode 100644 src/app/connect/components/shared/type-icon.pipe.ts create mode 100644 src/app/connect/components/sql-query-dialog/sql-query-dialog.ts create mode 100644 src/app/connect/components/validation-report/validation-report.html create mode 100644 src/app/connect/components/validation-report/validation-report.scss create mode 100644 src/app/connect/components/validation-report/validation-report.ts create mode 100644 src/app/connect/domain/connection-registry.spec.ts create mode 100644 src/app/connect/domain/connection-registry.ts create mode 100644 src/app/connect/domain/connector-catalog.spec.ts create mode 100644 src/app/connect/domain/connector-catalog.ts create mode 100644 src/app/connect/domain/data-source.ts create mode 100644 src/app/connect/domain/document-source.spec.ts create mode 100644 src/app/connect/domain/document-source.ts create mode 100644 src/app/connect/domain/eeg-source.ts create mode 100644 src/app/connect/domain/file-source.spec.ts create mode 100644 src/app/connect/domain/file-source.ts create mode 100644 src/app/connect/domain/import-flow.spec.ts create mode 100644 src/app/connect/domain/import-flow.ts create mode 100644 src/app/connect/domain/mapping-set.spec.ts create mode 100644 src/app/connect/domain/mapping-set.ts create mode 100644 src/app/connect/domain/pdf-source.ts create mode 100644 src/app/connect/domain/sql-source.spec.ts create mode 100644 src/app/connect/domain/sql-source.ts create mode 100644 src/app/connect/domain/sql-url.spec.ts create mode 100644 src/app/connect/domain/sql-url.ts create mode 100644 src/app/connect/domain/target-suggester.spec.ts create mode 100644 src/app/connect/domain/target-suggester.ts create mode 100644 src/app/connect/state/connect-workspace.store.spec.ts create mode 100644 src/app/connect/state/connect-workspace.store.ts create mode 100644 src/app/connect/testing/fakes.ts create mode 100644 src/app/features/indicadores/indicador-catalog-card.spec.ts create mode 100644 src/app/features/indicadores/indicador-catalog-card.ts create mode 100644 src/app/features/indicadores/indicador-figure-card.html create mode 100644 src/app/features/indicadores/indicador-figure-card.scss create mode 100644 src/app/features/indicadores/indicador-figure-card.spec.ts create mode 100644 src/app/features/indicadores/indicador-figure-card.ts create mode 100644 src/app/features/indicadores/indicador-figure-panel.spec.ts create mode 100644 src/app/features/indicadores/indicador-figure-panel.ts create mode 100644 src/app/features/indicadores/indicador-kpi-card.spec.ts create mode 100644 src/app/features/indicadores/indicador-kpi-card.ts create mode 100644 src/app/features/indicadores/indicador-kpi-initial.spec.ts create mode 100644 src/app/features/indicadores/indicador-kpi-panel.spec.ts create mode 100644 src/app/features/indicadores/indicador-kpi-panel.ts create mode 100644 src/app/features/indicadores/indicador-period-filters.html create mode 100644 src/app/features/indicadores/indicador-period-filters.scss create mode 100644 src/app/features/indicadores/indicador-period-filters.spec.ts create mode 100644 src/app/features/indicadores/indicador-period-filters.ts create mode 100644 src/app/features/indicadores/indicadores-axis-labels.spec.ts create mode 100644 src/app/features/indicadores/indicadores-axis-labels.ts create mode 100644 src/app/features/indicadores/indicadores-catalog-contract.spec.ts create mode 100644 src/app/features/indicadores/indicadores-figure-labels.spec.ts create mode 100644 src/app/features/indicadores/indicadores-figure-labels.ts create mode 100644 src/app/features/indicadores/indicadores-global-filters.spec.ts create mode 100644 src/app/features/indicadores/indicadores-http.ts create mode 100644 src/app/features/indicadores/indicadores-identities.spec.ts create mode 100644 src/app/features/indicadores/indicadores-identities.ts create mode 100644 src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts create mode 100644 src/app/features/indicadores/indicadores-kpi-queries.ts create mode 100644 src/app/features/indicadores/indicadores-kpi.spec.ts create mode 100644 src/app/features/indicadores/indicadores-kpi.ts create mode 100644 src/app/features/indicadores/indicadores-memory.spec.ts create mode 100644 src/app/features/indicadores/indicadores-memory.ts create mode 100644 src/app/features/indicadores/indicadores-navigation.spec.ts create mode 100644 src/app/features/indicadores/indicadores-page.html create mode 100644 src/app/features/indicadores/indicadores-page.scss create mode 100644 src/app/features/indicadores/indicadores-page.spec.ts create mode 100644 src/app/features/indicadores/indicadores-page.ts create mode 100644 src/app/features/indicadores/indicadores-periodos-integration.spec.ts create mode 100644 src/app/features/indicadores/indicadores-periodos.spec.ts create mode 100644 src/app/features/indicadores/indicadores-periodos.testing.ts create mode 100644 src/app/features/indicadores/indicadores-periodos.ts create mode 100644 src/app/features/indicadores/indicadores-pinning.spec.ts create mode 100644 src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts create mode 100644 src/app/features/indicadores/indicadores-requests.ts create mode 100644 src/app/features/indicadores/indicadores-search.spec.ts create mode 100644 src/app/features/indicadores/indicadores-visibility.spec.ts create mode 100644 src/app/features/indicadores/indicadores-visual-profile.spec.ts create mode 100644 src/app/features/indicadores/indicadores-visual-profile.ts create mode 100644 src/app/features/indicadores/indicadores.models.spec.ts create mode 100644 src/app/features/indicadores/indicadores.models.ts create mode 100644 src/app/features/indicadores/indicadores.presentation.spec.ts create mode 100644 src/app/features/indicadores/indicadores.presentation.ts create mode 100644 src/app/features/indicadores/indicadores.service.spec.ts create mode 100644 src/app/features/indicadores/indicadores.service.ts create mode 100644 src/app/features/indicadores/indicadores.synthetic-fixtures.ts create mode 100644 src/app/governance/api/governance.api.ts create mode 100644 src/app/governance/api/governance.types.ts create mode 100644 src/app/governance/components/cohort-exclusions-dialog/cohort-exclusions-dialog.html create mode 100644 src/app/governance/components/cohort-exclusions-dialog/cohort-exclusions-dialog.scss create mode 100644 src/app/governance/components/cohort-exclusions-dialog/cohort-exclusions-dialog.ts create mode 100644 src/app/governance/components/cohort-versions-panel/cohort-versions-panel.html create mode 100644 src/app/governance/components/cohort-versions-panel/cohort-versions-panel.scss create mode 100644 src/app/governance/components/cohort-versions-panel/cohort-versions-panel.ts create mode 100644 src/app/governance/components/governance-page/governance-page.html create mode 100644 src/app/governance/components/governance-page/governance-page.scss create mode 100644 src/app/governance/components/governance-page/governance-page.ts create mode 100644 src/app/governance/components/model-status-chip/model-status-chip.ts create mode 100644 src/app/governance/components/model-version-dialog/model-version-dialog.html create mode 100644 src/app/governance/components/model-version-dialog/model-version-dialog.scss create mode 100644 src/app/governance/components/model-version-dialog/model-version-dialog.ts create mode 100644 src/app/governance/components/model-versions-panel/model-versions-panel.html create mode 100644 src/app/governance/components/model-versions-panel/model-versions-panel.scss create mode 100644 src/app/governance/components/model-versions-panel/model-versions-panel.ts create mode 100644 src/app/governance/components/ocr-correction-dialog/ocr-correction-dialog.html create mode 100644 src/app/governance/components/ocr-correction-dialog/ocr-correction-dialog.scss create mode 100644 src/app/governance/components/ocr-correction-dialog/ocr-correction-dialog.ts create mode 100644 src/app/governance/components/ocr-review-panel/ocr-review-panel.html create mode 100644 src/app/governance/components/ocr-review-panel/ocr-review-panel.scss create mode 100644 src/app/governance/components/ocr-review-panel/ocr-review-panel.ts delete mode 100644 src/app/information-upload-dialog.html delete mode 100644 src/app/information-upload-dialog.scss create mode 100644 src/app/shared/plotly/plotly-chart.spec.ts create mode 100644 src/app/shared/plotly/plotly-chart.ts create mode 100644 src/app/shared/plotly/plotly-controller.spec.ts create mode 100644 src/app/shared/plotly/plotly-controller.ts create mode 100644 src/app/shared/plotly/plotly-runtime.spec.ts create mode 100644 src/app/shared/plotly/plotly-runtime.ts create mode 100644 src/app/shared/plotly/plotly.d.ts diff --git a/Dockerfile b/Dockerfile index aebd4d1..f0d4b22 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,10 +1,15 @@ -FROM node:22-slim - +# Production image: build the Angular app, serve the static bundle with +# nginx, and reverse-proxy the API paths to the `webapi` compose service — +# the same routing `proxy.conf.json` gives `ng serve` in development, so the +# app's relative `/imports`, `/data`, ... calls work unchanged. +FROM node:22-slim AS build WORKDIR /app COPY package.json package-lock.json* ./ -RUN npm install - +RUN npm ci COPY . . +RUN npx ng build --configuration production -EXPOSE 4200 -CMD ["npx", "ng", "serve", "--host", "0.0.0.0", "--port", "4200"] +FROM nginx:1.27-alpine +COPY nginx.conf /etc/nginx/conf.d/default.conf +COPY --from=build /app/dist/WebApp/browser /usr/share/nginx/html +EXPOSE 80 diff --git a/angular.json b/angular.json index d3f5a4a..52b923c 100644 --- a/angular.json +++ b/angular.json @@ -44,8 +44,8 @@ }, { "type": "anyComponentStyle", - "maximumWarning": "4kB", - "maximumError": "8kB" + "maximumWarning": "6kB", + "maximumError": "10kB" } ], "outputHashing": "all" @@ -60,6 +60,9 @@ }, "serve": { "builder": "@angular/build:dev-server", + "options": { + "proxyConfig": "proxy.conf.json" + }, "configurations": { "production": { "buildTarget": "WebApp:build:production" diff --git a/nginx.conf b/nginx.conf new file mode 100644 index 0000000..7f5d0fc --- /dev/null +++ b/nginx.conf @@ -0,0 +1,23 @@ +server { + listen 80; + server_name _; + root /usr/share/nginx/html; + + # Files travel inside the import requests (multipart or base64 JSON): + # keep this above WebApi's WEBAPI_MAX_UPLOAD_MB (200 MB default) plus + # the ~33% base64 overhead. + client_max_body_size 270m; + + location ~ ^/(api|imports|data|cacu|cama|tea|governance|health)(/|$) { + proxy_pass http://webapi:5000; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + # OCR over a stack of scanned pages takes a while. + proxy_read_timeout 600s; + } + + location / { + try_files $uri $uri/ /index.html; + } +} diff --git a/package-lock.json b/package-lock.json index 0f2ebd5..a70b188 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,6 +16,7 @@ "@angular/material": "^22.1.7", "@angular/platform-browser": "^22.1.0", "@angular/router": "^22.1.0", + "plotly.js-cartesian-dist-min": "4.1.2", "rxjs": "~7.8.0", "tslib": "^2.3.0" }, @@ -6481,6 +6482,12 @@ "node": ">=16.20.0" } }, + "node_modules/plotly.js-cartesian-dist-min": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/plotly.js-cartesian-dist-min/-/plotly.js-cartesian-dist-min-4.1.2.tgz", + "integrity": "sha512-3UkyAT7/U8f3sOLavLnUjA6mqFmnqEe246GZhxT0J3TT9oZ0mh6SgwsL1yo/3/4xfmRSDFdGOxe+EsvT2XiE0g==", + "license": "MIT" + }, "node_modules/postcss": { "version": "8.5.28", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", diff --git a/package.json b/package.json index f86bd9c..62be094 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,7 @@ "@angular/material": "^22.1.7", "@angular/platform-browser": "^22.1.0", "@angular/router": "^22.1.0", + "plotly.js-cartesian-dist-min": "4.1.2", "rxjs": "~7.8.0", "tslib": "^2.3.0" }, diff --git a/proxy.conf.json b/proxy.conf.json new file mode 100644 index 0000000..acc8f30 --- /dev/null +++ b/proxy.conf.json @@ -0,0 +1,10 @@ +{ + "/api": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true }, + "/imports": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true }, + "/data": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true }, + "/health": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true }, + "/cacu": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true }, + "/cama": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true }, + "/tea": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true }, + "/governance": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true } +} diff --git a/src/_theme-colors.scss b/src/_theme-colors.scss new file mode 100644 index 0000000..36ac7b0 --- /dev/null +++ b/src/_theme-colors.scss @@ -0,0 +1,137 @@ +// This file was generated by running 'ng generate @angular/material:theme-color'. +// Proceed with caution if making changes to this file. + +@use 'sass:map'; +@use '@angular/material' as mat; + +// Note: Color palettes are generated from primary: #a8c243, tertiary: #5f9ea0, neutral: #5c5f66 +$_palettes: ( + primary: ( + 0: #000000, + 10: #171e00, + 20: #2a3400, + 25: #344000, + 30: #3e4c00, + 35: #495900, + 40: #546500, + 50: #6a8000, + 60: #829a1c, + 70: #9cb638, + 80: #b7d251, + 90: #d3ef6a, + 95: #e1fd77, + 98: #f5ffc6, + 99: #faffe3, + 100: #ffffff, + ), + secondary: ( + 0: #000000, + 10: #171e00, + 20: #2b3407, + 25: #363f12, + 30: #414b1c, + 35: #4d5727, + 40: #596332, + 50: #717c48, + 60: #8b965f, + 70: #a5b177, + 80: #c1cc90, + 90: #dde9aa, + 95: #ebf7b7, + 98: #f5ffc6, + 99: #faffe3, + 100: #ffffff, + ), + tertiary: ( + 0: #000000, + 10: #002021, + 20: #003738, + 25: #004345, + 30: #004f51, + 35: #145b5e, + 40: #25686a, + 50: #418183, + 60: #5c9b9d, + 70: #77b6b8, + 80: #92d2d3, + 90: #aeeef0, + 95: #bcfcfe, + 98: #e3ffff, + 99: #f1ffff, + 100: #ffffff, + ), + neutral: ( + 0: #000000, + 10: #181c22, + 20: #2d3037, + 25: #383b42, + 30: #44474d, + 35: #4f5259, + 40: #5b5e65, + 50: #74777e, + 60: #8e9198, + 70: #a9abb3, + 80: #c4c6ce, + 90: #e0e2ea, + 95: #eff0f9, + 98: #f9f9ff, + 99: #fdfcff, + 100: #ffffff, + 4: #0b0e14, + 6: #101419, + 12: #1c2026, + 17: #272a30, + 22: #32353b, + 24: #363940, + 87: #d8dae2, + 92: #e6e8f0, + 94: #ecedf6, + 96: #f1f3fc, + ), + neutral-variant: ( + 0: #000000, + 10: #1a1d0f, + 20: #2f3222, + 25: #3a3d2d, + 30: #454837, + 35: #515442, + 40: #5d604e, + 50: #767965, + 60: #90927e, + 70: #aaad98, + 80: #c6c8b2, + 90: #e2e4cd, + 95: #f1f3db, + 98: #f9fbe3, + 99: #fcfdf1, + 100: #ffffff, + ), + error: ( + 0: #000000, + 10: #410002, + 20: #690005, + 25: #7e0007, + 30: #93000a, + 35: #a80710, + 40: #ba1a1a, + 50: #de3730, + 60: #ff5449, + 70: #ff897d, + 80: #ffb4ab, + 90: #ffdad6, + 95: #ffedea, + 98: #fff8f7, + 99: #fffbff, + 100: #ffffff, + ), +); + +$_rest: ( + secondary: map.get($_palettes, secondary), + neutral: map.get($_palettes, neutral), + neutral-variant: map.get($_palettes, neutral-variant), + error: map.get($_palettes, error), +); + +$primary-palette: map.merge(map.get($_palettes, primary), $_rest); +$tertiary-palette: map.merge(map.get($_palettes, tertiary), $_rest); diff --git a/src/app/app.config.ts b/src/app/app.config.ts index e60fc79..d9c42bd 100644 --- a/src/app/app.config.ts +++ b/src/app/app.config.ts @@ -1,10 +1,12 @@ import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core'; +import { provideHttpClient } from '@angular/common/http'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; export const appConfig: ApplicationConfig = { providers: [ provideBrowserGlobalErrorListeners(), - provideRouter(routes) + provideRouter(routes), + provideHttpClient(), ] }; diff --git a/src/app/app.html b/src/app/app.html index d52a576..b41af08 100644 --- a/src/app/app.html +++ b/src/app/app.html @@ -1,10 +1,15 @@ -
+
@@ -12,9 +17,11 @@ -
- -
+ @if (!workspace()) { +
+ +
+ }
diff --git a/src/app/app.routes.ts b/src/app/app.routes.ts index 9742bb2..943d41c 100644 --- a/src/app/app.routes.ts +++ b/src/app/app.routes.ts @@ -1,4 +1,31 @@ import { Routes } from '@angular/router'; import { Home } from './home'; +import { DOMINIOS } from './features/indicadores/indicadores.models'; -export const routes: Routes = [{ path: '', component: Home }]; +const loadIndicadores = () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage); + +export const routes: Routes = [ + { path: '', component: Home, title: 'Análisis de información | ISSSTELEON' }, + { + path: 'conectar', + title: 'Conectar datos | ISSSTELEON', + // Lazy: the workspace (and the ~15 Material modules it uses) only + // downloads when someone actually opens it. + loadComponent: () => import('./connect/components/connect-page/connect-page').then((m) => m.ConnectPage), + data: { workspace: true, breadcrumb: 'Conectar datos' }, + }, + { + path: 'gobernanza', + title: 'Gobernanza de modelos | ISSSTELEON', + loadComponent: () => import('./governance/components/governance-page/governance-page').then((m) => m.GovernancePage), + data: { workspace: true, breadcrumb: 'Gobernanza de modelos' }, + }, + { path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' }, + ...DOMINIOS.map(dominio => ({ + path: `indicadores/${dominio}`, + title: 'Indicadores | ISSSTELEON', + data: { workspace: true, breadcrumb: 'Indicadores', dominio }, + loadComponent: loadIndicadores, + })), + { path: '**', redirectTo: '' }, +]; diff --git a/src/app/app.scss b/src/app/app.scss index 4462be8..234d0f1 100644 --- a/src/app/app.scss +++ b/src/app/app.scss @@ -14,7 +14,7 @@ align-items: center; display: flex; justify-content: space-between; - min-height: 88px; + min-height: var(--site-header-height); padding: 0 clamp(32px, 3.2vw, 48px); } @@ -29,7 +29,20 @@ width: clamp(180px, 16vw, 200px); } +.site-header__nav { + align-items: center; + display: flex; + gap: 6px; +} + +.site-header__crumb { + color: var(--color-primary); + font-size: 15px; + font-weight: 600; +} + .site-header__section { + text-decoration: none; color: var(--color-text); font-size: 15px; font-weight: 500; @@ -39,6 +52,12 @@ .app-main { display: flex; flex: 1; + min-height: 0; +} + +.app-shell--workspace { + height: 100dvh; + overflow: hidden; } .site-footer { @@ -62,7 +81,7 @@ @media (max-width: 600px) { .site-header__content { - min-height: 70px; + min-height: var(--site-header-height); padding: 0 20px; } diff --git a/src/app/app.spec.ts b/src/app/app.spec.ts index 6c32756..f849d1f 100644 --- a/src/app/app.spec.ts +++ b/src/app/app.spec.ts @@ -1,6 +1,7 @@ import { TestBed } from '@angular/core/testing'; import { provideRouter, Router } from '@angular/router'; -import { MatDialog } from '@angular/material/dialog'; +import { provideHttpClient } from '@angular/common/http'; +import { provideHttpClientTesting } from '@angular/common/http/testing'; import { App } from './app'; import { routes } from './app.routes'; @@ -8,175 +9,38 @@ describe('App', () => { beforeEach(async () => { await TestBed.configureTestingModule({ imports: [App], - providers: [provideRouter(routes)], + providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()], }).compileComponents(); }); - it('should create the app', () => { + async function render(url: string) { const fixture = TestBed.createComponent(App); - const app = fixture.componentInstance; - expect(app).toBeTruthy(); + fixture.detectChanges(); + await TestBed.inject(Router).navigateByUrl(url); + await fixture.whenStable(); + fixture.detectChanges(); + return fixture.nativeElement as HTMLElement; + } + + it('renders the ISSSTELEON shell and home page with its footer', async () => { + const page = await render('/'); + expect(page.querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON'); + expect(page.querySelector('h1')?.textContent).toContain('Analiza tu información'); + expect(page.querySelector('.home__action')?.getAttribute('href')).toBe('/conectar'); + expect(page.querySelector('.site-footer')).not.toBeNull(); }); - it('should render the ISSSTELEON header and home page', async () => { - const fixture = TestBed.createComponent(App); - fixture.detectChanges(); - await TestBed.inject(Router).navigateByUrl('/'); - await fixture.whenStable(); - fixture.detectChanges(); - const compiled = fixture.nativeElement as HTMLElement; - expect(compiled.querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON'); - expect(compiled.querySelector('.site-header__section')?.textContent).toContain( - 'Análisis de información', - ); - expect(compiled.querySelector('h1')?.textContent).toContain('Analiza tu información'); + it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => { + const page = await render('/conectar'); + expect(page.querySelector('app-connect-page')).not.toBeNull(); + expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Conectar datos'); + expect(page.querySelector('.site-footer')).toBeNull(); }); - it('opens one dialog and keeps it open on backdrop and Escape', async () => { - const fixture = TestBed.createComponent(App); - fixture.detectChanges(); - await TestBed.inject(Router).navigateByUrl('/'); - await fixture.whenStable(); - fixture.detectChanges(); - - fixture.nativeElement.querySelector('.home__action').click(); - fixture.detectChanges(); - await fixture.whenStable(); - - const dialog = TestBed.inject(MatDialog); - expect(dialog.openDialogs).toHaveLength(1); - const overlay = document.querySelector('.cdk-overlay-container')!; - expect(overlay.querySelector('#upload-title')?.textContent).toContain('Cargar información'); - overlay.querySelector('.cdk-overlay-backdrop')?.click(); - document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); - expect(dialog.openDialogs).toHaveLength(1); - expect(overlay.querySelector('.upload-dialog__continue')?.hasAttribute('disabled')).toBe(true); - }); - - it('selects either source, continues, returns with selection, and closes explicitly', async () => { - const fixture = TestBed.createComponent(App); - fixture.detectChanges(); - await TestBed.inject(Router).navigateByUrl('/'); - await fixture.whenStable(); - fixture.detectChanges(); - - fixture.nativeElement.querySelector('.home__action').click(); - fixture.detectChanges(); - await fixture.whenStable(); - - const overlay = document.querySelector('.cdk-overlay-container')!; - const cards = () => overlay.querySelectorAll('.source-card'); - const continueButton = overlay.querySelector('.upload-dialog__continue')!; - const detectDialogChanges = () => TestBed.inject(MatDialog).openDialogs[0].componentRef?.changeDetectorRef.detectChanges(); - expect(continueButton.disabled).toBe(true); - overlay.querySelector('.source-card')!.click(); - detectDialogChanges(); - expect(continueButton.disabled).toBe(false); - continueButton.click(); - detectDialogChanges(); - fixture.detectChanges(); - expect(overlay.querySelector('.upload-dialog__description')?.textContent).toContain( - 'Selecciona los archivos que deseas procesar.', - ); - expect(overlay.querySelector('.upload-steps__item--active')?.textContent).toContain( - 'Configuración', - ); - expect(continueButton.disabled).toBe(true); - const fileInput = overlay.querySelector('input[type="file"]')!; - const validFile = new File(['contenido'], 'pacientes.XLSX', { - type: 'application/octet-stream', - }); - const csvFile = new File(['a,b'], 'consultas.csv', { type: 'text/csv' }); - const invalidFile = new File(['x'], 'documento.docx'); - const emptyFile = new File([], 'vacio.csv'); - const selectFiles = (...files: File[]) => { - Object.defineProperty(fileInput, 'files', { configurable: true, value: files }); - fileInput.dispatchEvent(new Event('change', { bubbles: true })); - detectDialogChanges(); - fixture.detectChanges(); - }; - selectFiles(validFile, csvFile, invalidFile, emptyFile); - expect(overlay.querySelectorAll('.file-row')).toHaveLength(2); - expect(overlay.querySelector('.file-messages')?.textContent).toContain( - 'documento.docx no fue agregado. Formato no compatible.', - ); - expect(overlay.querySelector('.file-messages')?.textContent).toContain( - 'vacio.csv no fue agregado. El archivo está vacío.', - ); - expect(continueButton.disabled).toBe(false); - selectFiles(validFile); - expect(overlay.querySelectorAll('.file-row')).toHaveLength(2); - expect(overlay.querySelector('.file-messages')?.textContent).toContain( - 'pacientes.XLSX ya se encuentra seleccionado.', - ); - const jsonFile = new File(['{}'], 'nuevo.json', { type: 'application/json' }); - const dialogComponent = TestBed.inject(MatDialog).openDialogs[0].componentRef! - .instance as import('./information-upload-dialog').InformationUploadDialog; - dialogComponent.onDrop({ - preventDefault: () => undefined, - dataTransfer: { files: [jsonFile] }, - } as unknown as DragEvent); - detectDialogChanges(); - fixture.detectChanges(); - expect(overlay.querySelectorAll('.file-row')).toHaveLength(3); - overlay.querySelector('.file-row__remove')!.click(); - detectDialogChanges(); - fixture.detectChanges(); - expect(overlay.querySelectorAll('.file-row')).toHaveLength(2); - continueButton.click(); - detectDialogChanges(); - fixture.detectChanges(); - expect(overlay.querySelector('h3')?.textContent).toContain('Confirmación'); - expect(overlay.querySelector('.configuration-placeholder p')?.textContent).toContain( - 'La confirmación de los archivos se implementará en la siguiente fase.', - ); - overlay.querySelector('.upload-dialog__back')!.click(); - detectDialogChanges(); - fixture.detectChanges(); - expect(overlay.querySelectorAll('.file-row')).toHaveLength(2); - while (overlay.querySelector('.file-row__remove')) { - overlay.querySelector('.file-row__remove')!.click(); - detectDialogChanges(); - fixture.detectChanges(); - } - expect(overlay.querySelectorAll('.file-row')).toHaveLength(0); - expect(overlay.querySelector('.upload-dialog__continue')?.disabled).toBe(true); - overlay.querySelector('.upload-dialog__back')!.click(); - detectDialogChanges(); - fixture.detectChanges(); - expect(cards()[0].getAttribute('aria-pressed')).toBe('true'); - overlay.querySelectorAll('.source-card')[1].click(); - detectDialogChanges(); - const sqlContinueButton = overlay.querySelector('.upload-dialog__continue')!; - expect(sqlContinueButton.disabled).toBe(false); - sqlContinueButton.click(); - detectDialogChanges(); - fixture.detectChanges(); - expect(overlay.querySelector('h3')?.textContent).toContain('Conexión SQL'); - expect(overlay.querySelector('.upload-dialog__continue')?.disabled).toBe(true); - overlay.querySelector('.upload-dialog__back')!.click(); - detectDialogChanges(); - fixture.detectChanges(); - expect(cards()[1].getAttribute('aria-pressed')).toBe('true'); - overlay.querySelector('.upload-dialog__close')!.click(); - fixture.detectChanges(); - await new Promise((resolve) => setTimeout(resolve, 200)); - expect(TestBed.inject(MatDialog).openDialogs).toHaveLength(0); - - fixture.nativeElement.querySelector('.home__action').click(); - fixture.detectChanges(); - await fixture.whenStable(); - const reopenedOverlay = document.querySelector('.cdk-overlay-container')!; - reopenedOverlay.querySelector('.source-card')!.click(); - const reopenedDialog = TestBed.inject(MatDialog).openDialogs[0].componentRef!; - reopenedDialog.changeDetectorRef.detectChanges(); - reopenedOverlay.querySelector('.upload-dialog__continue')!.click(); - reopenedDialog.changeDetectorRef.detectChanges(); - expect(reopenedOverlay.querySelector('.selected-files')).toBeNull(); - expect(reopenedOverlay.querySelector('.upload-dialog__continue')?.disabled).toBe(true); - reopenedOverlay.querySelector('.upload-dialog__cancel')!.click(); - fixture.detectChanges(); - await new Promise((resolve) => setTimeout(resolve, 200)); - expect(TestBed.inject(MatDialog).openDialogs).toHaveLength(0); + it('/gobernanza opens the governance workspace (breadcrumb, no footer)', async () => { + const page = await render('/gobernanza'); + expect(page.querySelector('app-governance-page')).not.toBeNull(); + expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Gobernanza de modelos'); + expect(page.querySelector('.site-footer')).toBeNull(); }); }); diff --git a/src/app/app.ts b/src/app/app.ts index 3e7d97c..b18cd4e 100644 --- a/src/app/app.ts +++ b/src/app/app.ts @@ -1,10 +1,31 @@ -import { Component } from '@angular/core'; -import { RouterOutlet } from '@angular/router'; +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'; @Component({ - imports: [RouterOutlet], + imports: [RouterLink, RouterOutlet], selector: 'app-root', styleUrl: './app.scss', templateUrl: './app.html', }) -export class App {} +export class App { + private readonly router = inject(Router); + private readonly route = inject(ActivatedRoute); + + private readonly leafRouteData = toSignal( + this.router.events.pipe( + filter((event) => event instanceof NavigationEnd), + map(() => { + let route = this.route; + while (route.firstChild) route = route.firstChild; + return route.snapshot.data; + }), + ), + { initialValue: {} as Record }, + ); + + /** 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); +} diff --git a/src/app/connect/api/api.types.ts b/src/app/connect/api/api.types.ts new file mode 100644 index 0000000..30e9cf9 --- /dev/null +++ b/src/app/connect/api/api.types.ts @@ -0,0 +1,247 @@ +/** Shapes of the WebApi JSON contract for `/imports/*` and `/data/*`. */ + +export type Domain = 'cacu' | 'cama' | 'tea'; + +export type InferredType = 'string' | 'integer' | 'float' | 'boolean' | 'date' | 'datetime' | 'binary' | 'unknown'; + +export type MatchReason = 'exact' | 'normalized' | 'synonym' | 'unprefixed' | 'fuzzy' | 'none'; + +export type ConflictStrategy = 'reject' | 'upsert'; + +export type ErrorCategory = 'missing' | 'out_of_catalog' | 'type_invalid' | 'conflict' | 'merge_conflict' | 'unknown'; + +export type FileKind = 'csv' | 'excel' | 'json'; + +export type SourceType = FileKind | 'sql' | 'pdf' | 'edf' | 'document'; + +/** Backend connector categories (`GET /imports/connectors`). */ +export type ConnectorCategory = 'file' | 'database' | 'document' | 'signal'; + +export interface SqlEngineInfo { + id: string; + label: string; + description: string; + default_port: number; + default_schema: string | null; + /** Whether the server has the driver installed. */ + available: boolean; +} + +export interface SegmentationInfo { + id: string; + label: string; +} + +export interface ConnectorInfo { + kind: SourceType; + label: string; + description: string; + category: ConnectorCategory; + icon: string; + extensions: string[]; + engines?: SqlEngineInfo[]; + segmentations?: SegmentationInfo[]; +} + +/** How a database is reached: form fields, or a raw SQLAlchemy URL. */ +export type SqlConnectionRef = + | { server: { engine: string; host: string; port: number | null; database: string; user: string; password: string } } + | { connection_string: string }; + +export interface TargetField { + name: string; + required: boolean; + /** JSON-schema type or format: string, integer, number, boolean, date, date-time, binary... */ + type: string; +} + +export interface TargetMeta { + key: string; + domain: Domain; + table: string; + conflict_fields: string[] | null; + fields: TargetField[]; +} + +export interface SourceColumn { + name: string; + inferred_type: InferredType; +} + +export interface SuggestedMapping { + source_column: string; + target_field: string | null; + confidence: number; + reason: MatchReason; +} + +export type Row = Record; + +export interface PreviewResponse { + columns: SourceColumn[]; + sample_rows: Row[]; + total_rows: number | null; + suggested_mapping: SuggestedMapping[]; + /** Sub-tables the source offers (Excel sheets...), with the options to read each. */ + tables?: { name: string; options: Record; kind: string }[]; + source_metadata?: Record; +} + +export interface FileOptions { + sheet_name?: string; + delimiter?: string; + encoding?: string; + record_path?: string; +} + +export interface TableCandidate { + page_number: number; + bbox: [number, number, number, number]; // PDF points + column_count: number; + row_count: number; + preview_grid: (string | null)[][]; +} + +export interface PdfDetectResponse { + page_count: number; + has_text_layer: boolean; + table_candidates: TableCandidate[]; +} + +export interface RegionSpec { + /** The name this region's text becomes as a source column. */ + target_field: string; + page_numbers: number[]; + bbox: [number, number, number, number]; // normalized 0..1 +} + +export interface RegionExtractResponse { + columns: SourceColumn[]; + rows: Row[]; + warnings: { page_number: number; message: string }[]; + suggested_mapping: SuggestedMapping[]; +} + +/** The `{source_type, payload}` part of a source, as built by its SourceTable. */ +export interface SourceLocator { + source_type: SourceType; + payload: Record; +} + +/** One entry of `/imports/validate`'s `source` / `/imports/commit`'s `sources`. */ +export interface ImportSourcePayload extends SourceLocator { + target: string; + label?: string; + column_mapping: Record; + defaults?: Record; +} + +// -- documents ----------------------------------------------------------------- + +export type OcrMode = 'auto' | 'always' | 'never'; + +export interface DocumentSettings { + segmentation: string; + pages_per_record: number; + ocr_mode: OcrMode; + key_pattern: string; +} + +export interface ExtractedField { + value: unknown; + confidence: number; + /** etiqueta | patron | texto_libre | manual */ + method: string; + raw?: string; + document?: string; + page_number?: number; + line?: string; + bbox?: [number, number, number, number] | null; +} + +export interface DocumentImage { + document: string; + page_number: number; + bbox: [number, number, number, number]; + kind: 'scan' | 'figure'; +} + +export interface ExtractedRecord { + index: number; + key: string | null; + confidence: number; + fields: Record; + missing: string[]; + conflicts: { field: string; kept: ExtractedField; discarded: ExtractedField }[]; + sources: { document: string; page_numbers: number[] }[]; + images: DocumentImage[]; +} + +export interface DocumentFieldSpec { + name: string; + kind: 'text' | 'identifier' | 'integer' | 'decimal' | 'date' | 'choice'; + required: boolean; + labels: string[]; +} + +export interface DocumentExtraction extends PreviewResponse { + key_field: string | null; + fields: DocumentFieldSpec[]; + records: ExtractedRecord[]; +} + +export interface RowError { + row_index: number; + field: string; + category: ErrorCategory; + message: string; + raw_value?: unknown; +} + +export interface ValidationResult { + total_rows: number; + valid_count: number; + error_count: number; + errors: RowError[]; +} + +export interface CommitSourceResult { + target: string; + label: string | null; + total: number; + created: number; + updated: number; + rejected: number; + errors: RowError[]; + /** Foreign keys filled from natural keys, e.g. `{pac_id: 12}`. */ + linked?: Record; + /** Rows combined into a row of another source (`merge_duplicates`). */ + merged?: number; + warnings?: RowError[]; +} + +export interface BatchResult { + ok: boolean; + results: CommitSourceResult[]; +} + +export interface DataPage { + target: string; + total: number; + limit: number; + offset: number; + /** Column names in table order. */ + columns: string[]; + rows: Row[]; +} + +export interface ApiError { + error: string; +} + +/** Pulls the backend's `{error}` message out of an HttpErrorResponse-like value. */ +export function apiErrorMessage(error: unknown, fallback: string): string { + const body = (error as { error?: unknown })?.error; + if (body && typeof body === 'object' && typeof (body as ApiError).error === 'string') return (body as ApiError).error; + return fallback; +} diff --git a/src/app/connect/api/connectors.api.ts b/src/app/connect/api/connectors.api.ts new file mode 100644 index 0000000..f6a2225 --- /dev/null +++ b/src/app/connect/api/connectors.api.ts @@ -0,0 +1,18 @@ +import { HttpClient } from '@angular/common/http'; +import { Injectable, inject } from '@angular/core'; +import { Observable, map, shareReplay } from 'rxjs'; +import { ConnectorInfo } from './api.types'; + +/** GET /imports/connectors: what the server can read. Fetched once per app. */ +@Injectable({ providedIn: 'root' }) +export class ConnectorsApi { + private readonly http = inject(HttpClient); + private readonly connectors$ = this.http.get<{ connectors: ConnectorInfo[] }>('/imports/connectors').pipe( + map((response) => response.connectors), + shareReplay({ bufferSize: 1, refCount: false }), + ); + + list(): Observable { + return this.connectors$; + } +} diff --git a/src/app/connect/api/data.api.ts b/src/app/connect/api/data.api.ts new file mode 100644 index 0000000..e84a43b --- /dev/null +++ b/src/app/connect/api/data.api.ts @@ -0,0 +1,15 @@ +import { HttpClient, HttpParams } from '@angular/common/http'; +import { Injectable, inject } from '@angular/core'; +import { Observable } from 'rxjs'; +import { DataPage } from './api.types'; + +/** GET /data/: rows actually stored in the destination database. */ +@Injectable({ providedIn: 'root' }) +export class DataApi { + private readonly http = inject(HttpClient); + + page(target: string, limit: number, offset: number): Observable { + const params = new HttpParams().set('limit', limit).set('offset', offset); + return this.http.get(`/data/${encodeURIComponent(target)}`, { params }); + } +} diff --git a/src/app/connect/api/document-source.api.ts b/src/app/connect/api/document-source.api.ts new file mode 100644 index 0000000..798797a --- /dev/null +++ b/src/app/connect/api/document-source.api.ts @@ -0,0 +1,25 @@ +import { HttpClient } from '@angular/common/http'; +import { Injectable, inject } from '@angular/core'; +import { Observable } from 'rxjs'; +import { DocumentExtraction } from './api.types'; + +/** Clinical documents: field extraction and page/image rendering. */ +@Injectable({ providedIn: 'root' }) +export class DocumentSourceApi { + private readonly http = inject(HttpClient); + + /** `payload` is the document source payload (files, segmentation, overrides...). */ + extract(payload: Record, target: string): Observable { + return this.http.post('/imports/sources/document/extract', { ...payload, target }); + } + + /** PNG of a page, or of a normalized region of it (an embedded image). */ + pageImage(file: File, pageNumber: number, bbox?: [number, number, number, number], dpi = 110): Observable { + const form = new FormData(); + form.append('file', file); + form.append('page_number', String(pageNumber)); + form.append('dpi', String(dpi)); + if (bbox) form.append('bbox', JSON.stringify(bbox)); + return this.http.post('/imports/sources/document/page-image', form, { responseType: 'blob' }); + } +} diff --git a/src/app/connect/api/file-encoding.ts b/src/app/connect/api/file-encoding.ts new file mode 100644 index 0000000..617aaf3 --- /dev/null +++ b/src/app/connect/api/file-encoding.ts @@ -0,0 +1,10 @@ +/** Base64 of a File's bytes, for JSON endpoints that carry a file. */ +export async function fileToBase64(file: Blob): Promise { + const bytes = new Uint8Array(await file.arrayBuffer()); + const chunk = 0x8000; + let binary = ''; + for (let i = 0; i < bytes.length; i += chunk) { + binary += String.fromCharCode(...bytes.subarray(i, i + chunk)); + } + return btoa(binary); +} diff --git a/src/app/connect/api/file-source.api.ts b/src/app/connect/api/file-source.api.ts new file mode 100644 index 0000000..c4c6e35 --- /dev/null +++ b/src/app/connect/api/file-source.api.ts @@ -0,0 +1,24 @@ +import { HttpClient } from '@angular/common/http'; +import { Injectable, inject } from '@angular/core'; +import { Observable } from 'rxjs'; +import { FileOptions, PreviewResponse, SourceType } from './api.types'; + +/** Previews of uploaded files: multipart for one file, JSON payload for any source. */ +@Injectable({ providedIn: 'root' }) +export class FileSourceApi { + private readonly http = inject(HttpClient); + + preview(file: File, kind: SourceType, target: string | null, options: FileOptions = {}): Observable { + const form = new FormData(); + form.append('file', file); + form.append('source_kind', kind); + if (target) form.append('target', target); + if (Object.keys(options).length > 0) form.append('options', JSON.stringify(options)); + return this.http.post('/imports/sources/file/preview', form); + } + + /** Same payload an import source carries, e.g. several EDF files at once. */ + previewPayload(kind: SourceType, payload: Record, target: string | null): Observable { + return this.http.post(`/imports/sources/${kind}/preview`, { payload, ...(target ? { target } : {}) }); + } +} diff --git a/src/app/connect/api/imports.api.ts b/src/app/connect/api/imports.api.ts new file mode 100644 index 0000000..5afe726 --- /dev/null +++ b/src/app/connect/api/imports.api.ts @@ -0,0 +1,19 @@ +import { HttpClient } from '@angular/common/http'; +import { Injectable, inject } from '@angular/core'; +import { Observable } from 'rxjs'; +import { BatchResult, ConflictStrategy, ImportSourcePayload, ValidationResult } from './api.types'; + +/** POST /imports/validate (one source, writes nothing) and POST /imports/commit (a batch, one transaction). */ +@Injectable({ providedIn: 'root' }) +export class ImportsApi { + private readonly http = inject(HttpClient); + + validate(source: ImportSourcePayload): Observable { + return this.http.post('/imports/validate', { source }); + } + + /** `mergeDuplicates`: rows of different sources with the same natural key become one record. */ + commit(sources: ImportSourcePayload[], onConflict: ConflictStrategy, mergeDuplicates = false): Observable { + return this.http.post('/imports/commit', { sources, on_conflict: onConflict, merge_duplicates: mergeDuplicates }); + } +} diff --git a/src/app/connect/api/pdf-source.api.ts b/src/app/connect/api/pdf-source.api.ts new file mode 100644 index 0000000..4cd089d --- /dev/null +++ b/src/app/connect/api/pdf-source.api.ts @@ -0,0 +1,48 @@ +import { HttpClient } from '@angular/common/http'; +import { Injectable, inject } from '@angular/core'; +import { Observable, from, switchMap } from 'rxjs'; +import { PdfDetectResponse, PreviewResponse, RegionExtractResponse, RegionSpec } from './api.types'; +import { fileToBase64 } from './file-encoding'; + +/** POST /imports/sources/pdf/... endpoints. Every call resends the file bytes. */ +@Injectable({ providedIn: 'root' }) +export class PdfSourceApi { + private readonly http = inject(HttpClient); + + detect(file: File): Observable { + const form = new FormData(); + form.append('file', file); + return this.http.post('/imports/sources/pdf/detect', form); + } + + /** Raw PNG bytes; the caller turns them into an object URL. */ + pageImage(file: File, pageNumber: number, dpi?: number): Observable { + const form = new FormData(); + form.append('file', file); + form.append('page_number', String(pageNumber)); + if (dpi) form.append('dpi', String(dpi)); + return this.http.post('/imports/sources/pdf/page-image', form, { responseType: 'blob' }); + } + + tablePreview(file: File, pageNumber: number, bbox: [number, number, number, number], target: string | null): Observable { + const form = new FormData(); + form.append('file', file); + form.append('page_number', String(pageNumber)); + form.append('bbox', JSON.stringify(bbox)); + if (target) form.append('target', target); + return this.http.post('/imports/sources/pdf/table/preview', form); + } + + extractRegions(file: File, regions: RegionSpec[], target: string | null, dpi = 150): Observable { + return from(fileToBase64(file)).pipe( + switchMap((file_base64) => + this.http.post('/imports/sources/pdf/regions/extract', { + file_base64, + regions, + dpi, + ...(target ? { target } : {}), + }), + ), + ); + } +} diff --git a/src/app/connect/api/source-gateway.ts b/src/app/connect/api/source-gateway.ts new file mode 100644 index 0000000..5cb8045 --- /dev/null +++ b/src/app/connect/api/source-gateway.ts @@ -0,0 +1,18 @@ +import { Injectable, inject } from '@angular/core'; +import { DocumentSourceApi } from './document-source.api'; +import { FileSourceApi } from './file-source.api'; +import { PdfSourceApi } from './pdf-source.api'; +import { SqlSourceApi } from './sql-source.api'; + +/** + * The source endpoints, handed to domain objects (`DataConnection.load`, + * `SourceTable.preview`) so each subclass calls the one it needs and the + * domain layer stays free of Angular DI. + */ +@Injectable({ providedIn: 'root' }) +export class SourceGateway { + readonly file = inject(FileSourceApi); + readonly sql = inject(SqlSourceApi); + readonly pdf = inject(PdfSourceApi); + readonly document = inject(DocumentSourceApi); +} diff --git a/src/app/connect/api/sql-source.api.ts b/src/app/connect/api/sql-source.api.ts new file mode 100644 index 0000000..7822d9c --- /dev/null +++ b/src/app/connect/api/sql-source.api.ts @@ -0,0 +1,42 @@ +import { HttpClient } from '@angular/common/http'; +import { Injectable, inject } from '@angular/core'; +import { Observable, map } from 'rxjs'; +import { PreviewResponse, SourceColumn, SqlConnectionRef } from './api.types'; + +/** POST /imports/sources/sql/*. Stateless: every call carries the connection. */ +@Injectable({ providedIn: 'root' }) +export class SqlSourceApi { + private readonly http = inject(HttpClient); + + testConnection(connection: SqlConnectionRef): Observable<{ ok: true; dialect: string }> { + return this.http.post<{ ok: true; dialect: string }>('/imports/sources/sql/test-connection', connection); + } + + schemas(connection: SqlConnectionRef): Observable { + return this.http.post<{ schemas: string[] }>('/imports/sources/sql/schemas', connection).pipe(map((response) => response.schemas)); + } + + tables(connection: SqlConnectionRef, schema?: string): Observable { + return this.http + .post<{ tables: string[] }>('/imports/sources/sql/tables', { ...connection, ...(schema ? { schema } : {}) }) + .pipe(map((response) => response.tables)); + } + + columns(connection: SqlConnectionRef, table: string, schema?: string): Observable { + return this.http + .post<{ columns: SourceColumn[] }>('/imports/sources/sql/columns', { ...connection, table, ...(schema ? { schema } : {}) }) + .pipe(map((response) => response.columns)); + } + + preview( + connection: SqlConnectionRef, + source: { table?: string; schema?: string; query?: string }, + target: string | null, + ): Observable { + return this.http.post('/imports/sources/sql/preview', { + ...connection, + ...(source.query ? { query: source.query } : { table: source.table, ...(source.schema ? { schema: source.schema } : {}) }), + ...(target ? { target } : {}), + }); + } +} diff --git a/src/app/connect/api/targets.api.ts b/src/app/connect/api/targets.api.ts new file mode 100644 index 0000000..a4706fd --- /dev/null +++ b/src/app/connect/api/targets.api.ts @@ -0,0 +1,20 @@ +import { HttpClient } from '@angular/common/http'; +import { Injectable, inject } from '@angular/core'; +import { Observable, map, shareReplay } from 'rxjs'; +import { TargetMeta } from './api.types'; + +/** GET /imports/targets, fetched once per app and shared. */ +@Injectable({ providedIn: 'root' }) +export class TargetsApi { + private readonly http = inject(HttpClient); + private readonly targets$ = this.http + .get<{ targets: TargetMeta[] }>('/imports/targets') + .pipe( + map((response) => response.targets), + shareReplay({ bufferSize: 1, refCount: false }), + ); + + list(): Observable { + return this.targets$; + } +} diff --git a/src/app/connect/components/column-mapper/column-mapper.html b/src/app/connect/components/column-mapper/column-mapper.html new file mode 100644 index 0000000..cc168ed --- /dev/null +++ b/src/app/connect/components/column-mapper/column-mapper.html @@ -0,0 +1,191 @@ +@let f = flow(); +@let s = summary(); +
+
+
+

Columnas de origen

+ + Todas ({{ f.sourceColumns().length }}) + Sin usar ({{ s.unused }}) + +
+ +
+ @for (column of columns(); track column.name) { +
+ + + {{ column.name }} + {{ samples().get(column.name) || '(vacío)' }} + + @if (mappedTo(column.name); as field) { + → {{ field }} + } + +
+ {{ column.name }} +
+
+ } @empty { +

{{ onlyUnusedColumns() ? 'Todas las columnas están asignadas.' : 'La fuente no tiene columnas.' }}

+ } +
+
+ +
+
+

Campos de {{ f.target.table }}

+ + {{ s.covered }}/{{ s.total }} asignados + @if (s.missing > 0) { + · {{ s.missing }} obligatorio(s) sin asignar + } + +
+ +
+ + + Buscar campo + + + + Todos + Obligatorios + Sin asignar + + + @if (s.suggestions > 0) { + + } + + +
+ @if (lastAutoMap() !== null) { +

+ {{ lastAutoMap() === 0 ? 'No se encontraron más coincidencias por nombre.' : 'Se asignaron ' + lastAutoMap() + ' campo(s).' }} +

+ } + +
+ @for (field of fields(); track field.name) { + @let mapping = f.mapping.byField().get(field.name); + @let defaultValue = f.defaults()[field.name]; +
+
+ + {{ field.name }} + @if (field.required) { + * + } + @if (errorsFor(field.name); as errors) { + + {{ errors }} + + } +
+ +
+ @if (mapping) { +
+ + {{ mapping.source }} + @if (mapping.confidence !== undefined) { + {{ + confidenceLabel(mapping.confidence) + }} + + } + +
{{ mapping.source }}
+
+ } @else { + + + @for (column of f.sourceColumns(); track column.name) { + + {{ column.name }} + @if (mappedTo(column.name); as other) { + (ahora en {{ other }}) + } + + } + + + } +
+ +
+ @if (editingDefault() === field.name) { + + Valor por defecto + + + } @else if (defaultValue) { + + + = {{ defaultValue }} + + + + } @else { + + } +
+
+ } @empty { +

Ningún campo coincide con el filtro.

+ } +
+
+
diff --git a/src/app/connect/components/column-mapper/column-mapper.scss b/src/app/connect/components/column-mapper/column-mapper.scss new file mode 100644 index 0000000..d629de8 --- /dev/null +++ b/src/app/connect/components/column-mapper/column-mapper.scss @@ -0,0 +1,340 @@ +:host { + display: block; +} + +.mapper { + align-items: start; + display: grid; + gap: var(--space-4); + grid-template-columns: minmax(260px, 340px) 1fr; +} + +.mapper__header { + align-items: center; + display: flex; + flex-wrap: wrap; + gap: var(--space-2); + justify-content: space-between; + margin-bottom: var(--space-2); + + h3 { + font: var(--mat-sys-title-small); + margin: 0; + } +} + +.mapper__summary { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); +} + +.mapper__missing { + color: var(--mat-sys-error); + font-weight: 500; +} + +.mapper__columns { + position: sticky; + top: 0; +} + +.tray { + background: var(--mat-sys-surface-container-low); + border: 1px solid var(--mat-sys-outline-variant); + border-radius: var(--mat-sys-corner-medium); + display: flex; + flex-direction: column; + gap: var(--space-1); + max-height: 60vh; + min-height: 96px; + overflow: auto; + padding: var(--space-2); +} + +.tray.cdk-drop-list-dragging { + outline: 2px dashed var(--mat-sys-outline); +} + +.tray__empty, +.fields__empty { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); + margin: var(--space-2); +} + +.column-chip { + align-items: center; + background: var(--mat-sys-surface); + border: 1px solid var(--mat-sys-outline-variant); + border-radius: var(--mat-sys-corner-small); + cursor: grab; + display: flex; + gap: var(--space-2); + padding: 6px var(--space-2); + + &:hover { + border-color: var(--mat-sys-primary); + } +} + +.column-chip--used { + opacity: 0.62; +} + +.column-chip__type { + color: var(--mat-sys-primary); + flex: none; + font-size: 18px; + height: 18px; + width: 18px; +} + +.column-chip__text { + display: flex; + flex: 1; + flex-direction: column; + line-height: 1.25; + min-width: 0; +} + +.column-chip__name { + font: var(--mat-sys-label-large); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.column-chip__sample { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.column-chip__target { + color: var(--mat-sys-primary); + flex: none; + font: var(--mat-sys-label-small); + max-width: 45%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.column-chip__grip { + color: var(--mat-sys-outline); + flex: none; + font-size: 18px; + height: 18px; + width: 18px; +} + +.mapper__toolbar { + align-items: center; + display: flex; + flex-wrap: wrap; + gap: var(--space-2); + margin-bottom: var(--space-2); +} + +.mapper__search { + width: 220px; +} + +.mapper__spacer { + flex: 1; +} + +.mapper__note { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); + margin: 0 0 var(--space-2); +} + +.fields { + border: 1px solid var(--mat-sys-outline-variant); + border-radius: var(--mat-sys-corner-medium); + overflow: hidden; +} + +.field { + align-items: center; + border-bottom: 1px solid var(--mat-sys-outline-variant); + display: grid; + gap: var(--space-3); + grid-template-columns: minmax(180px, 1fr) minmax(220px, 1.2fr) minmax(48px, 0.7fr); + min-height: 56px; + padding: var(--space-1) var(--space-3); + + &:last-child { + border-bottom: 0; + } +} + +.field--missing { + background: color-mix(in srgb, var(--mat-sys-error-container) 35%, transparent); +} + +.field__meta { + align-items: center; + display: flex; + gap: var(--space-2); + min-width: 0; +} + +.field__type { + color: var(--mat-sys-on-surface-variant); + flex: none; + font-size: 18px; + height: 18px; + width: 18px; +} + +.field__name { + font: var(--mat-sys-body-medium); + font-family: 'Roboto Mono', ui-monospace, monospace; + font-size: 13px; + overflow: hidden; + text-overflow: ellipsis; +} + +.field__required { + color: var(--mat-sys-error); + font-weight: 700; +} + +.field__errors { + align-items: center; + background: #fff1d6; + border-radius: 999px; + color: #7a4b00; + display: inline-flex; + font: var(--mat-sys-label-small); + gap: 2px; + padding: 1px 6px 1px 3px; + + mat-icon { + font-size: 14px; + height: 14px; + width: 14px; + } +} + +.slot { + border: 1.5px dashed transparent; + border-radius: var(--mat-sys-corner-small); + min-height: 44px; + padding: 2px; + transition: border-color 0.12s ease, background-color 0.12s ease; +} + +.slot.cdk-drop-list-receiving { + border-color: var(--mat-sys-outline); +} + +.slot.cdk-drop-list-dragging { + background: var(--mat-sys-primary-container); + border-color: var(--mat-sys-primary); +} + +.slot ::ng-deep .cdk-drag-placeholder { + display: none; +} + +.slot__select { + width: 100%; + --mat-form-field-container-height: 40px; + --mat-form-field-container-vertical-padding: 8px; +} + +.slot__option-note { + color: var(--mat-sys-on-surface-variant); + font-size: 12px; + margin-left: 4px; +} + +.slot__chip { + align-items: center; + background: var(--mat-sys-secondary-container); + border-radius: var(--mat-sys-corner-small); + color: var(--mat-sys-on-secondary-container); + cursor: grab; + display: flex; + gap: var(--space-1); + min-height: 40px; + padding: 0 var(--space-1) 0 var(--space-2); + + > mat-icon { + font-size: 18px; + height: 18px; + opacity: 0.6; + width: 18px; + } +} + +.slot__chip--suggested { + background: var(--mat-sys-surface-container-high); + border: 1px dashed var(--mat-sys-primary); + color: var(--mat-sys-on-surface); +} + +.slot__source { + flex: 1; + font: var(--mat-sys-label-large); + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.slot__confidence { + background: var(--mat-sys-primary); + border-radius: 999px; + color: var(--mat-sys-on-primary); + font: var(--mat-sys-label-small); + padding: 1px 6px; +} + +.slot__button { + --mat-icon-button-state-layer-size: 28px; + height: 28px; + padding: 2px; + width: 28px; + + mat-icon { + font-size: 18px; + height: 18px; + width: 18px; + } +} + +.field__default { + display: flex; + justify-content: flex-end; + min-width: 0; +} + +.field__default-input { + width: 100%; +} + +.field__default-button { + opacity: 0.5; +} + +.field:hover .field__default-button { + opacity: 1; +} + +@media (max-width: 1100px) { + .mapper { + grid-template-columns: 1fr; + } + .mapper__columns { + position: static; + } + .tray { + max-height: 260px; + } +} diff --git a/src/app/connect/components/column-mapper/column-mapper.spec.ts b/src/app/connect/components/column-mapper/column-mapper.spec.ts new file mode 100644 index 0000000..3094cb3 --- /dev/null +++ b/src/app/connect/components/column-mapper/column-mapper.spec.ts @@ -0,0 +1,54 @@ +import { TestBed } from '@angular/core/testing'; +import { CdkDragDrop } from '@angular/cdk/drag-drop'; +import { ImportFlow } from '../../domain/import-flow'; +import { FakeConnection, FakeTable, NO_GATEWAY, PACIENTE } from '../../testing/fakes'; +import { ColumnMapper } from './column-mapper'; + +describe('ColumnMapper', () => { + function setup() { + const flow = new ImportFlow(new FakeTable(new FakeConnection()), PACIENTE); + flow.load(NO_GATEWAY).subscribe(); + const fixture = TestBed.createComponent(ColumnMapper); + fixture.componentRef.setInput('flow', flow); + fixture.detectChanges(); + return { flow, fixture, mapper: fixture.componentInstance }; + } + + const drop = (column: string, target: string) => + ({ item: { data: column }, container: { data: target }, previousContainer: { data: 'tray' } }) as unknown as CdkDragDrop; + + it('renders a slot per destination field, required first, with the missing one flagged', () => { + const { fixture } = setup(); + const rows = Array.from(fixture.nativeElement.querySelectorAll('.field')) as HTMLElement[]; + expect(rows.map((row) => row.querySelector('.field__name')?.textContent?.trim())).toEqual(['pac_id_hospital', 'pac_sexo', 'pac_parentesco']); + expect(rows[0].classList).toContain('field--missing'); + }); + + it('dropping a column on a field maps it; dropping it back on the tray unmaps it', () => { + const { flow, mapper } = setup(); + mapper.onDropOnField(drop('Clave', 'pac_id_hospital')); + expect(flow.mapping.toRecord()).toEqual({ Sexo: 'pac_sexo', Clave: 'pac_id_hospital' }); + expect(flow.status()).toBe('ready'); + + mapper.onDropOnTray({ item: { data: 'Clave' }, container: {}, previousContainer: { other: true } } as unknown as CdkDragDrop); + expect(flow.mapping.toRecord()).toEqual({ Sexo: 'pac_sexo' }); + }); + + it('the select is an alternative to dragging, and a default value covers a required field', () => { + const { flow, mapper } = setup(); + mapper.pick('pac_sexo', null); + expect(flow.mapping.size()).toBe(0); + mapper.saveDefault('pac_id_hospital', ' H-DEFAULT '); + expect(flow.defaults()).toEqual({ pac_id_hospital: 'H-DEFAULT' }); + expect(flow.missingRequired()).toEqual([]); + }); + + it('filters fields and columns', () => { + const { mapper } = setup(); + mapper.fieldFilter.set('unassigned'); + expect(mapper.fields().map((f) => f.name)).toEqual(['pac_id_hospital', 'pac_parentesco']); + mapper.onlyUnusedColumns.set(true); + expect(mapper.columns().map((c) => c.name)).toEqual(['Clave']); + expect(mapper.samples().get('Sexo')).toBe('F · X'); + }); +}); diff --git a/src/app/connect/components/column-mapper/column-mapper.ts b/src/app/connect/components/column-mapper/column-mapper.ts new file mode 100644 index 0000000..ba20f98 --- /dev/null +++ b/src/app/connect/components/column-mapper/column-mapper.ts @@ -0,0 +1,152 @@ +import { CdkDrag, CdkDragDrop, DragDropModule } from '@angular/cdk/drag-drop'; +import { Component, computed, input, signal } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MatButtonToggleModule } from '@angular/material/button-toggle'; +import { MatChipsModule } from '@angular/material/chips'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatInputModule } from '@angular/material/input'; +import { MatSelectModule } from '@angular/material/select'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { SourceColumn, TargetField } from '../../api/api.types'; +import { ImportFlow } from '../../domain/import-flow'; +import { AutofocusDirective } from '../shared/autofocus.directive'; +import { TypeIconPipe, TypeLabelPipe } from '../shared/type-icon.pipe'; + +type FieldFilter = 'all' | 'required' | 'unassigned'; + +/** + * Drag-and-drop column mapping for one flow: source columns on the left, + * destination fields (drop slots) on the right. Every slot also takes a + * pick from a select (keyboard/accessibility path) and an optional default + * value, so a field the source lacks can still be filled. + * + * Presentation only: every edit goes through `ImportFlow`, which owns the + * mapping state. + */ +@Component({ + selector: 'app-column-mapper', + imports: [ + AutofocusDirective, + DragDropModule, + MatButtonModule, + MatButtonToggleModule, + MatChipsModule, + MatFormFieldModule, + MatIconModule, + MatInputModule, + MatSelectModule, + MatTooltipModule, + TypeIconPipe, + TypeLabelPipe, + ], + templateUrl: './column-mapper.html', + styleUrl: './column-mapper.scss', +}) +export class ColumnMapper { + readonly flow = input.required(); + + readonly fieldFilter = signal('all'); + readonly fieldSearch = signal(''); + readonly onlyUnusedColumns = signal(false); + readonly editingDefault = signal(null); + readonly lastAutoMap = signal(null); + + readonly acceptsColumns = (drag: CdkDrag) => typeof drag.data === 'string'; + + readonly fields = computed(() => { + const flow = this.flow(); + const mapped = flow.mapping.byField(); + const defaults = flow.defaults(); + const term = this.fieldSearch().trim().toLowerCase(); + return flow.target.fields + .filter((field) => !term || field.name.toLowerCase().includes(term)) + .filter((field) => { + switch (this.fieldFilter()) { + case 'required': + return field.required; + case 'unassigned': + return !mapped.has(field.name) && !defaults[field.name]; + default: + return true; + } + }) + .sort((a, b) => Number(b.required) - Number(a.required)); + }); + + readonly columns = computed(() => { + const flow = this.flow(); + return this.onlyUnusedColumns() ? flow.unmappedColumns() : flow.sourceColumns(); + }); + + /** Up to three distinct non-empty sample values per source column, for the tray. */ + readonly samples = computed(() => { + const rows = this.flow().preview()?.sample_rows ?? []; + const samples = new Map(); + for (const column of this.flow().sourceColumns()) { + const values = new Set(); + for (const row of rows) { + const value = row[column.name]; + if (value !== null && value !== undefined && String(value).trim() !== '') values.add(String(value)); + if (values.size === 3) break; + } + samples.set(column.name, [...values].join(' · ')); + } + return samples; + }); + + readonly summary = computed(() => { + const flow = this.flow(); + const covered = flow.target.fields.filter((f) => flow.mapping.byField().has(f.name) || flow.defaults()[f.name]).length; + return { + covered, + total: flow.target.fields.length, + missing: flow.missingRequired().length, + suggestions: flow.pendingSuggestions(), + unused: flow.unmappedColumns().length, + }; + }); + + onSearch(event: Event): void { + this.fieldSearch.set((event.target as HTMLInputElement).value); + } + + onDropOnField(event: CdkDragDrop): void { + this.flow().map(event.item.data as string, event.container.data); + } + + onDropOnTray(event: CdkDragDrop): void { + if (event.previousContainer !== event.container) this.flow().unmapSource(event.item.data as string); + } + + pick(field: string, source: string | null): void { + if (source) this.flow().map(source, field); + else this.flow().unmapField(field); + } + + autoMap(): void { + this.lastAutoMap.set(this.flow().autoMap()); + } + + confirmAll(): void { + const flow = this.flow(); + flow.mapping.items().forEach((m) => m.confidence !== undefined && flow.confirmSuggestion(m.field)); + } + + saveDefault(field: string, value: string): void { + this.flow().setDefault(field, value.trim() || null); + this.editingDefault.set(null); + } + + errorsFor(field: string): number { + return this.flow().quality().get(field)?.errors ?? 0; + } + + mappedTo(column: string): string | undefined { + return this.flow().mapping.bySource().get(column)?.field; + } + + confidenceLabel(confidence: number): string { + return `${Math.round(confidence * 100)}%`; + } +} diff --git a/src/app/connect/components/connect-page/connect-page.html b/src/app/connect/components/connect-page/connect-page.html new file mode 100644 index 0000000..1060c17 --- /dev/null +++ b/src/app/connect/components/connect-page/connect-page.html @@ -0,0 +1,87 @@ +
+ + +
+ Análisis de información +

Conectar datos

+
+ + + @for (domain of domains; track domain.id) { + {{ domain.label }} + } + + + + + + + + +
+ + @if (store.catalogError(); as error) { + + } + + + + + + + + + + @if (store.selectedFlow(); as flow) { + + } + + + +
+ @let s = store.summary(); + {{ s.connections }} conexión(es) + {{ s.flows }} flujo(s) · {{ s.ready }} listo(s) + @if (s.incomplete) { + {{ s.incomplete }} sin mapear + } + {{ s.rows | number }} filas de origen + @if (s.errors) { + {{ s.errors | number }} con errores + } + + Destino: {{ store.domain().toUpperCase() }} +
+
diff --git a/src/app/connect/components/connect-page/connect-page.scss b/src/app/connect/components/connect-page/connect-page.scss new file mode 100644 index 0000000..f92a749 --- /dev/null +++ b/src/app/connect/components/connect-page/connect-page.scss @@ -0,0 +1,115 @@ +:host { + display: flex; + flex: 1; + min-width: 0; +} + +.workspace { + display: flex; + flex: 1; + flex-direction: column; + height: calc(100dvh - var(--site-header-height)); + min-width: 0; +} + +.workspace__toolbar { + --mat-toolbar-container-background-color: var(--mat-sys-surface); + --mat-toolbar-standard-height: 68px; + border-bottom: 1px solid var(--mat-sys-outline-variant); + flex-wrap: wrap; + gap: var(--space-2); + height: auto; + min-height: 68px; + padding: var(--space-2) var(--space-4); +} + +.workspace__title { + display: flex; + flex-direction: column; + line-height: 1.1; + margin-right: var(--space-4); + + h1 { + color: var(--color-primary); + font-family: var(--font-heading); + font-size: 26px; + font-weight: 700; + letter-spacing: -0.02em; + margin: 0; + } +} + +.workspace__eyebrow { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-label-small); + letter-spacing: 0.1em; + text-transform: uppercase; +} + +.workspace__spacer { + flex: 1; +} + +.workspace__alert { + align-items: center; + background: var(--mat-sys-error-container); + color: var(--mat-sys-on-error-container); + display: flex; + gap: var(--space-2); + margin: 0; + padding: var(--space-2) var(--space-4); +} + +.workspace__body { + background: var(--color-background); + flex: 1; + min-height: 0; +} + +.workspace__pane { + --mat-sidenav-container-shape: 0; + background: var(--mat-sys-surface-container-lowest, #fff); + border-right: 1px solid var(--mat-sys-outline-variant); + width: 320px; +} + +.workspace__main { + display: flex; + flex-direction: column; + gap: var(--space-2); + padding: var(--space-2) var(--space-4) var(--space-6); +} + +.workspace__status { + align-items: center; + background: var(--color-text); + color: #dfe5ee; + display: flex; + flex-wrap: wrap; + font: var(--mat-sys-body-small); + gap: var(--space-1) var(--space-5); + min-height: 32px; + padding: 0 var(--space-4); + + span { + align-items: center; + display: inline-flex; + gap: 6px; + } + + mat-icon { + font-size: 16px; + height: 16px; + width: 16px; + } +} + +.workspace__status-warn { + color: #ffd27a; +} + +@media (max-width: 900px) { + .workspace__pane { + width: 280px; + } +} diff --git a/src/app/connect/components/connect-page/connect-page.ts b/src/app/connect/components/connect-page/connect-page.ts new file mode 100644 index 0000000..9a7c768 --- /dev/null +++ b/src/app/connect/components/connect-page/connect-page.ts @@ -0,0 +1,157 @@ +import { DragDropModule } from '@angular/cdk/drag-drop'; +import { DecimalPipe } from '@angular/common'; +import { Component, Injector, inject, signal } from '@angular/core'; +import { MatBadgeModule } from '@angular/material/badge'; +import { MatButtonModule } from '@angular/material/button'; +import { MatButtonToggleModule } from '@angular/material/button-toggle'; +import { MatDialog } from '@angular/material/dialog'; +import { MatPaginatorIntl } from '@angular/material/paginator'; +import { MatIconModule } from '@angular/material/icon'; +import { MatSidenavModule } from '@angular/material/sidenav'; +import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; +import { MatToolbarModule } from '@angular/material/toolbar'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { Domain, TargetMeta } from '../../api/api.types'; +import { DataConnection, SourceTable } from '../../domain/data-source'; +import { PdfConnection } from '../../domain/pdf-source'; +import { SqlConnection } from '../../domain/sql-source'; +import { ConnectWorkspaceStore, DOMAINS } from '../../state/connect-workspace.store'; +import { ConnectionsPanel, TableUse } from '../connections-panel/connections-panel'; +import { ConnectorGalleryDialog } from '../connector-gallery-dialog/connector-gallery-dialog'; +import { DatabaseExplorerData, DatabaseExplorerDialog } from '../database-explorer-dialog/database-explorer-dialog'; +import { FlowCanvas } from '../flow-canvas/flow-canvas'; +import { FlowEditor } from '../flow-editor/flow-editor'; +import { LoadDialog, LoadDialogResult } from '../load-dialog/load-dialog'; +import { NewFlowDialog, NewFlowDialogData } from '../new-flow-dialog/new-flow-dialog'; +import { PdfRegionsDialog, PdfRegionsDialogData, PdfRegionsResult } from '../pdf-regions-dialog/pdf-regions-dialog'; +import { SpanishPaginatorIntl } from '../shared/spanish-paginator-intl'; +import { SqlQueryDialog, SqlQueryResult } from '../sql-query-dialog/sql-query-dialog'; + +/** + * The "Conectar datos" workspace (route `/conectar`): connections pane on + * the left, composition canvas + selected flow's editor in the middle, a + * toolbar for the batch-level actions, a status bar. Owns the workspace + * store (one per visit) and the dialogs; everything else is delegated to + * the child components and the store. + */ +@Component({ + selector: 'app-connect-page', + imports: [ + ConnectionsPanel, + DecimalPipe, + DragDropModule, + FlowCanvas, + FlowEditor, + MatBadgeModule, + MatButtonModule, + MatButtonToggleModule, + MatIconModule, + MatSidenavModule, + MatSnackBarModule, + MatToolbarModule, + MatTooltipModule, + ], + // Workspace-scoped (the lazy chunk), including for dialogs opened with + // this page's injector. + providers: [ConnectWorkspaceStore, { provide: MatPaginatorIntl, useClass: SpanishPaginatorIntl }], + templateUrl: './connect-page.html', + styleUrl: './connect-page.scss', +}) +export class ConnectPage { + readonly store = inject(ConnectWorkspaceStore); + private readonly dialog = inject(MatDialog); + private readonly snackBar = inject(MatSnackBar); + private readonly injector = inject(Injector); + + readonly domains = DOMAINS; + readonly paneOpen = signal(true); + readonly validatingAll = signal(false); + + setDomain(domain: Domain): void { + this.store.setDomain(domain); + } + + openGallery(): void { + this.dialog + .open(ConnectorGalleryDialog, { width: '960px', maxWidth: '96vw', autoFocus: false }) + .afterClosed() + .subscribe((connections) => connections?.forEach((connection) => this.store.addConnection(connection))); + } + + useTable({ table, target }: TableUse): void { + if (target) { + this.store.createFlow(table, target); + return; + } + this.dialog + .open(NewFlowDialog, { + width: '560px', + maxWidth: '96vw', + data: { table, targets: this.store.targets(), existingTargets: this.store.flowsByTarget() }, + }) + .afterClosed() + .subscribe((chosen) => chosen && this.store.createFlow(table, chosen)); + } + + onTableDropped(table: SourceTable): void { + this.useTable({ table }); + } + + addQuery(connection: SqlConnection): void { + this.dialog + .open(SqlQueryDialog, { data: connection, maxWidth: '96vw' }) + .afterClosed() + .subscribe((result) => { + if (!result) return; + const table = connection.addQuery(result.name, result.query); + this.useTable({ table }); + }); + } + + drawRegions(connection: PdfConnection): void { + const fieldNames = [...new Set(this.store.targets().flatMap((target) => target.fields.map((field) => field.name)))].sort(); + this.dialog + .open(PdfRegionsDialog, { + data: { connection, fieldNames }, + width: '1280px', + maxWidth: '98vw', + autoFocus: false, + // Drawn regions are real work: Escape (which also dismisses the + // name autocomplete) must not discard them; only "Cancelar" does. + disableClose: true, + }) + .afterClosed() + .subscribe((result) => { + if (!result) return; + const table = connection.addRegions(result.name, result.regions); + this.useTable({ table }); + }); + } + + async validateAll(): Promise { + this.validatingAll.set(true); + await this.store.validateAll(); + this.validatingAll.set(false); + const { errors } = this.store.summary(); + this.snackBar.open(errors ? `Validación terminada: ${errors} fila(s) con errores.` : 'Validación terminada: sin errores.', 'OK', { + duration: 4000, + }); + } + + openLoad(): void { + this.dialog + .open(LoadDialog, { width: '920px', maxWidth: '96vw', injector: this.injector, autoFocus: false }) + .afterClosed() + .subscribe((result) => result === 'explore' && this.openExplorer()); + } + + openExplorer(initial?: string): void { + const flow = this.store.selectedFlow(); + this.dialog.open(DatabaseExplorerDialog, { + injector: this.injector, + width: '1280px', + maxWidth: '98vw', + data: { targets: this.store.targets(), initial: initial ?? flow?.target.key }, + }); + } +} diff --git a/src/app/connect/components/connections-panel/connections-panel.html b/src/app/connect/components/connections-panel/connections-panel.html new file mode 100644 index 0000000..ad44d52 --- /dev/null +++ b/src/app/connect/components/connections-panel/connections-panel.html @@ -0,0 +1,154 @@ +
+
+

Conexiones

+ +
+ + @if (store.connections().length === 0) { +
+ + +
+ } @else { + + @for (connection of store.connections(); track connection.id) { + + + + + {{ connection.label }} + {{ connection.typeLabel }} · {{ connection.tables().length }} tabla(s) + + @switch (connection.state()) { + @case ('loading') { + + } + @case ('error') { + error + } + } + + + @if (isSql(connection)) { + + } + @if (isPdf(connection)) { + + } + + + + + + @if (connection.error(); as error) { + + } + +
+ @for (table of connection.tables(); track table.id) { +
+ + + {{ table.name }} + {{ table.kindLabel }} + + @if (flowCount(table); as count) { + {{ count }} + } + + @if (table.removable) { + + } +
+ {{ table.label }} +
+
+
+ } @empty { + @if (connection.state() === 'ready') { +

+ Sin tablas. +

+ } + } +
+
+ } +
+ } + + + +
+

Destino

+ {{ store.targets().length }} tablas +
+

Arrastra una tabla de origen sobre una entidad para mapearla directamente.

+ + @for (target of store.targets(); track target.key) { + + + + {{ target.table }} + @if (store.flowsByTarget().get(target.key); as count) { + {{ count }} + } + + + {{ target.fields.length }} campos@if (target.conflict_fields) { · clave {{ target.conflict_fields.join(', ') }} } + + + } + +
diff --git a/src/app/connect/components/connections-panel/connections-panel.scss b/src/app/connect/components/connections-panel/connections-panel.scss new file mode 100644 index 0000000..2b41982 --- /dev/null +++ b/src/app/connect/components/connections-panel/connections-panel.scss @@ -0,0 +1,217 @@ +:host { + display: block; +} + +.pane__header { + align-items: center; + display: flex; + justify-content: space-between; + padding: var(--space-3) var(--space-3) var(--space-1) var(--space-4); + + h2 { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-label-large); + letter-spacing: 0.08em; + margin: 0; + text-transform: uppercase; + } +} + +.pane__caption, +.pane__hint { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); +} + +.pane__hint { + margin: 0 var(--space-4) var(--space-2); +} + +.pane__empty { + display: flex; + flex-direction: column; + gap: var(--space-3); + padding: var(--space-2) var(--space-4) var(--space-4); +} + +.pane__db-button { + align-self: stretch; +} + +.connections { + display: block; + padding: 0 var(--space-2) var(--space-3); +} + +.connection { + --mat-expansion-container-background-color: transparent; + --mat-expansion-header-collapsed-state-height: 56px; + --mat-expansion-header-expanded-state-height: 56px; + box-shadow: none !important; +} + +.connection__header { + padding: 0 var(--space-2) 0 var(--space-3); +} + +.connection__header ::ng-deep .mat-content { + align-items: center; + gap: var(--space-2); + overflow: hidden; +} + +.connection__icon { + color: var(--mat-sys-primary); + flex: none; +} + +.connection__text { + display: flex; + flex: 1; + flex-direction: column; + min-width: 0; +} + +.connection__label { + font: var(--mat-sys-title-small); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.connection__type { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); +} + +.connection__error-icon, +.connection__error { + color: var(--mat-sys-error); +} + +.connection__error { + font: var(--mat-sys-body-small); + margin: 0 0 var(--space-2); +} + +.connection ::ng-deep .mat-expansion-panel-body { + padding: 0 0 var(--space-2) var(--space-6); +} + +.tables__empty { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); + margin: 0; + padding: var(--space-1) var(--space-2); +} + +.table-item { + align-items: center; + border-radius: var(--mat-sys-corner-small); + cursor: grab; + display: flex; + gap: var(--space-2); + min-height: 40px; + padding: 0 0 0 var(--space-2); + + &:hover { + background: var(--mat-sys-surface-container-high); + } + + &:active { + cursor: grabbing; + } +} + +.table-item--placeholder { + background: var(--mat-sys-surface-container-highest); + opacity: 0.6; +} + +.table-item__icon { + color: var(--mat-sys-on-surface-variant); + flex: none; + font-size: 20px; + height: 20px; + width: 20px; +} + +.table-item__text { + display: flex; + flex: 1; + flex-direction: column; + line-height: 1.2; + min-width: 0; +} + +.table-item__name { + font: var(--mat-sys-body-medium); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.table-item__kind { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); +} + +.target-item__title { + align-items: center; + display: flex; + gap: var(--space-2); +} + +.table-item__flows, +.target-item__flows { + background: var(--mat-sys-primary); + border-radius: 999px; + color: var(--mat-sys-on-primary); + font: var(--mat-sys-label-small); + min-width: 20px; + padding: 2px 6px; + text-align: center; +} + +.table-item__action { + --mat-icon-button-state-layer-size: 32px; + flex: none; + height: 32px; + opacity: 0.55; + padding: 4px; + width: 32px; + + mat-icon { + font-size: 18px; + height: 18px; + width: 18px; + } +} + +.table-item:hover .table-item__action { + opacity: 1; +} + +.targets { + padding-top: 0; +} + +.target-item { + border-radius: var(--mat-sys-corner-small); + margin: 0 var(--space-2); + transition: background-color 0.12s ease, outline-color 0.12s ease; + width: auto !important; +} + +.target-item.cdk-drop-list-receiving { + outline: 1px dashed var(--mat-sys-primary); +} + +.target-item.cdk-drop-list-dragging { + background: var(--mat-sys-primary-container); + outline: 2px solid var(--mat-sys-primary); +} + +.target-item ::ng-deep .cdk-drag-placeholder { + display: none; +} diff --git a/src/app/connect/components/connections-panel/connections-panel.ts b/src/app/connect/components/connections-panel/connections-panel.ts new file mode 100644 index 0000000..177f858 --- /dev/null +++ b/src/app/connect/components/connections-panel/connections-panel.ts @@ -0,0 +1,86 @@ +import { CdkDrag, CdkDragDrop, DragDropModule } from '@angular/cdk/drag-drop'; +import { Component, inject, output } from '@angular/core'; +import { MatSnackBar } from '@angular/material/snack-bar'; +import { MatBadgeModule } from '@angular/material/badge'; +import { MatButtonModule } from '@angular/material/button'; +import { MatDividerModule } from '@angular/material/divider'; +import { MatExpansionModule } from '@angular/material/expansion'; +import { MatIconModule } from '@angular/material/icon'; +import { MatListModule } from '@angular/material/list'; +import { MatMenuModule } from '@angular/material/menu'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { TargetMeta } from '../../api/api.types'; +import { DataConnection, SourceTable } from '../../domain/data-source'; +import { PdfConnection } from '../../domain/pdf-source'; +import { SqlConnection } from '../../domain/sql-source'; +import { ConnectWorkspaceStore } from '../../state/connect-workspace.store'; +import { FileDropzone } from '../file-dropzone/file-dropzone'; + +/** Payload of a "use this table" request: a table, optionally already aimed at an entity. */ +export interface TableUse { + table: SourceTable; + target?: TargetMeta; +} + +/** + * The workspace's left pane: every + * connection with its tables (drag a table onto the canvas, or straight + * onto a destination entity below, to create a flow) and the destination + * schema of the current domain, with how many flows feed each entity. + */ +@Component({ + selector: 'app-connections-panel', + imports: [ + DragDropModule, + FileDropzone, + MatBadgeModule, + MatButtonModule, + MatDividerModule, + MatExpansionModule, + MatIconModule, + MatListModule, + MatMenuModule, + MatProgressSpinnerModule, + MatTooltipModule, + ], + templateUrl: './connections-panel.html', + styleUrl: './connections-panel.scss', +}) +export class ConnectionsPanel { + readonly store = inject(ConnectWorkspaceStore); + private readonly snackBar = inject(MatSnackBar); + + readonly addConnection = output(); + readonly useTable = output(); + readonly addQuery = output(); + readonly drawRegions = output(); + + /** Table lists are drag *sources* only. */ + readonly nothingEnters = () => false; + readonly onlyTables = (drag: CdkDrag) => drag.data instanceof SourceTable; + + isSql(connection: DataConnection): connection is SqlConnection { + return connection instanceof SqlConnection; + } + + isPdf(connection: DataConnection): connection is PdfConnection { + return connection instanceof PdfConnection; + } + + flowCount(table: SourceTable): number { + return this.store.flowsOf(table).length; + } + + onFilesDropped(files: File[]): void { + const rejected = this.store.addFiles(files); + if (rejected.length) { + this.snackBar.open(`Formato no soportado: ${rejected.map((file) => file.name).join(', ')}`, 'OK', { duration: 5000 }); + } + } + + onDropOnTarget(event: CdkDragDrop): void { + const table = event.item.data; + if (table instanceof SourceTable) this.useTable.emit({ table, target: event.container.data }); + } +} diff --git a/src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.html b/src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.html new file mode 100644 index 0000000..85e206d --- /dev/null +++ b/src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.html @@ -0,0 +1,138 @@ + + + + @switch (view()) { + @case ('catalog') { + + } + + @case ('files') { + + + } + + @case ('database') { + + @if (engine() === 'url') { +
+ + Cadena de conexión + + Formato SQLAlchemy: dialecto+driver://usuario:contraseña@host:puerto/base + +
+ } @else { +
+ + Servidor + + + + Puerto + + Predeterminado: {{ serverEngine()?.default_port }} + + + Base de datos + + + + Usuario + + + + Contraseña + + +
+ } + + @if (testing()) { + + } + @if (testResult(); as result) { +

+ {{ result.message }} +

+ } + } + } +
+ + + + @if (view() === 'files') { + + } + @if (view() === 'database') { + + + } + diff --git a/src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.scss b/src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.scss new file mode 100644 index 0000000..463b96f --- /dev/null +++ b/src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.scss @@ -0,0 +1,120 @@ +.gallery__title { + align-items: center; + display: flex; + gap: var(--space-2); +} + +.gallery__content { + min-height: 420px; +} + +.gallery { + display: grid; + gap: var(--space-4); + grid-template-columns: 200px 1fr; +} + +.gallery__categories { + border-right: 1px solid var(--mat-sys-outline-variant); + padding-right: var(--space-2); +} + +.gallery__search { + width: 100%; +} + +.gallery__grid { + display: grid; + gap: var(--space-3); + grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); + margin-top: var(--space-3); +} + +.connector-card { + align-items: flex-start; + background: var(--mat-sys-surface); + border: 1px solid var(--mat-sys-outline-variant); + border-radius: var(--mat-sys-corner-medium); + color: var(--mat-sys-on-surface); + cursor: pointer; + display: flex; + flex-direction: column; + font: inherit; + gap: var(--space-1); + min-height: 118px; + padding: var(--space-4); + position: relative; + text-align: left; + transition: border-color 0.15s ease, box-shadow 0.15s ease; + + &:hover, + &:focus-visible { + border-color: var(--mat-sys-primary); + box-shadow: var(--mat-sys-level1); + outline: none; + } +} + +.connector-card__icon { + color: var(--mat-sys-primary); + margin-bottom: var(--space-1); +} + +.connector-card__name { + font: var(--mat-sys-title-small); +} + +.connector-card__description { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); +} + +.gallery__hint { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-medium); + margin: 0 0 var(--space-4); + max-width: 720px; +} + +.gallery__empty { + color: var(--mat-sys-on-surface-variant); +} + +.db-form { + display: grid; + gap: 0 var(--space-4); + grid-template-columns: 1fr 1fr; +} + +.db-form__wide { + grid-column: 1 / -1; +} + +.db-test { + align-items: center; + color: var(--mat-sys-primary); + display: flex; + gap: var(--space-2); + margin: var(--space-3) 0 0; + + &.db-test--error { + color: var(--mat-sys-error); + } +} + +@media (max-width: 720px) { + .gallery { + grid-template-columns: 1fr; + } + .gallery__categories { + border-right: 0; + } + .db-form { + grid-template-columns: 1fr; + } +} + +.connector-card:disabled { + cursor: not-allowed; + opacity: 0.55; +} diff --git a/src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.ts b/src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.ts new file mode 100644 index 0000000..3151669 --- /dev/null +++ b/src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.ts @@ -0,0 +1,172 @@ +import { Component, computed, inject, signal } from '@angular/core'; +import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatInputModule } from '@angular/material/input'; +import { MatListModule } from '@angular/material/list'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatRippleModule } from '@angular/material/core'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { catchError, of } from 'rxjs'; +import { ConnectorInfo, SqlConnectionRef, SqlEngineInfo, apiErrorMessage } from '../../api/api.types'; +import { ConnectorsApi } from '../../api/connectors.api'; +import { SourceGateway } from '../../api/source-gateway'; +import { connectionsFor } from '../../domain/connection-registry'; +import { GALLERY_CATEGORIES, GalleryCategory, GalleryEntry, galleryEntries } from '../../domain/connector-catalog'; +import { DataConnection } from '../../domain/data-source'; +import { SqlConnection } from '../../domain/sql-source'; +import { describeSqlServer, describeSqlUrl } from '../../domain/sql-url'; +import { FileDropzone } from '../file-dropzone/file-dropzone'; + +type View = 'catalog' | 'files' | 'database'; + +/** + * "Obtener datos": pick a connector from the gallery (as reported by the + * server), then drop files or fill a database connection form. Closes + * with the new, not yet loaded, `DataConnection`s. + */ +@Component({ + selector: 'app-connector-gallery-dialog', + imports: [ + FileDropzone, + MatButtonModule, + MatDialogModule, + MatFormFieldModule, + MatIconModule, + MatInputModule, + MatListModule, + MatProgressBarModule, + MatRippleModule, + MatTooltipModule, + ReactiveFormsModule, + ], + templateUrl: './connector-gallery-dialog.html', + styleUrl: './connector-gallery-dialog.scss', +}) +export class ConnectorGalleryDialog { + private readonly dialogRef = inject>(MatDialogRef); + private readonly gateway = inject(SourceGateway); + private readonly formBuilder = inject(FormBuilder); + + readonly categories = GALLERY_CATEGORIES; + readonly category = signal('all'); + readonly search = signal(''); + readonly view = signal('catalog'); + readonly entry = signal(null); + readonly catalogError = signal(null); + + private readonly connectors = toSignal( + inject(ConnectorsApi) + .list() + .pipe( + catchError((error) => { + this.catalogError.set(apiErrorMessage(error, 'No se pudo consultar los conectores del servidor.')); + return of([] as ConnectorInfo[]); + }), + ), + { initialValue: [] as ConnectorInfo[] }, + ); + private readonly entries = computed(() => galleryEntries(this.connectors())); + + readonly visibleEntries = computed(() => { + const term = this.search().trim().toLowerCase(); + return this.entries().filter( + (entry) => + (this.category() === 'all' || entry.category === this.category()) && + (!term || entry.name.toLowerCase().includes(term) || entry.description.toLowerCase().includes(term)), + ); + }); + readonly visibleCategories = computed(() => + this.categories.filter((c) => c.id === 'all' || this.entries().some((entry) => entry.category === c.id)), + ); + + // -- files -- + readonly files = signal([]); + + // -- database -- + readonly serverForm = this.formBuilder.nonNullable.group({ + host: ['', Validators.required], + port: [null as number | null], + database: ['', Validators.required], + user: [''], + password: [''], + }); + readonly urlForm = this.formBuilder.nonNullable.group({ url: ['', Validators.required] }); + readonly testing = signal(false); + readonly testResult = signal<{ ok: boolean; message: string } | null>(null); + + readonly engine = computed(() => this.entry()?.engine ?? null); + readonly serverEngine = computed(() => { + const engine = this.engine(); + return engine && engine !== 'url' ? engine : null; + }); + + pick(entry: GalleryEntry): void { + if (!entry.available) return; + this.entry.set(entry); + this.testResult.set(null); + this.view.set(entry.engine ? 'database' : 'files'); + } + + back(): void { + this.view.set('catalog'); + this.files.set([]); + } + + onSearch(event: Event): void { + this.search.set((event.target as HTMLInputElement).value); + } + + testConnection(): void { + const ref = this.connectionRef(); + if (!ref) return; + this.testing.set(true); + this.testResult.set(null); + this.gateway.sql.testConnection(ref).subscribe({ + next: (response) => { + this.testing.set(false); + this.testResult.set({ ok: true, message: `Conexión correcta (${response.dialect}).` }); + }, + error: (error) => { + this.testing.set(false); + this.testResult.set({ ok: false, message: apiErrorMessage(error, 'No se pudo conectar.') }); + }, + }); + } + + connectFiles(): void { + const entry = this.entry(); + if (entry) this.dialogRef.close(connectionsFor(entry.connector.kind, this.files())); + } + + connectDatabase(): void { + const ref = this.connectionRef(); + if (!ref) return; + this.dialogRef.close([new SqlConnection(ref, this.connectionLabel(), this.serverEngine()?.default_schema ?? undefined)]); + } + + get databaseFormInvalid(): boolean { + return this.engine() === 'url' ? this.urlForm.invalid : this.serverForm.invalid; + } + + private connectionRef(): SqlConnectionRef | null { + const engine = this.engine(); + if (!engine) return null; + if (engine === 'url') { + this.urlForm.markAllAsTouched(); + return this.urlForm.valid ? { connection_string: this.urlForm.getRawValue().url.trim() } : null; + } + this.serverForm.markAllAsTouched(); + if (this.serverForm.invalid) return null; + return { server: { engine: engine.id, ...this.serverForm.getRawValue() } }; + } + + private connectionLabel(): string { + const engine = this.engine(); + if (engine === 'url') return describeSqlUrl(this.urlForm.getRawValue().url); + return describeSqlServer({ engine: engine as SqlEngineInfo, ...this.serverForm.getRawValue() }); + } +} diff --git a/src/app/connect/components/data-grid/data-grid.html b/src/app/connect/components/data-grid/data-grid.html new file mode 100644 index 0000000..ac44fd5 --- /dev/null +++ b/src/app/connect/components/data-grid/data-grid.html @@ -0,0 +1,82 @@ +@let f = flow(); +
+ + Destino + Origen + + @if (view() === 'target') { + + Solo filas con errores + + } + + Muestra de {{ shownOf().shown }}@if (shownOf().total !== null) { de {{ shownOf().total }} } filas + @if (view() === 'target' && !f.validation()) { + · valida el flujo para ver la calidad de cada campo + } + +
+ +@if (columns().length === 0) { +

+ @if (view() === 'target') { + Aún no hay campos asignados — mapea columnas en la pestaña «Mapeo». + } @else { + La fuente no tiene columnas. + } +

+} @else { +
+ + + + + + + @for (column of columns(); track column.id) { + + + + + } + + + + + + +
# + {{ row.index + 1 }} + + {{ column.title }} + @if (column.subtitle) { + {{ column.subtitle }} + } + @if (column.errorRate !== null) { + + + + + } + + @let value = cell(row, column); + @let cellErrors = errors(row, column); + + @if (cellErrors.length) { + + } + {{ value.text }} + +
Ninguna fila de la muestra tiene errores.
+
+} diff --git a/src/app/connect/components/data-grid/data-grid.scss b/src/app/connect/components/data-grid/data-grid.scss new file mode 100644 index 0000000..733a5b5 --- /dev/null +++ b/src/app/connect/components/data-grid/data-grid.scss @@ -0,0 +1,146 @@ +:host { + display: block; +} + +.grid-toolbar { + align-items: center; + display: flex; + flex-wrap: wrap; + gap: var(--space-3); + margin-bottom: var(--space-3); + + mat-button-toggle mat-icon { + font-size: 18px; + height: 18px; + margin-right: 4px; + vertical-align: middle; + width: 18px; + } +} + +.grid-toolbar__caption, +.grid-empty { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); +} + +.grid-empty { + padding: var(--space-4); +} + +.grid-scroll { + border: 1px solid var(--mat-sys-outline-variant); + border-radius: var(--mat-sys-corner-medium); + max-height: 62vh; + overflow: auto; +} + +.grid { + --mat-table-row-item-container-height: 36px; + --mat-table-header-container-height: 64px; + min-width: 100%; + width: max-content; +} + +.grid th, +.grid td { + border-right: 1px solid var(--mat-sys-outline-variant); + max-width: 280px; + padding: 0 var(--space-3); +} + +.grid__index { + background: var(--mat-sys-surface-container-low); + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-label-small); + text-align: right; + width: 48px; +} + +.grid__index--error { + box-shadow: inset 3px 0 0 var(--mat-sys-error); + color: var(--mat-sys-error); +} + +.grid__header { + background: var(--mat-sys-surface-container) !important; + vertical-align: top; + padding-top: var(--space-2) !important; + padding-bottom: var(--space-2) !important; +} + +.grid__title { + align-items: center; + display: flex; + font-family: 'Roboto Mono', ui-monospace, monospace; + font-size: 12px; + font-weight: 600; + gap: 4px; + white-space: nowrap; + + mat-icon { + color: var(--mat-sys-primary); + font-size: 16px; + height: 16px; + width: 16px; + } +} + +.grid__subtitle { + color: var(--mat-sys-on-surface-variant); + display: block; + font: var(--mat-sys-body-small); + white-space: nowrap; +} + +.quality { + border-radius: 2px; + display: flex; + height: 4px; + margin-top: 6px; + overflow: hidden; + width: 100%; +} + +.quality__ok { + background: var(--mat-sys-primary); +} + +.quality__bad { + background: var(--mat-sys-error); +} + +.grid__cell { + align-items: center; + display: flex; + font: var(--mat-sys-body-small); + gap: 4px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + + mat-icon { + flex: none; + font-size: 14px; + height: 14px; + width: 14px; + } +} + +.grid__cell--error { + background: var(--mat-sys-error-container); + border-radius: 4px; + color: var(--mat-sys-on-error-container); + margin: 0 -6px; + padding: 2px 6px; +} + +.grid__cell--default { + color: var(--mat-sys-primary); + font-style: italic; +} + +.grid__cell--empty { + color: var(--mat-sys-outline); + font-style: italic; +} diff --git a/src/app/connect/components/data-grid/data-grid.ts b/src/app/connect/components/data-grid/data-grid.ts new file mode 100644 index 0000000..6495000 --- /dev/null +++ b/src/app/connect/components/data-grid/data-grid.ts @@ -0,0 +1,118 @@ +import { Component, computed, input, signal } from '@angular/core'; +import { MatButtonToggleModule } from '@angular/material/button-toggle'; +import { MatIconModule } from '@angular/material/icon'; +import { MatSlideToggleModule } from '@angular/material/slide-toggle'; +import { MatTableModule } from '@angular/material/table'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { Row, RowError } from '../../api/api.types'; +import { ImportFlow } from '../../domain/import-flow'; +import { TypeIconPipe } from '../shared/type-icon.pipe'; + +type GridView = 'target' | 'source'; + +interface GridColumn { + id: string; + title: string; + subtitle: string | null; + type: string; + /** Destination view: source column feeding it; source view: the column itself. */ + sourceColumn: string | null; + defaultValue: string | null; + errorRate: number | null; +} + +interface GridRow { + index: number; + values: Row; + hasErrors: boolean; +} + +/** + * The sample rows of one flow, Power Query-style: "Destino" shows them as + * they will land in the database (destination field names, defaults + * applied, cells that failed validation highlighted with the reason, a + * quality bar per field), "Origen" shows the raw source columns. + */ +@Component({ + selector: 'app-data-grid', + imports: [MatButtonToggleModule, MatIconModule, MatSlideToggleModule, MatTableModule, MatTooltipModule, TypeIconPipe], + templateUrl: './data-grid.html', + styleUrl: './data-grid.scss', +}) +export class DataGrid { + readonly flow = input.required(); + + readonly view = signal('target'); + readonly onlyErrors = signal(false); + + readonly columns = computed(() => { + const flow = this.flow(); + if (this.view() === 'source') { + const bySource = flow.mapping.bySource(); + return flow.sourceColumns().map((column) => ({ + id: column.name, + title: column.name, + subtitle: bySource.get(column.name) ? `→ ${bySource.get(column.name)!.field}` : null, + type: column.inferred_type, + sourceColumn: column.name, + defaultValue: null, + errorRate: null, + })); + } + const byField = flow.mapping.byField(); + const defaults = flow.defaults(); + const quality = flow.quality(); + return flow.target.fields + .filter((field) => byField.has(field.name) || defaults[field.name]) + .map((field) => ({ + id: field.name, + title: field.name, + subtitle: byField.get(field.name) ? `← ${byField.get(field.name)!.source}` : `= ${defaults[field.name]}`, + type: field.type, + sourceColumn: byField.get(field.name)?.source ?? null, + defaultValue: defaults[field.name] ?? null, + errorRate: quality.get(field.name)?.errorRate ?? null, + })); + }); + + readonly displayedColumns = computed(() => ['__row', ...this.columns().map((column) => column.id)]); + + readonly rows = computed(() => { + const flow = this.flow(); + const errors = flow.errorsByCell(); + const erroredRows = new Set([...errors.keys()].map((key) => Number(key.split(':')[0]))); + const rows = (flow.preview()?.sample_rows ?? []).map((values, index) => ({ index, values, hasErrors: erroredRows.has(index) })); + return this.onlyErrors() && this.view() === 'target' ? rows.filter((row) => row.hasErrors) : rows; + }); + + readonly shownOf = computed(() => { + const flow = this.flow(); + return { shown: flow.preview()?.sample_rows.length ?? 0, total: flow.totalRows() }; + }); + + cell(row: GridRow, column: GridColumn): { text: string; isDefault: boolean; isEmpty: boolean } { + const raw = column.sourceColumn ? row.values[column.sourceColumn] : null; + const blank = raw === null || raw === undefined || String(raw).trim() === ''; + if (blank && column.defaultValue) return { text: column.defaultValue, isDefault: true, isEmpty: false }; + return { text: blank ? 'null' : displayValue(raw), isDefault: false, isEmpty: blank }; + } + + errors(row: GridRow, column: GridColumn): RowError[] { + if (this.view() !== 'target') return []; + return this.flow().errorsByCell().get(`${row.index}:${column.id}`) ?? []; + } + + errorText(errors: RowError[]): string { + return errors.map((error) => error.message).join('\n'); + } + + qualityPercent(rate: number): number { + return Math.round((1 - rate) * 100); + } +} + +/** Excel/SQL dates arrive as midnight timestamps ("2024-01-10T00:00:00"); show them as plain dates. */ +function displayValue(value: unknown): string { + const text = String(value); + return /^\d{4}-\d{2}-\d{2}T00:00:00$/.test(text) ? text.slice(0, 10) : text; +} diff --git a/src/app/connect/components/database-explorer-dialog/database-explorer-dialog.html b/src/app/connect/components/database-explorer-dialog/database-explorer-dialog.html new file mode 100644 index 0000000..288c88b --- /dev/null +++ b/src/app/connect/components/database-explorer-dialog/database-explorer-dialog.html @@ -0,0 +1,61 @@ +

+ Explorar la base de datos + +

+ + + @for (target of data.targets; track target.key) { + + + {{ target.table }} + + @if (totals().get(target.key); as total) { + {{ total | number }} filas + } @else if (totals().has(target.key)) { + {{ totals().get(target.key) === 0 ? 'vacía' : 'no disponible' }} + } @else { + … + } + + + } + + +
+ @if (loading()) { + + } + @if (error(); as message) { + + } + @if (page(); as p) { + @if (p.rows.length === 0) { +

La tabla está vacía.

+ } @else { +
+ + @for (column of allColumns(); track column) { + + + + + } + + +
{{ column }}{{ display(row[column]) }}
+
+ + } + } +
+
+ + + diff --git a/src/app/connect/components/database-explorer-dialog/database-explorer-dialog.scss b/src/app/connect/components/database-explorer-dialog/database-explorer-dialog.scss new file mode 100644 index 0000000..3c29817 --- /dev/null +++ b/src/app/connect/components/database-explorer-dialog/database-explorer-dialog.scss @@ -0,0 +1,76 @@ +.explorer__title { + align-items: center; + display: flex; + gap: var(--space-2); + + button { + margin-left: auto; + } +} + +.explorer { + display: grid; + gap: var(--space-4); + grid-template-columns: 240px minmax(0, 1fr); + height: 70vh; +} + +.explorer__tables { + border-right: 1px solid var(--mat-sys-outline-variant); + overflow: auto; +} + +.explorer__rows { + display: flex; + flex-direction: column; + min-width: 0; +} + +.explorer__scroll { + border: 1px solid var(--mat-sys-outline-variant); + border-radius: var(--mat-sys-corner-medium); + flex: 1; + overflow: auto; +} + +.explorer__table { + --mat-table-row-item-container-height: 36px; + width: max-content; + min-width: 100%; + + th, + td { + border-right: 1px solid var(--mat-sys-outline-variant); + font-size: 12px; + max-width: 260px; + overflow: hidden; + padding: 0 var(--space-3); + text-overflow: ellipsis; + white-space: nowrap; + } + + th { + font-family: 'Roboto Mono', ui-monospace, monospace; + } +} + +.explorer__null { + color: var(--mat-sys-outline); + font-style: italic; +} + +.explorer__empty, +.explorer__error { + color: var(--mat-sys-on-surface-variant); +} + +.explorer__error { + color: var(--mat-sys-error); +} + +@media (max-width: 800px) { + .explorer { + grid-template-columns: 1fr; + height: auto; + } +} diff --git a/src/app/connect/components/database-explorer-dialog/database-explorer-dialog.ts b/src/app/connect/components/database-explorer-dialog/database-explorer-dialog.ts new file mode 100644 index 0000000..cd1d879 --- /dev/null +++ b/src/app/connect/components/database-explorer-dialog/database-explorer-dialog.ts @@ -0,0 +1,96 @@ +import { DecimalPipe } from '@angular/common'; +import { Component, OnInit, computed, inject, signal } from '@angular/core'; +import { forkJoin, of } from 'rxjs'; +import { catchError, map } from 'rxjs/operators'; +import { MatButtonModule } from '@angular/material/button'; +import { MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog'; +import { MatIconModule } from '@angular/material/icon'; +import { MatListModule } from '@angular/material/list'; +import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatTableModule } from '@angular/material/table'; +import { DataPage, TargetMeta, apiErrorMessage } from '../../api/api.types'; +import { DataApi } from '../../api/data.api'; + +export interface DatabaseExplorerData { + targets: TargetMeta[]; + initial?: string; +} + +/** + * Read-only view of what's stored in the destination database, table by + * table, paged server-side through the backend's Repository. The "Vista de + * datos" to confirm a load landed as expected. + */ +@Component({ + selector: 'app-database-explorer-dialog', + imports: [DecimalPipe, MatButtonModule, MatDialogModule, MatIconModule, MatListModule, MatPaginatorModule, MatProgressBarModule, MatTableModule], + templateUrl: './database-explorer-dialog.html', + styleUrl: './database-explorer-dialog.scss', +}) +export class DatabaseExplorerDialog implements OnInit { + readonly data = inject(MAT_DIALOG_DATA); + private readonly api = inject(DataApi); + + readonly totals = signal>(new Map()); + readonly selected = signal(null); + readonly page = signal(null); + readonly pageIndex = signal(0); + readonly pageSize = signal(25); + readonly loading = signal(false); + readonly error = signal(null); + + /** Table order from the backend (keys and FKs first), not the alphabetical order JSON objects arrive in. */ + readonly allColumns = computed(() => this.page()?.columns ?? []); + + ngOnInit(): void { + forkJoin( + this.data.targets.map((target) => + this.api.page(target.key, 1, 0).pipe( + map((page) => [target.key, page.total] as const), + catchError(() => of([target.key, null] as const)), + ), + ), + ).subscribe((entries) => this.totals.set(new Map(entries))); + const initial = this.data.targets.find((target) => target.key === this.data.initial) ?? this.data.targets[0]; + if (initial) this.open(initial); + } + + open(target: TargetMeta): void { + this.selected.set(target); + this.pageIndex.set(0); + this.fetch(); + } + + onPage(event: PageEvent): void { + this.pageIndex.set(event.pageIndex); + this.pageSize.set(event.pageSize); + this.fetch(); + } + + refresh(): void { + this.ngOnInit(); + } + + display(value: unknown): string { + if (value === null || value === undefined) return 'null'; + return String(value); + } + + private fetch(): void { + const target = this.selected(); + if (!target) return; + this.loading.set(true); + this.error.set(null); + this.api.page(target.key, this.pageSize(), this.pageIndex() * this.pageSize()).subscribe({ + next: (page) => { + this.loading.set(false); + this.page.set(page); + }, + error: (error) => { + this.loading.set(false); + this.error.set(apiErrorMessage(error, 'No se pudo leer la tabla.')); + }, + }); + } +} diff --git a/src/app/connect/components/document-review-dialog/document-review-dialog.html b/src/app/connect/components/document-review-dialog/document-review-dialog.html new file mode 100644 index 0000000..a98e60a --- /dev/null +++ b/src/app/connect/components/document-review-dialog/document-review-dialog.html @@ -0,0 +1,184 @@ +

Revisar extracción · {{ target.domain.toUpperCase() }} {{ target.table }}

+ + + + +
+ @if (extracting()) { + +

Leyendo documentos; las páginas escaneadas pasan por OCR y pueden tardar.

+ } + @if (error(); as message) { + + } + + @if (selected(); as record) { +
+

{{ record.key ?? 'Registro ' + (selectedIndex() + 1) }}

+ + Confianza mínima {{ record.confidence | percent }} + +
+ + + + + + + + + + + + @for (field of fields(); track field.name) { + @let found = extracted(record, field.name); + @let conflict = conflictFor(record, field.name); + + + + + + + } + +
CampoValorConfianzaDe dónde se leyó
+ {{ field.name }}@if (field.required) {*} + + + @if (conflict) { + + difiere + + } + + @if (isOverridden(record, field.name)) { + Manual + } @else if (found) { + + {{ methodLabels[found.method] ?? found.method }} · {{ found.confidence | percent }} + } + + @if (found?.line && !isOverridden(record, field.name)) { + + } +
+ + @if (record.images.length) { +

Imágenes en sus páginas

+
+ @for (image of record.images; track $index) { + + } +
+ } + + @if (page(); as shown) { +

{{ shown.document }} · página {{ shown.page }}

+ @if (shown.url) { + + } @else { + + } + } + } +
+
+ + + + + diff --git a/src/app/connect/components/document-review-dialog/document-review-dialog.scss b/src/app/connect/components/document-review-dialog/document-review-dialog.scss new file mode 100644 index 0000000..8a24dc5 --- /dev/null +++ b/src/app/connect/components/document-review-dialog/document-review-dialog.scss @@ -0,0 +1,228 @@ +.review { + display: grid; + gap: var(--space-4); + grid-template-columns: minmax(240px, 300px) minmax(0, 1fr); + max-height: 78vh; +} + +.review__side { + border-right: 1px solid var(--mat-sys-outline-variant); + display: flex; + flex-direction: column; + gap: var(--space-3); + overflow-y: auto; + padding-right: var(--space-3); +} + +.settings { + display: flex; + flex-direction: column; + gap: var(--space-3); +} + +.records__header { + align-items: baseline; + display: flex; + font: var(--mat-sys-label-large); + justify-content: space-between; +} + +.records__review, +.records__warn { + color: var(--mat-sys-error); +} + +.records__empty, +.review__hint { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-medium); +} + +.review__main { + min-width: 0; + overflow-y: auto; +} + +.review__error { + align-items: center; + color: var(--mat-sys-error); + display: flex; + gap: var(--space-2); +} + +.record__header { + align-items: baseline; + display: flex; + gap: var(--space-3); + justify-content: space-between; + + h3 { + font: var(--mat-sys-title-medium); + margin: 0; + } +} + +.record__confidence { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-label-medium); +} + +.record__confidence--low { + color: var(--mat-sys-error); +} + +.record__subtitle { + font: var(--mat-sys-title-small); + margin: var(--space-4) 0 var(--space-2); +} + +.fields { + border-collapse: collapse; + margin-top: var(--space-3); + width: 100%; + + th, + td { + border-bottom: 1px solid var(--mat-sys-outline-variant); + padding: var(--space-1) var(--space-2); + text-align: left; + vertical-align: middle; + } + + thead th { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-label-medium); + } +} + +.fields__name { + font: var(--mat-sys-body-small); + font-family: var(--font-mono, monospace); + white-space: nowrap; +} + +.fields__required { + color: var(--mat-sys-error); + margin-left: 2px; +} + +.fields__row--missing .fields__input { + border-color: var(--mat-sys-error); +} + +.fields__value { + min-width: 180px; +} + +.fields__input { + background: transparent; + border: 1px solid var(--mat-sys-outline-variant); + border-radius: var(--mat-sys-corner-extra-small); + color: inherit; + font: var(--mat-sys-body-medium); + padding: 4px 8px; + width: 100%; + + &:focus { + border-color: var(--mat-sys-primary); + outline: none; + } +} + +.fields__input--edited { + background: color-mix(in srgb, var(--mat-sys-primary) 8%, transparent); +} + +.fields__conflict { + align-items: center; + color: var(--mat-sys-error); + display: inline-flex; + font: var(--mat-sys-label-small); + gap: 2px; + + mat-icon { + font-size: 16px; + height: 16px; + width: 16px; + } +} + +.fields__confidence { + min-width: 120px; + + mat-progress-bar.low { + --mat-progress-bar-active-indicator-color: var(--mat-sys-error); + } +} + +.method { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-label-small); +} + +.method--manual { + color: var(--mat-sys-primary); +} + +.evidence { + align-items: flex-start; + display: flex; + flex-direction: column; + height: auto; + max-width: 340px; + padding: 2px 6px; + text-align: left; +} + +.evidence__line { + font: var(--mat-sys-body-small); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + width: 100%; +} + +.evidence__where { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-label-small); +} + +.images { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); +} + +.image { + align-items: center; + background: var(--mat-sys-surface-container-low); + border: 1px solid var(--mat-sys-outline-variant); + border-radius: var(--mat-sys-corner-small); + cursor: pointer; + display: flex; + flex-direction: column; + font: var(--mat-sys-label-small); + gap: var(--space-1); + padding: var(--space-2); + + img { + max-height: 120px; + max-width: 160px; + } +} + +.page { + border: 1px solid var(--mat-sys-outline-variant); + max-width: 100%; +} + +@media (max-width: 900px) { + .review { + grid-template-columns: 1fr; + } + + .review__side { + border-right: none; + padding-right: 0; + } +} diff --git a/src/app/connect/components/document-review-dialog/document-review-dialog.ts b/src/app/connect/components/document-review-dialog/document-review-dialog.ts new file mode 100644 index 0000000..52344f0 --- /dev/null +++ b/src/app/connect/components/document-review-dialog/document-review-dialog.ts @@ -0,0 +1,208 @@ +import { PercentPipe } from '@angular/common'; +import { Component, DestroyRef, computed, inject, signal } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatInputModule } from '@angular/material/input'; +import { MatListModule } from '@angular/material/list'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatSelectModule } from '@angular/material/select'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { + DocumentFieldSpec, + DocumentImage, + DocumentSettings, + ExtractedField, + ExtractedRecord, + SegmentationInfo, + TargetMeta, + apiErrorMessage, +} from '../../api/api.types'; +import { SourceGateway } from '../../api/source-gateway'; +import { DocumentTable, FieldOverrides } from '../../domain/document-source'; + +export interface DocumentReviewData { + table: DocumentTable; + target: TargetMeta; + segmentations: SegmentationInfo[]; +} + +const METHOD_LABELS: Record = { + etiqueta: 'Etiqueta', + patron: 'Patrón', + texto_libre: 'Texto libre', + manual: 'Manual', +}; + +const REVIEW_BELOW = 0.8; + +/** + * Review of what was extracted from a set of documents for one target + * entity: how pages were split into patient records, every value with its + * confidence and the line it was read from, conflicts between documents, + * and the images on each record's pages. Values can be corrected; the + * corrections and settings are applied to the table on "Aplicar". + */ +@Component({ + selector: 'app-document-review-dialog', + imports: [ + FormsModule, + MatButtonModule, + MatDialogModule, + MatFormFieldModule, + MatIconModule, + MatInputModule, + MatListModule, + MatProgressBarModule, + MatSelectModule, + MatTooltipModule, + PercentPipe, + ], + templateUrl: './document-review-dialog.html', + styleUrl: './document-review-dialog.scss', +}) +export class DocumentReviewDialog { + private readonly data = inject(MAT_DIALOG_DATA); + private readonly dialogRef = inject>(MatDialogRef); + private readonly gateway = inject(SourceGateway); + private readonly destroyRef = inject(DestroyRef); + + readonly table = this.data.table; + readonly target = this.data.target; + readonly segmentations = this.data.segmentations; + readonly methodLabels = METHOD_LABELS; + readonly reviewBelow = REVIEW_BELOW; + + readonly settings = signal({ ...this.table.settings() }); + readonly overrides = signal(structuredClone(this.table.overrides(this.target.key))); + readonly extracting = signal(false); + readonly error = signal(null); + readonly selectedIndex = signal(0); + + readonly extraction = computed(() => this.table.extractions()[this.target.key] ?? null); + readonly records = computed(() => this.extraction()?.records ?? []); + readonly fields = computed(() => this.extraction()?.fields ?? []); + readonly selected = computed(() => this.records()[this.selectedIndex()] ?? null); + readonly needsReview = computed(() => this.records().filter((record) => this.recordNeedsReview(record)).length); + + /** Object URLs of rendered images, by `document|page|bbox`. */ + readonly thumbnails = signal>({}); + readonly page = signal<{ document: string; page: number; url: string | null } | null>(null); + + constructor() { + if (this.extraction()) this.select(0); + else this.extract(); + this.destroyRef.onDestroy(() => { + Object.values(this.thumbnails()).forEach((url) => URL.revokeObjectURL(url)); + const page = this.page(); + if (page?.url) URL.revokeObjectURL(page.url); + }); + } + + // -- settings ------------------------------------------------------------ + + updateSettings(patch: Partial): void { + this.settings.update((settings) => ({ ...settings, ...patch })); + } + + get settingsChanged(): boolean { + return JSON.stringify(this.settings()) !== JSON.stringify(this.table.settings()); + } + + extract(): void { + if (this.settingsChanged) this.overrides.set({}); + this.table.configure(this.settings()); + this.extracting.set(true); + this.error.set(null); + this.table.preview(this.gateway, this.target.key).subscribe({ + next: () => { + this.extracting.set(false); + this.select(0); + }, + error: (error) => { + this.extracting.set(false); + this.error.set(apiErrorMessage(error, 'No se pudieron leer los documentos.')); + }, + }); + } + + // -- records and values ------------------------------------------------------ + + select(index: number): void { + this.selectedIndex.set(index); + this.page.set(null); + this.selected()?.images.forEach((image) => this.loadThumbnail(image)); + } + + recordNeedsReview(record: ExtractedRecord): boolean { + return record.missing.length > 0 || record.conflicts.length > 0 || record.confidence < REVIEW_BELOW; + } + + extracted(record: ExtractedRecord, field: string): ExtractedField | null { + return record.fields[field] ?? null; + } + + value(record: ExtractedRecord, field: string): string { + const override = this.overrides()[String(record.index)]?.[field]; + if (override !== undefined) return String(override ?? ''); + const value = record.fields[field]?.value; + return value === null || value === undefined ? '' : String(value); + } + + isOverridden(record: ExtractedRecord, field: string): boolean { + return this.overrides()[String(record.index)]?.[field] !== undefined; + } + + setValue(record: ExtractedRecord, field: string, value: string): void { + const key = String(record.index); + this.overrides.update((all) => { + const next = { ...all, [key]: { ...(all[key] ?? {}) } }; + const original = record.fields[field]?.value; + if (value === (original === null || original === undefined ? '' : String(original))) delete next[key][field]; + else next[key][field] = value === '' ? null : value; + if (!Object.keys(next[key]).length) delete next[key]; + return next; + }); + } + + conflictFor(record: ExtractedRecord, field: string) { + return record.conflicts.find((conflict) => conflict.field === field) ?? null; + } + + // -- pages and images ---------------------------------------------------------- + + thumbnailKey(image: DocumentImage): string { + return `${image.document}|${image.page_number}|${image.bbox.join(',')}`; + } + + showPage(document: string | undefined, pageNumber: number | undefined): void { + const file = this.table.files.find((candidate) => candidate.name === document); + if (!file || !pageNumber) return; + const previous = this.page(); + if (previous?.url) URL.revokeObjectURL(previous.url); + this.page.set({ document: file.name, page: pageNumber, url: null }); + this.gateway.document.pageImage(file, pageNumber).subscribe((blob) => { + if (this.page()?.document === file.name && this.page()?.page === pageNumber) { + this.page.set({ document: file.name, page: pageNumber, url: URL.createObjectURL(blob) }); + } + }); + } + + private loadThumbnail(image: DocumentImage): void { + const key = this.thumbnailKey(image); + const file = this.table.files.find((candidate) => candidate.name === image.document); + if (!file || this.thumbnails()[key]) return; + this.gateway.document.pageImage(file, image.page_number, image.kind === 'figure' ? image.bbox : undefined, 72).subscribe((blob) => { + this.thumbnails.update((all) => ({ ...all, [key]: URL.createObjectURL(blob) })); + }); + } + + // -- close ------------------------------------------------------------------------- + + apply(): void { + this.table.configure(this.settings(), { [this.target.key]: this.overrides() }); + this.dialogRef.close(true); + } +} diff --git a/src/app/connect/components/file-dropzone/file-dropzone.html b/src/app/connect/components/file-dropzone/file-dropzone.html new file mode 100644 index 0000000..92fdaa0 --- /dev/null +++ b/src/app/connect/components/file-dropzone/file-dropzone.html @@ -0,0 +1,37 @@ +
+ +

Arrastra tus archivos aquí

+

{{ formatsLabel }}

+ + +
+ +@if (fileMessages().length > 0) { +
    + @for (message of fileMessages(); track $index) {
  • {{ message }}
  • } +
+} + +@if (files().length > 0) { +
+
+

Archivos seleccionados

+ {{ files().length }} +
+
    + @for (file of files(); track file.name + ':' + file.size) { +
  • + + {{ file.name }} + {{ formatFileSize(file.size) }} + +
  • + } +
+
+} diff --git a/src/app/connect/components/file-dropzone/file-dropzone.scss b/src/app/connect/components/file-dropzone/file-dropzone.scss new file mode 100644 index 0000000..092e196 --- /dev/null +++ b/src/app/connect/components/file-dropzone/file-dropzone.scss @@ -0,0 +1,157 @@ +:host { + display: block; +} +.dropzone { + align-items: center; + background: var(--color-surface); + border: 1.5px dashed #cbd2c4; + border-radius: 10px; + display: flex; + flex-direction: column; + justify-content: center; + min-height: 220px; + padding: var(--space-6); + text-align: center; + transition: + background-color 0.14s ease, + border-color 0.14s ease; +} +.dropzone--active { + background: #f5f8e9; + border-color: var(--color-primary); + border-style: solid; +} +.dropzone__icon { + color: #71882b; + font-size: 40px; + height: 40px; + width: 40px; +} +.dropzone__title { + font-size: 16px; + font-weight: 600; + margin: var(--space-4) 0 var(--space-1); + color: var(--color-text); +} +.dropzone__formats { + color: var(--color-text-secondary); + font-size: 13px; + margin: 0 0 var(--space-4); +} +.select-files-button { + --mat-button-outlined-label-text-color: var(--color-text); + --mat-button-outlined-outline-color: #d7dccf; + --mat-button-outlined-state-layer-color: transparent; + --mat-button-outlined-ripple-color: transparent; + background: var(--color-surface); + border: 1px solid var(--mat-button-outlined-outline-color); + transition: border-color 0.18s ease; +} +.upload-action--outlined:hover { + background: #f3f6e9; + border-color: var(--color-primary); +} +.upload-action--outlined:active { + background: #e8eed5; +} +.select-files-button mat-icon { + color: #5f9ea0; + margin: 0; +} +.visually-hidden { + clip: rect(0, 0, 0, 0); + clip-path: inset(50%); + height: 1px; + overflow: hidden; + position: absolute; + white-space: nowrap; + width: 1px; +} +.file-messages { + background: #fffaf0; + border: 1px solid #ead8a7; + border-radius: 7px; + color: #634d13; + font-size: 13px; + line-height: 1.45; + list-style: none; + margin: var(--space-3) 0 0; + padding: var(--space-3) var(--space-4); +} +.file-messages li + li { + margin-top: var(--space-1); +} +.selected-files { + margin-top: var(--space-5); +} +.selected-files__header { + align-items: center; + display: flex; + gap: var(--space-3); + justify-content: space-between; + margin-bottom: var(--space-2); +} +.selected-files__header h3 { + font-size: 15px; + font-weight: 600; + margin: 0; + color: var(--color-text); +} +.selected-files__count { + align-items: center; + background: var(--color-step); + border-radius: 20px; + color: #52651d; + display: inline-flex; + font-size: 12px; + font-weight: 600; + height: 25px; + justify-content: center; + min-width: 25px; + padding: 0 var(--space-2); +} +.selected-files__list { + border: 1px solid #e7eae3; + border-radius: 8px; + list-style: none; + margin: 0; + max-height: 220px; + overflow-y: auto; + padding: 0; +} +.file-row { + align-items: center; + display: grid; + gap: var(--space-3); + grid-template-columns: 22px minmax(0, 1fr) auto 40px; + min-height: 54px; + padding: var(--space-2) var(--space-2) var(--space-2) var(--space-3); +} +.file-row + .file-row { + border-top: 1px solid #eef0eb; +} +.file-row__icon { + color: #71882b; + font-size: 20px; + height: 20px; + width: 20px; +} +.file-row__name { + font-size: 13px; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--color-text); +} +.file-row__size { + color: #737b6b; + font-size: 12px; + white-space: nowrap; +} +.file-row__remove { + color: #596273; + height: 36px; + line-height: 36px; + width: 36px; +} diff --git a/src/app/connect/components/file-dropzone/file-dropzone.spec.ts b/src/app/connect/components/file-dropzone/file-dropzone.spec.ts new file mode 100644 index 0000000..4be0e3f --- /dev/null +++ b/src/app/connect/components/file-dropzone/file-dropzone.spec.ts @@ -0,0 +1,104 @@ +import { TestBed } from '@angular/core/testing'; +import { FileDropzone } from './file-dropzone'; + +describe('FileDropzone', () => { + function createFixture() { + const fixture = TestBed.createComponent(FileDropzone); + fixture.detectChanges(); + return fixture; + } + + beforeEach(async () => { + await TestBed.configureTestingModule({ imports: [FileDropzone] }).compileComponents(); + }); + + it('accepts valid files and rejects invalid extension, empty, and duplicate files', () => { + const fixture = createFixture(); + const compiled = fixture.nativeElement as HTMLElement; + const validFile = new File(['contenido'], 'pacientes.XLSX', { type: 'application/octet-stream' }); + const csvFile = new File(['a,b'], 'consultas.csv', { type: 'text/csv' }); + const invalidFile = new File(['x'], 'documento.docx'); + const emptyFile = new File([], 'vacio.csv'); + + const fileInput = compiled.querySelector('input[type="file"]')!; + Object.defineProperty(fileInput, 'files', { + configurable: true, + value: [validFile, csvFile, invalidFile, emptyFile], + }); + fileInput.dispatchEvent(new Event('change', { bubbles: true })); + fixture.detectChanges(); + + expect(compiled.querySelectorAll('.file-row')).toHaveLength(2); + expect(compiled.querySelector('.file-messages')?.textContent).toContain( + 'documento.docx no fue agregado. Formato no compatible.', + ); + expect(compiled.querySelector('.file-messages')?.textContent).toContain( + 'vacio.csv no fue agregado. El archivo está vacío.', + ); + }); + + it('rejects a duplicate file (same name + size) already selected', () => { + const fixture = createFixture(); + const compiled = fixture.nativeElement as HTMLElement; + const validFile = new File(['contenido'], 'pacientes.xlsx', { type: 'application/octet-stream' }); + const fileInput = compiled.querySelector('input[type="file"]')!; + + const selectFiles = (files: File[]) => { + Object.defineProperty(fileInput, 'files', { configurable: true, value: files }); + fileInput.dispatchEvent(new Event('change', { bubbles: true })); + fixture.detectChanges(); + }; + + selectFiles([validFile]); + expect(compiled.querySelectorAll('.file-row')).toHaveLength(1); + selectFiles([validFile]); + expect(compiled.querySelectorAll('.file-row')).toHaveLength(1); + expect(compiled.querySelector('.file-messages')?.textContent).toContain( + 'pacientes.xlsx ya se encuentra seleccionado.', + ); + }); + + it('supports drag and drop and removing a file, and emits filesChange', () => { + const fixture = createFixture(); + const compiled = fixture.nativeElement as HTMLElement; + const component = fixture.componentInstance; + const emitted: File[][] = []; + component.filesChange.subscribe((files) => emitted.push(files)); + + const jsonFile = new File(['{}'], 'nuevo.json', { type: 'application/json' }); + component.onDrop({ + preventDefault: () => undefined, + dataTransfer: { files: [jsonFile] }, + } as unknown as DragEvent); + fixture.detectChanges(); + + expect(compiled.querySelectorAll('.file-row')).toHaveLength(1); + expect(emitted.at(-1)).toEqual([jsonFile]); + + compiled.querySelector('.file-row__remove')!.click(); + fixture.detectChanges(); + expect(compiled.querySelectorAll('.file-row')).toHaveLength(0); + expect(emitted.at(-1)).toEqual([]); + }); + + it('honors a custom accept input, keeping pdf available by default', () => { + const fixture = createFixture(); + expect(fixture.componentInstance.allowedExtensions.has('pdf')).toBe(true); + + fixture.componentRef.setInput('accept', ['csv']); + fixture.detectChanges(); + expect(fixture.componentInstance.allowedExtensions.has('pdf')).toBe(false); + expect(fixture.componentInstance.allowedExtensions.has('csv')).toBe(true); + }); + + it('reflects drag-over state via dragenter/dragleave', () => { + const fixture = createFixture(); + const component = fixture.componentInstance; + const preventDefault = () => undefined; + + component.onDragEnter({ preventDefault } as unknown as DragEvent); + expect(component.isDragOver()).toBe(true); + component.onDragLeave({ preventDefault } as unknown as DragEvent); + expect(component.isDragOver()).toBe(false); + }); +}); diff --git a/src/app/information-upload-dialog.ts b/src/app/connect/components/file-dropzone/file-dropzone.ts similarity index 67% rename from src/app/information-upload-dialog.ts rename to src/app/connect/components/file-dropzone/file-dropzone.ts index 2901f6b..4702123 100644 --- a/src/app/information-upload-dialog.ts +++ b/src/app/connect/components/file-dropzone/file-dropzone.ts @@ -1,47 +1,35 @@ -import { Component, signal } from '@angular/core'; +import { Component, EventEmitter, Input, Output, signal } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; -import { MatDialogModule, MatDialogRef } from '@angular/material/dialog'; import { MatIconModule } from '@angular/material/icon'; -type UploadSource = 'file' | 'sql'; -type UploadStep = 'source' | 'configuration' | 'confirmation'; - +/** Drag-and-drop and file-picker area that collects a validated list of files. */ @Component({ - imports: [MatButtonModule, MatDialogModule, MatIconModule], - selector: 'app-information-upload-dialog', - styleUrl: './information-upload-dialog.scss', - templateUrl: './information-upload-dialog.html', + imports: [MatButtonModule, MatIconModule], + selector: 'app-file-dropzone', + styleUrl: './file-dropzone.scss', + templateUrl: './file-dropzone.html', }) -export class InformationUploadDialog { - readonly step = signal('source'); - readonly source = signal(null); +export class FileDropzone { + @Input() accept: string[] = ['xlsx', 'csv', 'json', 'pdf']; + @Input() multiple = true; + @Output() readonly filesChange = new EventEmitter(); + readonly files = signal([]); readonly fileMessages = signal([]); readonly isDragOver = signal(false); private dragDepth = 0; - private readonly allowedExtensions = new Set(['xlsx', 'csv', 'json', 'pdf']); - constructor(private readonly dialogRef: MatDialogRef) {} - - selectSource(source: UploadSource): void { - this.source.set(source); + get allowedExtensions(): Set { + return new Set(this.accept.map((extension) => extension.toLowerCase())); } - continue(): void { - if (this.step() === 'source' && this.source()) this.step.set('configuration'); - else if (this.step() === 'configuration' && this.source() === 'file' && this.files().length > 0) { - this.step.set('confirmation'); - } + get acceptAttribute(): string { + return this.accept.map((extension) => `.${extension}`).join(','); } - back(): void { - if (this.step() === 'confirmation') this.step.set('configuration'); - else if (this.step() === 'configuration') this.step.set('source'); - } - - close(): void { - this.dialogRef.close(); + get formatsLabel(): string { + return this.accept.map((extension) => extension.toUpperCase()).join(' · '); } onFileSelection(event: Event): void { @@ -76,6 +64,7 @@ export class InformationUploadDialog { removeFile(fileToRemove: File): void { this.files.update((files) => files.filter((file) => file !== fileToRemove)); + this.filesChange.emit(this.files()); } formatFileSize(size: number): string { @@ -99,7 +88,7 @@ export class InformationUploadDialog { private addFiles(incomingFiles: File[]): void { const messages: string[] = []; - const accepted = [...this.files()]; + const accepted = this.multiple ? [...this.files()] : []; for (const file of incomingFiles) { const extension = this.extensionOf(file.name); @@ -115,11 +104,16 @@ export class InformationUploadDialog { messages.push(`${file.name} ya se encuentra seleccionado.`); continue; } + if (!this.multiple) { + accepted.length = 0; + } accepted.push(file); + if (!this.multiple) break; } - if (accepted.length !== this.files().length) this.files.set(accepted); + this.files.set(accepted); this.fileMessages.set(messages); + this.filesChange.emit(accepted); } private extensionOf(fileName: string): string { diff --git a/src/app/connect/components/flow-canvas/flow-canvas.html b/src/app/connect/components/flow-canvas/flow-canvas.html new file mode 100644 index 0000000..11564c9 --- /dev/null +++ b/src/app/connect/components/flow-canvas/flow-canvas.html @@ -0,0 +1,102 @@ +
+
+

Flujos de carga

+ + {{ store.flows().length }} flujo(s) · cada uno lleva una tabla de origen a una tabla de la base + +
+ +
+ @for (flow of store.flows(); track flow.id) { + +
+ + + {{ flow.table.name }} + + + + + {{ flow.target.table }} + + + + + + +
+ +

{{ flow.table.connection.label }}

+ + + +
+ + + {{ mappedFields(flow) }}/{{ flow.target.fields.length }} campos + + @if (flow.totalRows() !== null) { + {{ flow.totalRows() | number }} filas + } + @if (flow.validation(); as validation) { + @if (validation.error_count > 0) { + {{ validation.error_count | number }} con errores + } + } + @if (flow.result(); as result) { + +{{ result.created }} / ↻{{ result.updated }} + } +
+
+ } + +
+ +

+ @if (store.connections().length === 0) { + Agrega una conexión y arrastra sus tablas aquí para componer tu carga. + } @else { + Arrastra aquí una tabla de «Conexiones» — o usa su botón . + } +

+ @if (store.connections().length === 0) { + + } +
+
+
diff --git a/src/app/connect/components/flow-canvas/flow-canvas.scss b/src/app/connect/components/flow-canvas/flow-canvas.scss new file mode 100644 index 0000000..7dc86a6 --- /dev/null +++ b/src/app/connect/components/flow-canvas/flow-canvas.scss @@ -0,0 +1,167 @@ +:host { + display: block; +} + +.canvas { + border-radius: var(--mat-sys-corner-large); + padding: var(--space-4); + transition: background-color 0.15s ease, outline-color 0.15s ease; +} + +.canvas.cdk-drop-list-receiving { + outline: 2px dashed var(--mat-sys-primary); + outline-offset: -2px; +} + +.canvas.cdk-drop-list-dragging { + background: color-mix(in srgb, var(--mat-sys-primary-container) 45%, transparent); +} + +.canvas ::ng-deep .cdk-drag-placeholder { + display: none; +} + +.canvas__header { + align-items: baseline; + display: flex; + flex-wrap: wrap; + gap: var(--space-1) var(--space-3); + margin-bottom: var(--space-3); + + h2 { + font: var(--mat-sys-title-medium); + margin: 0; + } +} + +.canvas__caption { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); +} + +.canvas__grid { + display: grid; + gap: var(--space-3); + grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); +} + +.flow-card { + cursor: pointer; + display: flex; + flex-direction: column; + gap: var(--space-2); + padding: var(--space-3) var(--space-3) var(--space-3) var(--space-4); + transition: border-color 0.15s ease, box-shadow 0.15s ease; + + &:hover { + box-shadow: var(--mat-sys-level1); + } + + &:focus-visible { + outline: 2px solid var(--mat-sys-primary); + } +} + +.flow-card--selected { + border-color: var(--mat-sys-primary) !important; + box-shadow: 0 0 0 1px var(--mat-sys-primary), var(--mat-sys-level1); +} + +.flow-card__route { + align-items: center; + display: flex; + gap: var(--space-1); +} + +.flow-card__end { + align-items: center; + display: inline-flex; + flex: 1 1 0; + gap: var(--space-1); + min-width: 0; + + mat-icon { + color: var(--mat-sys-on-surface-variant); + flex: none; + font-size: 20px; + height: 20px; + width: 20px; + } +} + +.flow-card__end--target mat-icon { + color: var(--mat-sys-primary); +} + +.flow-card__name { + font: var(--mat-sys-title-small); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.flow-card__arrow { + color: var(--mat-sys-outline); + flex: none; +} + +.flow-card__menu { + flex: none; + margin: -8px -4px -8px 0; +} + +.flow-card__source { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); + margin: -4px 0 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.flow-card__facts { + align-items: center; + color: var(--mat-sys-on-surface-variant); + display: flex; + flex-wrap: wrap; + font: var(--mat-sys-body-small); + gap: var(--space-1) var(--space-3); +} + +.flow-card__errors { + color: #9a5b00; +} + +.flow-card__loaded { + color: var(--mat-sys-primary); + font-weight: 500; +} + +.canvas__drop { + align-items: center; + border: 1.5px dashed var(--mat-sys-outline-variant); + border-radius: var(--mat-sys-corner-medium); + color: var(--mat-sys-on-surface-variant); + display: flex; + flex-direction: column; + font: var(--mat-sys-body-medium); + gap: var(--space-2); + justify-content: center; + min-height: 132px; + padding: var(--space-4); + text-align: center; + + p { + margin: 0; + max-width: 360px; + } + + > mat-icon { + color: var(--mat-sys-primary); + } +} + +.canvas__drop--alone { + grid-column: 1 / -1; + min-height: 220px; +} diff --git a/src/app/connect/components/flow-canvas/flow-canvas.ts b/src/app/connect/components/flow-canvas/flow-canvas.ts new file mode 100644 index 0000000..c041352 --- /dev/null +++ b/src/app/connect/components/flow-canvas/flow-canvas.ts @@ -0,0 +1,56 @@ +import { CdkDrag, CdkDragDrop, DragDropModule } from '@angular/cdk/drag-drop'; +import { DecimalPipe } from '@angular/common'; +import { Component, inject, output } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCardModule } from '@angular/material/card'; +import { MatIconModule } from '@angular/material/icon'; +import { MatMenuModule } from '@angular/material/menu'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { SourceTable } from '../../domain/data-source'; +import { ImportFlow } from '../../domain/import-flow'; +import { ConnectWorkspaceStore } from '../../state/connect-workspace.store'; +import { FlowStatusChip } from '../shared/flow-status'; + +/** + * The composition canvas: one card per import flow (source table → + * destination entity), the whole batch visible at once. Drop a table from + * the connections pane anywhere on it to add a flow. + */ +@Component({ + selector: 'app-flow-canvas', + imports: [ + DecimalPipe, + DragDropModule, + FlowStatusChip, + MatButtonModule, + MatCardModule, + MatIconModule, + MatMenuModule, + MatProgressBarModule, + MatTooltipModule, + ], + templateUrl: './flow-canvas.html', + styleUrl: './flow-canvas.scss', +}) +export class FlowCanvas { + readonly store = inject(ConnectWorkspaceStore); + + readonly tableDropped = output(); + readonly addConnection = output(); + + readonly onlyTables = (drag: CdkDrag) => drag.data instanceof SourceTable; + + onDrop(event: CdkDragDrop): void { + if (event.item.data instanceof SourceTable) this.tableDropped.emit(event.item.data); + } + + mappedFields(flow: ImportFlow): number { + return flow.mapping.size() + Object.keys(flow.activeDefaults()).length; + } + + coverage(flow: ImportFlow): number { + const total = flow.target.fields.length; + return total ? Math.round((this.mappedFields(flow) / total) * 100) : 0; + } +} diff --git a/src/app/connect/components/flow-editor/flow-editor.html b/src/app/connect/components/flow-editor/flow-editor.html new file mode 100644 index 0000000..4a4b976 --- /dev/null +++ b/src/app/connect/components/flow-editor/flow-editor.html @@ -0,0 +1,73 @@ +@let f = flow(); +
+
+
+ + {{ f.label }} + + + {{ f.target.domain.toUpperCase() }} · {{ f.target.table }} + +
+
+ @if (f.totalRows() !== null) { + {{ f.totalRows() | number }} filas en la fuente + } + @if (documentTable()) { + + } + + +
+
+ + @if (f.loading()) { + + } + @if (f.error(); as error) { + + } + + @if (f.preview()) { + + + + Mapeo + @if (f.missingRequired().length) { + {{ f.missingRequired().length }} + } + +
+
+ + Datos +
+
+ + + Validación + @if (f.validation(); as validation) { + {{ validation.error_count | number }} + } + +
+
+
+ } +
diff --git a/src/app/connect/components/flow-editor/flow-editor.scss b/src/app/connect/components/flow-editor/flow-editor.scss new file mode 100644 index 0000000..4c28daf --- /dev/null +++ b/src/app/connect/components/flow-editor/flow-editor.scss @@ -0,0 +1,101 @@ +:host { + display: block; +} + +.editor { + background: var(--mat-sys-surface); + border: 1px solid var(--mat-sys-outline-variant); + border-radius: var(--mat-sys-corner-large); + overflow: hidden; +} + +.editor__header { + align-items: center; + border-bottom: 1px solid var(--mat-sys-outline-variant); + display: flex; + flex-wrap: wrap; + gap: var(--space-3); + justify-content: space-between; + padding: var(--space-3) var(--space-4); +} + +.editor__route { + align-items: center; + display: flex; + gap: var(--space-2); + min-width: 0; + + > mat-icon { + color: var(--mat-sys-on-surface-variant); + flex: none; + } +} + +.editor__source, +.editor__target { + font: var(--mat-sys-title-small); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.editor__source { + max-width: 36ch; +} + +.editor__arrow { + color: var(--mat-sys-outline) !important; +} + +.editor__target-icon { + color: var(--mat-sys-primary) !important; +} + +.editor__actions { + align-items: center; + display: flex; + flex-wrap: wrap; + gap: var(--space-2); +} + +.editor__rows { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); + margin-right: var(--space-2); +} + +.editor__error { + align-items: center; + background: var(--mat-sys-error-container); + color: var(--mat-sys-on-error-container); + display: flex; + gap: var(--space-2); + margin: 0; + padding: var(--space-2) var(--space-4); +} + +.editor__tabs ::ng-deep .mat-mdc-tab .mdc-tab__text-label { + gap: 6px; + + mat-icon { + font-size: 18px; + height: 18px; + width: 18px; + } +} + +.editor__panel { + padding: var(--space-4); +} + +.tab-count { + background: var(--mat-sys-surface-container-highest); + border-radius: 999px; + font: var(--mat-sys-label-small); + padding: 1px 7px; +} + +.tab-count--warn { + background: #fff1d6; + color: #7a4b00; +} diff --git a/src/app/connect/components/flow-editor/flow-editor.ts b/src/app/connect/components/flow-editor/flow-editor.ts new file mode 100644 index 0000000..c07fa5a --- /dev/null +++ b/src/app/connect/components/flow-editor/flow-editor.ts @@ -0,0 +1,72 @@ +import { DecimalPipe } from '@angular/common'; +import { Component, computed, inject, input, signal } from '@angular/core'; +import { MatBadgeModule } from '@angular/material/badge'; +import { MatButtonModule } from '@angular/material/button'; +import { MatDialog } from '@angular/material/dialog'; +import { MatIconModule } from '@angular/material/icon'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatTabsModule } from '@angular/material/tabs'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { DocumentTable } from '../../domain/document-source'; +import { ImportFlow } from '../../domain/import-flow'; +import { ConnectWorkspaceStore } from '../../state/connect-workspace.store'; +import { ColumnMapper } from '../column-mapper/column-mapper'; +import { DataGrid } from '../data-grid/data-grid'; +import { DocumentReviewData, DocumentReviewDialog } from '../document-review-dialog/document-review-dialog'; +import { FlowStatusChip } from '../shared/flow-status'; +import { ValidationReport } from '../validation-report/validation-report'; + +const VALIDATION_TAB = 2; + +/** Everything about the selected flow: its mapping, its data, its validation. */ +@Component({ + selector: 'app-flow-editor', + imports: [ + ColumnMapper, + DataGrid, + DecimalPipe, + FlowStatusChip, + MatBadgeModule, + MatButtonModule, + MatIconModule, + MatProgressBarModule, + MatTabsModule, + MatTooltipModule, + ValidationReport, + ], + templateUrl: './flow-editor.html', + styleUrl: './flow-editor.scss', +}) +export class FlowEditor { + readonly flow = input.required(); + readonly store = inject(ConnectWorkspaceStore); + private readonly dialog = inject(MatDialog); + readonly tab = signal(0); + + /** Document sources get a review of what was extracted, record by record. */ + readonly documentTable = computed(() => { + const table = this.flow().table; + return table instanceof DocumentTable ? table : null; + }); + + reviewExtraction(): void { + const table = this.documentTable(); + if (!table) return; + const segmentations = this.store.connectors().find((c) => c.kind === 'document')?.segmentations ?? []; + this.dialog + .open(DocumentReviewDialog, { + data: { table, target: this.flow().target, segmentations }, + width: '1280px', + maxWidth: '98vw', + autoFocus: false, + disableClose: true, + }) + .afterClosed() + .subscribe((applied) => applied && this.store.flowsOf(table).forEach((flow) => this.store.reloadFlow(flow))); + } + + async validate(): Promise { + await this.store.validate(this.flow()); + this.tab.set(VALIDATION_TAB); + } +} diff --git a/src/app/connect/components/load-dialog/load-dialog.html b/src/app/connect/components/load-dialog/load-dialog.html new file mode 100644 index 0000000..e7f3302 --- /dev/null +++ b/src/app/connect/components/load-dialog/load-dialog.html @@ -0,0 +1,115 @@ +

Cargar a la base de datos · {{ store.domain().toUpperCase() }}

+ + @if (validating()) { +

Validando todas las filas de {{ flows().length }} flujo(s)…

+ + } @else { + @if (!batch()) { +

+ Se escribirán {{ totals().valid | number }} filas válidas de {{ totals().rows | number }} en + {{ flows().length }} flujo(s), en una sola transacción: si algo falla en la base, no se escribe nada. + @if (totals().errors > 0) { + {{ totals().errors | number }} fila(s) con errores se omitirán. + } +

+ } @else if (outcome(); as o) { +

+ + Carga completa: {{ o.created | number }} insertadas, {{ o.updated | number }} actualizadas, {{ o.rejected | number }} omitidas. + @if (o.merged) { + {{ o.merged | number }} combinadas con registros de otras fuentes@if (o.warnings) {, {{ o.warnings | number }} valor(es) en desacuerdo}. + } +

+ } + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Flujo + {{ flow.table.name }} + → {{ flow.target.table }} + EstadoFilas{{ flow.validation()?.total_rows | number }}Válidas{{ flow.validation()?.valid_count | number }}Con error{{ flow.validation()?.error_count | number }}Resultado + @if (resultOf(flow); as result) { + +{{ result.created }} · ↻{{ result.updated }} · ✕{{ result.rejected }}@if (result.merged) { · ⧉{{ result.merged }} } + } @else { + — + } +
+ + @if (skipped().length > 0) { +

+ + {{ skipped().length }} flujo(s) no se cargarán porque no están listos (faltan obligatorios o la fuente falló). +

+ } + + @if (!batch()) { +
+

Si un registro ya existe en la base

+ + Omitirlo (se reporta como conflicto) + + Actualizarlo con los campos mapeados (los demás campos no se tocan) + + + @if (!store.upsertAvailable()) { +

Actualizar solo es posible cuando todas las tablas destino tienen clave natural (p. ej. Paciente).

+ } +
+ @if (mergeAvailable()) { +
+

Datos de un mismo paciente en varias fuentes

+ + Combinar las filas con la misma clave en un solo registro antes de validar + +

+ Cada fuente completa los campos que a las demás les faltan; si dos fuentes no coinciden en un valor se conserva + el del primer flujo y se reporta. La validación previa por flujo no considera esta combinación. +

+
+ } + } + + @if (store.committing()) { + + } + @if (store.commitError(); as error) { + + } + } +
+ + @if (batch()) { + + + } @else { + + + } + diff --git a/src/app/connect/components/load-dialog/load-dialog.scss b/src/app/connect/components/load-dialog/load-dialog.scss new file mode 100644 index 0000000..e7fa64a --- /dev/null +++ b/src/app/connect/components/load-dialog/load-dialog.scss @@ -0,0 +1,60 @@ +.lead { + font: var(--mat-sys-body-large); + margin-top: 0; + max-width: 760px; +} + +.lead--done { + align-items: center; + color: var(--mat-sys-primary); + display: flex; + gap: var(--space-2); +} + +.warn { + color: #9a5b00; +} + +.flows { + --mat-table-row-item-container-height: 44px; + margin-bottom: var(--space-3); + width: 100%; +} + +.flows__name { + font: var(--mat-sys-title-small); +} + +.flows__target { + color: var(--mat-sys-on-surface-variant); + margin-left: var(--space-2); +} + +.note, +.error { + align-items: center; + color: var(--mat-sys-on-surface-variant); + display: flex; + font: var(--mat-sys-body-small); + gap: var(--space-2); +} + +.error { + color: var(--mat-sys-error); +} + +.policy { + border-top: 1px solid var(--mat-sys-outline-variant); + margin-top: var(--space-3); + padding-top: var(--space-3); + + h3 { + font: var(--mat-sys-title-small); + margin: 0 0 var(--space-2); + } + + mat-radio-group { + display: flex; + flex-direction: column; + } +} diff --git a/src/app/connect/components/load-dialog/load-dialog.ts b/src/app/connect/components/load-dialog/load-dialog.ts new file mode 100644 index 0000000..7ef5234 --- /dev/null +++ b/src/app/connect/components/load-dialog/load-dialog.ts @@ -0,0 +1,106 @@ +import { DecimalPipe } from '@angular/common'; +import { Component, OnInit, computed, inject, signal } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCheckboxModule } from '@angular/material/checkbox'; +import { MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { MatIconModule } from '@angular/material/icon'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatRadioModule } from '@angular/material/radio'; +import { MatTableModule } from '@angular/material/table'; +import { ConflictStrategy } from '../../api/api.types'; +import { ImportFlow } from '../../domain/import-flow'; +import { ConnectWorkspaceStore } from '../../state/connect-workspace.store'; +import { FlowStatusChip } from '../shared/flow-status'; + +export type LoadDialogResult = 'explore' | undefined; + +/** + * "Cargar a la base": validates every flow, shows what will be written, + * sets the batch options (conflict policy, merging a patient's data spread + * across sources) and loads the batch in one request and one transaction. + * Rows failing validation are skipped and reported, never written. + */ +@Component({ + selector: 'app-load-dialog', + imports: [DecimalPipe, FlowStatusChip, MatButtonModule, MatCheckboxModule, MatDialogModule, MatIconModule, MatProgressBarModule, MatRadioModule, MatTableModule], + templateUrl: './load-dialog.html', + styleUrl: './load-dialog.scss', +}) +export class LoadDialog implements OnInit { + readonly store = inject(ConnectWorkspaceStore); + private readonly dialogRef = inject>(MatDialogRef); + + readonly columns = ['flow', 'status', 'rows', 'valid', 'errors', 'outcome']; + readonly validating = signal(true); + /** Whether merging is even possible here; independent of the checkbox itself. */ + readonly mergeAvailable = this.store.mergeAvailable; + /** With merging, rows incomplete on their own may be completed by another source. */ + readonly canLoad = computed(() => this.totals().valid > 0 || (this.store.mergeDuplicates() && this.totals().rows > 0)); + + /** + * The flows the next batch would write. Reactive to the merge checkbox + * while nothing has loaded yet, so ticking it reveals the flow it + * completes; frozen the moment a batch starts, so the results table + * keeps listing exactly what was sent. + */ + private readonly _frozenFlows = signal(null); + readonly flows = computed(() => this._frozenFlows() ?? this.store.submittableFlows()); + readonly skipped = computed(() => this.store.flows().filter((flow) => !this.flows().includes(flow) && !flow.canSubmit)); + + readonly totals = computed(() => + this.flows().reduce( + (acc, flow) => { + const validation = flow.validation(); + acc.rows += validation?.total_rows ?? 0; + acc.valid += validation?.valid_count ?? 0; + acc.errors += validation?.error_count ?? 0; + return acc; + }, + { rows: 0, valid: 0, errors: 0 }, + ), + ); + + readonly batch = this.store.lastBatch; + readonly outcome = computed(() => { + const batch = this.batch(); + if (!batch) return null; + return batch.results.reduce( + (acc, result) => ({ + created: acc.created + result.created, + updated: acc.updated + result.updated, + rejected: acc.rejected + result.rejected, + merged: acc.merged + (result.merged ?? 0), + warnings: acc.warnings + (result.warnings?.length ?? 0), + }), + { created: 0, updated: 0, rejected: 0, merged: 0, warnings: 0 }, + ); + }); + + async ngOnInit(): Promise { + await Promise.all(this.flows().filter((flow) => !flow.validation()).map((flow) => this.store.validate(flow))); + this.validating.set(false); + } + + setStrategy(strategy: ConflictStrategy): void { + this.store.setOnConflict(strategy); + } + + /** Toggling may bring an until-now-skipped flow into `flows()`; preview its rows too. */ + toggleMerge(merge: boolean): void { + this.store.setMergeDuplicates(merge); + Promise.all(this.flows().filter((flow) => !flow.validation()).map((flow) => this.store.validate(flow))); + } + + load(): void { + this._frozenFlows.set(this.store.submittableFlows()); + this.store.commit().subscribe(); + } + + explore(): void { + this.dialogRef.close('explore'); + } + + resultOf(flow: ImportFlow) { + return flow.result(); + } +} diff --git a/src/app/connect/components/new-flow-dialog/new-flow-dialog.ts b/src/app/connect/components/new-flow-dialog/new-flow-dialog.ts new file mode 100644 index 0000000..983405a --- /dev/null +++ b/src/app/connect/components/new-flow-dialog/new-flow-dialog.ts @@ -0,0 +1,74 @@ +import { Component, inject, signal } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { MatIconModule } from '@angular/material/icon'; +import { MatListModule } from '@angular/material/list'; +import { TargetMeta } from '../../api/api.types'; +import { SourceTable } from '../../domain/data-source'; +import { suggestTarget } from '../../domain/target-suggester'; + +export interface NewFlowDialogData { + table: SourceTable; + targets: TargetMeta[]; + existingTargets: Map; +} + +/** "¿A qué tabla de la base va esta fuente?" — picks the destination entity for a new flow. */ +@Component({ + selector: 'app-new-flow-dialog', + imports: [MatButtonModule, MatDialogModule, MatIconModule, MatListModule], + template: ` +

Nueva carga desde «{{ data.table.name }}»

+ +

Elige la tabla de destino. Puedes cargar varias fuentes en la misma tabla y una misma fuente en varias tablas.

+ + @for (target of data.targets; track target.key) { + + + + {{ target.table }} + @if (target === suggested) { + Sugerida + } + + + {{ target.fields.length }} campos · {{ requiredCount(target) }} obligatorios + @if (data.existingTargets.get(target.key); as count) { + · ya la cargan {{ count }} flujo(s) + } + + + } + +
+ + + + + `, + styles: ` + .hint { color: var(--mat-sys-on-surface-variant); margin-top: 0; } + .tag { + background: var(--mat-sys-primary-container); + border-radius: 999px; + color: var(--mat-sys-on-primary-container); + font: var(--mat-sys-label-small); + margin-left: 6px; + padding: 1px 8px; + } + `, +}) +export class NewFlowDialog { + readonly data = inject(MAT_DIALOG_DATA); + readonly dialogRef = inject>(MatDialogRef); + readonly suggested = suggestTarget(this.data.table.name, this.data.targets, this.data.table.connection.label); + readonly selected = signal(this.suggested); + + requiredCount(target: TargetMeta): number { + return target.fields.filter((field) => field.required).length; + } +} diff --git a/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.html b/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.html new file mode 100644 index 0000000..f9d0bea --- /dev/null +++ b/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.html @@ -0,0 +1,56 @@ +
+
+ + Página {{ pageNumber() }} de {{ pageCount() }} + +
+ + @if (loading()) { + + } + @if (error()) { + + } + +
+ @if (imageUrl(); as url) { + +
+ @for (region of regionsOnCurrentPage(); track region.target_field) { +
+ + {{ region.target_field }} + + +
+ } + + @if (overlay.liveBox(); as box) { +
+ } +
+ } +
+
diff --git a/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.scss b/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.scss new file mode 100644 index 0000000..8772c77 --- /dev/null +++ b/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.scss @@ -0,0 +1,92 @@ +:host { + display: block; +} + +.viewer__toolbar { + align-items: center; + display: flex; + gap: var(--space-2); + justify-content: center; +} + +.viewer__page-label { + color: var(--color-text); + font-size: 13px; + font-weight: 600; + min-width: 120px; + text-align: center; +} + +.viewer__error { + background: #fdeeee; + border: 1px solid #e3a6a6; + border-radius: 7px; + color: #7a2222; + font-size: 13px; + margin: var(--space-2) 0 0; + padding: var(--space-3) var(--space-4); +} + +.viewer__stage { + background: var(--color-step); + border: 1px solid var(--color-border); + border-radius: 8px; + margin-top: var(--space-3); + overflow: auto; + position: relative; + text-align: center; +} + +.viewer__image { + display: block; + margin: 0 auto; + max-width: 100%; + user-select: none; +} + +.region-overlay { + cursor: crosshair; + inset: 0; + position: absolute; + touch-action: none; +} + +.region-overlay__box { + background: rgb(168 194 67 / 18%); + border: 2px solid var(--color-primary); + pointer-events: none; + position: absolute; +} + +.region-overlay__live { + background: rgb(168 194 67 / 12%); + border: 2px dashed var(--color-primary); + pointer-events: none; + position: absolute; +} + +.region-overlay__label { + align-items: center; + background: var(--color-primary); + color: var(--color-text); + display: inline-flex; + font-size: 11px; + font-weight: 600; + gap: var(--space-1); + left: -2px; + padding: 1px var(--space-1); + pointer-events: auto; + position: absolute; + top: -20px; + white-space: nowrap; +} + +.region-overlay__remove { + background: none; + border: none; + color: var(--color-text); + cursor: pointer; + font-size: 13px; + line-height: 1; + padding: 0 0 0 var(--space-1); +} diff --git a/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.spec.ts b/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.spec.ts new file mode 100644 index 0000000..b7e330d --- /dev/null +++ b/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.spec.ts @@ -0,0 +1,116 @@ +import { TestBed } from '@angular/core/testing'; +import { Observable, of } from 'rxjs'; +import { PdfSourceApi } from '../../api/pdf-source.api'; +import { PdfPageViewer } from './pdf-page-viewer'; + +class FakePdfSourceApi { + readonly calls: number[] = []; + + pageImage(_file: File, pageNumber: number): Observable { + this.calls.push(pageNumber); + return of(new Blob([`page-${pageNumber}`], { type: 'image/png' })); + } +} + +describe('PdfPageViewer', () => { + let fakeApi: FakePdfSourceApi; + let createObjectURL: ReturnType; + let revokeObjectURL: ReturnType; + let urlCounter = 0; + + beforeEach(async () => { + fakeApi = new FakePdfSourceApi(); + urlCounter = 0; + createObjectURL = vi.spyOn(URL, 'createObjectURL').mockImplementation(() => `blob:mock-${++urlCounter}`); + revokeObjectURL = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined); + + await TestBed.configureTestingModule({ + imports: [PdfPageViewer], + providers: [{ provide: PdfSourceApi, useValue: fakeApi }], + }).compileComponents(); + }); + + afterEach(() => { + createObjectURL.mockRestore(); + revokeObjectURL.mockRestore(); + }); + + function createFixture(pageNumber = 1, pageCount = 3) { + const fixture = TestBed.createComponent(PdfPageViewer); + fixture.componentRef.setInput('file', new File(['%PDF'], 'doc.pdf', { type: 'application/pdf' })); + fixture.componentRef.setInput('pageNumber', pageNumber); + fixture.componentRef.setInput('pageCount', pageCount); + fixture.detectChanges(); + return fixture; + } + + it('fetches and displays page 1 on init via an object URL', () => { + const fixture = createFixture(1); + const component = fixture.componentInstance; + + expect(fakeApi.calls).toEqual([1]); + expect(createObjectURL).toHaveBeenCalledTimes(1); + expect(component.imageUrl()).toBe('blob:mock-1'); + }); + + it('revokes the previous object URL and creates a new one when navigating to a new page', () => { + const fixture = createFixture(1); + fixture.componentRef.setInput('pageNumber', 2); + fixture.detectChanges(); + + expect(fakeApi.calls).toEqual([1, 2]); + expect(createObjectURL).toHaveBeenCalledTimes(2); + expect(revokeObjectURL).toHaveBeenCalledWith('blob:mock-1'); + expect(fixture.componentInstance.imageUrl()).toBe('blob:mock-2'); + }); + + it('does not refetch an already-fetched page, but still swaps to a fresh object URL for it', () => { + const fixture = createFixture(1); + fixture.componentRef.setInput('pageNumber', 2); + fixture.detectChanges(); + fixture.componentRef.setInput('pageNumber', 1); + fixture.detectChanges(); + + // Only two distinct pages were ever fetched from the API, even though + // page 1 was visited twice. + expect(fakeApi.calls).toEqual([1, 2]); + // But a fresh object URL is still minted from the cached Blob each time + // the page is (re)displayed, and the previously-shown one is revoked. + expect(createObjectURL).toHaveBeenCalledTimes(3); + expect(revokeObjectURL).toHaveBeenCalledWith('blob:mock-2'); + expect(fixture.componentInstance.imageUrl()).toBe('blob:mock-3'); + }); + + it('revokes the current object URL on destroy', () => { + const fixture = createFixture(1); + fixture.destroy(); + expect(revokeObjectURL).toHaveBeenCalledWith('blob:mock-1'); + }); + + it('emits pageNumberChange from the pager buttons, clamped to [1, pageCount]', () => { + const fixture = createFixture(2, 3); + const component = fixture.componentInstance; + const emitted: number[] = []; + component.pageNumberChange.subscribe((n) => emitted.push(n)); + + component.next(); + component.previous(); + fixture.componentRef.setInput('pageNumber', 1); + fixture.detectChanges(); + component.previous(); // no-op, already at page 1 + + expect(emitted).toEqual([3, 1]); + }); + + it('filters regions to only those whose page_numbers include the current page', () => { + const fixture = createFixture(1); + fixture.componentRef.setInput('regions', [ + { target_field: 'a', page_numbers: [1], bbox: [0, 0, 0.5, 0.5] }, + { target_field: 'b', page_numbers: [2], bbox: [0, 0, 0.5, 0.5] }, + { target_field: 'c', page_numbers: [1, 2], bbox: [0, 0, 0.5, 0.5] }, + ]); + fixture.detectChanges(); + + expect(fixture.componentInstance.regionsOnCurrentPage().map((r) => r.target_field)).toEqual(['a', 'c']); + }); +}); diff --git a/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.ts b/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.ts new file mode 100644 index 0000000..5064de8 --- /dev/null +++ b/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.ts @@ -0,0 +1,105 @@ +import { Component, OnDestroy, effect, inject, input, output, signal } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MatIconModule } from '@angular/material/icon'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { RegionSpec } from '../../api/api.types'; +import { PdfSourceApi } from '../../api/pdf-source.api'; +import { DrawnRegionBox, RegionDrawOverlay } from './region-draw-overlay.directive'; + +/** + * Shows one PDF page at a time as an image, with a prev/next pager and a + * RegionDrawOverlay on top. The parent listens to `regionDrawn` and decides + * what a drawn box means. + * + * Page images are cached as Blobs rather than object URLs. The displayed + * URL is revoked on every navigation and a fresh one is created from the + * cached Blob, so no URL is leaked and no page is fetched twice. + */ +@Component({ + imports: [MatButtonModule, MatIconModule, MatProgressBarModule, RegionDrawOverlay], + selector: 'app-pdf-page-viewer', + styleUrl: './pdf-page-viewer.scss', + templateUrl: './pdf-page-viewer.html', +}) +export class PdfPageViewer implements OnDestroy { + readonly file = input.required(); + readonly pageNumber = input.required(); + readonly pageCount = input.required(); + /** Drawn regions on all pages; only the current page's are rendered. */ + readonly regions = input([]); + + readonly pageNumberChange = output(); + readonly regionDrawn = output(); + readonly regionRemove = output(); + + private readonly pdfApi = inject(PdfSourceApi); + + readonly imageUrl = signal(null); + readonly loading = signal(false); + readonly error = signal(null); + + private readonly blobCache = new Map(); + private currentObjectUrl: string | null = null; + private currentFile: File | null = null; + + constructor() { + effect(() => { + const file = this.file(); + const pageNumber = this.pageNumber(); + if (file !== this.currentFile) { + this.blobCache.clear(); + this.currentFile = file; + } + this.loadPage(file, pageNumber); + }); + } + + ngOnDestroy(): void { + if (this.currentObjectUrl) URL.revokeObjectURL(this.currentObjectUrl); + } + + previous(): void { + if (this.pageNumber() > 1) this.pageNumberChange.emit(this.pageNumber() - 1); + } + + next(): void { + if (this.pageNumber() < this.pageCount()) this.pageNumberChange.emit(this.pageNumber() + 1); + } + + regionsOnCurrentPage(): RegionSpec[] { + return this.regions().filter((region) => region.page_numbers.includes(this.pageNumber())); + } + + onRemoveClick(event: Event, region: RegionSpec): void { + event.stopPropagation(); + this.regionRemove.emit(region); + } + + private loadPage(file: File, pageNumber: number): void { + const cached = this.blobCache.get(pageNumber); + if (cached) { + this.showBlob(cached); + return; + } + this.loading.set(true); + this.error.set(null); + this.pdfApi.pageImage(file, pageNumber).subscribe({ + next: (blob) => { + this.blobCache.set(pageNumber, blob); + this.loading.set(false); + this.showBlob(blob); + }, + error: () => { + this.loading.set(false); + this.error.set('No se pudo cargar la página.'); + }, + }); + } + + private showBlob(blob: Blob): void { + const url = URL.createObjectURL(blob); + if (this.currentObjectUrl) URL.revokeObjectURL(this.currentObjectUrl); + this.currentObjectUrl = url; + this.imageUrl.set(url); + } +} diff --git a/src/app/connect/components/pdf-page-viewer/region-draw-overlay.directive.spec.ts b/src/app/connect/components/pdf-page-viewer/region-draw-overlay.directive.spec.ts new file mode 100644 index 0000000..f170c06 --- /dev/null +++ b/src/app/connect/components/pdf-page-viewer/region-draw-overlay.directive.spec.ts @@ -0,0 +1,136 @@ +import { Component } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { By } from '@angular/platform-browser'; +import { DrawnRegionBox, RegionDrawOverlay } from './region-draw-overlay.directive'; + +@Component({ + imports: [RegionDrawOverlay], + template: `
`, +}) +class TestHostComponent { + readonly drawn: DrawnRegionBox[] = []; + onRegionDrawn(box: DrawnRegionBox): void { + this.drawn.push(box); + } +} + +function pointerEvent(clientX: number, clientY: number, pointerId = 1, button = 0): PointerEvent { + return { clientX, clientY, pointerId, button } as unknown as PointerEvent; +} + +describe('RegionDrawOverlay', () => { + beforeEach(async () => { + await TestBed.configureTestingModule({ imports: [TestHostComponent] }).compileComponents(); + }); + + function createFixture(rect: { left?: number; top?: number; width: number; height: number }) { + const fixture = TestBed.createComponent(TestHostComponent); + fixture.detectChanges(); + const overlayEl = fixture.nativeElement.querySelector('.overlay') as HTMLElement; + vi.spyOn(overlayEl, 'getBoundingClientRect').mockReturnValue({ + left: 0, + top: 0, + right: 0, + bottom: 0, + x: 0, + y: 0, + toJSON: () => ({}), + ...rect, + } as DOMRect); + const directive = fixture.debugElement.query(By.directive(RegionDrawOverlay)).injector.get(RegionDrawOverlay); + return { fixture, overlayEl, directive }; + } + + it('emits a normalized bbox (relative to the overlay, not the viewport) on a drag above the minimum threshold', () => { + const { fixture, directive } = createFixture({ left: 100, top: 50, width: 400, height: 300 }); + const host = fixture.componentInstance; + + directive.onPointerDown(pointerEvent(140, 80)); // 40,30 relative to the overlay's origin + directive.onPointerMove(pointerEvent(340, 230)); // 240,180 relative + directive.onPointerUp(pointerEvent(340, 230)); + + expect(host.drawn).toHaveLength(1); + const box = host.drawn[0]; + expect(box.x0).toBeCloseTo(40 / 400); + expect(box.y0).toBeCloseTo(30 / 300); + expect(box.x1).toBeCloseTo(240 / 400); + expect(box.y1).toBeCloseTo(180 / 300); + }); + + it('normalizes corners regardless of drag direction (bottom-right to top-left still yields x0 { + const { fixture, directive } = createFixture({ width: 400, height: 300 }); + const host = fixture.componentInstance; + + directive.onPointerDown(pointerEvent(240, 180)); + directive.onPointerMove(pointerEvent(40, 30)); + directive.onPointerUp(pointerEvent(40, 30)); + + expect(host.drawn).toHaveLength(1); + const box = host.drawn[0]; + expect(box.x0).toBeCloseTo(40 / 400); + expect(box.y0).toBeCloseTo(30 / 300); + expect(box.x1).toBeCloseTo(240 / 400); + expect(box.y1).toBeCloseTo(180 / 300); + expect(box.x0).toBeLessThan(box.x1); + expect(box.y0).toBeLessThan(box.y1); + }); + + it('produces the same normalized bbox for the same relative drag, independent of the overlay rect size/position', () => { + const drag = (rect: { left?: number; top?: number; width: number; height: number }) => { + const { fixture, directive } = createFixture(rect); + const host = fixture.componentInstance; + const left = rect.left ?? 0; + const top = rect.top ?? 0; + const { width, height } = rect; + // Same *relative* drag in both cases: from 10%,10% to 60%,70% of the overlay. + directive.onPointerDown(pointerEvent(left + width * 0.1, top + height * 0.1)); + directive.onPointerMove(pointerEvent(left + width * 0.6, top + height * 0.7)); + directive.onPointerUp(pointerEvent(left + width * 0.6, top + height * 0.7)); + return host.drawn[0]; + }; + + const small = drag({ width: 200, height: 100 }); + const large = drag({ left: 500, top: 300, width: 1200, height: 900 }); + + expect(small).toBeDefined(); + expect(large).toBeDefined(); + expect(small.x0).toBeCloseTo(large.x0, 6); + expect(small.y0).toBeCloseTo(large.y0, 6); + expect(small.x1).toBeCloseTo(large.x1, 6); + expect(small.y1).toBeCloseTo(large.y1, 6); + }); + + it('ignores drags below the minimum pixel threshold, treating them as accidental clicks', () => { + const { fixture, directive } = createFixture({ width: 400, height: 300 }); + const host = fixture.componentInstance; + + directive.onPointerDown(pointerEvent(10, 10)); + directive.onPointerMove(pointerEvent(12, 11)); + directive.onPointerUp(pointerEvent(12, 11)); + + expect(host.drawn).toHaveLength(0); + }); + + it('exposes the in-progress drag via the exported liveBox signal, and clears it on pointerup', () => { + const { directive } = createFixture({ width: 400, height: 300 }); + + expect(directive.liveBox()).toBeNull(); + directive.onPointerDown(pointerEvent(10, 10)); + directive.onPointerMove(pointerEvent(60, 90)); + expect(directive.liveBox()).toEqual({ x: 10, y: 10, width: 50, height: 80 }); + directive.onPointerUp(pointerEvent(60, 90)); + expect(directive.liveBox()).toBeNull(); + }); + + it('ignores non-primary pointer buttons on pointerdown', () => { + const { fixture, directive } = createFixture({ width: 400, height: 300 }); + const host = fixture.componentInstance; + + directive.onPointerDown(pointerEvent(10, 10, 1, 2)); // right-click + directive.onPointerMove(pointerEvent(200, 200)); + directive.onPointerUp(pointerEvent(200, 200)); + + expect(host.drawn).toHaveLength(0); + expect(directive.liveBox()).toBeNull(); + }); +}); diff --git a/src/app/connect/components/pdf-page-viewer/region-draw-overlay.directive.ts b/src/app/connect/components/pdf-page-viewer/region-draw-overlay.directive.ts new file mode 100644 index 0000000..2968b5f --- /dev/null +++ b/src/app/connect/components/pdf-page-viewer/region-draw-overlay.directive.ts @@ -0,0 +1,97 @@ +import { Directive, ElementRef, HostListener, inject, output, signal } from '@angular/core'; + +/** A normalized (0..1) region box, corners already sorted so x0(); + + readonly liveBox = signal(null); + + private readonly element = inject(ElementRef); + private start: { x: number; y: number } | null = null; + + @HostListener('pointerdown', ['$event']) + onPointerDown(event: PointerEvent): void { + if (event.button > 0) return; + const rect = this.element.nativeElement.getBoundingClientRect(); + this.start = { x: event.clientX - rect.left, y: event.clientY - rect.top }; + this.liveBox.set({ x: this.start.x, y: this.start.y, width: 0, height: 0 }); + try { + this.element.nativeElement.setPointerCapture?.(event.pointerId); + } catch { + // Pointer capture is unsupported in some test environments; drawing + // still works through events dispatched on the host. + } + } + + @HostListener('pointermove', ['$event']) + onPointerMove(event: PointerEvent): void { + if (!this.start) return; + const rect = this.element.nativeElement.getBoundingClientRect(); + this.liveBox.set(this.boxFrom(this.start, { x: event.clientX - rect.left, y: event.clientY - rect.top })); + } + + @HostListener('pointerup', ['$event']) + onPointerUp(event: PointerEvent): void { + if (!this.start) return; + const rect = this.element.nativeElement.getBoundingClientRect(); + const box = this.boxFrom(this.start, { x: event.clientX - rect.left, y: event.clientY - rect.top }); + this.start = null; + this.liveBox.set(null); + try { + if (this.element.nativeElement.hasPointerCapture?.(event.pointerId)) { + this.element.nativeElement.releasePointerCapture(event.pointerId); + } + } catch { + // Capture may be unsupported here, see onPointerDown. + } + + if (box.width < MIN_DRAG_PX || box.height < MIN_DRAG_PX) return; + if (rect.width <= 0 || rect.height <= 0) return; + this.regionDrawn.emit({ + x0: box.x / rect.width, + y0: box.y / rect.height, + x1: (box.x + box.width) / rect.width, + y1: (box.y + box.height) / rect.height, + }); + } + + private boxFrom(start: { x: number; y: number }, current: { x: number; y: number }): LiveDrawBox { + const x0 = Math.min(start.x, current.x); + const y0 = Math.min(start.y, current.y); + const x1 = Math.max(start.x, current.x); + const y1 = Math.max(start.y, current.y); + return { x: x0, y: y0, width: x1 - x0, height: y1 - y0 }; + } +} diff --git a/src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.html b/src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.html new file mode 100644 index 0000000..e43122e --- /dev/null +++ b/src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.html @@ -0,0 +1,74 @@ +

Dibujar regiones · {{ connection.label }}

+ +
+ +
+ + +
+ + + + diff --git a/src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.scss b/src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.scss new file mode 100644 index 0000000..e391529 --- /dev/null +++ b/src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.scss @@ -0,0 +1,72 @@ +.regions { + display: grid; + gap: var(--space-4); + grid-template-columns: minmax(0, 1fr) 340px; + max-height: 78vh; +} + +.regions__viewer { + min-width: 0; + overflow: auto; +} + +.regions__side { + display: flex; + flex-direction: column; + gap: var(--space-2); + overflow: auto; +} + +.regions__name { + width: 100%; +} + +.regions__hint, +.regions__empty { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); + margin: 0 0 var(--space-2); +} + +.regions__empty { + align-items: center; + display: flex; + gap: var(--space-2); +} + +.region { + border: 1px solid var(--mat-sys-outline-variant); + border-radius: var(--mat-sys-corner-medium); + padding: var(--space-2) var(--space-2) 0; +} + +.region--invalid { + border-color: var(--mat-sys-error); +} + +.region__name { + width: 100%; +} + +.region__meta { + align-items: center; + display: flex; + gap: var(--space-1); +} + +.region__pages { + color: var(--mat-sys-on-surface-variant); + flex: 1; + font: var(--mat-sys-body-small); +} + +.regions__error { + color: var(--mat-sys-error); + font: var(--mat-sys-body-small); +} + +@media (max-width: 960px) { + .regions { + grid-template-columns: 1fr; + } +} diff --git a/src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.ts b/src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.ts new file mode 100644 index 0000000..062e9b9 --- /dev/null +++ b/src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.ts @@ -0,0 +1,106 @@ +import { Component, computed, inject, signal } from '@angular/core'; +import { MatAutocompleteModule } from '@angular/material/autocomplete'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCheckboxModule } from '@angular/material/checkbox'; +import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatInputModule } from '@angular/material/input'; +import { RegionSpec } from '../../api/api.types'; +import { PdfConnection } from '../../domain/pdf-source'; +import { PdfPageViewer } from '../pdf-page-viewer/pdf-page-viewer'; +import { DrawnRegionBox } from '../pdf-page-viewer/region-draw-overlay.directive'; + +export interface PdfRegionsDialogData { + connection: PdfConnection; + /** Destination field names in the current domain, suggested as column names. */ + fieldNames: string[]; +} + +export interface PdfRegionsResult { + name: string; + regions: RegionSpec[]; +} + +/** + * Draw one box per column over the rendered page (a column of a scanned + * table, a form field); each box becomes a named source column, read by + * OCR (or from the text layer when the page has one) and aligned into rows + * across all boxes on the page. "Todas las páginas" repeats a box on every + * page, which suits multi-page reports with a fixed layout. + */ +@Component({ + selector: 'app-pdf-regions-dialog', + imports: [ + MatAutocompleteModule, + MatButtonModule, + MatCheckboxModule, + MatDialogModule, + MatFormFieldModule, + MatIconModule, + MatInputModule, + PdfPageViewer, + ], + templateUrl: './pdf-regions-dialog.html', + styleUrl: './pdf-regions-dialog.scss', +}) +export class PdfRegionsDialog { + readonly data = inject(MAT_DIALOG_DATA); + private readonly dialogRef = inject>(MatDialogRef); + + readonly connection = this.data.connection; + readonly pageCount = this.connection.detection()?.page_count ?? 1; + readonly page = signal(1); + readonly regions = signal([]); + readonly name = signal(`Regiones ${this.connection.tables().filter((t) => t.removable).length + 1}`); + + readonly duplicateNames = computed(() => { + const names = this.regions().map((region) => region.target_field.trim()); + return new Set(names.filter((name, index) => !name || names.indexOf(name) !== index)); + }); + + readonly canAccept = computed(() => this.regions().length > 0 && this.duplicateNames().size === 0 && !!this.name().trim()); + + onRegionDrawn(box: DrawnRegionBox): void { + const taken = new Set(this.regions().map((region) => region.target_field)); + let index = this.regions().length + 1; + while (taken.has(`columna_${index}`)) index++; + this.regions.update((regions) => [ + ...regions, + { target_field: `columna_${index}`, page_numbers: [this.page()], bbox: [box.x0, box.y0, box.x1, box.y1] }, + ]); + } + + rename(region: RegionSpec, value: string): void { + // Committed on change/Enter, not per keystroke: replacing the region + // object while typing re-renders the row and drops the input's focus. + this.regions.update((regions) => regions.map((r) => (r === region ? { ...r, target_field: value } : r))); + } + + setAllPages(region: RegionSpec, allPages: boolean): void { + const pages = allPages ? Array.from({ length: this.pageCount }, (_, i) => i + 1) : [this.page()]; + this.regions.update((regions) => regions.map((r) => (r === region ? { ...r, page_numbers: pages } : r))); + } + + remove(region: RegionSpec): void { + this.regions.update((regions) => regions.filter((r) => r !== region)); + } + + suggestionsFor(value: string): string[] { + const term = value.trim().toLowerCase(); + return this.data.fieldNames.filter((name) => !term || name.toLowerCase().includes(term)).slice(0, 30); + } + + pagesLabel(region: RegionSpec): string { + return region.page_numbers.length === this.pageCount && this.pageCount > 1 + ? `${this.pageCount} págs.` + : `pág. ${region.page_numbers.join(', ')}`; + } + + accept(): void { + this.dialogRef.close({ + name: this.name().trim(), + regions: this.regions().map((region) => ({ ...region, target_field: region.target_field.trim() })), + }); + } +} diff --git a/src/app/connect/components/shared/autofocus.directive.ts b/src/app/connect/components/shared/autofocus.directive.ts new file mode 100644 index 0000000..55f89d1 --- /dev/null +++ b/src/app/connect/components/shared/autofocus.directive.ts @@ -0,0 +1,13 @@ +import { Directive, ElementRef, afterNextRender, inject } from '@angular/core'; + +/** Focuses and selects its input when it renders, for inline editors that appear on demand. */ +@Directive({ selector: 'input[appAutofocus]' }) +export class AutofocusDirective { + constructor() { + const element = inject>(ElementRef).nativeElement; + afterNextRender(() => { + element.focus(); + element.select(); + }); + } +} diff --git a/src/app/connect/components/shared/flow-status.ts b/src/app/connect/components/shared/flow-status.ts new file mode 100644 index 0000000..1b40d03 --- /dev/null +++ b/src/app/connect/components/shared/flow-status.ts @@ -0,0 +1,47 @@ +import { Component, computed, input } from '@angular/core'; +import { MatIconModule } from '@angular/material/icon'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { FlowStatus } from '../../domain/import-flow'; + +const PRESENTATION: Record = { + loading: { label: 'Leyendo', icon: 'hourglass_top', tone: 'neutral', hint: 'Leyendo la fuente…' }, + error: { label: 'Error', icon: 'error', tone: 'error', hint: 'No se pudo leer la fuente' }, + incomplete: { label: 'Sin mapear', icon: 'rule', tone: 'warn', hint: 'Faltan campos obligatorios por asignar' }, + ready: { label: 'Listo', icon: 'check_circle_outline', tone: 'neutral', hint: 'Mapeo completo, sin validar' }, + validating: { label: 'Validando', icon: 'hourglass_top', tone: 'neutral', hint: 'Validando filas…' }, + valid: { label: 'Válido', icon: 'verified', tone: 'ok', hint: 'Todas las filas pasan la validación' }, + invalid: { label: 'Con errores', icon: 'report', tone: 'warn', hint: 'Algunas filas no pasan la validación y se omitirán' }, + loaded: { label: 'Cargado', icon: 'cloud_done', tone: 'ok', hint: 'Escrito en la base de datos' }, +}; + +/** Compact status pill for a flow (canvas cards, editor header, load dialog). */ +@Component({ + selector: 'app-flow-status', + imports: [MatIconModule, MatTooltipModule], + template: ` + + {{ view().label }} + + `, + styles: ` + .flow-status { + align-items: center; + border-radius: 999px; + display: inline-flex; + font: var(--mat-sys-label-medium); + gap: 4px; + padding: 2px 10px 2px 6px; + white-space: nowrap; + background: var(--mat-sys-surface-container-high); + color: var(--mat-sys-on-surface-variant); + } + .flow-status mat-icon { font-size: 16px; height: 16px; width: 16px; } + .flow-status[data-tone='ok'] { background: var(--mat-sys-primary-container); color: var(--mat-sys-on-primary-container); } + .flow-status[data-tone='warn'] { background: #fff1d6; color: #7a4b00; } + .flow-status[data-tone='error'] { background: var(--mat-sys-error-container); color: var(--mat-sys-on-error-container); } + `, +}) +export class FlowStatusChip { + readonly status = input.required(); + readonly view = computed(() => PRESENTATION[this.status()]); +} diff --git a/src/app/connect/components/shared/spanish-paginator-intl.ts b/src/app/connect/components/shared/spanish-paginator-intl.ts new file mode 100644 index 0000000..99c241a --- /dev/null +++ b/src/app/connect/components/shared/spanish-paginator-intl.ts @@ -0,0 +1,18 @@ +import { Injectable } from '@angular/core'; +import { MatPaginatorIntl } from '@angular/material/paginator'; + +/** Material's paginator speaks English by default; the whole app is in Spanish. */ +@Injectable() +export class SpanishPaginatorIntl extends MatPaginatorIntl { + override itemsPerPageLabel = 'Filas por página'; + override nextPageLabel = 'Página siguiente'; + override previousPageLabel = 'Página anterior'; + override firstPageLabel = 'Primera página'; + override lastPageLabel = 'Última página'; + override getRangeLabel = (page: number, pageSize: number, length: number): string => { + if (length === 0 || pageSize === 0) return `0 de ${length}`; + const start = page * pageSize; + const end = Math.min(start + pageSize, length); + return `${start + 1} – ${end} de ${length}`; + }; +} diff --git a/src/app/connect/components/shared/type-icon.pipe.ts b/src/app/connect/components/shared/type-icon.pipe.ts new file mode 100644 index 0000000..a56cffb --- /dev/null +++ b/src/app/connect/components/shared/type-icon.pipe.ts @@ -0,0 +1,41 @@ +import { Pipe, PipeTransform } from '@angular/core'; + +const ICONS: Record = { + string: 'text_fields', + integer: 'tag', + float: 'numbers', + number: 'numbers', + boolean: 'toggle_on', + date: 'calendar_today', + datetime: 'schedule', + 'date-time': 'schedule', + binary: 'attachment', +}; + +const LABELS: Record = { + string: 'Texto', + integer: 'Entero', + float: 'Decimal', + number: 'Decimal', + boolean: 'Sí/No', + date: 'Fecha', + datetime: 'Fecha y hora', + 'date-time': 'Fecha y hora', + binary: 'Binario', +}; + +/** A column/field type (source `inferred_type` or target JSON-schema type) as a Material icon name. */ +@Pipe({ name: 'typeIcon' }) +export class TypeIconPipe implements PipeTransform { + transform(type: string | null | undefined): string { + return ICONS[type ?? ''] ?? 'help_outline'; + } +} + +/** The same type as a human label ("Fecha", "Entero"...). */ +@Pipe({ name: 'typeLabel' }) +export class TypeLabelPipe implements PipeTransform { + transform(type: string | null | undefined): string { + return LABELS[type ?? ''] ?? (type || 'Desconocido'); + } +} diff --git a/src/app/connect/components/sql-query-dialog/sql-query-dialog.ts b/src/app/connect/components/sql-query-dialog/sql-query-dialog.ts new file mode 100644 index 0000000..bdaecfa --- /dev/null +++ b/src/app/connect/components/sql-query-dialog/sql-query-dialog.ts @@ -0,0 +1,116 @@ +import { Component, inject, signal } from '@angular/core'; +import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatInputModule } from '@angular/material/input'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatTableModule } from '@angular/material/table'; +import { PreviewResponse, apiErrorMessage } from '../../api/api.types'; +import { SourceGateway } from '../../api/source-gateway'; +import { SqlConnection } from '../../domain/sql-source'; + +export interface SqlQueryResult { + name: string; + query: string; +} + +/** + * Custom SELECT against a database connection (joins, filters, computed + * columns), added to the connection as one more table. "Probar" runs it + * (read-only, first rows only) before it's accepted. + */ +@Component({ + selector: 'app-sql-query-dialog', + imports: [MatButtonModule, MatDialogModule, MatFormFieldModule, MatIconModule, MatInputModule, MatProgressBarModule, MatTableModule, ReactiveFormsModule], + template: ` +

Consulta SQL · {{ connection.label }}

+ +
+ + Nombre + + + + SELECT + + Una sola sentencia SELECT (o WITH … SELECT). La conexión es de solo lectura. + +
+ @if (running()) { + + } + @if (error(); as message) { + + } + @if (preview(); as result) { +

{{ result.total_rows }} filas · {{ result.columns.length }} columnas

+
+ + @for (column of result.columns; track column.name) { + + + + + } + + +
{{ column.name }}{{ row[column.name] }}
+
+ } +
+ + + + + + `, + styles: ` + .query-form { display: grid; gap: 0; min-width: min(640px, 80vw); } + .query-form__sql textarea { font-family: 'Roboto Mono', ui-monospace, monospace; font-size: 13px; } + .query-error { align-items: center; color: var(--mat-sys-error); display: flex; gap: 8px; } + .query-summary { color: var(--mat-sys-on-surface-variant); font: var(--mat-sys-body-small); } + .query-preview { border: 1px solid var(--mat-sys-outline-variant); border-radius: 8px; max-width: 80vw; overflow: auto; } + `, +}) +export class SqlQueryDialog { + readonly connection = inject(MAT_DIALOG_DATA); + private readonly dialogRef = inject>(MatDialogRef); + private readonly gateway = inject(SourceGateway); + + readonly form = inject(FormBuilder).nonNullable.group({ + name: [`Consulta ${this.connection.tables().filter((t) => t.removable).length + 1}`, Validators.required], + query: ['SELECT * FROM ', Validators.required], + }); + readonly running = signal(false); + readonly error = signal(null); + readonly preview = signal(null); + readonly columnNames = signal([]); + + constructor() { + this.form.controls.query.valueChanges.subscribe(() => this.preview.set(null)); + } + + run(): void { + this.running.set(true); + this.error.set(null); + this.gateway.sql.preview(this.connection.ref, { query: this.form.getRawValue().query }, null).subscribe({ + next: (preview) => { + this.running.set(false); + this.preview.set(preview); + this.columnNames.set(preview.columns.map((column) => column.name)); + }, + error: (error) => { + this.running.set(false); + this.error.set(apiErrorMessage(error, 'La consulta falló.')); + }, + }); + } + + accept(): void { + this.dialogRef.close(this.form.getRawValue()); + } +} diff --git a/src/app/connect/components/validation-report/validation-report.html b/src/app/connect/components/validation-report/validation-report.html new file mode 100644 index 0000000..2e3942e --- /dev/null +++ b/src/app/connect/components/validation-report/validation-report.html @@ -0,0 +1,99 @@ +@let f = flow(); +@if (f.validating()) { + +} + +@if (f.validation(); as validation) { +
+
+ {{ validation.total_rows | number }} + filas leídas +
+
+ {{ validation.valid_count | number }} + válidas · {{ validPercent() }}% +
+
+ {{ validation.error_count | number }} + con errores (se omiten) +
+ @if (f.result(); as result) { +
+ {{ result.created | number }} / {{ result.updated | number }} + insertadas / actualizadas +
+ } +
+ + @if (errors().length > 0) { +
+ + @for (item of countsByCategory(); track item.category) { + {{ categoryLabels[item.category] }} · {{ item.count }} + } + + + Campo + + Todos + @for (name of fieldsWithErrors(); track name) { + {{ name }} + } + + +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
Fila{{ error.row_index + 1 }}Campo{{ error.field }}Tipo + {{ categoryLabel(error.category) }} + Valor{{ display(error.raw_value) }}Detalle{{ error.message }}
+
+ + } @else { +

Todas las filas pasan la validación.

+ } +} @else if (!f.validating()) { +
+ +

+ La validación revisa todas las filas de la fuente contra las reglas de la tabla destino + (obligatorios, catálogos, formatos) sin escribir nada en la base. +

+ + @if (!f.canSubmit) { +

Completa primero los campos obligatorios en «Mapeo».

+ } +
+} diff --git a/src/app/connect/components/validation-report/validation-report.scss b/src/app/connect/components/validation-report/validation-report.scss new file mode 100644 index 0000000..365c64e --- /dev/null +++ b/src/app/connect/components/validation-report/validation-report.scss @@ -0,0 +1,120 @@ +:host { + display: block; +} + +.tiles { + display: grid; + gap: var(--space-3); + grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); + margin-bottom: var(--space-4); +} + +.tile { + background: var(--mat-sys-surface-container-low); + border: 1px solid var(--mat-sys-outline-variant); + border-radius: var(--mat-sys-corner-medium); + display: flex; + flex-direction: column; + padding: var(--space-3) var(--space-4); +} + +.tile__value { + font: var(--mat-sys-headline-small); +} + +.tile__label { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); +} + +.tile--ok .tile__value { + color: var(--mat-sys-primary); +} + +.tile--warn .tile__value { + color: #9a5b00; +} + +.filters { + align-items: center; + display: flex; + flex-wrap: wrap; + gap: var(--space-3); + margin-bottom: var(--space-3); +} + +.filters__field { + width: 240px; +} + +.table-scroll { + border: 1px solid var(--mat-sys-outline-variant); + border-radius: var(--mat-sys-corner-medium); + max-height: 50vh; + overflow: auto; +} + +.errors { + --mat-table-row-item-container-height: 40px; + width: 100%; +} + +.errors__field, +.errors__value { + font-family: 'Roboto Mono', ui-monospace, monospace; + font-size: 12px; +} + +.category { + border-radius: 999px; + font: var(--mat-sys-label-small); + padding: 2px 8px; + white-space: nowrap; + background: var(--mat-sys-surface-container-high); +} + +.category[data-category='missing'], +.category[data-category='conflict'] { + background: var(--mat-sys-error-container); + color: var(--mat-sys-on-error-container); +} + +.category[data-category='out_of_catalog'], +.category[data-category='type_invalid'] { + background: #fff1d6; + color: #7a4b00; +} + +.all-good, +.empty { + align-items: center; + color: var(--mat-sys-on-surface-variant); + display: flex; + gap: var(--space-2); +} + +.all-good mat-icon { + color: var(--mat-sys-primary); +} + +.empty { + flex-direction: column; + padding: var(--space-6); + text-align: center; + + > mat-icon { + color: var(--mat-sys-primary); + font-size: 36px; + height: 36px; + width: 36px; + } + + p { + margin: 0; + max-width: 520px; + } +} + +.empty__hint { + font: var(--mat-sys-body-small); +} diff --git a/src/app/connect/components/validation-report/validation-report.ts b/src/app/connect/components/validation-report/validation-report.ts new file mode 100644 index 0000000..1d463eb --- /dev/null +++ b/src/app/connect/components/validation-report/validation-report.ts @@ -0,0 +1,100 @@ +import { DecimalPipe } from '@angular/common'; +import { Component, computed, input, output, signal } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MatChipsModule } from '@angular/material/chips'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatSelectModule } from '@angular/material/select'; +import { MatTableModule } from '@angular/material/table'; +import { ErrorCategory, RowError } from '../../api/api.types'; +import { ImportFlow } from '../../domain/import-flow'; + +export const CATEGORY_LABELS: Record = { + missing: 'Falta dato obligatorio', + out_of_catalog: 'Fuera de catálogo', + type_invalid: 'Formato inválido', + conflict: 'Ya existe (clave duplicada)', + merge_conflict: 'Difiere de otra fuente (se conservó la primera)', + unknown: 'Otro', +}; + +/** Validation outcome of one flow: totals, then every row error, filterable by category and field. */ +@Component({ + selector: 'app-validation-report', + imports: [ + DecimalPipe, + MatButtonModule, + MatChipsModule, + MatFormFieldModule, + MatIconModule, + MatPaginatorModule, + MatProgressBarModule, + MatSelectModule, + MatTableModule, + ], + templateUrl: './validation-report.html', + styleUrl: './validation-report.scss', +}) +export class ValidationReport { + readonly flow = input.required(); + readonly validate = output(); + + readonly categoryLabels = CATEGORY_LABELS; + readonly columns = ['row', 'field', 'category', 'value', 'message']; + + readonly categories = signal([]); + readonly field = signal(null); + readonly page = signal({ index: 0, size: 25 }); + + readonly errors = computed(() => this.flow().validation()?.errors ?? []); + + readonly countsByCategory = computed(() => { + const counts = new Map(); + for (const error of this.errors()) counts.set(error.category, (counts.get(error.category) ?? 0) + 1); + return [...counts.entries()].map(([category, count]) => ({ category, count })); + }); + + readonly fieldsWithErrors = computed(() => [...new Set(this.errors().map((error) => error.field))].sort()); + + readonly filtered = computed(() => { + const categories = this.categories(); + const field = this.field(); + return this.errors().filter( + (error) => (categories.length === 0 || categories.includes(error.category)) && (!field || error.field === field), + ); + }); + + readonly pageRows = computed(() => { + const { index, size } = this.page(); + return this.filtered().slice(index * size, (index + 1) * size); + }); + + readonly validPercent = computed(() => { + const validation = this.flow().validation(); + return validation && validation.total_rows ? Math.round((validation.valid_count / validation.total_rows) * 100) : 0; + }); + + onCategories(value: ErrorCategory[]): void { + this.categories.set(value); + this.page.update((page) => ({ ...page, index: 0 })); + } + + onField(value: string | null): void { + this.field.set(value); + this.page.update((page) => ({ ...page, index: 0 })); + } + + onPage(event: PageEvent): void { + this.page.set({ index: event.pageIndex, size: event.pageSize }); + } + + categoryLabel(category: ErrorCategory): string { + return CATEGORY_LABELS[category] ?? category; + } + + display(value: unknown): string { + return value === null || value === undefined || value === '' ? '(vacío)' : String(value); + } +} diff --git a/src/app/connect/domain/connection-registry.spec.ts b/src/app/connect/domain/connection-registry.spec.ts new file mode 100644 index 0000000..f497cd3 --- /dev/null +++ b/src/app/connect/domain/connection-registry.spec.ts @@ -0,0 +1,52 @@ +import { ConnectorInfo } from '../api/api.types'; +import { acceptedExtensions, connectionsFor, connectionsForFiles, kindForFile } from './connection-registry'; +import { DocumentConnection } from './document-source'; +import { EegConnection } from './eeg-source'; +import { FileConnection } from './file-source'; +import { PdfConnection } from './pdf-source'; + +const connector = (kind: ConnectorInfo['kind'], extensions: string[], category: ConnectorInfo['category'] = 'file'): ConnectorInfo => ({ + kind, + label: kind, + description: '', + category, + icon: 'x', + extensions, +}); + +const CATALOG: ConnectorInfo[] = [ + connector('csv', ['csv', 'txt']), + connector('excel', ['xlsx']), + connector('pdf', ['pdf'], 'document'), + connector('document', ['pdf', 'png', 'tif'], 'document'), + connector('edf', ['edf'], 'signal'), + connector('sql', [], 'database'), +]; + +describe('connection registry', () => { + it('picks the first connector that reads an extension, as the server does', () => { + expect(kindForFile('a.CSV', CATALOG)).toBe('csv'); + expect(kindForFile('reporte.pdf', CATALOG)).toBe('pdf'); + expect(kindForFile('escaneo.tif', CATALOG)).toBe('document'); + expect(kindForFile('notas.docx', CATALOG)).toBeNull(); + expect(acceptedExtensions(CATALOG)).toEqual(['csv', 'txt', 'xlsx', 'pdf', 'png', 'tif', 'edf']); + }); + + it('one connection per tabular file, one for all recordings or documents dropped together', () => { + const files = ['a.csv', 'b.csv', 'r1.edf', 'r2.edf', 'p.png', 'q.tif', 'x.docx', 'informe.pdf'].map((name) => new File(['x'], name)); + const { connections, rejected } = connectionsForFiles(files, CATALOG); + expect(rejected.map((file) => file.name)).toEqual(['x.docx']); + expect(connections.filter((c) => c instanceof FileConnection)).toHaveLength(2); + const [eeg] = connections.filter((c) => c instanceof EegConnection) as EegConnection[]; + expect(eeg.files).toHaveLength(2); + expect(eeg.label).toBe('2 registros EEG'); + const [documents] = connections.filter((c) => c instanceof DocumentConnection) as DocumentConnection[]; + expect(documents.files.map((f) => f.name)).toEqual(['p.png', 'q.tif']); + expect(connections.some((c) => c instanceof PdfConnection)).toBe(true); + }); + + it('the connector picked in the gallery decides, e.g. PDFs read as documents', () => { + const [connection] = connectionsFor('document', [new File(['x'], 'a.pdf'), new File(['y'], 'b.pdf')]); + expect(connection).toBeInstanceOf(DocumentConnection); + }); +}); diff --git a/src/app/connect/domain/connection-registry.ts b/src/app/connect/domain/connection-registry.ts new file mode 100644 index 0000000..cec14a7 --- /dev/null +++ b/src/app/connect/domain/connection-registry.ts @@ -0,0 +1,52 @@ +import { ConnectorInfo, SourceType } from '../api/api.types'; +import { DataConnection } from './data-source'; +import { DocumentConnection } from './document-source'; +import { EegConnection } from './eeg-source'; +import { FileConnection } from './file-source'; +import { PdfConnection } from './pdf-source'; + +/** Turns the files chosen for one source kind into workspace connections. */ +export type ConnectionFactory = (files: File[]) => DataConnection[]; + +const FACTORIES = new Map([ + ['csv', (files) => files.map((file) => new FileConnection(file, 'csv'))], + ['excel', (files) => files.map((file) => new FileConnection(file, 'excel'))], + ['json', (files) => files.map((file) => new FileConnection(file, 'json'))], + ['pdf', (files) => files.map((file) => new PdfConnection(file))], + // Several recordings or documents are read together: one connection, one table. + ['edf', (files) => [new EegConnection(files)]], + ['document', (files) => [new DocumentConnection(files)]], +]); + +/** Adding a file source on the client is one `DataConnection` subclass and one call here. */ +export function registerConnectionFactory(kind: SourceType, factory: ConnectionFactory): void { + FACTORIES.set(kind, factory); +} + +export function connectionsFor(kind: SourceType, files: File[]): DataConnection[] { + const factory = FACTORIES.get(kind); + return factory && files.length ? factory(files) : []; +} + +/** First connector (in the server's order) that reads this extension, like the server does. */ +export function kindForFile(fileName: string, connectors: ConnectorInfo[]): SourceType | null { + const extension = fileName.slice(fileName.lastIndexOf('.') + 1).toLowerCase(); + return connectors.find((c) => FACTORIES.has(c.kind) && c.extensions.includes(extension))?.kind ?? null; +} + +export function acceptedExtensions(connectors: ConnectorInfo[]): string[] { + return [...new Set(connectors.filter((c) => FACTORIES.has(c.kind)).flatMap((c) => c.extensions))]; +} + +/** Dropped files grouped by kind; unsupported ones come back in `rejected`. */ +export function connectionsForFiles(files: File[], connectors: ConnectorInfo[]): { connections: DataConnection[]; rejected: File[] } { + const byKind = new Map(); + const rejected: File[] = []; + for (const file of files) { + const kind = kindForFile(file.name, connectors); + if (kind) byKind.set(kind, [...(byKind.get(kind) ?? []), file]); + else rejected.push(file); + } + const connections = [...byKind].flatMap(([kind, group]) => connectionsFor(kind, group)); + return { connections, rejected }; +} diff --git a/src/app/connect/domain/connector-catalog.spec.ts b/src/app/connect/domain/connector-catalog.spec.ts new file mode 100644 index 0000000..9df1728 --- /dev/null +++ b/src/app/connect/domain/connector-catalog.spec.ts @@ -0,0 +1,24 @@ +import { galleryEntries } from './connector-catalog'; + +describe('galleryEntries', () => { + it('expands SQL into one tile per engine plus a raw connection string, unavailable drivers disabled', () => { + const entries = galleryEntries([ + { kind: 'csv', label: 'CSV', description: 'd', category: 'file', icon: 'table_view', extensions: ['csv'] }, + { + kind: 'sql', + label: 'Base de datos', + description: '', + category: 'database', + icon: 'storage', + extensions: [], + engines: [ + { id: 'mysql', label: 'MySQL', description: 'MySQL 8', default_port: 3306, default_schema: null, available: true }, + { id: 'mssql', label: 'SQL Server', description: 'SQL Server', default_port: 1433, default_schema: 'dbo', available: false }, + ], + }, + ]); + expect(entries.map((e) => e.id)).toEqual(['csv', 'sql-mysql', 'sql-mssql', 'sql-url']); + expect(entries.find((e) => e.id === 'sql-mssql')?.available).toBe(false); + expect(entries.find((e) => e.id === 'sql-url')?.engine).toBe('url'); + }); +}); diff --git a/src/app/connect/domain/connector-catalog.ts b/src/app/connect/domain/connector-catalog.ts new file mode 100644 index 0000000..321ec9f --- /dev/null +++ b/src/app/connect/domain/connector-catalog.ts @@ -0,0 +1,62 @@ +import { ConnectorCategory, ConnectorInfo, SqlEngineInfo } from '../api/api.types'; + +/** + * The "Obtener datos" gallery, built from what the server reports it can + * read (`GET /imports/connectors`): one tile per connector, and one per + * database engine for SQL. A new connector on the server shows up here + * without client changes. + */ +export type GalleryCategory = ConnectorCategory | 'all'; + +export interface GalleryEntry { + id: string; + name: string; + description: string; + icon: string; + category: ConnectorCategory; + connector: ConnectorInfo; + /** SQL tiles: the engine the connection form is for; `url` for a raw connection string. */ + engine?: SqlEngineInfo | 'url'; + /** False when the server lacks what this tile needs (e.g. a database driver). */ + available: boolean; +} + +export const GALLERY_CATEGORIES: { id: GalleryCategory; label: string; icon: string }[] = [ + { id: 'all', label: 'Todos', icon: 'apps' }, + { id: 'file', label: 'Archivo', icon: 'folder_open' }, + { id: 'database', label: 'Base de datos', icon: 'storage' }, + { id: 'document', label: 'Documento', icon: 'description' }, + { id: 'signal', label: 'Señales', icon: 'monitor_heart' }, +]; + +export function galleryEntries(connectors: ConnectorInfo[]): GalleryEntry[] { + return connectors.flatMap((connector): GalleryEntry[] => { + if (connector.kind !== 'sql') { + return [{ ...pick(connector), id: connector.kind, name: connector.label, connector, available: true }]; + } + const engines = (connector.engines ?? []).map((engine) => ({ + ...pick(connector), + id: `sql-${engine.id}`, + name: engine.label, + description: engine.available ? engine.description : `${engine.description} (driver no instalado en el servidor)`, + connector, + engine, + available: engine.available, + })); + const raw: GalleryEntry = { + ...pick(connector), + id: 'sql-url', + name: 'Otra base de datos', + description: 'Cadena de conexión SQLAlchemy (avanzado)', + icon: 'link', + connector, + engine: 'url', + available: true, + }; + return [...engines, raw]; + }); +} + +function pick(connector: ConnectorInfo) { + return { description: connector.description, icon: connector.icon, category: connector.category }; +} diff --git a/src/app/connect/domain/data-source.ts b/src/app/connect/domain/data-source.ts new file mode 100644 index 0000000..d504e0f --- /dev/null +++ b/src/app/connect/domain/data-source.ts @@ -0,0 +1,121 @@ +import { Signal, signal } from '@angular/core'; +import { Observable, catchError, map, of, tap } from 'rxjs'; +import { PreviewResponse, SourceLocator, apiErrorMessage } from '../api/api.types'; +import { SourceGateway } from '../api/source-gateway'; + +let sequence = 0; +const nextId = (prefix: string) => `${prefix}-${++sequence}`; + +export type ConnectionState = 'loading' | 'ready' | 'error'; + +/** + * A place data comes from (a file, a database, a set of documents): the + * "Conexiones" of the workspace. It exposes `SourceTable`s (Excel sheets, + * database tables, a PDF's tables), which are what gets mapped. + * + * Each kind is one subclass (`file-source.ts`, `sql-source.ts`, + * `pdf-source.ts`, `eeg-source.ts`, `document-source.ts`) that owns how its + * tables are discovered and previewed; nothing else switches on the kind. + * New kinds are wired to file extensions in `connection-registry.ts`. + */ +export abstract class DataConnection { + readonly id = nextId('conn'); + abstract readonly icon: string; + abstract readonly typeLabel: string; + + private readonly _tables = signal([]); + private readonly _state = signal('loading'); + private readonly _error = signal(null); + + readonly tables: Signal = this._tables.asReadonly(); + readonly state: Signal = this._state.asReadonly(); + readonly error: Signal = this._error.asReadonly(); + + constructor(readonly label: string) {} + + /** A connection that can only ever have one table (a CSV) is shown flat, without a table level. */ + get singleTable(): boolean { + return false; + } + + /** Discovers this connection's tables. Does not throw; failures are reported in `state`/`error`. */ + load(gateway: SourceGateway): Observable { + this._state.set('loading'); + this._error.set(null); + return this.discover(gateway).pipe( + tap((tables) => { + this._tables.set(tables); + this._state.set('ready'); + }), + map(() => undefined), + catchError((error) => { + this._error.set(apiErrorMessage(error, `No se pudo abrir ${this.label}.`)); + this._state.set('error'); + return of(undefined); + }), + ); + } + + addTable(table: SourceTable): void { + this._tables.update((tables) => [...tables, table]); + } + + removeTable(table: SourceTable): void { + this._tables.update((tables) => tables.filter((existing) => existing !== table)); + } + + protected abstract discover(gateway: SourceGateway): Observable; +} + +/** + * One tabular source inside a connection, the unit dragged onto the canvas + * to create an import flow. Previews itself against a target entity and + * describes itself to the backend (`SourceLocator`); knows nothing about + * mapping. + */ +export abstract class SourceTable { + readonly id = nextId('table'); + abstract readonly icon: string; + /** What kind of table this is, for the UI: "Hoja", "Tabla", "Consulta SQL"... */ + abstract readonly kindLabel: string; + + constructor( + readonly connection: DataConnection, + readonly name: string, + ) {} + + get label(): string { + return this.connection.singleTable ? this.connection.label : `${this.connection.label} › ${this.name}`; + } + + /** Whether the user created this table (a custom query, drawn regions) and may remove it. */ + get removable(): boolean { + return false; + } + + abstract preview(gateway: SourceGateway, target: string | null): Observable; + + /** `target`: the entity the rows go to, for sources whose reading depends on it. */ + abstract locator(target?: string): Promise; +} + +/** Lazily computed base64 of a file, shared by every table of a connection. */ +export class EncodedFile { + private encoded: Promise | null = null; + + constructor( + readonly file: File, + private readonly encode: (file: File) => Promise, + ) {} + + base64(): Promise { + this.encoded ??= this.encode(this.file); + return this.encoded; + } +} + + +/** Encoded `{name, file_base64}` entries, the shape multi-file payloads use. */ +export async function encodeFiles(files: EncodedFile[]): Promise<{ name: string; file_base64: string }[]> { + return Promise.all(files.map(async (encoded) => ({ name: encoded.file.name, file_base64: await encoded.base64() }))); +} diff --git a/src/app/connect/domain/document-source.spec.ts b/src/app/connect/domain/document-source.spec.ts new file mode 100644 index 0000000..b370c48 --- /dev/null +++ b/src/app/connect/domain/document-source.spec.ts @@ -0,0 +1,60 @@ +import { firstValueFrom, of } from 'rxjs'; +import { SourceGateway } from '../api/source-gateway'; +import { DocumentConnection, DocumentTable } from './document-source'; +import { PdfConnection } from './pdf-source'; + +describe('DocumentTable', () => { + const extraction = { columns: [], sample_rows: [], total_rows: 1, suggested_mapping: [], key_field: 'pac_id_hospital', fields: [], records: [] }; + + function table(): DocumentTable { + const connection = new DocumentConnection([new File(['a'], 'a.pdf'), new File(['b'], 'b.png')]); + return new DocumentTable(connection, 'Registros'); + } + + it('sends every file, the settings and the corrections for the flow target only', async () => { + const t = table(); + t.configure({ segmentation: 'pages', pages_per_record: 2, ocr_mode: 'always', key_pattern: ' EXP-\\d+ ' }, { + 'cacu.Paciente': { '0': { pac_sexo: 'F' } }, + 'cacu.CitologiaCervical': { '1': { cit_vph_resultado: 'NEGATIVO' } }, + }); + const locator = await t.locator('cacu.Paciente'); + expect(locator).toEqual({ + source_type: 'document', + payload: { + files: [ + { name: 'a.pdf', file_base64: btoa('a') }, + { name: 'b.png', file_base64: btoa('b') }, + ], + segmentation: 'pages', + pages_per_record: 2, + ocr_mode: 'always', + key_pattern: 'EXP-\\d+', + overrides: { '0': { pac_sexo: 'F' } }, + }, + }); + }); + + it('changing how pages are split drops corrections, which point at record numbers', () => { + const t = table(); + t.configure(t.settings(), { 'cacu.Paciente': { '0': { pac_sexo: 'F' } } }); + t.configure({ ...t.settings(), segmentation: 'document' }); + expect(t.overrides('cacu.Paciente')).toEqual({}); + }); + + it('keeps the last extraction per target', async () => { + const t = table(); + const calls: unknown[][] = []; + const gateway = { document: { extract: (...args: unknown[]) => (calls.push(args), of(extraction)) } } as unknown as SourceGateway; + await firstValueFrom(t.preview(gateway, 'cacu.Paciente')); + expect(t.extractions()['cacu.Paciente']).toBe(extraction); + expect(calls[0][1]).toBe('cacu.Paciente'); + }); + + it('a PDF offers its whole text as a document table next to its detected tables', () => { + const gateway = { pdf: { detect: () => of({ page_count: 1, has_text_layer: false, table_candidates: [] }) } } as unknown as SourceGateway; + const pdf = new PdfConnection(new File(['%PDF'], 'informe.pdf')); + pdf.load(gateway).subscribe(); + expect(pdf.tables()).toEqual([pdf.documentTable]); + expect(pdf.documentTable.files.map((f) => f.name)).toEqual(['informe.pdf']); + }); +}); diff --git a/src/app/connect/domain/document-source.ts b/src/app/connect/domain/document-source.ts new file mode 100644 index 0000000..3da343c --- /dev/null +++ b/src/app/connect/domain/document-source.ts @@ -0,0 +1,110 @@ +import { Signal, signal } from '@angular/core'; +import { Observable, from, of, switchMap, tap } from 'rxjs'; +import { DocumentExtraction, DocumentSettings, PreviewResponse, SourceLocator } from '../api/api.types'; +import { fileToBase64 } from '../api/file-encoding'; +import { SourceGateway } from '../api/source-gateway'; +import { DataConnection, EncodedFile, SourceTable, encodeFiles } from './data-source'; + +/** A connection whose files can be read as clinical documents. */ +export interface DocumentFiles { + readonly encodedFiles: EncodedFile[]; +} + +export const DEFAULT_DOCUMENT_SETTINGS: DocumentSettings = { + segmentation: 'auto', + pages_per_record: 1, + ocr_mode: 'auto', + key_pattern: '', +}; + +export type FieldOverrides = Record>; + +/** + * Reports, forms and notes (PDF or images) that aren't tables. The server + * splits them into one record per patient (however many pages or files + * that takes) and fills the target entity's fields from labels and free + * text; see `DocumentTable`. + */ +export class DocumentConnection extends DataConnection implements DocumentFiles { + readonly icon = 'document_scanner'; + readonly typeLabel = 'Documentos clínicos'; + readonly encodedFiles: EncodedFile[]; + + constructor(readonly files: File[]) { + super(files.length === 1 ? files[0].name : `${files.length} documentos`); + this.encodedFiles = files.map((file) => new EncodedFile(file, fileToBase64)); + } + + override get singleTable(): boolean { + return true; + } + + protected discover(): Observable { + return of([new DocumentTable(this, 'Registros por paciente')]); + } +} + +/** + * The records extracted from a connection's documents. Extraction depends + * on the target entity (which fields to look for), so the last result and + * the user's corrections are kept per target. Settings and corrections + * travel in the payload; the server re-extracts on every call. + */ +export class DocumentTable extends SourceTable { + readonly icon = 'document_scanner'; + readonly kindLabel = 'Extracción de campos'; + + private readonly _settings = signal(DEFAULT_DOCUMENT_SETTINGS); + private readonly _overrides = signal>({}); + private readonly _extractions = signal>({}); + + readonly settings: Signal = this._settings.asReadonly(); + readonly extractions = this._extractions.asReadonly(); + + constructor( + override readonly connection: DataConnection & DocumentFiles, + name: string, + ) { + super(connection, name); + } + + get files(): File[] { + return this.connection.encodedFiles.map((encoded) => encoded.file); + } + + overrides(target: string): FieldOverrides { + return this._overrides()[target] ?? {}; + } + + /** Settings apply to every target: they decide how pages become records. */ + configure(settings: DocumentSettings, overridesByTarget?: Record): void { + const resegmented = JSON.stringify(settings) !== JSON.stringify(this._settings()); + this._settings.set(settings); + // Record numbers change when the segmentation does; old corrections would land on the wrong patient. + if (resegmented) this._overrides.set({}); + if (overridesByTarget) this._overrides.update((all) => ({ ...all, ...overridesByTarget })); + } + + preview(gateway: SourceGateway, target: string | null): Observable { + if (!target) return of({ columns: [], sample_rows: [], total_rows: null, suggested_mapping: [] }); + return from(this.payload(target)).pipe( + switchMap((payload) => gateway.document.extract(payload, target)), + tap((extraction) => this._extractions.update((all) => ({ ...all, [target]: extraction }))), + ); + } + + async locator(target?: string): Promise { + return { source_type: 'document', payload: await this.payload(target) }; + } + + private async payload(target?: string): Promise> { + const { key_pattern, ...settings } = this._settings(); + const overrides = target ? this.overrides(target) : {}; + return { + files: await encodeFiles(this.connection.encodedFiles), + ...settings, + ...(key_pattern.trim() ? { key_pattern: key_pattern.trim() } : {}), + ...(Object.keys(overrides).length ? { overrides } : {}), + }; + } +} diff --git a/src/app/connect/domain/eeg-source.ts b/src/app/connect/domain/eeg-source.ts new file mode 100644 index 0000000..3505bb1 --- /dev/null +++ b/src/app/connect/domain/eeg-source.ts @@ -0,0 +1,52 @@ +import { Observable, from, map, switchMap } from 'rxjs'; +import { PreviewResponse, SourceLocator } from '../api/api.types'; +import { fileToBase64 } from '../api/file-encoding'; +import { SourceGateway } from '../api/source-gateway'; +import { DataConnection, EncodedFile, SourceTable, encodeFiles } from './data-source'; + +/** + * EEG recordings (`.edf`). All files added together form one table with a + * row per recording: header data, an estimated background rhythm and the + * file itself, shaped for TEA's `EegEstudio`. + */ +export class EegConnection extends DataConnection { + readonly icon = 'monitor_heart'; + readonly typeLabel = 'EEG (EDF)'; + readonly encoded: EncodedFile[]; + + constructor(readonly files: File[]) { + super(files.length === 1 ? files[0].name : `${files.length} registros EEG`); + this.encoded = files.map((file) => new EncodedFile(file, fileToBase64)); + } + + override get singleTable(): boolean { + return true; + } + + async payload(): Promise> { + return { files: await encodeFiles(this.encoded) }; + } + + protected discover(gateway: SourceGateway): Observable { + // Reading the headers up front rejects files MNE can't open. + const table = new EegTable(this); + return table.preview(gateway, null).pipe(map(() => [table])); + } +} + +export class EegTable extends SourceTable { + readonly icon = 'monitor_heart'; + readonly kindLabel = 'Registros'; + + constructor(override readonly connection: EegConnection) { + super(connection, 'Registros'); + } + + preview(gateway: SourceGateway, target: string | null): Observable { + return from(this.connection.payload()).pipe(switchMap((payload) => gateway.file.previewPayload('edf', payload, target))); + } + + async locator(): Promise { + return { source_type: 'edf', payload: await this.connection.payload() }; + } +} diff --git a/src/app/connect/domain/file-source.spec.ts b/src/app/connect/domain/file-source.spec.ts new file mode 100644 index 0000000..7de3d21 --- /dev/null +++ b/src/app/connect/domain/file-source.spec.ts @@ -0,0 +1,47 @@ +import { of, throwError } from 'rxjs'; +import { SourceGateway } from '../api/source-gateway'; +import { FileConnection } from './file-source'; +import { preview } from '../testing/fakes'; + +describe('FileConnection', () => { + it('exposes one table per Excel sheet, each previewing and loading with its sheet_name', async () => { + const calls: unknown[][] = []; + const gateway = { + file: { + preview: (...args: unknown[]) => { + calls.push(args); + return of(preview({ tables: ['Órdenes', 'Notas'].map((name) => ({ name, options: { sheet_name: name }, kind: 'sheet' })) })); + }, + }, + } as unknown as SourceGateway; + + const connection = new FileConnection(new File(['x'], 'libro.xlsx'), 'excel'); + connection.load(gateway).subscribe(); + expect(connection.state()).toBe('ready'); + expect(connection.tables().map((t) => t.name)).toEqual(['Órdenes', 'Notas']); + expect(connection.tables()[1].label).toBe('libro.xlsx › Notas'); + + connection.tables()[1].preview(gateway, 'cacu.NotaMedica').subscribe(); + expect(calls.at(-1)?.slice(1)).toEqual(['excel', 'cacu.NotaMedica', { sheet_name: 'Notas' }]); + + const locator = await connection.tables()[1].locator(); + expect(locator).toEqual({ source_type: 'excel', payload: { file_base64: btoa('x'), options: { sheet_name: 'Notas' } } }); + }); + + it('a CSV is a single table labelled by the file name', () => { + const gateway = { file: { preview: () => of(preview()) } } as unknown as SourceGateway; + const connection = new FileConnection(new File(['a,b'], 'p.csv'), 'csv'); + connection.load(gateway).subscribe(); + expect(connection.singleTable).toBe(true); + expect(connection.tables().map((t) => t.label)).toEqual(['p.csv']); + }); + + it('a file that fails to parse lands in the error state with the backend message', () => { + const gateway = { file: { preview: () => throwError(() => ({ error: { error: 'could not parse CSV' } })) } } as unknown as SourceGateway; + const connection = new FileConnection(new File(['?'], 'x.csv'), 'csv'); + connection.load(gateway).subscribe(); + expect(connection.state()).toBe('error'); + expect(connection.error()).toBe('could not parse CSV'); + expect(connection.tables()).toEqual([]); + }); +}); diff --git a/src/app/connect/domain/file-source.ts b/src/app/connect/domain/file-source.ts new file mode 100644 index 0000000..2c4e737 --- /dev/null +++ b/src/app/connect/domain/file-source.ts @@ -0,0 +1,69 @@ +import { Observable, map } from 'rxjs'; +import { FileKind, FileOptions, PreviewResponse, SourceLocator } from '../api/api.types'; +import { fileToBase64 } from '../api/file-encoding'; +import { SourceGateway } from '../api/source-gateway'; +import { DataConnection, EncodedFile, SourceTable } from './data-source'; + +const FILE_PRESENTATION: Record = { + csv: { icon: 'table_view', typeLabel: 'Texto / CSV' }, + excel: { icon: 'grid_on', typeLabel: 'Libro de Excel' }, + json: { icon: 'data_object', typeLabel: 'JSON' }, +}; + +/** A CSV, Excel or JSON file. Excel exposes one table per sheet; CSV/JSON exactly one. */ +export class FileConnection extends DataConnection { + readonly icon: string; + readonly typeLabel: string; + readonly encoded: EncodedFile; + + constructor( + readonly file: File, + readonly fileKind: FileKind, + ) { + super(file.name); + this.icon = FILE_PRESENTATION[fileKind].icon; + this.typeLabel = FILE_PRESENTATION[fileKind].typeLabel; + this.encoded = new EncodedFile(file, fileToBase64); + } + + override get singleTable(): boolean { + return this.fileKind !== 'excel'; + } + + protected discover(gateway: SourceGateway): Observable { + // A target-less preview proves the file parses and lists its sub-tables (Excel sheets). + return gateway.file.preview(this.file, this.fileKind, null).pipe( + map((preview) => { + const tables = preview.tables ?? []; + if (!tables.length) return [new FileTable(this, this.file.name, {})]; + return tables.map((table) => new FileTable(this, table.name, table.options as FileOptions)); + }), + ); + } +} + +export class FileTable extends SourceTable { + readonly icon: string; + readonly kindLabel: string; + + constructor( + override readonly connection: FileConnection, + name: string, + readonly options: FileOptions, + ) { + super(connection, name); + this.icon = connection.fileKind === 'excel' ? 'tab' : connection.icon; + this.kindLabel = connection.fileKind === 'excel' ? 'Hoja' : 'Archivo'; + } + + preview(gateway: SourceGateway, target: string | null): Observable { + return gateway.file.preview(this.connection.file, this.connection.fileKind, target, this.options); + } + + async locator(): Promise { + return { + source_type: this.connection.fileKind, + payload: { file_base64: await this.connection.encoded.base64(), options: this.options }, + }; + } +} diff --git a/src/app/connect/domain/import-flow.spec.ts b/src/app/connect/domain/import-flow.spec.ts new file mode 100644 index 0000000..da50dbd --- /dev/null +++ b/src/app/connect/domain/import-flow.spec.ts @@ -0,0 +1,95 @@ +import { of, throwError } from 'rxjs'; +import { FakeConnection, FakeTable, NO_GATEWAY, PACIENTE, preview } from '../testing/fakes'; +import { ImportFlow } from './import-flow'; + +function loadedFlow(): ImportFlow { + const flow = new ImportFlow(new FakeTable(new FakeConnection()), PACIENTE); + flow.load(NO_GATEWAY).subscribe(); + return flow; +} + +describe('ImportFlow', () => { + it('loads the preview and seeds the mapping from the suggestions', () => { + const flow = loadedFlow(); + expect(flow.totalRows()).toBe(2); + expect(flow.mapping.toRecord()).toEqual({ Sexo: 'pac_sexo' }); + expect(flow.pendingSuggestions()).toBe(1); + }); + + it('is incomplete until every required field has a column or a default', () => { + const flow = loadedFlow(); + expect(flow.status()).toBe('incomplete'); + expect(flow.missingRequired().map((f) => f.name)).toEqual(['pac_id_hospital']); + + flow.setDefault('pac_id_hospital', 'H-X'); + expect(flow.status()).toBe('ready'); + flow.setDefault('pac_id_hospital', null); + flow.map('Clave', 'pac_id_hospital'); + expect(flow.status()).toBe('ready'); + expect(flow.canSubmit).toBe(true); + }); + + it('reports a preview failure as an error status with the backend message', () => { + const table = new FakeTable(new FakeConnection(), 'bad', () => throwError(() => ({ error: { error: 'could not parse CSV' } }))); + const flow = new ImportFlow(table, PACIENTE); + flow.load(NO_GATEWAY).subscribe(); + expect(flow.status()).toBe('error'); + expect(flow.error()).toBe('could not parse CSV'); + }); + + it('builds the backend payload: locator + target + mapping + only non-empty defaults', async () => { + const flow = loadedFlow(); + flow.map('Clave', 'pac_id_hospital'); + flow.setDefault('pac_parentesco', 'Afiliado'); + flow.setDefault('pac_sexo', ' '); + expect(await flow.toPayload()).toEqual({ + source_type: 'csv', + payload: { file_base64: 'QQ==' }, + target: 'cacu.Paciente', + label: 'fake.csv', + column_mapping: { Sexo: 'pac_sexo', Clave: 'pac_id_hospital' }, + defaults: { pac_parentesco: 'Afiliado' }, + }); + }); + + it('validates, indexes errors by cell and per-field quality, and any edit invalidates the result', async () => { + const flow = loadedFlow(); + flow.map('Clave', 'pac_id_hospital'); + await flow.validate({ + validate: () => + of({ + total_rows: 2, + valid_count: 1, + error_count: 1, + errors: [{ row_index: 1, field: 'pac_sexo', category: 'out_of_catalog' as const, message: 'no', raw_value: 'X' }], + }), + }); + expect(flow.status()).toBe('invalid'); + expect(flow.errorsByCell().get('1:pac_sexo')?.[0].raw_value).toBe('X'); + expect(flow.quality().get('pac_sexo')).toEqual({ field: 'pac_sexo', total: 2, errors: 1, errorRate: 0.5 }); + + flow.unmapField('pac_sexo'); + expect(flow.validation()).toBeNull(); + expect(flow.status()).toBe('ready'); + }); + + it('records a commit result as loaded, with its errors as the freshest validation', () => { + const flow = loadedFlow(); + flow.map('Clave', 'pac_id_hospital'); + flow.recordResult({ target: 'cacu.Paciente', label: null, total: 2, created: 1, updated: 0, rejected: 1, errors: [] }); + expect(flow.status()).toBe('loaded'); + expect(flow.validation()?.valid_count).toBe(1); + }); + + it('autoMap only fills what is still free', () => { + const table = new FakeTable(new FakeConnection(), 't', () => + of(preview({ suggested_mapping: [{ source_column: 'Clave', target_field: 'pac_id_hospital', confidence: 0.8, reason: 'synonym' }] })), + ); + const flow = new ImportFlow(table, PACIENTE); + flow.load(NO_GATEWAY).subscribe(); + flow.clearMapping(); + flow.map('Sexo', 'pac_sexo'); + expect(flow.autoMap()).toBe(1); + expect(flow.mapping.toRecord()).toEqual({ Sexo: 'pac_sexo', Clave: 'pac_id_hospital' }); + }); +}); diff --git a/src/app/connect/domain/import-flow.ts b/src/app/connect/domain/import-flow.ts new file mode 100644 index 0000000..0ad8608 --- /dev/null +++ b/src/app/connect/domain/import-flow.ts @@ -0,0 +1,264 @@ +import { Signal, computed, signal } from '@angular/core'; +import { Observable, catchError, finalize, map, of, tap } from 'rxjs'; +import { + CommitSourceResult, + ImportSourcePayload, + PreviewResponse, + RowError, + SourceColumn, + TargetField, + TargetMeta, + ValidationResult, + apiErrorMessage, +} from '../api/api.types'; +import { SourceGateway } from '../api/source-gateway'; +import { SourceTable } from './data-source'; +import { MappingSet } from './mapping-set'; + +export type FlowStatus = 'loading' | 'error' | 'incomplete' | 'ready' | 'validating' | 'valid' | 'invalid' | 'loaded'; + +export interface FieldQuality { + field: string; + total: number; + errors: number; + /** 0..1 */ + errorRate: number; +} + +/** The part of the imports API that `validate`/`commit` use, kept narrow so tests can fake it. */ +export interface Validator { + validate(source: ImportSourcePayload): Observable; +} + +let sequence = 0; + +/** + * One source table flowing into one destination entity: the unit the user + * composes the database from. A workspace can feed several tables into one + * entity or one file into several entities. + * + * Owns its mapping (`MappingSet`), per-field default values, the latest + * preview and validation, and derives its own status. Any change to what + * would be sent clears the previous validation, so a stale result is not + * shown. + */ +export class ImportFlow { + readonly id = `flow-${++sequence}`; + readonly mapping = new MappingSet(); + + private readonly _preview = signal(null); + private readonly _loading = signal(false); + private readonly _error = signal(null); + private readonly _defaults = signal>({}); + private readonly _validation = signal(null); + private readonly _validating = signal(false); + private readonly _result = signal(null); + + readonly preview: Signal = this._preview.asReadonly(); + readonly loading: Signal = this._loading.asReadonly(); + readonly error: Signal = this._error.asReadonly(); + readonly defaults: Signal> = this._defaults.asReadonly(); + readonly validation: Signal = this._validation.asReadonly(); + readonly validating: Signal = this._validating.asReadonly(); + readonly result: Signal = this._result.asReadonly(); + + readonly sourceColumns = computed(() => this._preview()?.columns ?? []); + readonly totalRows = computed(() => this._preview()?.total_rows ?? null); + + /** A field is covered when a column feeds it or it has a default value. */ + readonly missingRequired = computed(() => { + const mapped = this.mapping.byField(); + const defaults = this._defaults(); + return this.target.fields.filter((f) => f.required && !mapped.has(f.name) && !defaults[f.name]?.trim()); + }); + + readonly unmappedColumns = computed(() => { + const used = this.mapping.bySource(); + return this.sourceColumns().filter((column) => !used.has(column.name)); + }); + + readonly pendingSuggestions = computed(() => this.mapping.items().filter((m) => m.confidence !== undefined).length); + + readonly status = computed(() => { + if (this._loading()) return 'loading'; + if (this._error() || !this._preview()) return 'error'; + if (this._result()) return 'loaded'; + if (this._validating()) return 'validating'; + if (this.missingRequired().length > 0 || this.mapping.size() + Object.keys(this.activeDefaults()).length === 0) { + return 'incomplete'; + } + const validation = this._validation(); + if (!validation) return 'ready'; + return validation.error_count > 0 ? 'invalid' : 'valid'; + }); + + /** Row errors indexed by `":"` for the data grid's cell highlighting. */ + readonly errorsByCell = computed(() => { + const index = new Map(); + for (const error of this._validation()?.errors ?? []) { + const key = `${error.row_index}:${error.field}`; + index.set(key, [...(index.get(key) ?? []), error]); + } + return index; + }); + + /** Per destination field: how many rows failed on it (Power Query-style column quality). */ + readonly quality = computed(() => { + const validation = this._validation(); + const qualities = new Map(); + if (!validation) return qualities; + const failingRows = new Map>(); + for (const error of validation.errors) { + if (!failingRows.has(error.field)) failingRows.set(error.field, new Set()); + failingRows.get(error.field)!.add(error.row_index); + } + for (const field of this.target.fields) { + const errors = failingRows.get(field.name)?.size ?? 0; + const total = validation.total_rows; + qualities.set(field.name, { field: field.name, total, errors, errorRate: total ? errors / total : 0 }); + } + return qualities; + }); + + constructor( + readonly table: SourceTable, + readonly target: TargetMeta, + ) {} + + get label(): string { + return this.table.label; + } + + /** Complete enough to validate. */ + get canSubmit(): boolean { + return !['loading', 'error', 'incomplete'].includes(this.status()); + } + + /** + * Belongs in the next load: complete and not already written. A loaded + * flow stays out of later batches (re-sending it would duplicate rows in + * tables without a natural key) until it's edited, since any edit clears + * its result. + */ + get pendingLoad(): boolean { + return this.canSubmit && this.status() !== 'loaded'; + } + + /** Fetches the preview against this flow's target and seeds the mapping from the server's suggestions. */ + load(gateway: SourceGateway): Observable { + this._loading.set(true); + this._error.set(null); + return this.table.preview(gateway, this.target.key).pipe( + tap((preview) => { + this._preview.set(preview); + this.mapping.seed(preview.suggested_mapping); + }), + map(() => undefined), + catchError((error) => { + this._error.set(apiErrorMessage(error, 'No se pudo leer la fuente.')); + return of(undefined); + }), + finalize(() => this._loading.set(false)), + ); + } + + // -- mapping edits (every one invalidates the last validation) ----------- + + map(source: string, field: string): void { + this.mapping.assign(source, field); + this.touch(); + } + + unmapField(field: string): void { + this.mapping.releaseField(field); + this.touch(); + } + + unmapSource(source: string): void { + this.mapping.releaseSource(source); + this.touch(); + } + + confirmSuggestion(field: string): void { + this.mapping.confirm(field); + } + + /** Re-applies the server's suggestions to whatever is still unmapped. Returns how many were added. */ + autoMap(): number { + const added = this.mapping.fillFrom(this._preview()?.suggested_mapping ?? []); + if (added) this.touch(); + return added; + } + + clearMapping(): void { + this.mapping.clear(); + this._defaults.set({}); + this.touch(); + } + + setDefault(field: string, value: string | null): void { + this._defaults.update((defaults) => { + const next = { ...defaults }; + if (value === null || value === '') delete next[field]; + else next[field] = value; + return next; + }); + this.touch(); + } + + activeDefaults(): Record { + return Object.fromEntries(Object.entries(this._defaults()).filter(([, value]) => value.trim() !== '')); + } + + // -- backend round trips --------------------------------------------------- + + async toPayload(): Promise { + const locator = await this.table.locator(this.target.key); + const defaults = this.activeDefaults(); + return { + ...locator, + target: this.target.key, + label: this.label, + column_mapping: this.mapping.toRecord(), + ...(Object.keys(defaults).length ? { defaults } : {}), + }; + } + + validate(validator: Validator): Promise { + this._validating.set(true); + return this.toPayload() + .then( + (payload) => + new Promise((resolve) => { + validator.validate(payload).subscribe({ + next: (result) => { + this._validation.set(result); + this._error.set(null); + resolve(); + }, + error: (error) => { + this._error.set(apiErrorMessage(error, 'No se pudo validar la fuente.')); + resolve(); + }, + }); + }), + ) + .finally(() => this._validating.set(false)); + } + + recordResult(result: CommitSourceResult): void { + this._result.set(result); + // The commit re-validated every row server-side; its errors are the freshest view. + this._validation.set({ + total_rows: result.total, + valid_count: result.created + result.updated, + error_count: result.rejected, + errors: result.errors, + }); + } + + private touch(): void { + this._validation.set(null); + this._result.set(null); + } +} diff --git a/src/app/connect/domain/mapping-set.spec.ts b/src/app/connect/domain/mapping-set.spec.ts new file mode 100644 index 0000000..189cf09 --- /dev/null +++ b/src/app/connect/domain/mapping-set.spec.ts @@ -0,0 +1,44 @@ +import { MappingSet } from './mapping-set'; + +describe('MappingSet', () => { + it('seeds from suggestions, skipping unmatched columns and keeping confidence', () => { + const set = new MappingSet(); + set.seed([ + { source_column: 'a', target_field: 'x', confidence: 0.8, reason: 'synonym' }, + { source_column: 'b', target_field: null, confidence: 0, reason: 'none' }, + ]); + expect(set.items()).toEqual([{ source: 'a', field: 'x', confidence: 0.8, reason: 'synonym' }]); + }); + + it('keeps the mapping 1:1 in both directions', () => { + const set = new MappingSet(); + set.assign('a', 'x'); + set.assign('b', 'x'); // field x now fed by b + set.assign('b', 'y'); // column b moves to y + expect(set.toRecord()).toEqual({ b: 'y' }); + }); + + it('fillFrom never overrides a manual choice', () => { + const set = new MappingSet(); + set.assign('manual', 'x'); + const added = set.fillFrom([ + { source_column: 'auto', target_field: 'x', confidence: 0.9, reason: 'normalized' }, + { source_column: 'other', target_field: 'y', confidence: 0.7, reason: 'fuzzy' }, + ]); + expect(added).toBe(1); + expect(set.toRecord()).toEqual({ manual: 'x', other: 'y' }); + }); + + it('confirm drops the suggestion marker; release removes by field or by source', () => { + const set = new MappingSet(); + set.seed([ + { source_column: 'a', target_field: 'x', confidence: 0.8, reason: 'synonym' }, + { source_column: 'b', target_field: 'y', confidence: 0.8, reason: 'synonym' }, + ]); + set.confirm('x'); + expect(set.byField().get('x')).toEqual({ source: 'a', field: 'x' }); + set.releaseField('x'); + set.releaseSource('b'); + expect(set.size()).toBe(0); + }); +}); diff --git a/src/app/connect/domain/mapping-set.ts b/src/app/connect/domain/mapping-set.ts new file mode 100644 index 0000000..9125755 --- /dev/null +++ b/src/app/connect/domain/mapping-set.ts @@ -0,0 +1,79 @@ +import { Signal, computed, signal } from '@angular/core'; +import { MatchReason, SuggestedMapping } from '../api/api.types'; + +/** One source column feeding one destination field. */ +export interface ColumnMapping { + source: string; + field: string; + /** Set while the mapping is an unconfirmed auto-suggestion; cleared by any manual action. */ + confidence?: number; + reason?: MatchReason; +} + +/** + * The column mapping of one import flow, 1:1 in both directions, matching + * the backend's source-to-field `column_mapping` dict. Every view (field + * slots, the unused-columns tray, data grid headers) derives from `items`. + */ +export class MappingSet { + private readonly _items = signal([]); + readonly items: Signal = this._items.asReadonly(); + + readonly byField = computed(() => new Map(this._items().map((m) => [m.field, m]))); + readonly bySource = computed(() => new Map(this._items().map((m) => [m.source, m]))); + readonly size = computed(() => this._items().length); + + /** Replaces everything with the server's suggestions (confidence kept, so the UI can flag them). */ + seed(suggestions: SuggestedMapping[]): void { + this._items.set( + suggestions + .filter((s): s is SuggestedMapping & { target_field: string } => !!s.target_field) + .map((s) => ({ source: s.source_column, field: s.target_field, confidence: s.confidence, reason: s.reason })), + ); + } + + /** Adds suggestions only for fields and columns that are still free, keeping manual choices. */ + fillFrom(suggestions: SuggestedMapping[]): number { + let added = 0; + this._items.update((items) => { + const next = [...items]; + const usedFields = new Set(next.map((m) => m.field)); + const usedSources = new Set(next.map((m) => m.source)); + for (const s of suggestions) { + if (!s.target_field || usedFields.has(s.target_field) || usedSources.has(s.source_column)) continue; + next.push({ source: s.source_column, field: s.target_field, confidence: s.confidence, reason: s.reason }); + usedFields.add(s.target_field); + usedSources.add(s.source_column); + added++; + } + return next; + }); + return added; + } + + assign(source: string, field: string): void { + this._items.update((items) => [...items.filter((m) => m.source !== source && m.field !== field), { source, field }]); + } + + /** Accepts an auto-suggestion as-is (drops its confidence marker). */ + confirm(field: string): void { + this._items.update((items) => items.map((m) => (m.field === field ? { source: m.source, field: m.field } : m))); + } + + releaseField(field: string): void { + this._items.update((items) => items.filter((m) => m.field !== field)); + } + + releaseSource(source: string): void { + this._items.update((items) => items.filter((m) => m.source !== source)); + } + + clear(): void { + this._items.set([]); + } + + /** The backend's `column_mapping` shape: `{source_column: target_field}`. */ + toRecord(): Record { + return Object.fromEntries(this._items().map((m) => [m.source, m.field])); + } +} diff --git a/src/app/connect/domain/pdf-source.ts b/src/app/connect/domain/pdf-source.ts new file mode 100644 index 0000000..559f75a --- /dev/null +++ b/src/app/connect/domain/pdf-source.ts @@ -0,0 +1,117 @@ +import { Signal, signal } from '@angular/core'; +import { Observable, map, tap } from 'rxjs'; +import { PdfDetectResponse, PreviewResponse, RegionSpec, SourceLocator, TableCandidate } from '../api/api.types'; +import { fileToBase64 } from '../api/file-encoding'; +import { SourceGateway } from '../api/source-gateway'; +import { DataConnection, EncodedFile, SourceTable } from './data-source'; +import { DocumentFiles, DocumentTable } from './document-source'; + +/** + * A PDF, readable three ways: + * - tables the server detects in its text layer; + * - columns the user draws over the pages (OCR'd when scanned); + * - as a clinical document: fields extracted from labels and free text, + * one record per patient (`DocumentTable`), for reports that aren't tables. + */ +export class PdfConnection extends DataConnection implements DocumentFiles { + readonly icon = 'picture_as_pdf'; + readonly typeLabel = 'Documento PDF'; + readonly encoded: EncodedFile; + readonly documentTable: DocumentTable; + private readonly _detection = signal(null); + readonly detection: Signal = this._detection.asReadonly(); + + constructor(readonly file: File) { + super(file.name); + this.encoded = new EncodedFile(file, fileToBase64); + this.documentTable = new DocumentTable(this, 'Campos del documento'); + } + + get encodedFiles(): EncodedFile[] { + return [this.encoded]; + } + + addRegions(name: string, regions: RegionSpec[]): PdfRegionTable { + const table = new PdfRegionTable(this, name, regions); + this.addTable(table); + return table; + } + + protected discover(gateway: SourceGateway): Observable { + return gateway.pdf.detect(this.file).pipe( + tap((detection) => this._detection.set(detection)), + map((detection) => { + const drawn = this.tables().filter((table) => table instanceof PdfRegionTable); + const detected = detection.table_candidates.map( + (candidate, index) => new PdfDetectedTable(this, `Tabla ${index + 1} · pág. ${candidate.page_number}`, candidate), + ); + return [this.documentTable, ...detected, ...drawn]; + }), + ); + } +} + +export class PdfDetectedTable extends SourceTable { + readonly icon = 'table_chart'; + readonly kindLabel = 'Tabla detectada'; + + constructor( + override readonly connection: PdfConnection, + name: string, + readonly candidate: TableCandidate, + ) { + super(connection, name); + } + + preview(gateway: SourceGateway, target: string | null): Observable { + return gateway.pdf.tablePreview(this.connection.file, this.candidate.page_number, this.candidate.bbox, target); + } + + async locator(): Promise { + return { + source_type: 'pdf', + payload: { + file_base64: await this.connection.encoded.base64(), + mode: 'table', + page_number: this.candidate.page_number, + bbox: this.candidate.bbox, + }, + }; + } +} + +export class PdfRegionTable extends SourceTable { + readonly icon = 'crop_free'; + readonly kindLabel = 'Regiones dibujadas'; + + constructor( + override readonly connection: PdfConnection, + name: string, + readonly regions: RegionSpec[], + ) { + super(connection, name); + } + + override get removable(): boolean { + return true; + } + + preview(gateway: SourceGateway, target: string | null): Observable { + return gateway.pdf.extractRegions(this.connection.file, this.regions, target).pipe( + map((extraction) => ({ + columns: extraction.columns, + sample_rows: extraction.rows.slice(0, 50), + total_rows: extraction.rows.length, + suggested_mapping: extraction.suggested_mapping, + source_metadata: { warnings: extraction.warnings }, + })), + ); + } + + async locator(): Promise { + return { + source_type: 'pdf', + payload: { file_base64: await this.connection.encoded.base64(), mode: 'regions', regions: this.regions }, + }; + } +} diff --git a/src/app/connect/domain/sql-source.spec.ts b/src/app/connect/domain/sql-source.spec.ts new file mode 100644 index 0000000..d8126bb --- /dev/null +++ b/src/app/connect/domain/sql-source.spec.ts @@ -0,0 +1,16 @@ +import { SqlConnection, SqlQueryTable, SqlTable } from './sql-source'; + +describe('SqlConnection', () => { + it('sends the server settings, never a hand-built URL', async () => { + const server = { engine: 'mssql', host: 'his.local', port: null, database: 'HIS', user: 'lector', password: 'p@ss' }; + const connection = new SqlConnection({ server }, 'HIS · lector@his.local:1433', 'dbo'); + expect(await new SqlTable(connection, 'pacientes').locator()).toEqual({ + source_type: 'sql', + payload: { server, table: 'pacientes', schema: 'dbo' }, + }); + expect(await new SqlQueryTable(connection, 'q', 'SELECT 1').locator()).toEqual({ + source_type: 'sql', + payload: { server, query: 'SELECT 1' }, + }); + }); +}); diff --git a/src/app/connect/domain/sql-source.ts b/src/app/connect/domain/sql-source.ts new file mode 100644 index 0000000..9dbd098 --- /dev/null +++ b/src/app/connect/domain/sql-source.ts @@ -0,0 +1,109 @@ +import { Signal, signal } from '@angular/core'; +import { Observable, map, switchMap, tap } from 'rxjs'; +import { PreviewResponse, SourceLocator, SqlConnectionRef } from '../api/api.types'; +import { SourceGateway } from '../api/source-gateway'; +import { DataConnection, SourceTable } from './data-source'; + +/** + * A live database. Its tables are discovered from the server's catalog; + * the user can add custom SELECT queries as extra tables (a join, a + * filter, a computed column). + * + * The credentials travel with every request (the API is stateless) but + * are never shown: `label` is a credential-free display name. + */ +export class SqlConnection extends DataConnection { + readonly icon = 'storage'; + private readonly _dialect = signal(null); + readonly dialect: Signal = this._dialect.asReadonly(); + + constructor( + readonly ref: SqlConnectionRef, + displayName: string, + readonly schema?: string, + ) { + super(displayName); + } + + get typeLabel(): string { + return SQL_DIALECT_LABELS[this._dialect() ?? ''] ?? 'Base de datos'; + } + + addQuery(name: string, query: string): SqlQueryTable { + const table = new SqlQueryTable(this, name, query); + this.addTable(table); + return table; + } + + protected discover(gateway: SourceGateway): Observable { + return gateway.sql.testConnection(this.ref).pipe( + tap((response) => this._dialect.set(response.dialect)), + switchMap(() => gateway.sql.tables(this.ref, this.schema)), + map((tables) => { + const queries = this.tables().filter((table) => table instanceof SqlQueryTable); + return [...tables.map((name) => new SqlTable(this, name)), ...queries]; + }), + ); + } +} + +const SQL_DIALECT_LABELS: Record = { + mysql: 'MySQL', + mariadb: 'MariaDB', + postgresql: 'PostgreSQL', + mssql: 'SQL Server', + oracle: 'Oracle', + sqlite: 'SQLite', +}; + +export class SqlTable extends SourceTable { + readonly icon = 'table_rows'; + readonly kindLabel = 'Tabla'; + + constructor( + override readonly connection: SqlConnection, + name: string, + ) { + super(connection, name); + } + + preview(gateway: SourceGateway, target: string | null): Observable { + return gateway.sql.preview(this.connection.ref, { table: this.name, schema: this.connection.schema }, target); + } + + async locator(): Promise { + return { + source_type: 'sql', + payload: { + ...this.connection.ref, + table: this.name, + ...(this.connection.schema ? { schema: this.connection.schema } : {}), + }, + }; + } +} + +export class SqlQueryTable extends SourceTable { + readonly icon = 'manage_search'; + readonly kindLabel = 'Consulta SQL'; + + constructor( + override readonly connection: SqlConnection, + name: string, + readonly query: string, + ) { + super(connection, name); + } + + override get removable(): boolean { + return true; + } + + preview(gateway: SourceGateway, target: string | null): Observable { + return gateway.sql.preview(this.connection.ref, { query: this.query }, target); + } + + async locator(): Promise { + return { source_type: 'sql', payload: { ...this.connection.ref, query: this.query } }; + } +} diff --git a/src/app/connect/domain/sql-url.spec.ts b/src/app/connect/domain/sql-url.spec.ts new file mode 100644 index 0000000..c796bb0 --- /dev/null +++ b/src/app/connect/domain/sql-url.spec.ts @@ -0,0 +1,12 @@ +import { describeSqlServer, describeSqlUrl } from './sql-url'; + +describe('sql-url', () => { + const mssql = { id: 'mssql', label: 'SQL Server', description: '', default_port: 1433, default_schema: 'dbo', available: true }; + + it('never puts the password in what the UI shows', () => { + const settings = { engine: mssql, host: '10.0.10.41', port: null, database: 'his', user: 'lector', password: 'p@ss:w/rd' }; + expect(describeSqlServer(settings)).toBe('his · lector@10.0.10.41:1433'); + expect(describeSqlUrl('mysql+pymysql://u:secret@db.local:3307/hospital_legacy')).toBe('hospital_legacy · db.local:3307'); + expect(describeSqlUrl('not a url')).toBe('Base de datos'); + }); +}); diff --git a/src/app/connect/domain/sql-url.ts b/src/app/connect/domain/sql-url.ts new file mode 100644 index 0000000..059e198 --- /dev/null +++ b/src/app/connect/domain/sql-url.ts @@ -0,0 +1,24 @@ +import { SqlEngineInfo } from '../api/api.types'; + +export interface SqlServerSettings { + engine: SqlEngineInfo; + host: string; + port: number | null; + database: string; + user: string; + password: string; +} + +/** What the UI shows for a connection; never the password. */ +export function describeSqlServer(settings: SqlServerSettings): string { + const port = settings.port ?? settings.engine.default_port; + return `${settings.database} · ${settings.user ? `${settings.user}@` : ''}${settings.host}:${port}`; +} + +/** Credential-free label for a raw connection string (`scheme://user:pass@host/db` -> `db · host`). */ +export function describeSqlUrl(url: string): string { + const match = /^([^:]+):\/\/(?:[^@/]*@)?([^/?#]*)\/?([^?#]*)/.exec(url.trim()); + if (!match) return 'Base de datos'; + const [, , host, database] = match; + return database ? `${decodeURIComponent(database)} · ${host}` : host || 'Base de datos'; +} diff --git a/src/app/connect/domain/target-suggester.spec.ts b/src/app/connect/domain/target-suggester.spec.ts new file mode 100644 index 0000000..5b9523b --- /dev/null +++ b/src/app/connect/domain/target-suggester.spec.ts @@ -0,0 +1,29 @@ +import { TargetMeta } from '../api/api.types'; +import { suggestTarget, words } from './target-suggester'; + +const targets = ['Paciente', 'OrdenesEstudio', 'NotaMedica', 'BiopsiaCervical', 'BiometriaHematica'].map( + (table) => ({ key: `cacu.${table}`, domain: 'cacu', table, conflict_fields: null, fields: [] }) as TargetMeta, +); + +describe('suggestTarget', () => { + it('splits camelCase, strips accents and extensions', () => { + expect(words('OrdenesEstudio')).toEqual(['ordenes', 'estudio']); + expect(words('Notas médicas.xlsx')).toEqual(['notas', 'medicas']); + }); + + it.each([ + ['pacientes.csv', '', 'Paciente'], + ['Órdenes', 'libro.xlsx', 'OrdenesEstudio'], + ['Notas médicas', 'libro.xlsx', 'NotaMedica'], + ['cacu_biometrias.json', '', 'BiometriaHematica'], + // Nothing in the table's own name — fall back to the connection's. + ['Tabla 1 · pág. 1', 'cacu_biopsias_reporte.pdf', 'BiopsiaCervical'], + ['Regiones 1', 'pacientes_escaneados.pdf', 'Paciente'], + ])('%s (%s) → %s', (table, connection, expected) => { + expect(suggestTarget(table, targets, connection)?.table).toBe(expected); + }); + + it('suggests nothing rather than guessing', () => { + expect(suggestTarget('datos', targets, 'export.csv')).toBeNull(); + }); +}); diff --git a/src/app/connect/domain/target-suggester.ts b/src/app/connect/domain/target-suggester.ts new file mode 100644 index 0000000..c9ca4b7 --- /dev/null +++ b/src/app/connect/domain/target-suggester.ts @@ -0,0 +1,49 @@ +import { TargetMeta } from '../api/api.types'; + +/** Lower-case, accent-free words: "Notas médicas" -> ["notas", "medicas"], "OrdenesEstudio" -> ["ordenes", "estudio"]. */ +export function words(text: string): string[] { + return text + .replace(/\.[a-z0-9]{2,4}$/i, '') // file extension + .replace(/([a-z])([A-Z])/g, '$1 $2') // camelCase + .normalize('NFKD') + .replace(/[̀-ͯ]/g, '') + .toLowerCase() + .split(/[^a-z0-9]+/) + .filter((word) => word.length > 2); +} + +/** + * Singular/plural-insensitive forms of a word. Spanish plurals add "-s" + * after a vowel (paciente → pacientes, nota → notas) and "-es" after a + * consonant (orden → órdenes), so both sides are compared as-is, minus "s" + * and minus "es" instead of guessing one singular form. + */ +function forms(word: string): string[] { + const result = [word]; + if (word.length > 4 && word.endsWith('s')) result.push(word.slice(0, -1)); + if (word.length > 5 && word.endsWith('es')) result.push(word.slice(0, -2)); + return result; +} + +function overlap(sourceText: string, targetText: string): number { + const source = new Set(words(sourceText).flatMap(forms)); + return words(targetText).filter((word) => forms(word).some((form) => source.has(form))).length; +} + +/** + * Best-guess destination entity for a source table from its words ("Órdenes" + * → OrdenesEstudio, "pacientes.csv" → Paciente), falling back to the + * connection's name when the table's own name says nothing ("Regiones 1" + * inside "pacientes_escaneados.pdf"). Only a default; the user confirms it. + */ +export function suggestTarget(tableName: string, targets: TargetMeta[], connectionName = ''): TargetMeta | null { + for (const name of [tableName, connectionName]) { + let best: { target: TargetMeta; score: number } | null = null; + for (const target of targets) { + const score = overlap(name, target.table); + if (score > (best?.score ?? 0)) best = { target, score }; + } + if (best) return best.target; + } + return null; +} diff --git a/src/app/connect/state/connect-workspace.store.spec.ts b/src/app/connect/state/connect-workspace.store.spec.ts new file mode 100644 index 0000000..ad8d21b --- /dev/null +++ b/src/app/connect/state/connect-workspace.store.spec.ts @@ -0,0 +1,122 @@ +import { TestBed } from '@angular/core/testing'; +import { Observable, firstValueFrom, of } from 'rxjs'; +import { BatchResult, ConflictStrategy, ImportSourcePayload, TargetMeta } from '../api/api.types'; +import { ImportsApi } from '../api/imports.api'; +import { SourceGateway } from '../api/source-gateway'; +import { TargetsApi } from '../api/targets.api'; +import { FakeConnection, FakeTable, NOTA, PACIENTE } from '../testing/fakes'; +import { ConnectWorkspaceStore } from './connect-workspace.store'; + +class FakeImportsApi { + committed: { sources: ImportSourcePayload[]; onConflict: ConflictStrategy } | null = null; + validate = () => of({ total_rows: 2, valid_count: 2, error_count: 0, errors: [] }); + commit(sources: ImportSourcePayload[], onConflict: ConflictStrategy): Observable { + this.committed = { sources, onConflict }; + return of({ + ok: true, + results: sources.map((s) => ({ target: s.target, label: s.label ?? null, total: 2, created: 2, updated: 0, rejected: 0, errors: [] })), + }); + } +} + +describe('ConnectWorkspaceStore', () => { + let store: ConnectWorkspaceStore; + let imports: FakeImportsApi; + const tama: TargetMeta = { ...PACIENTE, key: 'tea.Pacientes', domain: 'tea', table: 'Pacientes', conflict_fields: null }; + + beforeEach(() => { + imports = new FakeImportsApi(); + TestBed.configureTestingModule({ + providers: [ + ConnectWorkspaceStore, + { provide: TargetsApi, useValue: { list: () => of([PACIENTE, NOTA, tama]) } }, + { provide: ImportsApi, useValue: imports }, + { provide: SourceGateway, useValue: {} }, + ], + }); + store = TestBed.inject(ConnectWorkspaceStore); + }); + + function flowFrom(label: string, target: TargetMeta) { + const connection = new FakeConnection(label); + store.addConnection(connection); + const flow = store.createFlow(new FakeTable(connection), target); + flow.map('Clave', 'pac_id_hospital'); + return { connection, flow }; + } + + it('filters targets by the domain, and locks the domain once a flow exists', () => { + expect(store.targets().map((t) => t.key)).toEqual(['cacu.Paciente', 'cacu.NotaMedica']); + flowFrom('a.csv', PACIENTE); + store.setDomain('tea'); + expect(store.domain()).toBe('cacu'); + }); + + it('removing a connection removes the flows built on its tables', () => { + const { connection } = flowFrom('a.csv', PACIENTE); + flowFrom('b.csv', PACIENTE); + store.removeConnection(connection); + expect(store.flows().map((f) => f.label)).toEqual(['b.csv']); + expect(store.selectedFlow()?.label).toBe('b.csv'); + }); + + it('counts how many flows feed each destination table', () => { + flowFrom('a.csv', PACIENTE); + flowFrom('b.csv', PACIENTE); + expect(store.flowsByTarget().get('cacu.Paciente')).toBe(2); + }); + + it('commits every submittable flow in ONE request and hands each flow its result', async () => { + const { flow: first } = flowFrom('a.csv', PACIENTE); + const { flow: second } = flowFrom('b.csv', PACIENTE); + const incomplete = store.createFlow(new FakeTable(new FakeConnection('c.csv')), PACIENTE); + + await firstValueFrom(store.commit()); + + expect(imports.committed?.sources.map((s) => s.label)).toEqual(['a.csv', 'b.csv']); + expect(incomplete.status()).toBe('incomplete'); + expect(first.status()).toBe('loaded'); + expect(second.result()?.created).toBe(2); + + // Loaded flows are not re-sent (keyless tables would get duplicates)… + expect(store.submittableFlows()).toEqual([]); + // …until they're edited. + first.setDefault('pac_parentesco', 'Afiliado'); + expect(store.submittableFlows()).toEqual([first]); + }); + + it('only sends upsert when every target has a natural key', async () => { + flowFrom('a.csv', PACIENTE); + store.setOnConflict('upsert'); + await firstValueFrom(store.commit()); + expect(imports.committed?.onConflict).toBe('upsert'); + + const { flow: again } = flowFrom('a2.csv', PACIENTE); + expect(store.submittableFlows()).toEqual([again]); + const nota = store.createFlow(new FakeTable(new FakeConnection('n.csv')), NOTA); + nota.map('Clave', 'pac_id_hospital'); + nota.map('Sexo', 'nm_id_hospital'); + expect(store.upsertAvailable()).toBe(false); + await firstValueFrom(store.commit()); + expect(imports.committed?.onConflict).toBe('reject'); + }); + + it('with mergeDuplicates on, a flow missing a required field joins the batch when a sibling shares its key', async () => { + const { flow: complete } = flowFrom('padron.csv', PACIENTE); + const incomplete = store.createFlow(new FakeTable(new FakeConnection('ficha.pdf')), PACIENTE); + + // Off by default: the incomplete one stays out, same as before this feature. + expect(store.submittableFlows()).toEqual([complete]); + + store.setMergeDuplicates(true); + expect(store.submittableFlows()).toEqual([complete, incomplete]); + + await firstValueFrom(store.commit()); + expect(imports.committed?.sources.map((s) => s.label)).toEqual(['padron.csv', 'ficha.pdf']); + + // Both flows are now 'loaded'; a fresh incomplete flow with no live sibling on + // the same keyed target still never submits, even with merging on. + store.createFlow(new FakeTable(new FakeConnection('solo.pdf')), PACIENTE); + expect(store.submittableFlows()).toEqual([]); + }); +}); diff --git a/src/app/connect/state/connect-workspace.store.ts b/src/app/connect/state/connect-workspace.store.ts new file mode 100644 index 0000000..f683deb --- /dev/null +++ b/src/app/connect/state/connect-workspace.store.ts @@ -0,0 +1,235 @@ +import { Injectable, computed, inject, signal } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { Observable, catchError, from, of, switchMap, tap } from 'rxjs'; +import { BatchResult, ConflictStrategy, ConnectorInfo, Domain, TargetMeta, apiErrorMessage } from '../api/api.types'; +import { ConnectorsApi } from '../api/connectors.api'; +import { ImportsApi } from '../api/imports.api'; +import { SourceGateway } from '../api/source-gateway'; +import { TargetsApi } from '../api/targets.api'; +import { acceptedExtensions, connectionsForFiles } from '../domain/connection-registry'; +import { DataConnection, SourceTable } from '../domain/data-source'; +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: 'tea', label: 'TEA', description: 'Trastorno del espectro autista' }, +]; + +/** + * State of one "Conectar datos" workspace: connections, the import flows + * composed from their tables, the selected flow, the destination domain + * and the batch options. + * + * Network work is delegated to the domain objects (`connection.load`, + * `flow.load`, `flow.validate`) and, for the batch, to `ImportsApi.commit`. + * Provided per page, so leaving it discards the session. + */ +@Injectable() +export class ConnectWorkspaceStore { + private readonly gateway = inject(SourceGateway); + private readonly importsApi = inject(ImportsApi); + + private readonly targetsError = signal(null); + readonly allTargets = toSignal( + inject(TargetsApi) + .list() + .pipe( + catchError((error) => { + this.targetsError.set(apiErrorMessage(error, 'No se pudo cargar el esquema de la base de datos.')); + return of([] as TargetMeta[]); + }), + ), + { initialValue: [] as TargetMeta[] }, + ); + readonly catalogError = this.targetsError.asReadonly(); + + /** What the server can read; drives the gallery and which dropped files are accepted. */ + readonly connectors = toSignal(inject(ConnectorsApi).list().pipe(catchError(() => of([] as ConnectorInfo[]))), { + initialValue: [] as ConnectorInfo[], + }); + readonly acceptedExtensions = computed(() => acceptedExtensions(this.connectors())); + + private readonly _domain = signal('cacu'); + private readonly _connections = signal([]); + private readonly _flows = signal([]); + private readonly _selectedFlowId = signal(null); + private readonly _onConflict = signal('reject'); + private readonly _mergeDuplicates = signal(false); + private readonly _committing = signal(false); + private readonly _lastBatch = signal(null); + private readonly _commitError = signal(null); + + readonly domain = this._domain.asReadonly(); + readonly connections = this._connections.asReadonly(); + readonly flows = this._flows.asReadonly(); + readonly onConflict = this._onConflict.asReadonly(); + readonly mergeDuplicates = this._mergeDuplicates.asReadonly(); + readonly committing = this._committing.asReadonly(); + readonly lastBatch = this._lastBatch.asReadonly(); + readonly commitError = this._commitError.asReadonly(); + + readonly targets = computed(() => this.allTargets().filter((target) => target.domain === this._domain())); + readonly selectedFlow = computed(() => this._flows().find((flow) => flow.id === this._selectedFlowId()) ?? null); + + /** A batch writes to one domain's database, so the domain can only change while there are no flows. */ + readonly domainLocked = computed(() => this._flows().length > 0); + + /** + * Flows with a known target and a natural key, not still loading/erroring + * and not already written — candidates to combine by `mergeDuplicates`, + * complete or not (a source missing a required field may still supply + * others a sibling source lacks). + */ + private readonly mergeCandidateFlows = computed(() => + this._flows().filter((flow) => !!flow.target.conflict_fields && !['loading', 'error', 'loaded'].includes(flow.status())), + ); + + /** Merging only makes sense when several flows feed the same keyed entity. */ + readonly mergeAvailable = computed(() => { + const keyed = this.mergeCandidateFlows(); + return new Set(keyed.map((flow) => flow.target.key)).size < keyed.length; + }); + + private readonly mergeableTargetKeys = computed(() => { + const counts = new Map(); + for (const flow of this.mergeCandidateFlows()) counts.set(flow.target.key, (counts.get(flow.target.key) ?? 0) + 1); + return new Set([...counts].filter(([, count]) => count > 1).map(([key]) => key)); + }); + + /** + * Flows the next batch will write. Normally just the complete ones; with + * `mergeDuplicates` on, a flow missing a required field joins them too + * when another flow targets the same keyed entity — the gap may be + * exactly what that other source supplies, so the batch combines them + * before validating instead of dropping the incomplete one silently. + */ + readonly submittableFlows = computed(() => { + const complete = this._flows().filter((flow) => flow.pendingLoad); + if (!this._mergeDuplicates()) return complete; + const mergeableKeys = this.mergeableTargetKeys(); + const extra = this.mergeCandidateFlows().filter((flow) => !complete.includes(flow) && mergeableKeys.has(flow.target.key)); + return [...complete, ...extra]; + }); + + readonly upsertAvailable = computed(() => { + const flows = this.submittableFlows(); + return flows.length > 0 && flows.every((flow) => !!flow.target.conflict_fields); + }); + + readonly summary = computed(() => { + const flows = this._flows(); + const rows = flows.reduce((total, flow) => total + (flow.totalRows() ?? 0), 0); + const errors = flows.reduce((total, flow) => total + (flow.validation()?.error_count ?? 0), 0); + return { + connections: this._connections().length, + flows: flows.length, + ready: this.submittableFlows().length, + incomplete: flows.filter((flow) => flow.status() === 'incomplete').length, + rows, + errors, + }; + }); + + /** How many flows feed each destination entity. */ + readonly flowsByTarget = computed(() => { + const counts = new Map(); + for (const flow of this._flows()) counts.set(flow.target.key, (counts.get(flow.target.key) ?? 0) + 1); + return counts; + }); + + setDomain(domain: Domain): void { + if (!this.domainLocked()) this._domain.set(domain); + } + + setOnConflict(strategy: ConflictStrategy): void { + this._onConflict.set(strategy); + } + + setMergeDuplicates(merge: boolean): void { + this._mergeDuplicates.set(merge); + } + + /** Adds dropped files as connections; returns the ones no connector reads. */ + addFiles(files: File[]): File[] { + const { connections, rejected } = connectionsForFiles(files, this.connectors()); + connections.forEach((connection) => this.addConnection(connection)); + return rejected; + } + + addConnection(connection: DataConnection): void { + this._connections.update((connections) => [...connections, connection]); + connection.load(this.gateway).subscribe(); + } + + reloadConnection(connection: DataConnection): void { + connection.load(this.gateway).subscribe(); + } + + removeConnection(connection: DataConnection): void { + this._flows().filter((flow) => flow.table.connection === connection).forEach((flow) => this.removeFlow(flow)); + this._connections.update((connections) => connections.filter((existing) => existing !== connection)); + } + + removeTable(table: SourceTable): void { + this._flows().filter((flow) => flow.table === table).forEach((flow) => this.removeFlow(flow)); + table.connection.removeTable(table); + } + + createFlow(table: SourceTable, target: TargetMeta): ImportFlow { + const flow = new ImportFlow(table, target); + this._flows.update((flows) => [...flows, flow]); + this._selectedFlowId.set(flow.id); + this._lastBatch.set(null); + flow.load(this.gateway).subscribe(); + return flow; + } + + reloadFlow(flow: ImportFlow): void { + flow.load(this.gateway).subscribe(); + } + + removeFlow(flow: ImportFlow): void { + const remaining = this._flows().filter((existing) => existing !== flow); + this._flows.set(remaining); + if (this._selectedFlowId() === flow.id) this._selectedFlowId.set(remaining.at(-1)?.id ?? null); + } + + select(flow: ImportFlow | null): void { + this._selectedFlowId.set(flow?.id ?? null); + } + + flowsOf(table: SourceTable): ImportFlow[] { + return this._flows().filter((flow) => flow.table === table); + } + + validate(flow: ImportFlow): Promise { + return flow.validate(this.importsApi); + } + + validateAll(): Promise { + return Promise.all(this.submittableFlows().map((flow) => flow.validate(this.importsApi))).then(() => undefined); + } + + /** Loads every submittable flow in one request, written in one transaction. */ + commit(): Observable { + const flows = this.submittableFlows(); + if (flows.length === 0) return of(null); + const strategy = this.upsertAvailable() ? this._onConflict() : 'reject'; + this._committing.set(true); + this._commitError.set(null); + return from(Promise.all(flows.map((flow) => flow.toPayload()))).pipe( + switchMap((payloads) => this.importsApi.commit(payloads, strategy, this._mergeDuplicates())), + tap((batch) => { + batch.results.forEach((result, index) => flows[index].recordResult(result)); + this._lastBatch.set(batch); + this._committing.set(false); + }), + catchError((error) => { + this._commitError.set(apiErrorMessage(error, 'No se pudo cargar la información.')); + this._committing.set(false); + return of(null); + }), + ); + } +} diff --git a/src/app/connect/testing/fakes.ts b/src/app/connect/testing/fakes.ts new file mode 100644 index 0000000..1b56a0d --- /dev/null +++ b/src/app/connect/testing/fakes.ts @@ -0,0 +1,84 @@ +import { Observable, of } from 'rxjs'; +import { PreviewResponse, SourceLocator, TargetMeta } from '../api/api.types'; +import { SourceGateway } from '../api/source-gateway'; +import { DataConnection, SourceTable } from '../domain/data-source'; + +/** Test doubles for the domain layer, with no HTTP or Angular DI. */ +export const PACIENTE: TargetMeta = { + key: 'cacu.Paciente', + domain: 'cacu', + table: 'Paciente', + conflict_fields: ['pac_id_hospital'], + fields: [ + { name: 'pac_id_hospital', required: true, type: 'string' }, + { name: 'pac_sexo', required: false, type: 'string' }, + { name: 'pac_parentesco', required: false, type: 'string' }, + ], +}; + +export const NOTA: TargetMeta = { + key: 'cacu.NotaMedica', + domain: 'cacu', + table: 'NotaMedica', + conflict_fields: null, + fields: [ + { name: 'pac_id_hospital', required: true, type: 'string' }, + { name: 'nm_id_hospital', required: true, type: 'string' }, + ], +}; + +export function preview(overrides: Partial = {}): PreviewResponse { + return { + columns: [ + { name: 'Clave', inferred_type: 'string' }, + { name: 'Sexo', inferred_type: 'string' }, + ], + sample_rows: [ + { Clave: 'H-1', Sexo: 'F' }, + { Clave: 'H-2', Sexo: 'X' }, + ], + total_rows: 2, + suggested_mapping: [ + { source_column: 'Clave', target_field: null, confidence: 0, reason: 'none' }, + { source_column: 'Sexo', target_field: 'pac_sexo', confidence: 0.8, reason: 'synonym' }, + ], + ...overrides, + }; +} + +export class FakeConnection extends DataConnection { + readonly icon = 'table_view'; + readonly typeLabel = 'Fake'; + constructor( + label = 'fake.csv', + private readonly discovered: () => SourceTable[] = () => [], + ) { + super(label); + } + override get singleTable(): boolean { + return true; + } + protected discover(): Observable { + return of(this.discovered()); + } +} + +export class FakeTable extends SourceTable { + readonly icon = 'table_view'; + readonly kindLabel = 'Fake'; + constructor( + connection: DataConnection, + name = 'fake', + private readonly response: () => Observable = () => of(preview()), + ) { + super(connection, name); + } + preview(): Observable { + return this.response(); + } + async locator(): Promise { + return { source_type: 'csv', payload: { file_base64: 'QQ==' } }; + } +} + +export const NO_GATEWAY = {} as SourceGateway; diff --git a/src/app/features/indicadores/indicador-catalog-card.spec.ts b/src/app/features/indicadores/indicador-catalog-card.spec.ts new file mode 100644 index 0000000..1427933 --- /dev/null +++ b/src/app/features/indicadores/indicador-catalog-card.spec.ts @@ -0,0 +1,123 @@ +import { Component } from '@angular/core'; +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'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { IndicadoresMemory, GlobalApplied } from './indicadores-memory'; +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) +class ChartStub {} +describe('UX-06E.D.2.1 selector de representación', () => { + let fixture: ReturnType>; + let http: HttpTestingController; + const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 1 }; + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + http = TestBed.inject(HttpTestingController); create(['f', 'g']); + }); + afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); + function create(figuras: string[], domain = 'cacu') { + fixture = TestBed.createComponent(IndicadorCatalogCard); + fixture.componentRef.setInput('dominio', domain); + 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(); } + it.each(['C1', 'C2', 'C3r'])('UX-07A omite IDs y contrato %s y conserva título y contador', contrato => { + fixture.componentRef.setInput('indicador', { id: 'K05_eeg_20_minutos', titulo: 'EEG con ≥ 20 min de registro', contrato, + figuras: ['fig_c1_grupos', 'fig_c1_puntos'], tipos_periodo: ['semestre'] }); + fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('h2').textContent).toBe('EEG con ≥ 20 min de registro'); + expect(fixture.nativeElement.querySelector('.indicator-id')).toBeNull(); + expect(fixture.nativeElement.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas'); + // The internal panel heading is deliberately visually hidden and retains identity. + const copy = fixture.nativeElement.cloneNode(true) as HTMLElement; + copy.querySelectorAll('.visually-hidden').forEach(node => node.remove()); + expect(copy.textContent).not.toMatch(/K05_eeg_20_minutos|Contrato|fig_c1_/); + expect(fixture.componentInstance.indicador.id).toBe('K05_eeg_20_minutos'); + 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', () => { + fixture.destroy(); create(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c2_barras', 'fig_c2_donas', 'fig_c9_futura']); + 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 [ + ['fig_c2_apiladas', 'Barras apiladas'], + ['fig_c2_barras', 'Barras'], + ['fig_c2_donas', 'Donas'], + ['fig_c9_futura', 'Representación 5'], + ]) { + select().selectionChange.emit({ source: select(), value: 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'); + expect(pending.request.params.get('periodos')).toBe('2025-S1'); + pending.flush({ data: [], layout: {} }); fixture.detectChanges(); + expect(fixture.componentInstance.selectedFigure).toBe(id); + expect(TestBed.inject(IndicadoresMemory).figure('cacu', 'i')).toBe(id); + expect(fixture.nativeElement.querySelector('.figure-id').textContent).toBe(`Figura: ${label}`); + } + 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('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(); + 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); + request('f').flush({ data: [{ y: [7] }], layout: {} }); fixture.detectChanges(); + expect(panels()[0].componentInstance.result().figure.data[0].y).toEqual([7]); http.expectNone(() => true); + }); + it('restaura memoria por dominio e indicador sólo si sigue publicada y conserva carga diferida', () => { + open(); request('f').flush({ data: [], layout: {} }); fixture.componentInstance.selectFigure('g'); fixture.detectChanges(); + request('g').flush({ data: [], layout: {} }); fixture.destroy(); create(['f', 'g']); + expect(fixture.componentInstance.selectedFigure).toBe('g'); expect(fixture.componentInstance.visible).toBe(false); http.expectNone(() => true); + fixture.componentInstance.setVisible(true); fixture.detectChanges(); request('g').flush({ data: [], layout: {} }); + fixture.destroy(); create(['f', 'g'], 'cama'); expect(fixture.componentInstance.selectedFigure).toBe('f'); + fixture.destroy(); create(['f']); expect(fixture.componentInstance.selectedFigure).toBe('f'); + }); + it('cambio de aplicado conserva elección y consulta sólo su representación; fuera de vista cancela revisión obsoleta', () => { + open(); request('f').flush({ data: [], layout: {} }); fixture.componentInstance.selectFigure('g'); fixture.detectChanges(); request('g').flush({ data: [], layout: {} }); + fixture.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2025-S2'] } }); fixture.detectChanges(); + const current = request('g'); expect(current.request.params.get('periodos')).toBe('2025-S2'); http.expectNone(r => r.url.endsWith('/figuras/f')); + fixture.componentInstance.setVisible(false); fixture.detectChanges(); + fixture.componentRef.setInput('applied', { ...applied, revision: 3 }); fixture.detectChanges(); expect(current.cancelled).toBe(true); + expect(panels()).toHaveLength(0); http.expectNone(() => true); + }); + it('opciones ajenas al catálogo y selección repetida no consultan', () => { + open(); request('f').flush({ data: [], layout: {} }); fixture.componentInstance.selectFigure('bad'); fixture.componentInstance.selectFigure('f'); fixture.detectChanges(); + expect(fixture.componentInstance.selectedFigure).toBe('f'); http.expectNone(() => true); + }); +}); + +it('C2 sin magnitudes elimina la copia HTML de la nota y no cambia trazas Plotly', () => { + TestBed.configureTestingModule({ imports: [IndicadorFigureCard] }); + TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + const fixture = TestBed.createComponent(IndicadorFigureCard); + const figure = { data: [{ type: 'pie', values: [null, null] }], layout: { annotations: [{ text: 'Valores ocultos por supresión.' }] } }; + fixture.componentRef.setInput('state', { status: 'ready', figure, presentationFigure: structuredClone(figure) }); + fixture.componentRef.setInput('selected', { id: 'i', titulo: 'I', contrato: 'C2', figuras: ['fig_c2_donas'], tipos_periodo: ['semestre'] }); + fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('figuraId', 'fig_c2_donas'); fixture.componentRef.setInput('tema', 'claro'); fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('[aria-label="Advertencias y notas del servicio"]')).toBeNull(); + expect(fixture.nativeElement.textContent).toContain('No hay valores visibles'); expect(fixture.nativeElement.textContent).toContain('Los sectores'); + expect(figure.data[0].values).toEqual([null, null]); fixture.destroy(); +}); diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts new file mode 100644 index 0000000..f35a152 --- /dev/null +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -0,0 +1,108 @@ +import { ChangeDetectorRef, Component, ElementRef, inject, Input, OnChanges, output, ViewChild } from '@angular/core'; +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, Tema } from './indicadores.models'; +import { GlobalApplied, IndicadoresMemory } from './indicadores-memory'; +import { indicatorIdentity, figureIdentity, identityElementId } from './indicadores-identities'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; +import { figureDisplayName } from './indicadores-figure-labels'; +import { READABLE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visual-profile'; + +@Component({ + selector: 'app-indicador-catalog-card', + imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel], + template: ` + +
+
+

{{ indicador.titulo }}

+
+
+ +
+ + @if (selectedFigure) { + + Representación gráfica + + @for (figure of indicador.figuras; track figure) { {{ figureDisplayName(figure, indicador.figuras) }} } + + +
+ @for (figure of [selectedFigure]; track panelIdentity(figure)) { + + } +
+ } @else {

El indicador no tiene figuras disponibles.

} +
+
+ `, + styles: ` + :host { display: block; min-width: 0; margin: var(--issste-space-4) 0; } + mat-card { 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; } + header { display: grid; grid-template-columns: minmax(0, 1fr); align-items: start; gap: var(--issste-space-3); } + .graphic-region { min-height: 620px; } + .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; } + .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; } + button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } + mat-form-field { width: 100%; margin-top: var(--issste-space-4); } + .catalog-metadata { margin: var(--issste-space-4) 0 0; padding-top: var(--issste-space-4); + border-top: 1px solid var(--issste-border); color: var(--issste-text-secondary); font: var(--mat-sys-body-small); } + @media (max-width: 550px) { h2 { font-size: 1.25rem; } header { gap: var(--issste-space-2); } } + `, +}) +export class IndicadorCatalogCard implements OnChanges { + readonly figureDisplayName = figureDisplayName; + @Input({ required: true }) dominio!: Dominio; + @Input({ required: true }) indicador!: Indicador; + @Input({ required: true }) tema!: Tema; + @Input({ required: true }) applied!: GlobalApplied; + @Input() pinned = false; + @Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE; + readonly pinChanged = output(); + @ViewChild('visibilityRegion') visibilityRegion?: ElementRef; + readonly host = inject>(ElementRef); + private readonly changeDetector = inject(ChangeDetectorRef); + private readonly memory = inject(IndicadoresMemory); + private identity = ''; + visible = false; + titleId = ''; + contentId = ''; + panelIdentity(figure: string) { return figureIdentity(this.dominio, this.indicador.id, figure); } + selectedFigure?: string; + selectFigure(figure: string) { + if (!this.indicador.figuras.includes(figure) || figure === this.selectedFigure) return; + this.selectedFigure = figure; + this.memory.rememberFigure(this.dominio, this.indicador.id, figure); + this.changeDetector.markForCheck(); + } + ngOnChanges() { + const remembered = this.memory.figure(this.dominio, this.indicador.id); + this.selectedFigure = remembered && this.indicador.figuras.includes(remembered) ? remembered : this.indicador.figuras[0]; + const identity = indicatorIdentity(this.dominio, this.indicador.id); + if (identity === this.identity) return; + this.identity = identity; + const id = identityElementId(identity); + this.titleId = id + '-title'; + this.contentId = id + '-content'; + this.visible = false; + } + setVisible(visible: boolean) { + if (this.visible === visible) return; + this.visible = visible; + this.changeDetector.markForCheck(); + } +} diff --git a/src/app/features/indicadores/indicador-figure-card.html b/src/app/features/indicadores/indicador-figure-card.html new file mode 100644 index 0000000..7378b91 --- /dev/null +++ b/src/app/features/indicadores/indicador-figure-card.html @@ -0,0 +1,58 @@ +@if (selected) { +
+ +
+
    + @for (line of interpretation; track $index) {
  • {{ line }}
  • } +
+

Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.

+
+
+} + + @if (state.status === 'loading') { + +

Cargando figura…

+ } @else if (state.status === 'deferred') { +

{{ state.message }}

+ } @else if (state.status === 'incompatible') { +

Filtro general incompatible con esta figura.

{{ state.message }}

+ } @else if (state.status === 'error') { + + } @else if (state.figure; as figure) { + @if (hasNoVisibleValues(figure)) { +

No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.

+ } +

+

Figura: {{ figureDisplayName(figuraId, selected?.figuras ?? []) }}

+ } @else { +

{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}

+ } + @if (chartFigure) { +
+ + @if (state.footnotes?.length) { +
+ @for (note of state.footnotes; track $index) {

{{ note }}

} +
+ } + @if (state.categoryLabels?.length) { +
+ Nombres completos de las categorías +
    + @for (label of state.categoryLabels; track $index) { +
  • {{ label.abbreviated }}: {{ label.original }}
  • + } +
+
+ } +
+ } +
diff --git a/src/app/features/indicadores/indicador-figure-card.scss b/src/app/features/indicadores/indicador-figure-card.scss new file mode 100644 index 0000000..c62cf22 --- /dev/null +++ b/src/app/features/indicadores/indicador-figure-card.scss @@ -0,0 +1,52 @@ +:host { display: block; min-width: 0; } +.interpretation { + margin-bottom: var(--issste-space-4); + color: var(--issste-text); + font-family: var(--issste-font-body); + line-height: 1.5; + overflow-wrap: anywhere; +} +.methodology-detail { + margin-top: var(--issste-space-3); + padding: var(--issste-space-4); + border-left: 3px solid var(--issste-accent); +} +.interpretation ul { margin: 0; padding-left: 1.25rem; } +.interpretation li + li { margin-top: .25rem; } +.period-note { margin: .75rem 0 0; color: var(--issste-text-secondary); } +.methodology-toggle { margin-top: var(--issste-space-3); min-height: 44px; max-width: 100%; height: auto; white-space: normal; } +.methodology-detail p { margin: 0; } +.methodology-detail p + p { margin-top: var(--issste-space-2); } +.methodology-toggle:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } +.figure-card { overflow: visible; min-width: 0; border: 1px solid var(--issste-border); } +.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; } +.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); } } + +.notes { padding: 1rem; overflow-wrap: anywhere; } +.notes h2 { font-size: 1rem; } +.notes p { line-height: 1.5; } +.methodological-footnotes { + padding: .75rem 1rem 1rem; + min-width: 0; + max-width: 100%; + box-sizing: border-box; + font: var(--mat-sys-body-small); + font-family: var(--issste-font-body); + font-size: .875rem; + color: var(--issste-text-secondary); + line-height: 1.5; +} +.dark .methodological-footnotes { color: var(--mat-sys-outline); } +.methodological-footnotes p { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; } +.methodological-footnotes p + p { margin-top: .75rem; } +.category-labels { padding: 0 1rem 1rem; overflow-wrap: anywhere; font: var(--mat-sys-body-small); line-height: 1.5; } +.category-labels summary { cursor: pointer; min-height: 44px; align-content: center; } +.category-labels summary:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; } +.category-labels ul { margin: .25rem 0 0; padding-left: 1.25rem; } +.category-labels li + li { margin-top: .5rem; } + +.figure-skeleton { min-height: 620px; display: flex; flex-direction: column; } +.skeleton { flex: 1; margin: 0 1.25rem 1.25rem; border-radius: var(--issste-radius); background: var(--issste-border); opacity: .35; } diff --git a/src/app/features/indicadores/indicador-figure-card.spec.ts b/src/app/features/indicadores/indicador-figure-card.spec.ts new file mode 100644 index 0000000..8df5a30 --- /dev/null +++ b/src/app/features/indicadores/indicador-figure-card.spec.ts @@ -0,0 +1,373 @@ +import { TestBed } from '@angular/core/testing'; +import { By } from '@angular/platform-browser'; +import { vi } from 'vitest'; +import { FigureState, IndicadorFigureCard } from './indicador-figure-card'; +import { Indicador, PlotlyFigure } from './indicadores.models'; +import { presentationFigure } from './indicadores.presentation'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; + +describe('IndicadorFigureCard', () => { + const selected: Indicador = { id: 'i1', titulo: 'Indicador de prueba', contrato: 'C1', figuras: ['fig_c1_puntos'], tipos_periodo: ['semestre'] }; + let fixture: ReturnType>; + let react: ReturnType; + let purge: ReturnType; + let disconnect: ReturnType; + let observe: ReturnType; + beforeEach(() => { + react = vi.fn().mockResolvedValue(undefined); + purge = vi.fn(); + disconnect = vi.fn(); + observe = vi.fn(); + vi.stubGlobal('ResizeObserver', class { observe = observe; disconnect = disconnect; }); + TestBed.configureTestingModule({ + imports: [IndicadorFigureCard], + providers: [{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve({ + react, purge, Plots: { resize: vi.fn().mockResolvedValue(undefined) }, + addFrames: vi.fn().mockResolvedValue(undefined), deleteFrames: vi.fn().mockResolvedValue(undefined), + }) }], + }); + fixture = TestBed.createComponent(IndicadorFigureCard); + fixture.componentRef.setInput('selected', selected); + fixture.componentRef.setInput('figuraId', 'fig_c1_puntos'); + fixture.componentRef.setInput('dominio', 'tea'); + fixture.componentRef.setInput('tema', 'claro'); + fixture.componentRef.setInput('state', { status: 'idle' }); + }); + afterEach(() => { fixture.destroy(); vi.unstubAllGlobals(); }); + function state(value: FigureState) { fixture.componentRef.setInput('state', value); fixture.detectChanges(); } + async function settle() { + await fixture.whenStable(); + for (let i = 0; i < 12; i++) await Promise.resolve(); + fixture.detectChanges(); + } + function ready(original: PlotlyFigure) { + const copy = presentationFigure(original, { indicador: selected.id, figura: 'fig_c1_puntos', tema: 'claro' }); + state({ status: 'ready', figure: original, presentationFigure: copy }); + return copy; + } + it.each(['tea', 'cacu', 'cama'])('UX-07D.2 presenta notas %s como texto seguro inmediatamente después del gráfico', dominio => { + fixture.componentRef.setInput('dominio', dominio); + const original: PlotlyFigure = { data: [{ y: [0] }], layout: {} }; + const notes = ['Fuente: A & B\nSegunda línea', '', 'ID_'.repeat(150)]; + state({ status: 'ready', figure: original, presentationFigure: original, footnotes: notes, + minimumPlotWidth: 1200, categoryLabels: [{ axis: 'x', original: 'Categoría', abbreviated: 'Cat.' }] }); + const section = fixture.nativeElement.querySelector('.methodological-footnotes') as HTMLElement; + expect(section.getAttribute('aria-label')).toBe('Notas al pie de la figura'); + expect([...section.querySelectorAll('p')].map(p => p.textContent)).toEqual(notes); + expect(section.querySelector('img, script, a')).toBeNull(); + expect(section.previousElementSibling?.tagName).toBe('APP-PLOTLY-CHART'); + expect(section.closest('.plot-viewport, app-plotly-chart, details')).toBeNull(); + expect(section.nextElementSibling?.classList.contains('category-labels')).toBe(true); + for (const status of ['loading', 'deferred', 'error', 'incompatible', 'idle'] as const) { + state({ status }); + expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull(); + } + state({ status: 'ready', figure: original, presentationFigure: original, footnotes: ['Nota nueva'] }); + expect(fixture.nativeElement.querySelector('.methodological-footnotes').textContent).toBe('Nota nueva'); + }); + it('UX-07D conserva el ancho desplazable durante carga y lo revierte sin recrear el host', async () => { + const original: PlotlyFigure = { data: [{ type: 'bar', x: ['A', 'B', 'C'], y: [0, null, 20] }], layout: {} }; + state({ status: 'ready', figure: original, presentationFigure: original, minimumPlotWidth: 598 }); await settle(); + const chart = fixture.nativeElement.querySelector('app-plotly-chart') as HTMLElement; + const host = chart.querySelector('.plot'); + expect(chart.style.getPropertyValue('--plot-min-width')).toBe('598px'); + expect(chart.querySelector('.plot-viewport')!.getAttribute('tabindex')).toBe('0'); + state({ status: 'loading' }); await settle(); + expect(chart.style.getPropertyValue('--plot-min-width')).toBe('598px'); + state({ status: 'ready', figure: original, presentationFigure: original }); await settle(); + expect(chart.style.getPropertyValue('--plot-min-width')).toBe(''); + expect(chart.querySelector('.plot')).toBe(host); expect(original.data[0]['y']).toEqual([0, null, 20]); + }); + it('UX-07C ofrece nombres completos en un details nativo sin rerenderizar Plotly ni ocultar notas', async () => { + const original: PlotlyFigure = { data: [{ y: [0] }], layout: {} }; + const copy = presentationFigure(original, { indicador: 'i1', figura: 'fig_c1_puntos', tema: 'claro' }); + state({ status: 'ready', figure: original, presentationFigure: copy, + categoryLabels: [{ axis: 'x', abbreviated: 'Fármaco…', original: 'Fármaco de riesgo para el neurodesarrollo' }], + footnotes: ['Nota metodológica siempre visible'] }); await settle(); + const details = fixture.nativeElement.querySelector('details') as HTMLDetailsElement; + const summary = details.querySelector('summary')!; + expect(summary.textContent).toContain('Nombres completos'); expect(details.open).toBe(false); + expect(details.querySelector('li')!.textContent).toContain('Fármaco de riesgo para el neurodesarrollo'); + const plot = fixture.nativeElement.querySelector('.plot'), calls = react.mock.calls.length; + summary.focus(); summary.click(); fixture.detectChanges(); await settle(); + expect(details.open).toBe(true); expect(document.activeElement).toBe(summary); + expect(react).toHaveBeenCalledTimes(calls); expect(fixture.nativeElement.querySelector('.plot')).toBe(plot); + expect(fixture.nativeElement.querySelector('.methodological-footnotes').closest('details')).toBeNull(); + state({ status: 'loading' }); expect(fixture.nativeElement.querySelector('.category-labels')).toBeNull(); + expect(fixture.nativeElement.querySelector('.plot').closest('[hidden]')).not.toBeNull(); + }); + it('muestra carga, error y emite reintento sin coordinar HTTP', () => { + state({ status: 'loading' }); + expect(fixture.nativeElement.querySelector('mat-card').getAttribute('aria-busy')).toBe('true'); + expect(fixture.nativeElement.textContent).toContain('Cargando figura'); + const retry = vi.fn(); + fixture.componentInstance.retry.subscribe(retry); + state({ status: 'error', message: 'La figura o los reportes no están disponibles para esta selección.' }); + expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('reportes no están disponibles'); + fixture.nativeElement.querySelector('.state button').click(); + expect(retry).toHaveBeenCalledTimes(1); + expect(fixture.debugElement.query(By.directive(PlotlyChart))).toBeNull(); + }); + it('presenta selección incompleta y un indicador sin figuras', () => { + state({ status: 'idle' }); + expect(fixture.nativeElement.textContent).toContain('Completa una selección válida'); + fixture.componentRef.setInput('selected', { ...selected, figuras: [] }); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('El indicador no tiene figuras disponibles'); + }); + it('presenta título del JSON, nombre amigable y conserva datos incluso si Plotly los muta', async () => { + const original: PlotlyFigure = { + data: [{ type: 'scatter', y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], x: { dtype: 'i1', bdata: 'AAE=' } }], + layout: { title: { text: 'Título publicado', font: { size: 20 } }, annotations: [{ text: 'Nota de supresión' }] }, + config: { staticPlot: false }, frames: [], extra: { preserved: true }, + }; + const snapshot = JSON.stringify(original); + react.mockImplementation(async (_host, data, layout) => { + data[0].y[0] = 0; + layout.annotations[0].text = 'Cambio interno de Plotly'; + }); + const copy = ready(original); + await settle(); + expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Título publicado'); + expect(fixture.nativeElement.querySelector('.figure-id').textContent).toBe('Figura: Puntos'); + expect(fixture.nativeElement.textContent).not.toContain('fig_c1_puntos'); + expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.figure).toBe(copy); + expect(JSON.stringify(original)).toBe(snapshot); + expect(copy.data).toEqual(original.data); + expect(copy.layout['annotations']).toEqual(original.layout['annotations']); + }); + it('distingue resultado sin puntos del error y mantiene valores binarios indeterminados', async () => { + ready({ data: [{ y: [null] }], layout: {} }); + await settle(); + expect(fixture.nativeElement.textContent).toContain('No hay valores visibles'); + expect(fixture.debugElement.query(By.directive(PlotlyChart))).not.toBeNull(); + ready({ data: [{ y: { dtype: 'f8', bdata: 'AAAAAAAAAAA=' } }], layout: {} }); + await settle(); + expect(fixture.nativeElement.textContent).not.toContain('No hay valores visibles'); + }); + it('UX-07B representa pies como texto seguro, sin duplicación ni notas genéricas', async () => { + const figure = { data: [{ y: [42] }], layout: {} }; + const note = 'Primera línea\n\nAviso completo'; + state({ status: 'ready', figure, presentationFigure: figure, footnotes: [note] }); await settle(); + const notes = fixture.nativeElement.querySelector('.methodological-footnotes'); + expect(notes.textContent).toBe(note); expect(notes.querySelector('img')).toBeNull(); + expect(fixture.nativeElement.querySelectorAll('.methodological-footnotes p')).toHaveLength(1); + expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.showNotes).toBe(false); + state({ status: 'loading' }); + expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull(); + state({ status: 'ready', figure, presentationFigure: figure, footnotes: [] }); await settle(); + expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull(); + }); + it.each(['cacu', 'cama'])('conserva advertencias específicas de %s durante la carga', dominio => { + fixture.componentRef.setInput('dominio', dominio); + state({ status: 'loading' }); + expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('no entregan intervalos Wilson efectivos'); + expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('suprimidos no representan tasas observadas de 0 %'); + }); + it('conserva el error y reintento de renderizado dentro de PlotlyChart', async () => { + react.mockRejectedValueOnce(new Error('render')); + ready({ data: [{ y: [42] }], layout: {} }); + await settle(); + expect(fixture.nativeElement.textContent).toContain('No se pudo representar la figura'); + const retry = vi.fn(); + fixture.componentInstance.retry.subscribe(retry); + fixture.nativeElement.querySelector('app-plotly-chart button').click(); + await settle(); + expect(react).toHaveBeenCalledTimes(2); + expect(retry).not.toHaveBeenCalled(); + expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.status()).toBe('ready'); + }); + it('D.2 mantiene Plotly oculto entre resultados y purga al destruir la card', async () => { + ready({ data: [{ y: [42] }], layout: {} }); await settle(); + const firstHost = fixture.nativeElement.querySelector('.plot'); + expect(observe).toHaveBeenCalledWith(firstHost); + state({ status: 'loading' }); + expect(firstHost.closest('[hidden]')).toBeTruthy(); + expect(purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled(); + state({ status: 'incompatible', message: 'Granularidad no publicada' }); + expect(firstHost.closest('[hidden]')).toBeTruthy(); + expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('Granularidad no publicada'); + ready({ data: [{ y: [50] }], layout: {} }); await settle(); + expect(fixture.nativeElement.querySelector('.plot')).toBe(firstHost); + expect(firstHost.closest('[hidden]')).toBeNull(); + fixture.destroy(); + expect(purge).toHaveBeenCalledWith(firstHost); expect(purge).toHaveBeenCalledTimes(1); + expect(disconnect).toHaveBeenCalledTimes(1); + }); + it('UX-06E.P0.2 inicia cerrado y despliega toda la explicación con estado accesible', () => { + fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas'); + state({ status: 'idle' }); + const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement; + expect(section.textContent).toContain('Cómo leer'); + expect(section.querySelector('h2')).toBeNull(); + expect(section.classList.contains('expanded')).toBe(false); + expect(section.querySelector('.methodology-detail ul')).not.toBeNull(); + expect(section.querySelector('ul')?.closest('[hidden]')).not.toBeNull(); + expect(section.querySelectorAll('button')).toHaveLength(1); + expect(section.querySelectorAll('[hidden]')).toHaveLength(1); + const button = section.querySelector('button')!; + const detail = section.querySelector('[id]') as HTMLElement; + expect(button.getAttribute('aria-expanded')).toBe('false'); + expect(button.getAttribute('aria-controls')).toBe(detail.id); + expect(detail.hidden).toBe(true); + expect(button.tagName).toBe('BUTTON'); + expect(button.nextElementSibling?.classList.contains('methodology-detail')).toBe(true); + button.focus(); + expect(document.activeElement).toBe(button); + expect(detail.textContent).toContain('SIN_DATO'); + expect(detail.textContent).toContain('suprimidos no representan tasas'); + expect(detail.textContent).toContain('no permite determinar la disponibilidad'); + expect([...detail.querySelectorAll('li')].map(li => li.textContent)).toEqual(fixture.componentInstance.interpretation); + button.click(); fixture.detectChanges(); + expect(detail.hidden).toBe(false); expect(button.getAttribute('aria-expanded')).toBe('true'); + state({ status: 'loading' }); + expect(detail.hidden).toBe(false); + button.click(); fixture.detectChanges(); + expect(detail.hidden).toBe(true); + expect(section.querySelector('.methodology-detail[hidden]')).toBe(detail); + }); + it('UX-06E.P0.2 muestra el contenido de la figura seleccionada al cambiarla', () => { + fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas'); + state({ status: 'idle' }); + const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement; + button.click(); fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('.methodology-detail').textContent).toContain('composición porcentual'); + fixture.componentRef.setInput('figuraId', 'fig_c3r_cajas'); + fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('.methodology-detail').textContent).toContain('La caja representa Q1'); + expect(fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls')) + .toBe(fixture.nativeElement.querySelector('.methodology-detail').id); + }); + it.each([ + ['fig_c2_barras', 'Barras'], + ['fig_c2_donas', 'Donas'], + ])('UX-07D.1 identifica %s con el nombre %s en la tarjeta de figura', (id, label) => { + fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', figuras: [id] }); + fixture.componentRef.setInput('figuraId', id); + ready({ data: [], layout: {} }); + expect(fixture.nativeElement.querySelector('.figure-id').textContent).toBe(`Figura: ${label}`); + }); + it.each(['fig_c3r_cajas', 'desconocida'])('UX-06E.P0.2 mantiene íntegra la interpretación %s dentro de la ayuda', figura => { + fixture.componentRef.setInput('figuraId', figura); + if (figura === 'desconocida') fixture.componentRef.setInput('selected', { ...selected, contrato: 'desconocido' }); + state({ status: 'idle' }); + expect(fixture.nativeElement.querySelector('.methodology-toggle')).not.toBeNull(); + expect([...fixture.nativeElement.querySelectorAll('.methodology-detail li')].map((li: any) => li.textContent)) + .toEqual(fixture.componentInstance.interpretation); + }); + it.each(['cacu', 'cama'])('UX-06E.P0.2 conserva advertencias C2 de %s en ayuda cerrada', dominio => { + fixture.componentRef.setInput('dominio', dominio); + fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas'); + state({ status: 'loading' }); + expect(fixture.nativeElement.querySelector('.methodology-toggle')).not.toBeNull(); + const detail = fixture.nativeElement.querySelector('[hidden]') as HTMLElement; + expect(detail.hidden).toBe(true); + expect(detail.textContent).toContain('Las barras muestran la composición porcentual de las categorías publicadas para cada periodo.'); + expect(detail.textContent).toContain('SIN_DATO'); + expect(detail.textContent).toContain('nulos o suprimidos no representan porcentajes observados de 0 %'); + }); + it('UX-06E.P0.2 quita el panel redundante y preserva todas las anotaciones en Plotly', async () => { + const figure: PlotlyFigure = { data: [{ y: [null, 0] }], layout: { annotations: [ + { text: 'Denominador pequeño
Intervalos no disponibles' }, + { text: 'Uso exclusivo de investigación. No usar para decisiones clínicas.' }, + { text: 'Supresión: consulta las notas completas' }, + ] }, frames: [] }; + const snapshot = JSON.stringify(figure); + ready(figure); await settle(); + expect(fixture.nativeElement.querySelector('.notes')).toBeNull(); + const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart; + expect(chart.figure.layout['annotations']).toEqual(figure.layout['annotations']); + expect(chart.notes).toEqual((figure.layout['annotations'] as { text: string }[]).map(a => a.text)); + expect(JSON.stringify(figure)).toBe(snapshot); + expect(fixture.nativeElement.querySelector('.plot-viewport')?.getAttribute('tabindex')).toBe('0'); + }); + it.each(['claro', 'oscuro'] as const)('UX-06E.P0.2 conserva el tema %s sin duplicar anotaciones en HTML', async tema => { + fixture.componentRef.setInput('tema', tema); + const annotation = 'Advertencia metodológica única de la figura.'; + const original: PlotlyFigure = { data: [{ y: [1] }], layout: { annotations: [{ text: annotation }] } }; + ready(original); await settle(); + const card = fixture.nativeElement.querySelector('.figure-card'); + expect(card.classList.contains('dark')).toBe(tema === 'oscuro'); + expect(fixture.nativeElement.querySelector('.notes')).toBeNull(); + expect(fixture.nativeElement.textContent).not.toContain(annotation); + const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart; + expect(chart.notes).toEqual([annotation]); + expect(JSON.stringify(original)).toContain(annotation); + }); + it('UX-06D mantiene relaciones de detalle únicas incluso con separadores en IDs publicados', () => { + fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', id: 'a--b' }); + fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas'); + state({ status: 'idle' }); + const first = fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls'); + fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', id: 'a' }); + fixture.componentRef.setInput('figuraId', 'b--fig_c2_apiladas'); + fixture.detectChanges(); + const second = fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls'); + expect(first).not.toBe(second); + expect(fixture.nativeElement.querySelector('[id]').id).toBe(second); + }); + it.each(['tea', 'cacu', 'cama'])('UX-06E.B1 conserva C1 de %s íntegro con condiciones críticas visibles', dominio => { + fixture.componentRef.setInput('dominio', dominio); + state({ status: 'idle' }); + const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement; + const button = section.querySelector('button')!; + const detail = section.querySelector('[hidden]') as HTMLElement; + expect(button.tagName).toBe('BUTTON'); expect(button.type).toBe('button'); + // jsdom does not perform native Enter/Space activation; leave both keys + // available to the browser and validate activation in Chrome. + for (const key of ['Enter', ' ']) { + const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); + button.dispatchEvent(event); expect(event.defaultPrevented).toBe(false); + } + expect(button.textContent).toContain('Cómo leer'); + expect(button.getAttribute('aria-label')).toBe('Cómo leer esta figura: Indicador de prueba · ' + dominio + ' · fig_c1_puntos'); + expect(button.getAttribute('aria-expanded')).toBe('false'); + expect(button.getAttribute('aria-controls')).toBe(detail.id); expect(detail.hidden).toBe(true); + const warnings = detail.querySelector('ul')!; + expect(warnings.closest('[hidden]')).not.toBeNull(); + expect(warnings.textContent).toContain('100 % no implica certeza poblacional'); + expect(warnings.textContent).toContain('suprimidos no representan tasas observadas de 0 %'); + if (dominio === 'tea') { + expect(warnings.textContent).toContain('Wilson al 95 %'); + expect(warnings.textContent).toContain('No se infieren intervalos cuando faltan'); + expect(warnings.textContent).toContain('denominadores pequeños'); + } else expect(warnings.textContent).toContain('no entregan intervalos Wilson efectivos'); + expect([...warnings.querySelectorAll('li')].map(p => p.textContent)) + .toEqual(fixture.componentInstance.interpretation); + button.focus(); button.click(); fixture.detectChanges(); + expect(document.activeElement).toBe(button); expect(detail.hidden).toBe(false); + expect(button.getAttribute('aria-expanded')).toBe('true'); + button.click(); fixture.detectChanges(); + expect(document.activeElement).toBe(button); expect(detail.hidden).toBe(true); + }); + it('UX-06E.P0.2 mantiene la oración mixta C3r y sus límites en ayuda cerrada', () => { + fixture.componentRef.setInput('figuraId', 'fig_c3r_cajas'); state({ status: 'idle' }); + const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement; + expect(section.querySelector('[hidden]')).not.toBeNull(); + expect(section.querySelector('button')).not.toBeNull(); + expect([...section.querySelectorAll('.methodology-detail li')].map(p => p.textContent)).toEqual([ + 'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.', + 'Los límites de dibujo no representan necesariamente extremos observados.', + 'Plotly puede mostrar las etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.', + 'Los puntos suprimidos no representan tasas observadas de 0 %.', + ]); + }); + it('UX-06E.P0.2 al alternar ayuda conserva Plotly, JSON y observadores sin react ni purge', async () => { + const original: PlotlyFigure = { data: [{ y: [42, null] }], layout: { annotations: [{ text: 'Advertencia íntegra del servicio' }] } }; + const copy = ready(original); await settle(); + const snapshot = JSON.stringify(original), copySnapshot = JSON.stringify(copy); + const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance; + const host = fixture.nativeElement.querySelector('.plot'); + const button = fixture.nativeElement.querySelector('.methodology-toggle'); + const calls = react.mock.calls.length, observers = observe.mock.calls.length; + for (let i = 0; i < 4; i++) { button.click(); fixture.detectChanges(); await settle(); } + expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance).toBe(chart); + expect(fixture.nativeElement.querySelector('.plot')).toBe(host); + expect(fixture.nativeElement.querySelector('.notes')).toBeNull(); + expect(react).toHaveBeenCalledTimes(calls); expect(observe).toHaveBeenCalledTimes(observers); + expect(purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled(); + expect(JSON.stringify(original)).toBe(snapshot); expect(JSON.stringify(copy)).toBe(copySnapshot); + }); + +}); diff --git a/src/app/features/indicadores/indicador-figure-card.ts b/src/app/features/indicadores/indicador-figure-card.ts new file mode 100644 index 0000000..fbfdd16 --- /dev/null +++ b/src/app/features/indicadores/indicador-figure-card.ts @@ -0,0 +1,120 @@ +import { Component, Input, output, signal } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MatIconModule } from '@angular/material/icon'; +import { MatCardModule } from '@angular/material/card'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { Dominio, hasNoVisibleValues, Indicador, PlotlyFigure, Tema } from './indicadores.models'; +import { figureTitle } from './indicadores.presentation'; +import { figureDisplayName } from './indicadores-figure-labels'; +import { CategoryLabel } from './indicadores-axis-labels'; +import { figureIdentity, identityElementId } from './indicadores-identities'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; + +// The panel owns requests; the card receives the original and its presentation copy. +export interface FigureState { + status: 'idle' | 'deferred' | 'loading' | 'ready' | 'error' | 'incompatible'; + figure?: PlotlyFigure; + presentationFigure?: PlotlyFigure; + footnotes?: readonly string[]; + categoryLabels?: readonly CategoryLabel[]; + minimumPlotWidth?: number; + message?: string; +} + +// Presentation only: contract semantics documented in G3 and G5C. +const CONTRACT_INTERPRETATIONS: Readonly> = { + C1: [ + 'El punto representa la proporción observada.', + 'En las figuras TEA con intervalos calculados, la línea vertical representa el intervalo de confianza Wilson al 95 %. No se infieren intervalos cuando faltan.', + 'Los intervalos amplios pueden deberse a denominadores pequeños.', + 'Un porcentaje observado del 100 % no implica certeza poblacional.', + ], + C2: [ + 'Las barras muestran la composición porcentual de cada grupo y periodo.', + 'Las categorías corresponden a la distribución de cada grupo y periodo.', + 'SIN_DATO, cuando aparece, es una categoría legítima de la representación.', + ], + C3r: [ + 'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.', + 'Los límites de dibujo no representan necesariamente extremos observados.', + 'Plotly puede mostrar las etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.', + ], +}; +const UNKNOWN_INTERPRETATION = ['No hay una explicación específica disponible para este contrato. Consulta las anotaciones de Plotly; no se infiere su significado estadístico.']; + +@Component({ + selector: 'app-indicador-figure-card', + standalone: true, + imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, PlotlyChart], + templateUrl: './indicador-figure-card.html', + styleUrl: './indicador-figure-card.scss', +}) +export class IndicadorFigureCard { + private currentState!: FigureState; + // Keep the mounted host's last presentation only. The template hides it whenever + // it is not the current result; this is neither applied state nor a results cache. + chartFigure?: PlotlyFigure; + chartMinimumWidth?: number; + @Input({ required: true }) set state(value: FigureState) { + this.currentState = value; + if (value.status === 'ready') { + this.chartFigure = value.presentationFigure; + this.chartMinimumWidth = value.minimumPlotWidth; + } + } + get state() { return this.currentState; } + @Input() selected?: Indicador; + @Input({ required: true }) figuraId!: string; + @Input({ required: true }) dominio!: Dominio; + @Input({ required: true }) tema!: Tema; + readonly retry = output(); + readonly plotWidthChanged = output(); + reportPlotWidth(width: unknown) { + if (typeof width === 'number') this.plotWidthChanged.emit(width); + } + readonly methodologyExpanded = signal(false); + get methodologyId(): string { + return identityElementId(figureIdentity(this.dominio, this.selected?.id ?? '', this.figuraId)) + '-methodology'; + } + + // Editorial classification of complete local sentences by known family. + // Keep mixed C3r/Wilson sentences and all backend content visible. + private get contract(): string | undefined { + return this.figuraId.startsWith('fig_c1') ? 'C1' + : this.figuraId.startsWith('fig_c2') ? 'C2' + : this.figuraId.startsWith('fig_c3r') ? 'C3r' : this.selected?.contrato; + } + private get complementaryLineCount(): number { + return this.contract === 'C1' ? 1 + : this.contract === 'C2' ? (this.dominio === 'tea' ? 2 : 1) : 0; + } + get methodologyDetail(): readonly string[] { + return this.interpretation.slice(0, this.complementaryLineCount); + } + get visibleInterpretation(): readonly string[] { + return this.interpretation.slice(this.complementaryLineCount); + } + readonly hasNoVisibleValues = hasNoVisibleValues; + readonly figureTitle = figureTitle; + readonly figureDisplayName = figureDisplayName; + + get interpretation(): readonly string[] { + const contract = this.contract; + if (contract === 'C2' && this.dominio !== 'tea') return [ + this.state.figure?.data.some(trace => trace['type'] === 'pie') + ? 'Los sectores muestran la composición porcentual de las categorías publicadas para cada periodo.' + : 'Las barras muestran la composición porcentual de las categorías publicadas para cada periodo.', + 'SIN_DATO, cuando aparece, es una categoría legítima de la representación.', + 'Los valores nulos o suprimidos no representan porcentajes observados de 0 %.', + ]; + if (contract === 'C1' && this.dominio !== 'tea') return [ + 'Los puntos representan porcentajes observados; el eje horizontal muestra el periodo.', + 'Estas figuras no entregan intervalos Wilson efectivos; no se interpretan sus barras como intervalos al 95 %.', + 'Los puntos suprimidos no representan tasas observadas de 0 %. Consulta las notas del servicio.', + 'Un porcentaje observado del 100 % no implica certeza poblacional.', + ]; + return contract && Object.hasOwn(CONTRACT_INTERPRETATIONS, contract) + ? [...CONTRACT_INTERPRETATIONS[contract], 'Los puntos suprimidos no representan tasas observadas de 0 %.'] : UNKNOWN_INTERPRETATION; + } + +} diff --git a/src/app/features/indicadores/indicador-figure-panel.spec.ts b/src/app/features/indicadores/indicador-figure-panel.spec.ts new file mode 100644 index 0000000..570d589 --- /dev/null +++ b/src/app/features/indicadores/indicador-figure-panel.spec.ts @@ -0,0 +1,333 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { By } from '@angular/platform-browser'; +import { applyGlobal, GlobalFilterState, IndicadoresMemory } from './indicadores-memory'; +import { PlotlyFigure } from './indicadores.models'; +import { Component } from '@angular/core'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { IndicadorFigureCard } from './indicador-figure-card'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE, READABLE_VISUAL_PROFILE } from './indicadores-visual-profile'; + +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) +class ChartStub { figure?: PlotlyFigure; } +const catalog = [ + { id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre'] }, + { id: 'i2', titulo: 'Dos', contrato: 'C3r', figuras: ['box'], tipos_periodo: ['semestre'] }, + { id: 'empty', titulo: 'Sin figuras', contrato: 'C1', figuras: [], tipos_periodo: ['semestre'] }, +]; +describe('IndicadorFigurePanel', () => { + let page: IndicadorFigurePanel; + let state: GlobalFilterState; + let editor: IndicadorPeriodFilters; + let http: HttpTestingController; + let fixture: ReturnType>; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadorFigurePanel, IndicadorPeriodFilters], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + fixture = TestBed.createComponent(IndicadorFigurePanel); + fixture.componentRef.setInput('dominio', 'tea'); + fixture.componentRef.setInput('indicador', catalog[0]); + fixture.componentRef.setInput('figuraId', 'f1'); + fixture.componentRef.setInput('tema', 'claro'); + state = TestBed.inject(IndicadoresMemory).restoreGlobal('tea', ['semestre']); + fixture.componentRef.setInput('applied', state.applied); + editor = new IndicadorPeriodFilters(); editor.state = state; editor.types = ['semestre']; + page = fixture.componentInstance; + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => { fixture.destroy(); http.verify(); }); + function filters() { + fixture.detectChanges(); + return editor; + } + function apply() { if (applyGlobal(state, ['semestre'])) { fixture.componentRef.setInput('applied', state.applied); fixture.detectChanges(); } } + function load() { fixture.detectChanges(); } + function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); } + + it('UX-07D.2 conserva notas al cambiar perfil/ancho y elimina resultados obsoletos durante carga', () => { + fixture.componentRef.setInput('dominio', 'cama'); + fixture.componentRef.setInput('indicador', { ...catalog[0], figuras: ['fig_c2_barras'], contrato: 'C2' }); + fixture.componentRef.setInput('figuraId', 'fig_c2_barras'); + const request = () => http.expectOne(req => req.url.includes('/cama/indicadores/') && req.url.includes('/figuras/')); + const response = (text: string): PlotlyFigure => ({ data: [{ type: 'bar', x: ['A'], y: [0] }], + layout: { annotations: [{ text, xref: 'paper', yref: 'paper', x: 0, y: -0.22, + xanchor: 'left', yanchor: 'top', align: 'left', showarrow: false, font: { size: 11 } }] } }); + load(); request().flush(response('Nota vigente')); fixture.detectChanges(); + for (const profile of [BASE_VISUAL_PROFILE, READABLE_VISUAL_PROFILE]) { + fixture.componentRef.setInput('visualProfile', profile); fixture.detectChanges(); + for (const width of [230, 320, 768, 1440]) page.updatePlotWidth(width); + expect(page.result().footnotes).toEqual(['Nota vigente']); http.expectNone(() => true); + } + page.requestFigure(); const old = request(); fixture.detectChanges(); + expect(page.result().footnotes).toBeUndefined(); + expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull(); + fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges(); + expect(old.cancelled).toBe(true); + const current = request(); current.flush(response('Nota del periodo actual')); fixture.detectChanges(); + expect(page.result().footnotes).toEqual(['Nota del periodo actual']); + expect(fixture.nativeElement.querySelector('.methodological-footnotes').textContent).toBe('Nota del periodo actual'); + http.expectNone(() => true); + }); + + it('UX-07C alterna etiquetas desde el original sin HTTP, conserva el host y restaura hover/categorías', () => { + const label = 'Fármaco de riesgo para el neurodesarrollo'; + const received: PlotlyFigure = { data: [{ type: 'bar', x: [label], y: [0], customdata: [null], + hovertemplate: '%{x}
%{y:.1f}%' }], layout: { xaxis: { type: 'category' } } }; + load(); figure().flush(received); fixture.detectChanges(); + const before = structuredClone(received), host = fixture.debugElement.query(By.directive(ChartStub)).componentInstance; + expect(page.result().categoryLabels?.[0].original).toBe(label); + expect(fixture.nativeElement.querySelector('.category-labels')).not.toBeNull(); + page.updatePlotWidth(1400); fixture.detectChanges(); + expect(page.result().categoryLabels).toEqual([]); + const unchanged = page.result(); + for (const width of [1400.7, 1399, 1350, 0, NaN]) page.updatePlotWidth(width); + expect(page.result()).toBe(unchanged); + page.updatePlotWidth(320); fixture.detectChanges(); + expect(page.result().categoryLabels).toHaveLength(1); + http.expectNone(() => true); + for (const profile of [BASE_VISUAL_PROFILE, READABLE_VISUAL_PROFILE, BASE_VISUAL_PROFILE]) { + fixture.componentRef.setInput('visualProfile', profile); fixture.detectChanges(); + http.expectNone(() => true); + expect(page.result().figure).toEqual(before); + expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(host); + if (profile === BASE_VISUAL_PROFILE) { + expect(page.result().presentationFigure?.data).toEqual(before.data); + expect(page.result().categoryLabels).toEqual([]); + } else expect(page.result().categoryLabels).toHaveLength(1); + } + expect(received).toEqual(before); + }); + + it.each([ + ['C1', ['proporción observada', 'Wilson al 95 %', 'denominadores pequeños', '100 % no implica certeza poblacional']], + ['C2', ['composición porcentual', 'distribución de cada grupo y periodo', 'SIN_DATO']], + ['C3r', ['Q1, mediana y Q3', 'no contiene observaciones individuales', 'min/max', 'derivados de Q1 y Q3', 'no deben interpretarse como los extremos observados de los pacientes']], + ['C4', ['No hay una explicación específica', 'no se infiere su significado estadístico']], + ['toString', ['No hay una explicación específica']], + ])('explica el contrato %s y la distinción entre reporte y valores representables', (contract, expected) => { + fixture.componentRef.setInput('indicador', { ...catalog[0], contrato: contract, figuras: ['f1'] }); load(); + figure().flush({ data: [], layout: {} }); + fixture.detectChanges(); + const help = fixture.nativeElement.querySelector('.interpretation').textContent; + for (const text of expected) expect(help).toContain(text); + if (contract === 'C3r') { + expect(help).toContain('Los límites de dibujo no representan necesariamente extremos observados'); + expect(help).not.toMatch(/serving|corrección|fase independiente/i); + } + expect(help).toContain('Un periodo puede tener reportes calculados sin valores estadísticos representables'); + }); + it('oculta sólo visualmente el encabezado y conserva identidad, lectura y títulos sin HTTP adicional', () => { + load(); figure().flush({ data: [], layout: {} }); fixture.detectChanges(); + const id = page.titleId; + const heading = fixture.nativeElement.querySelector('h3') as HTMLElement; + const section = fixture.nativeElement.querySelector('section') as HTMLElement; + expect(heading.id).toBe(id); expect(id).not.toBe(''); + expect(section.getAttribute('aria-labelledby')).toBe(id); + expect(section.firstElementChild).toBe(heading); + expect(heading.textContent).toBe('tea · i1 · Uno · f1'); + expect(heading.hasAttribute('aria-hidden')).toBe(false); expect(heading.hidden).toBe(false); + const style = getComputedStyle(heading); + expect(style.display).not.toBe('none'); expect(style.visibility).not.toBe('hidden'); + expect(style.position).toBe('absolute'); expect(style.width).toBe('1px'); expect(style.height).toBe('1px'); + expect(style.clipPath).toBe('inset(50%)'); expect(style.overflow).toBe('hidden'); + expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno'); + expect(fixture.nativeElement.querySelector('app-indicador-period-filters')).toBeNull(); + const result = page.result(), savedState = state; + fixture.detectChanges(); + expect(page.titleId).toBe(id); expect(state).toBe(savedState); expect(page.result()).toBe(result); + expect(fixture.nativeElement.querySelector('h3')).toBe(heading); + http.expectNone(() => true); + }); + it('entrega al gráfico una copia de presentación y conserva el JSON HTTP íntegro', () => { + load(); + const received: PlotlyFigure = { + data: [{ type: 'scatter', x: ['grupo'], y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], marker: { color: '#123456' } }], + layout: { yaxis: { range: [0, 100] }, annotations: [{ text: 'Nota del servicio' }], showlegend: true }, + config: { staticPlot: false }, frames: [], extra: { preserved: true }, + }; + const original = JSON.stringify(received); + figure().flush(received); fixture.detectChanges(); + expect(JSON.stringify(received)).toBe(original); + expect(page.result().figure).toEqual(received); + const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance as ChartStub; + expect(chart.figure).toBe(page.result().presentationFigure); + expect(chart.figure).not.toBe(page.result().figure); + expect(chart.figure?.data).toEqual(received.data); + expect(chart.figure?.layout).toEqual({ ...received.layout, title: { text: '' } }); + 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', () => { + load(); figure().flush({ data: [], layout: {} }); + const control = filters(); + control.changeMode('manual'); + expect(control.canApply).toBe(false); + apply(); + http.expectNone(req => req.url.includes('/figuras/')); + control.year = '2025'; control.unit = 'S1'; control.add(); + control.unit = 'S2'; control.add(); + http.expectNone(req => req.url.includes('/figuras/')); + expect(state?.applied?.selection.mode).toBe('todos'); + apply(); + const manual = figure(); + expect(manual.request.params.get('periodos')).toBe('2025-S1,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: {} }); + }); + 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 }; + figure().flush(received); fixture.detectChanges(); + const base = structuredClone(page.result().presentationFigure); + const original = page.result().figure; + const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance; + const applied = page.applied; + fixture.componentRef.setInput('visualProfile', DEMO_VISUAL_PROFILE); fixture.detectChanges(); + expect(page.result().presentationFigure?.layout['paper_bgcolor']).toBe('#f2f7fc'); + expect(page.result().figure).toBe(original); expect(page.applied).toBe(applied); + expect(page.result().presentationFigure?.data).toEqual(received.data); + expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(chart); + http.expectNone(() => true); + fixture.componentRef.setInput('visualProfile', BASE_VISUAL_PROFILE); fixture.detectChanges(); + expect(page.result().presentationFigure).toEqual(base); + expect(page.result().figure).toEqual(received); http.expectNone(() => true); + }); + it('UX-07B cambiar perfil durante carga no cancela ni inicia solicitudes', () => { + load(); const pending = figure(); + fixture.componentRef.setInput('visualProfile', DEMO_VISUAL_PROFILE); fixture.detectChanges(); + expect(pending.cancelled).toBe(false); http.expectNone(() => true); + pending.flush({ data: [], layout: {} }); fixture.detectChanges(); + expect(page.result().presentationFigure?.layout['paper_bgcolor']).toBe('#f2f7fc'); + http.expectNone(() => true); + }); + it('cancela figuras al cambiar tema rápidamente', () => { + load(); + const old = figure(); + fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges(); + const dark = figure(); + expect(old.cancelled).toBe(true); + expect(dark.request.params.get('tema')).toBe('oscuro'); + fixture.componentRef.setInput('tema', 'claro'); fixture.detectChanges(); + expect(dark.cancelled).toBe(true); + figure().flush({ data: [], layout: {} }); + }); + it.each([ + [400, 'rechazó los parámetros'], [404, 'reportes no están disponibles'], [500, 'error interno'], + ])('controla HTTP %i con cuerpo no uniforme y permite reintentar', (status, message) => { + load(); + figure().flush('error privado', { status: status as number, statusText: 'Error' }); + expect(page.result().status).toBe('error'); + expect(page.result().message).toContain(message); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).not.toContain('error privado'); + fixture.nativeElement.querySelector('app-indicador-figure-card .state button').click(); + figure().flush({ data: [], layout: {} }); + expect(page.result().status).toBe('ready'); + }); + it('distingue conexión fallida y cancela HTTP al destruirse', () => { + load(); figure().error(new ProgressEvent('error')); + expect(page.result().message).toContain('conectar'); + page.requestFigure(); + const pending = figure(); + fixture.destroy(); + expect(pending.cancelled).toBe(true); + }); + it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => { + load(); figure().flush({ data: [{ y: [0, null] }], layout: {} }); + const control = filters(); control.changeMode('manual'); + control.year = '2025'; control.unit = 'S1'; control.add(); + fixture.detectChanges(); + expect(page.result().figure?.data[0]['y']).toEqual([0, null]); + expect(editor.hasPending).toBe(true); + 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 }) => { + load(); figure().flush({ data: [{ y: [42] }], layout: {} }); + const control = filters(); control.changeMode('manual'); control.year = '2025'; + for (const period of periodos) { control.unit = period.slice(-2); control.add(); } + apply(); + const req = figure(); + expect(page.result().figure).toBeUndefined(); + req.flush('private', { status: 404, statusText: 'Not Found' }); + expect(page.result().status).toBe('error'); + 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(); + const retry = figure(); + expect(retry.request.params.get('periodos')).toBe(periodos.join(',')); + retry.flush({ data: [{ y: [null] }], layout: {} }); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('No hay valores visibles'); + expect(control.entry.draft.mode).toBe('empty'); + }); + 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(); + apply(); figure().flush({ data: [{ y: [20] }], layout: {} }); + control.unit = 'S2'; control.add(); + fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges(); + const themed = figure(); + expect(themed.request.params.get('periodos')).toBe('2025-S1'); + expect(themed.request.params.get('tema')).toBe('oscuro'); + themed.flush('error', { status: 500, statusText: 'Server Error' }); + 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']); + }); + 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(); + 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'); + current.flush({ data: [{ y: [12] }], layout: {} }); + expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); + expect(page.result().figure?.data[0]['y']).toEqual([12]); + }); + + 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(); + fixture.detectChanges(); + const result = page.result(), filterState = state, snapshot = JSON.stringify(filterState); + const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance; + const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance; + const button = fixture.nativeElement.querySelector('.methodology-toggle'); + for (let i = 0; i < 4; i++) { button.click(); fixture.detectChanges(); } + http.expectNone(() => true); + expect(page.result()).toBe(result); expect(state).toBe(filterState); + expect(JSON.stringify(state)).toBe(snapshot); + expect(filters()).toBe(control); + expect(fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance).toBe(card); + expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(chart); + fixture.destroy(); + fixture = TestBed.createComponent(IndicadorFigurePanel); + fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('indicador', catalog[0]); + fixture.componentRef.setInput('figuraId', 'f1'); fixture.componentRef.setInput('tema', 'claro'); + fixture.componentRef.setInput('applied', state.applied); + page = fixture.componentInstance; load(); figure().flush({ data: [], layout: {} }); + expect(JSON.stringify(state)).toBe(snapshot); + expect(fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-expanded')).toBe('false'); + }); +}); diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts new file mode 100644 index 0000000..c1c3b6a --- /dev/null +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -0,0 +1,136 @@ +import { Component, DestroyRef, inject, Input, OnChanges, SimpleChanges, signal } from '@angular/core'; +import { HttpErrorResponse } from '@angular/common/http'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs'; +import { Dominio, FigureSelection, Indicador, Tema } from './indicadores.models'; +import { IndicadoresService } from './indicadores.service'; +import { figurePresentation } from './indicadores.presentation'; +import { READABLE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visual-profile'; +import { FigureState, IndicadorFigureCard } from './indicador-figure-card'; +import { describePeriods, filterCompatibility, GlobalApplied, selectionKey } from './indicadores-memory'; +import { httpMessage } from './indicadores-http'; +import { figureIdentity, identityElementId } from './indicadores-identities'; + +@Component({ + selector: 'app-indicador-figure-panel', + imports: [IndicadorFigureCard], + template: ` +
+

{{ dominio }} · {{ indicador.id }} · {{ indicador.titulo }} · {{ figuraId }}

+

Filtro general aplicado: {{ appliedSummary }}

+ +
+ `, + styles: ` + :host { display: block; min-width: 0; } + section { margin-top: var(--issste-space-6); padding-top: var(--issste-space-4); border-top: 1px solid var(--issste-border); } + .applied-summary { color: var(--issste-text-secondary); overflow-wrap: anywhere; } + .visually-hidden { + position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; + overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; + } + `, +}) +export class IndicadorFigurePanel implements OnChanges { + @Input({ required: true }) dominio!: Dominio; + @Input({ required: true }) indicador!: Indicador; + @Input({ required: true }) figuraId!: string; + @Input({ required: true }) tema!: Tema; + @Input({ required: true }) applied!: GlobalApplied; + @Input() visible = true; + @Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE; + private readySelection?: FigureSelection; + private plotWidth?: number; + private readonly service = inject(IndicadoresService); + private readonly destroyRef = inject(DestroyRef); + private readonly figureRequests = new Subject<{ selection: FigureSelection; revision: number; generation: number } | null>(); + private generation = 0; + private currentKey = ''; + titleId = ''; + readonly result = signal({ status: 'idle' }); + get appliedSummary() { return this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin selección aplicada'; } + constructor() { + this.figureRequests.pipe(switchMap(request => request + ? defer(() => this.service.figura(request.selection)).pipe( + map(figure => this.present(figure, request.selection)), + catchError(error => of({ + status: 'error', + message: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404 + && (request.selection.periodos?.length ?? 0) > 1 + ? ' La consulta corresponde al conjunto de periodos; esta respuesta no identifica un periodo concreto.' : ''), + } as FigureState)), + startWith({ status: 'loading' } as FigureState), + map(state => ({ state, selection: request.selection, revision: request.revision, generation: request.generation }))) + : of({ state: { status: 'idle' } as FigureState, selection: undefined, revision: this.applied?.revision, generation: this.generation })), takeUntilDestroyed(this.destroyRef)) + .subscribe(({ state, selection, revision, generation }) => { + if (generation === this.generation && revision === this.applied?.revision) { + if (state.status === 'ready') this.readySelection = selection; + this.result.set(state); + } + }); + } + private present(figure: NonNullable, selection: FigureSelection): FigureState { + const presentation = figurePresentation(figure, selection, this.visualProfile, this.plotWidth); + return { status: 'ready', figure, presentationFigure: presentation.figure, footnotes: presentation.footnotes, + categoryLabels: presentation.categoryLabels, minimumPlotWidth: presentation.minimumPlotWidth }; + } + updatePlotWidth(width: number) { + if (!Number.isFinite(width) || width <= 0 || Math.floor(width) === this.plotWidth) return; + this.plotWidth = Math.floor(width); + const state = this.result(); + if (this.visualProfile.axisLabels?.enabled && state.status === 'ready' && state.figure && this.readySelection) { + const next = this.present(state.figure, this.readySelection); + // A width change within the same label budget must not hide/repaint an + // equivalent graph (for example when only the scrollbar gutter changes). + if (JSON.stringify([next.presentationFigure, next.categoryLabels, next.minimumPlotWidth]) + !== JSON.stringify([state.presentationFigure, state.categoryLabels, state.minimumPlotWidth])) this.result.set(next); + } + } + ngOnChanges(changes: SimpleChanges) { + const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId); + this.titleId = identityElementId(identity) + '-title'; + const key = this.requestKey(); + if (key === this.currentKey) { + const state = this.result(); + if (changes['visualProfile'] && state.status === 'ready' && state.figure && this.readySelection) { + this.result.set(this.present(state.figure, this.readySelection)); + } + return; + } + if (this.visible) this.requestFigure(); + else { + // Cancel stale work immediately but retain the panel and its Plotly host. + const message = this.generation === 0 + ? 'Figura pendiente: se cargará al acercarse a esta región.' + : 'Actualización pendiente: se consultará al volver a esta región.'; + this.generation++; + this.figureRequests.next(null); + this.currentKey = ''; + this.result.set({ status: 'deferred', message }); + } + } + private requestKey() { + return JSON.stringify([figureIdentity(this.dominio, this.indicador.id, this.figuraId), + this.tema, this.applied?.revision, this.applied && selectionKey(this.applied), + this.indicador.tipos_periodo, this.indicador.figuras.includes(this.figuraId)]); + } + requestFigure() { + if (!this.visible) return; + this.currentKey = this.requestKey(); + const applied = this.applied; + const compatibility = filterCompatibility(applied, this.indicador.tipos_periodo); + this.generation++; + if (!this.indicador.figuras.includes(this.figuraId) || !compatibility.compatible) { + this.figureRequests.next(null); + this.result.set({ status: 'incompatible', message: !compatibility.compatible + ? compatibility.reason : 'Esta figura ya no está publicada en el catálogo.' }); + return; + } + this.figureRequests.next({ revision: applied.revision, generation: this.generation, selection: { + dominio: this.dominio, indicador: this.indicador.id, figura: this.figuraId, + tipoPeriodo: applied.tipo, tema: this.tema, + periodos: applied.selection.mode === 'explicit' ? [...applied.selection.periodos] : undefined, + } }); + } +} diff --git a/src/app/features/indicadores/indicador-kpi-card.spec.ts b/src/app/features/indicadores/indicador-kpi-card.spec.ts new file mode 100644 index 0000000..ae3a5a1 --- /dev/null +++ b/src/app/features/indicadores/indicador-kpi-card.spec.ts @@ -0,0 +1,50 @@ +import { TestBed } from '@angular/core/testing'; +import { IndicadorKpiCard } from './indicador-kpi-card'; + + describe('UX-06E.D.1 KPI presentacional', () => { + it('presenta título y definición pendiente sin valores, unidades, fechas ni controles', () => { + const fixture = TestBed.createComponent(IndicadorKpiCard); + fixture.componentRef.setInput('title', 'Indicador destacado 1'); fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('h3').textContent).toBe('Indicador destacado 1'); + expect(fixture.nativeElement.querySelector('.kpi-state').textContent).toBe('Pendiente de definición'); + expect(fixture.nativeElement.querySelector('.value')).toBeNull(); + expect(fixture.nativeElement.querySelectorAll('p')).toHaveLength(1); + expect(fixture.nativeElement.querySelector('button, input, app-plotly-chart')).toBeNull(); + fixture.destroy(); + }); + it.each([null, undefined])('omite el valor opcional %s sin convertirlo a cero', value => { + const fixture = TestBed.createComponent(IndicadorKpiCard); + fixture.componentRef.setInput('title', 'Presentación'); fixture.componentRef.setInput('value', value); + fixture.detectChanges(); expect(fixture.nativeElement.querySelector('.value')).toBeNull(); fixture.destroy(); + }); + it('admite contenido opcional suministrado por su consumidor sin servicios ni formatos impuestos', () => { + const fixture = TestBed.createComponent(IndicadorKpiCard); + for (const [name, value] of Object.entries({ title: 'Título de prueba', value: 'Valor de prueba', unit: 'Unidad de prueba', + temporalReference: 'Referencia de prueba', state: 'Estado de prueba', additionalInfo: 'Información de prueba' })) { + fixture.componentRef.setInput(name, value); + } + fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('.value').textContent).toContain('Valor de prueba'); + expect(fixture.nativeElement.querySelector('.value span').textContent).toBe('Unidad de prueba'); + expect(fixture.nativeElement.textContent).toContain('Referencia de prueba'); + expect(fixture.nativeElement.querySelector('.kpi-state').textContent).toBe('Estado de prueba'); + expect(fixture.nativeElement.querySelector('.additional-info').textContent).toBe('Información de prueba'); + expect(fixture.nativeElement.textContent).not.toContain('Definición provisional'); + fixture.destroy(); + }); + it('separa valor y unidad y reúne descripción y notas útiles en una sola línea', () => { + const fixture = TestBed.createComponent(IndicadorKpiCard); + fixture.componentRef.setInput('title', 'Días de la toma al resultado'); + fixture.componentRef.setInput('value', 7.5); + fixture.componentRef.setInput('unit', 'días (mediana)'); + fixture.componentRef.setInput('additionalInfo', '98 mastografías; Q1 a Q3: 3 a 11 días.'); + fixture.componentRef.setInput('notes', ['La referencia de 60 días es provisional.', 'La referencia de 60 días es provisional.']); + fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('.value').firstChild.textContent.trim()).toBe('7.5'); + expect(fixture.nativeElement.querySelector('.value span').textContent).toBe('días (mediana)'); + expect(getComputedStyle(fixture.nativeElement.querySelector('.value span')).marginInlineStart).toBe('0.3em'); + expect(fixture.nativeElement.querySelectorAll('.additional-info')).toHaveLength(1); + expect(fixture.nativeElement.querySelector('.additional-info').textContent).toBe('98 mastografías; Q1 a Q3: 3 a 11 días. La referencia de 60 días es provisional.'); + fixture.destroy(); + }); +}); diff --git a/src/app/features/indicadores/indicador-kpi-card.ts b/src/app/features/indicadores/indicador-kpi-card.ts new file mode 100644 index 0000000..363d5b1 --- /dev/null +++ b/src/app/features/indicadores/indicador-kpi-card.ts @@ -0,0 +1,46 @@ +import { Component, Input } from '@angular/core'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatCardModule } from '@angular/material/card'; + +@Component({ + selector: 'app-indicador-kpi-card', + imports: [MatCardModule, MatProgressBarModule], + template: ` + +

{{ title }}

+ @if (loading) { } + @if (value !== null && value !== undefined) { +

{{ value }}@if (unit) { {{ unit }} }

+ } + @if (temporalReference) {

{{ temporalReference }}

} +

{{ state }}

+ @if (informationLine) {

{{ informationLine }}

} +
+ `, + styles: ` + :host { display: block; min-width: 0; } + 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, 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); } + .value span { margin-inline-start: .3em; } + `, +}) +export class IndicadorKpiCard { + @Input({ required: true }) title!: string; + @Input() value?: string | number | null; + @Input() unit?: string; + @Input() temporalReference?: string; + @Input() loading = false; + @Input() notes: string[] = []; + @Input() state = 'Pendiente de definición'; + @Input() additionalInfo?: string; + get informationLine(): string | undefined { + const lines = [this.additionalInfo, ...this.notes].map(value => value?.trim()).filter((value): value is string => !!value); + return [...new Set(lines)].join(' '); + } +} diff --git a/src/app/features/indicadores/indicador-kpi-initial.spec.ts b/src/app/features/indicadores/indicador-kpi-initial.spec.ts new file mode 100644 index 0000000..c712fd5 --- /dev/null +++ b/src/app/features/indicadores/indicador-kpi-initial.spec.ts @@ -0,0 +1,121 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { IndicadorKpiPanel } from './indicador-kpi-panel'; +import { KPI_BY_DOMAIN } from './indicadores-kpi'; +import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos'; + +describe('KPI búsqueda inicial del último dato visible', () => { + let fixture: ReturnType>; + let http: HttpTestingController; + const definition = KPI_BY_DOMAIN.cacu[0]; + const periods = ['2025-S2', '2025-S1', '2024-S2']; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadorKpiPanel], providers: [provideHttpClient(), provideHttpClientTesting()] }); + fixture = TestBed.createComponent(IndicadorKpiPanel); + http = TestBed.inject(HttpTestingController); + const availability = emptyAvailability('ready'); + availability.byIndicator[definition.id] = [periods[2], '2026-01', periods[0], periods[1]].map(periodo => ({ periodo, tipo: periodo.includes('-S') ? 'semestre' : 'mes' })); + fixture.componentRef.setInput('dominio', 'cacu'); + fixture.componentRef.setInput('definition', definition); + fixture.componentRef.setInput('indicador', { id: definition.id, contrato: 'C2', tipos_periodo: ['semestre', 'mes'], figuras: [], titulo: definition.title }); + fixture.componentRef.setInput('applied', { tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 }); + fixture.componentRef.setInput('initialPresentation', true); + fixture.componentRef.setInput('availability', availability); + fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); }); + function request(period: string) { + return http.expectOne(r => r.url.endsWith('/datos') && r.params.get('periodos') === period); + } + function data(period: string, kind: 'visible' | 'suppressed' | 'incomplete' | 'null' = 'visible', value = 5) { + return { id: definition.id, contrato: 'C2', tipo_periodo: 'semestre', periodos: [period], + categorias: kind === 'incomplete' ? { A: {}, B: {} } : { A: {} }, + filas: [{ periodo: period, grupo: 'TOTAL', categoria: 'A', n: kind === 'null' ? null : value, suprimido: kind === 'suppressed' ? 1 : 0 }] }; + } + it('consulta secuencialmente por granularidad, detiene al visible y explica supresión posterior', () => { + const latest = request(periods[0]); http.expectNone(() => true); + expect(fixture.componentInstance.result().loading).toBe(true); + latest.flush(data(periods[0], 'suppressed')); + request(periods[1]).flush(data(periods[1])); fixture.detectChanges(); + expect(fixture.componentInstance.result().value).toBe(5); + expect(fixture.nativeElement.textContent).toContain('Último dato visible · 2025-S1'); + expect(fixture.nativeElement.textContent).toContain('Existen reportes posteriores con datos ocultos por tamaño.'); + http.expectNone(() => true); + }); + it('recorre varios suprimidos sin consultar todos los periodos a la vez', () => { + request(periods[0]).flush(data(periods[0], 'suppressed')); + const second = request(periods[1]); http.expectNone(() => true); + second.flush(data(periods[1], 'suppressed')); + request(periods[2]).flush(data(periods[2])); + expect(fixture.componentInstance.temporalReference).toBe('Último dato visible · 2024-S2'); + expect(fixture.componentInstance.result().info).toContain('datos ocultos por tamaño'); + }); + it('agotado el inventario conserva el estado del último reporte', () => { + request(periods[0]).flush(data(periods[0], 'suppressed')); + request(periods[1]).flush(data(periods[1], 'incomplete')); + request(periods[2]).flush(data(periods[2], 'null')); + expect(fixture.componentInstance.result().state).toBe('Dato oculto por tamaño'); + expect(fixture.componentInstance.result().value).toBeUndefined(); + expect(fixture.componentInstance.temporalReference).toBe(periods[0]); + }); + it('acepta cero legítimo del último periodo y termina sin retroceder', () => { + request(periods[0]).flush(data(periods[0], 'visible', 0)); + expect(fixture.componentInstance.result().value).toBe(0); + expect(fixture.componentInstance.temporalReference).toBe(periods[0]); + http.expectNone(() => true); + }); + it.each(['incomplete', 'null', 'missing'] as const)('no muestra %s ni afirma supresión si encuentra un anterior', kind => { + const latest = request(periods[0]); + if (kind === 'missing') latest.flush('', { status: 404, statusText: 'Not Found' }); + else latest.flush(data(periods[0], kind)); + expect(fixture.componentInstance.result().value).toBeUndefined(); + request(periods[1]).flush(data(periods[1])); + expect(fixture.componentInstance.result().value).toBe(5); + expect(fixture.componentInstance.result().info).not.toContain('datos ocultos por tamaño'); + }); + it('un error HTTP detiene, se comunica y reintenta sin repetir datos resueltos', () => { + request(periods[0]).flush(data(periods[0], 'suppressed')); + request(periods[1]).flush('private', { status: 503, statusText: 'Unavailable' }); fixture.detectChanges(); + expect(fixture.componentInstance.result().state).toBe('Error de consulta'); + expect(fixture.componentInstance.result().value).toBeUndefined(); + expect(fixture.nativeElement.textContent).not.toContain('private'); + expect(fixture.nativeElement.textContent).not.toContain('datos ocultos por tamaño'); + http.expectNone(() => true); + (fixture.nativeElement.querySelector('button') as HTMLButtonElement).click(); + request(periods[1]).flush(data(periods[1])); + expect(fixture.componentInstance.result().value).toBe(5); http.expectNone(() => true); + }); + it('aplicar Todos durante la búsqueda cancela el pasado y recupera solo el último reporte', () => { + request(periods[0]).flush(data(periods[0], 'suppressed')); + const old = request(periods[1]); + fixture.componentRef.setInput('initialPresentation', false); fixture.detectChanges(); + expect(old.cancelled).toBe(true); + expect(fixture.componentInstance.result().state).toBe('Dato oculto por tamaño'); + expect(fixture.componentInstance.temporalReference).toBe(periods[0]); http.expectNone(() => true); + }); + it('aplicar explícito cancela el recorrido e impide sobrescritura antigua', () => { + request(periods[0]).flush(data(periods[0], 'suppressed')); const old = request(periods[1]); + fixture.componentRef.setInput('initialPresentation', false); + fixture.componentRef.setInput('applied', { tipo: 'semestre', selection: { mode: 'explicit', periodos: [periods[2]] }, revision: 1 }); fixture.detectChanges(); + expect(old.cancelled).toBe(true); request(periods[2]).flush(data(periods[2], 'visible', 0)); + expect(fixture.componentInstance.result().value).toBe(0); expect(fixture.componentInstance.temporalReference).toBe(periods[2]); + http.expectNone(() => true); + }); + it('comparte el límite cuatro entre periodos y datos; cancela trabajos en cola', () => { + const latest = request(periods[0]); + const service = TestBed.inject(IndicadoresPeriodos); + const subscriptions = ['a', 'b', 'c', 'd', 'e'].map(id => service.periodos('cacu', id).subscribe()); + const inventory = http.match(r => r.url.endsWith('/periodos')); + expect(inventory).toHaveLength(3); + subscriptions[4].unsubscribe(); + latest.flush(data(periods[0], 'suppressed')); + const fourth = http.expectOne('/cacu/indicadores/d/periodos'); + http.expectNone(() => true); + inventory[0].flush({ id: 'a', periodos: [] }); + request(periods[1]).flush(data(periods[1])); + inventory.slice(1).forEach((r, i) => r.flush({ id: ['b', 'c'][i], periodos: [] })); + fourth.flush({ id: 'd', periodos: [] }); http.expectNone('/cacu/indicadores/e/periodos'); + subscriptions.forEach(subscription => subscription.unsubscribe()); + }); +}); diff --git a/src/app/features/indicadores/indicador-kpi-panel.spec.ts b/src/app/features/indicadores/indicador-kpi-panel.spec.ts new file mode 100644 index 0000000..6c0efd1 --- /dev/null +++ b/src/app/features/indicadores/indicador-kpi-panel.spec.ts @@ -0,0 +1,208 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { By } from '@angular/platform-browser'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadorKpiPanel } from './indicador-kpi-panel'; +import { KPI_BY_DOMAIN } from './indicadores-kpi'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { IndicadorDatos, Dominio } from './indicadores.models'; +describe('KPI integración con autoridad global', () => { + let fixture: ReturnType>; + let http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController); + http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); }); + function load(domain: Dominio, missing = false, periods = ['2025-S1']) { + 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 })) }); + fixture.detectChanges(); + } + function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel); } + function requests() { return http.match(r => r.url.endsWith('/datos')); } + function response(index: number, domain: Dominio = 'cacu', period = '2025-S1'): IndicadorDatos { + const d = KPI_BY_DOMAIN[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], categorias: { A: {} }, filas: [ + { periodo: period, grupo: index === 1 && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: 5, valor: 40, numerador: 2, denominador: 5, mediana: 7, q1: 3, q3: 9, unidad: 'dias', suprimido: 0 }] }; + } + function apply(periods: string[], tipo: 'mes' | 'semestre' = 'semestre') { + const state = fixture.componentInstance.filters!; state.tipo = tipo; state.editors[tipo]!.draft = { mode: 'explicit', periodos: periods as [string, ...string[]] }; + fixture.componentInstance.applyFilters(); fixture.detectChanges(); + } + it('TEA sin catálogo muestra sus tres destacados sin consultar datos', () => { + expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores destacados'); + expect(panels().map(p => p.definition.id)).toEqual(KPI_BY_DOMAIN.tea.map(d => d.id)); + 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', () => { + fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush([]); + load('tea'); const req = requests(); + expect(req.map(r => r.request.url)).toEqual(KPI_BY_DOMAIN.tea.map(d => '/tea/indicadores/' + d.id + '/datos')); + req.forEach((r, i) => r.flush(response(i, 'tea'))); fixture.detectChanges(); + expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7]]); + expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.'); + }); + it('tres tarjetas independientes manejan 404, error y éxito sin cifras anteriores', () => { + load('cacu'); const req = requests(); expect(req).toHaveLength(3); expect(panels().every(p => p.result().loading)).toBe(true); + for (const r of req) { expect(r.request.params.has('tipoPeriodo')).toBe(false); expect(r.request.params.has('tema')).toBe(false); } + req[0].flush('private', { status: 404, statusText: 'Not Found' }); req[1].flush('private', { status: 503, statusText: 'Unavailable' }); req[2].flush(response(2)); fixture.detectChanges(); + expect(panels().map(p => p.result().state)).toEqual(['Sin datos del periodo', 'Error de consulta', 'Disponible']); + expect(panels()[2].result().value).toBe(7); expect(fixture.nativeElement.textContent).not.toContain('private'); + expect(fixture.nativeElement.textContent).not.toContain('Definición provisional'); + apply(['2025-S2']); expect(panels().every(p => p.result().value === undefined)).toBe(true); requests().forEach((r,i) => r.flush(response(i, 'cacu', '2025-S2'))); + }); + 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); + fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(0); + expect(panels().map(p => p.result().value)).toEqual([5, '40.0', 7]); + expect(single.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true); + fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true); + apply(['2025-S2']); expect(single.every(r => r.cancelled)).toBe(true); const next = requests(); expect(next).toHaveLength(3); + next.forEach((r,i) => r.flush(response(i, 'cacu', '2025-S2'))); + apply(['2025-S2']); http.expectNone(() => true); + }); + it('selección múltiple cancela, no consulta ni suma meses para un semestre', () => { + load('cacu'); const pending = requests(); apply(['2025-01', '2025-02'], 'mes'); + expect(pending.every(r => r.cancelled)).toBe(true); expect(panels().every(p => p.result().state === 'Selección no consolidable')).toBe(true); http.expectNone(() => true); + apply(['2025-01'], 'mes'); requests().forEach((r,i) => { expect(r.request.params.get('periodos')).toBe('2025-01'); r.flush(response(i, 'cacu', '2025-01')); }); + }); + it('dominio cancela solicitudes salientes y restaura aplicado independiente del borrador', () => { + load('cacu'); const outgoing = requests(); apply(['2025-S1']); const applied = requests(); expect(outgoing.every(r => r.cancelled)).toBe(true); + fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2'] }; + load('cama'); expect(applied.every(r => r.cancelled)).toBe(true); const cama = requests(); expect(cama.every(r => r.request.url.startsWith('/cama/'))).toBe(true); cama.forEach((r,i) => r.flush(response(i, 'cama'))); + load('cacu'); const restored = requests(); expect(restored.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true); + expect(fixture.componentInstance.filters!.editors.semestre!.draft).toEqual({ mode: 'explicit', periodos: ['2025-S2'] }); restored.forEach((r,i) => r.flush(response(i))); + }); + it('el catálogo gráfico no determina membresía de los KPI destacados', () => { + load('cacu', true); expect(panels().map(p => p.definition.id)).toEqual(KPI_BY_DOMAIN.cacu.map(d => d.id)); + expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(3); + const req = requests(); expect(req).toHaveLength(2); req.forEach((r,i) => r.flush(response(i+1))); + }); + it.each([0, 1, 2])('retirar definiciones deja %i tarjetas y conserva filtros y valores retenidos', count => { + load('cacu'); requests().forEach((r, i) => r.flush(response(i))); fixture.detectChanges(); + const page = fixture.componentInstance, before = panels(), state = page.filters!; + state.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2'] }; + const snapshot = structuredClone(state), definitions = page.kpisByDomain.cacu; + try { + page.kpisByDomain.cacu = definitions.slice(0, count); page.catalog.set([...page.catalog()]); fixture.detectChanges(); + expect(panels()).toHaveLength(count); panels().forEach((panel, i) => expect(panel).toBe(before[i])); + expect(panels().map(p => p.result().value)).toEqual([5, '40.0', 7].slice(0, count)); + expect(page.filters).toBe(state); expect(state).toEqual(snapshot); + const grid = fixture.nativeElement.querySelector('.kpi-grid') as HTMLElement | null; + if (count) { + expect(grid!.children).toHaveLength(count); + expect(grid!.style.getPropertyValue('--kpi-count')).toBe(String(count)); + } else expect(fixture.nativeElement.querySelector('.kpi-section')).toBeNull(); + http.expectNone(() => true); + page.kpisByDomain.cacu = definitions; page.catalog.set([...page.catalog()]); fixture.detectChanges(); + const added = requests(); expect(added).toHaveLength(0); + added.forEach((r, i) => r.flush(response(count + i))); + expect(panels()).toHaveLength(3); expect(state).toEqual(snapshot); + } finally { page.kpisByDomain.cacu = definitions; } + }); + it('retirar un ID del catálogo gráfico conserva todos los KPI configurados', () => { + load('cacu'); requests().forEach((r, i) => r.flush(response(i))); fixture.detectChanges(); + const page = fixture.componentInstance, before = panels(), filters = structuredClone(page.filters); + page.catalog.set(page.catalog().slice(1)); fixture.detectChanges(); + expect(panels()).toEqual(before); expect(page.filters).toEqual(filters); + expect(panels()).toHaveLength(3); http.expectNone(() => true); + }); + it('CaCu no presenta KPI disponibles durante carga/error y reintenta sin confirmar vacío', () => { + const page = fixture.componentInstance; page.changeDominio('cacu'); fixture.detectChanges(); + expect(page.catalogLoading()).toBe(true); expect(panels()).toHaveLength(3); + expect(fixture.nativeElement.textContent).toContain('Cargando catálogo'); + http.expectOne('/cacu/indicadores').flush('private', { status: 503, statusText: 'Unavailable' }); fixture.detectChanges(); + expect(page.catalogError()).toBeTruthy(); expect(fixture.nativeElement.querySelector('[role="alert"]')).toBeTruthy(); + expect(fixture.nativeElement.querySelector('.kpi-section')).toBeTruthy(); expect(panels()).toHaveLength(3); + expect(fixture.nativeElement.textContent).not.toContain('No hay indicadores disponibles'); + page.retryCatalog(); fixture.detectChanges(); + http.expectOne('/cacu/indicadores').flush([]); fixture.detectChanges(); + expect(page.catalogError()).toBe(''); expect(page.catalogLoading()).toBe(false); + expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); expect(panels()).toHaveLength(3); + http.expectNone(() => true); + }); + it.each(['suprimido', 'nulo', 'sin filas'] as const)('KPI publicado con resultado %s conserva tarjeta y definición', scenario => { + load('cacu'); const before = panels(); + const data = response(1); + if (scenario === 'suprimido') data.filas[0]['suprimido'] = 1; + if (scenario === 'nulo') data.filas[0]['valor'] = null; + if (scenario === 'sin filas') { data.filas = []; data.periodos = []; } + requests().forEach((r, i) => r.flush(i === 1 ? data : response(i))); fixture.detectChanges(); + expect(panels()).toEqual(before); expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(3); + expect(panels()[1].result().state).toBe(scenario === 'suprimido' ? 'Dato oculto por tamaño' : scenario === 'nulo' ? 'Sin valor disponible' : 'Sin filas utilizables'); + expect(panels()[1].result().value).toBeUndefined(); http.expectNone(() => true); + }); + it('KPI publicado sin periodos con reporte mantiene sus tres tarjetas sin consultar datos', () => { + 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(); + expect(panels()).toHaveLength(3); 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', () => { + for (const domain of ['cacu', 'cama'] as const) { + load(domain); + const req = requests(); expect(req).toHaveLength(3); + req.forEach((r, i) => r.flush(response(i, domain))); + fixture.detectChanges(); + const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')]; + expect(cards).toHaveLength(3); + expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['5', '40.0', '7']); + expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(['pacientes', '%', 'días (mediana)']); + expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(['Disponible', 'Disponible', 'Disponible']); + expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([ + expect.stringContaining('2025-S1'), expect.stringContaining('2 de 5'), + expect.stringContaining(`5 ${domain === 'cacu' ? 'citologías' : 'mastografías'}; Q1 a Q3: 3 a 9 días.`), + ])); + expect(fixture.nativeElement.textContent).not.toContain('Definición provisional'); + } + }); + it('Aplicar equivalente termina el modo inicial sin cambiar revisión, borrador o selección', () => { + load('cacu', false, ['2025-S2', '2025-S1']); + requests().forEach((r, i) => { const data = response(i, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; r.flush(data); }); + requests().forEach((r, i) => r.flush(response(i))); fixture.detectChanges(); + expect(panels().every(p => p.temporalReference === 'Último dato visible · 2025-S1')).toBe(true); + const page = fixture.componentInstance, applied = page.filters!.applied, snapshot = structuredClone(page.filters); + expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(false); + (fixture.nativeElement.querySelector('.apply-button') as HTMLButtonElement).click(); fixture.detectChanges(); + expect(page.initialKpiPresentation).toBe(false); expect(page.filters!.applied).toBe(applied); expect(page.filters).toEqual(snapshot); + expect(panels().every(p => p.result().state === 'Dato oculto por tamaño' && p.temporalReference === '2025-S2')).toBe(true); + expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true); http.expectNone(() => true); + load('cama'); requests().forEach((r, i) => r.flush(response(i, 'cama'))); expect(page.initialKpiPresentation).toBe(true); + load('cacu'); expect(page.initialKpiPresentation).toBe(false); expect(panels()).toHaveLength(3); + expect(panels().every(p => p.temporalReference === '2025-S2' && p.result().state === 'Dato oculto por tamaño')).toBe(true); http.expectNone(() => true); + }); + it('primera entrada independiente y regreso inicial reutilizan datos, sin reiniciar filtros', () => { + load('cacu'); requests().forEach((r, i) => r.flush(response(i))); + load('cama'); expect(fixture.componentInstance.initialKpiPresentation).toBe(true); requests().forEach((r, i) => r.flush(response(i, 'cama'))); + load('cacu'); expect(fixture.componentInstance.initialKpiPresentation).toBe(true); + expect(panels().map(p => p.result().value)).toEqual([5, '40.0', 7]); http.expectNone(() => true); + }); + it('salir durante el recorrido cancela periodos antiguos y volver reutiliza últimos resueltos', () => { + load('cacu', false, ['2025-S2', '2025-S1']); + requests().forEach((r, i) => { const data = response(i, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; r.flush(data); }); + const old = requests(); expect(old).toHaveLength(3); + load('cama'); expect(old.every(r => r.cancelled)).toBe(true); + requests().forEach((r, i) => r.flush(response(i, 'cama'))); + load('cacu'); const resumed = requests(); expect(resumed).toHaveLength(3); + resumed.forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush(response(i)); }); + expect(panels().every(p => p.temporalReference === 'Último dato visible · 2025-S1')).toBe(true); http.expectNone(() => true); + }); + it('aplicado explícito y luego Todos nunca buscan periodos anteriores', () => { + load('cacu', false, ['2025-S2', '2025-S1']); const outgoing = requests(); + apply(['2025-S1']); expect(outgoing.every(r => r.cancelled)).toBe(true); + requests().forEach((r, i) => { const data = response(i); data.filas[0]['suprimido'] = 1; r.flush(data); }); + expect(panels().every(p => p.result().state === 'Dato oculto por tamaño')).toBe(true); http.expectNone(() => true); + fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'todos' }; + fixture.componentInstance.applyFilters(); fixture.detectChanges(); + const latest = requests(); expect(latest).toHaveLength(3); + latest.forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S2'); const data = response(i, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; r.flush(data); }); + expect(panels().every(p => p.temporalReference === '2025-S2')).toBe(true); http.expectNone(() => true); + }); +}); diff --git a/src/app/features/indicadores/indicador-kpi-panel.ts b/src/app/features/indicadores/indicador-kpi-panel.ts new file mode 100644 index 0000000..dacc93e --- /dev/null +++ b/src/app/features/indicadores/indicador-kpi-panel.ts @@ -0,0 +1,100 @@ +import { Component, DestroyRef, inject, Input, OnChanges, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { HttpErrorResponse } from '@angular/common/http'; +import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs'; +import { MatButtonModule } from '@angular/material/button'; +import { Dominio, Indicador } from './indicadores.models'; +import { GlobalApplied, describePeriods, filterCompatibility, selectionKey } from './indicadores-memory'; +import { IndicadoresKpiQueries } from './indicadores-kpi-queries'; +import { IndicadorKpiCard } from './indicador-kpi-card'; +import { KpiDefinition, KpiResult, kpiResult } from './indicadores-kpi'; +import { PeriodAvailability, sortedPeriods } from './indicadores-periodos'; +import { httpMessage } from './indicadores-http'; + +interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; } + +@Component({ + selector: 'app-indicador-kpi-panel', + imports: [IndicadorKpiCard, MatButtonModule], + template: ` + @if (result().state === 'Error de consulta') { + + }`, + styles: ':host { display: block; min-width: 0; }', +}) +export class IndicadorKpiPanel implements OnChanges { + @Input({ required: true }) dominio!: Dominio; + @Input({ required: true }) definition!: KpiDefinition; + @Input() indicador?: Indicador; + @Input() applied?: GlobalApplied; + @Input() availability?: PeriodAvailability; + @Input() initialPresentation = false; + private readonly queries = inject(IndicadoresKpiQueries); + private readonly destroyRef = inject(DestroyRef); + private readonly requests = new Subject(); + private key = ''; + readonly usedPeriod = signal(undefined); + readonly result = signal({ state: 'Esperando catálogo' }); + get temporalReference() { + if (this.result().earlier) return 'Último dato visible · ' + this.usedPeriod(); + return this.usedPeriod() ?? (this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado'); + } + retry() { this.requests.next(); } + constructor() { + this.requests.pipe(switchMap((): Observable => { + const applied = this.applied, definition = this.definition, domain = this.dominio; + this.usedPeriod.set(undefined); + if (!applied) return of({ state: 'Esperando filtro aplicado' }); + if (this.indicador && this.indicador.contrato !== definition.contrato) return of({ state: 'Error de contrato' }); + const compatible = filterCompatibility(applied, this.indicador?.tipos_periodo ?? [applied.tipo]); + if (!compatible.compatible || !applied) return of({ state: 'Filtro incompatible', info: !compatible.compatible ? compatible.reason : '' }); + if (applied.selection.mode === 'explicit' && applied.selection.periodos.length !== 1) return of({ state: 'Selección no consolidable', info: 'Elige un único periodo; no hay una regla aprobada para consolidarlos.' }); + let periods: string[]; + if (applied.selection.mode === 'todos') { + if (!this.indicador) return of({ state: 'Sin reportes disponibles' }); + const availability = this.availability; + if (!availability || availability.status === 'loading') return of({ state: 'Consultando periodos…', loading: true }); + if (availability.errors[definition.id]) return of({ state: 'Error de disponibilidad', info: 'Reintenta la consulta de periodos disponibles en los filtros generales.' }); + const available = availability.byIndicator[definition.id]; + if (!available) return of({ state: 'Error de disponibilidad' }); + periods = sortedPeriods(available.filter(p => p.tipo === applied.tipo).map(p => p.periodo)); + if (!periods.length) return of({ state: 'Sin reportes disponibles' }); + if (!this.initialPresentation) periods = periods.slice(0, 1); + } else periods = applied.selection.periodos; + // One request per KPI at a time: the three configured panels start only after + // the existing availability queue (concurrency four) has finished. + const search = (index: number, latest?: KpiDisplay, allSuppressed = true): Observable => { + const period = periods[index]; + const resolved: GlobalApplied = { ...applied, selection: { mode: 'explicit', periodos: [period] } }; + return this.queries.datos(domain, definition.id, applied.tipo, period).pipe( + map(data => ({ ...kpiResult(data, definition, domain, resolved), notes: data.notas, period } as KpiDisplay)), + catchError(error => of({ period, + state: error instanceof HttpErrorResponse && error.status === 404 ? 'Sin datos del periodo' : 'Error de consulta', + info: error instanceof HttpErrorResponse && error.status === 404 ? undefined : httpMessage(error) })), + switchMap(result => { + // Network/contract transport failures stay visible and can be retried. + if (result.state === 'Error de consulta') return of(result); + if (result.state === 'Disponible' && result.value !== undefined) return of({ ...result, earlier: index > 0, + info: [result.info, index > 0 && allSuppressed ? 'Existen reportes posteriores con datos ocultos por tamaño.' : ''].filter(Boolean).join(' ') }); + const first = latest ?? result; + return index + 1 < periods.length + ? search(index + 1, first, allSuppressed && result.state === 'Dato oculto por tamaño') : of(first); + })); + }; + return search(0).pipe(startWith({ state: this.initialPresentation && applied.selection.mode === 'todos' + ? 'Buscando último dato visible…' : 'Cargando…', loading: true })); + }), takeUntilDestroyed(this.destroyRef)).subscribe(result => { + this.usedPeriod.set(result.period); + this.result.set(result); + }); + } + ngOnChanges() { + const key = JSON.stringify([this.dominio, this.definition.id, this.indicador, this.initialPresentation, this.applied && selectionKey(this.applied), + this.applied?.selection.mode === 'todos' ? [this.availability?.status, this.availability?.byIndicator[this.definition.id], this.availability?.errors[this.definition.id]] : undefined]); + if (key === this.key) return; + this.key = key; + this.requests.next(); + } +} diff --git a/src/app/features/indicadores/indicador-period-filters.html b/src/app/features/indicadores/indicador-period-filters.html new file mode 100644 index 0000000..7a12fe8 --- /dev/null +++ b/src/app/features/indicadores/indicador-period-filters.html @@ -0,0 +1,66 @@ +
+@if (state.tipo === 'mes') {

Para consultar meses debes elegir periodos explícitos. Todos con reporte utiliza semestres.

} +@if (!types.includes(state.tipo)) {

La granularidad del borrador ya no está publicada para este proyecto. Elige una granularidad disponible.

} +
+ @if (types.length > 1 || !types.includes(state.tipo)) { + Granularidad + + @for (tipo of types; track tipo) { {{ tipo === 'mes' ? 'Mes' : 'Semestre' }} } + + + } + @if (state.tipo === 'semestre' && state.tipo === types[0]) { + Modalidad + + {{ entry.draft.mode === 'todos' ? 'Todos con reporte' : 'Elegir periodos' }} + Todos con reporte + Elegir periodos + + + } + @if (entry.draft.mode !== 'todos') { + Periodos seleccionados + + {{ selectedPeriods.join(', ') }} + @for (period of options; track period) { {{ period }} } + @if (availability) { + @for (period of unavailableSelection; track period) { {{ period }} — disponibilidad no confirmada } + } + + {{ availability ? 'Existe reporte en al menos un indicador del dominio; la cobertura puede variar.' : 'Disponibilidad desconocida hasta consultar.' }} + + } +
+@if (availability) { + @if (availability.status === 'loading') {

Consultando periodos disponibles…

} + @else if (availability.status === 'error') { +

No se pudo completar la consulta de periodos disponibles.

+ + } @else if (!options.length) {

Sin reportes disponibles para esta granularidad.

} + @if (entry.draft.mode === 'explicit' && unavailableSelection.length) {

La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.

} +} +@if (!availability && entry.draft.mode !== 'todos') { +

Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.

+
+ Año + {{ state.tipo === 'mes' ? 'Mes' : 'Semestre' }} + + @for (value of state.tipo === 'mes' ? months : ['S1', 'S2']; track value) { {{ value }} } + + + +
+
+ @for (period of entry.added; track period) { + + } +
+} +@if (error) { } +

Selección en edición: {{ summary }}

+@if (!canApply) {

Selecciona al menos un periodo válido para aplicar.

} +@if (!hasPending) {

Sin cambios pendientes.

} +@if (hasPending) {

Hay cambios sin aplicar.

} + +

Filtro general aplicado: {{ appliedSummary }}

+
diff --git a/src/app/features/indicadores/indicador-period-filters.scss b/src/app/features/indicadores/indicador-period-filters.scss new file mode 100644 index 0000000..ed8f559 --- /dev/null +++ b/src/app/features/indicadores/indicador-period-filters.scss @@ -0,0 +1,19 @@ +:host { display: block; min-width: 0; margin: var(--issste-space-4) 0; } +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; } +.period-builder mat-form-field { flex: 0 1 10rem; } +.period-builder button { margin-top: var(--issste-space-2); min-height: 44px; } +p { overflow-wrap: anywhere; line-height: 1.5; margin: var(--issste-space-3) 0; } +.select-value { white-space: normal; overflow-wrap: anywhere; line-height: 1.5; } +.filter-help, .applied-summary { color: var(--issste-text-secondary); font: var(--mat-sys-body-small); } +.draft-summary { font-weight: 500; } +.pending { border-left: 3px solid var(--issste-text); padding-left: var(--issste-space-3); } +.error { color: var(--mat-sys-error); } +.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); } +@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; } +} diff --git a/src/app/features/indicadores/indicador-period-filters.spec.ts b/src/app/features/indicadores/indicador-period-filters.spec.ts new file mode 100644 index 0000000..31bd18c --- /dev/null +++ b/src/app/features/indicadores/indicador-period-filters.spec.ts @@ -0,0 +1,138 @@ +import { TestBed } from '@angular/core/testing'; +import { NgModel } from '@angular/forms'; +import { By } from '@angular/platform-browser'; +import { MatSelect } from '@angular/material/select'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; + +describe('UX-04 control asistido', () => { + let control: IndicadorPeriodFilters; + let fixture: ReturnType>; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadorPeriodFilters] }); + fixture = TestBed.createComponent(IndicadorPeriodFilters); + fixture.componentRef.setInput('types', ['semestre', 'mes']); + fixture.componentRef.setInput('state', { tipo: 'semestre', editors: { + semestre: { added: [], draft: { mode: 'todos' } }, mes: { added: [], draft: { mode: 'empty' } }, + }, applied: { tipo: 'semestre', selection: { mode: 'todos' } } }); + fixture.detectChanges(); + 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'); + fixture.componentRef.setInput('state', { + ...control.state, editors: { ...control.state.editors, semestre: { + added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] }, + } }, + }); + fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); + const values = Array.from(fixture.nativeElement.querySelectorAll('.select-value') as NodeListOf); + expect(values.map(e => e.textContent)).toContain('2025-S1, 2025-S2'); + expect(values.map(e => e.textContent)).toContain('Elegir periodos'); + fixture.componentRef.setInput('state', { + ...control.state, editors: { ...control.state.editors, semestre: { + added: ['2025-S1', '2025-S2'], draft: { mode: 'empty' }, + } }, + }); + fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); + expect(control.canApply).toBe(false); + expect(control.state.applied?.selection.mode).toBe('todos'); + expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true); + }); + 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'); + fixture.detectChanges(); + await Promise.resolve(); + const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!; + const model = select.injector.get(NgModel); + const writes = vi.spyOn(model.control, 'setValue'); + const edits = vi.spyOn(control.edited, 'emit'); + for (let i = 0; i < 4; i++) { + fixture.detectChanges(); + await Promise.resolve(); + } + expect(model.control.value).toEqual([]); + 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 () => { + 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 model = select.injector.get(NgModel); + const writes = vi.spyOn(model.control, 'setValue'); + for (let i = 0; i < 3; i++) { + select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable(); + expect(select.componentInstance.panelOpen).toBe(true); + select.componentInstance.close(); fixture.detectChanges(); await fixture.whenStable(); + expect(select.componentInstance.panelOpen).toBe(false); + } + expect(writes).not.toHaveBeenCalled(); + expect(control.entry.draft.mode).toBe('empty'); + expect(control.state.applied?.tipo).toBe('semestre'); + expect(control.canApply).toBe(false); + }); + it('normaliza el año y rechaza agregar duplicados', () => { + control.changeMode('manual'); + control.year = '1'; control.unit = 'S1'; control.add(); + expect(control.selectedPeriods).toEqual(['0001-S1']); + control.add(); + expect(control.error).toContain('ya está agregado'); + 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(); + expect(control.error).toContain('unidad válida'); expect(control.canApply).toBe(false); + }); + it.each(['00', '13', 'S1'])('rechaza unidad mensual %s', unit => { + control.changeTipo('mes'); control.year = '2025'; control.unit = unit; control.add(); + 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.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(); + control.unit = 'S2'; control.add(); + control.select(['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(); + expect(select.nativeElement.querySelector('button')).toBeNull(); + expect(fixture.nativeElement.textContent).toContain('Eliminar 2025-S2'); + fixture.nativeElement.querySelector('.remove button').click(); + fixture.detectChanges(); + expect(control.entry.draft.mode).toBe('empty'); + expect(fixture.nativeElement.querySelector('button[mat-flat-button]').disabled).toBe(true); + }); + 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(); + expect(edited).toHaveBeenCalledTimes(2); expect(apply).not.toHaveBeenCalled(); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar'); + expect(fixture.nativeElement.textContent).toContain('no es un inventario de reportes'); + expect(fixture.nativeElement.textContent).toContain('Filtro general aplicado: Todos con reporte'); + 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'); + }); +}); diff --git a/src/app/features/indicadores/indicador-period-filters.ts b/src/app/features/indicadores/indicador-period-filters.ts new file mode 100644 index 0000000..170abce --- /dev/null +++ b/src/app/features/indicadores/indicador-period-filters.ts @@ -0,0 +1,83 @@ +import { Component, EventEmitter, Input, Output, OnChanges } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { MatSelectModule } from '@angular/material/select'; +import { parsePeriodos, TipoPeriodo } from './indicadores.models'; +import { PeriodAvailability } from './indicadores-periodos'; +import { describePeriods, newEditor, FilterState, pending, validDraft } from './indicadores-memory'; + +@Component({ + selector: 'app-indicador-period-filters', + imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule], + templateUrl: './indicador-period-filters.html', + styleUrl: './indicador-period-filters.scss', +}) +export class IndicadorPeriodFilters implements OnChanges { + @Input({ required: true }) state!: FilterState; + @Input({ required: true }) types!: TipoPeriodo[]; + @Input() availability?: PeriodAvailability; + @Input() initialPresentation = false; + @Output() retryAvailability = new EventEmitter(); + @Output() edited = new EventEmitter(); + @Output() apply = new EventEmitter(); + year = ''; + unit = ''; + error = ''; + readonly months = Array.from({ length: 12 }, (_, i) => String(i + 1).padStart(2, '0')); + 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. + 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; } + get unavailableSelection() { return this.selectedPeriods.filter(p => !this.options.includes(p)); } + get canApply() { + return validDraft(this.entry.draft, this.state.tipo, this.types) + && (!this.availability || this.entry.draft.mode === 'todos' + || (this.availability.status === 'ready' && !this.unavailableSelection.length)); + } + 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'; } + 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 = ''; + 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(); + } + select(values: string[]) { + const unique = [...new Set(values)]; + 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(); + } + add() { + this.error = ''; + const year = /^\d{1,4}$/.test(this.year) ? this.year.padStart(4, '0') : ''; + const period = year + '-' + this.unit; + if (!parsePeriodos(period, this.state.tipo)) { + this.error = 'Introduce un año entre 0001 y 9999 y una unidad válida.'; + 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]); + } + 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(); + } +} diff --git a/src/app/features/indicadores/indicadores-axis-labels.spec.ts b/src/app/features/indicadores/indicadores-axis-labels.spec.ts new file mode 100644 index 0000000..24ace9f --- /dev/null +++ b/src/app/features/indicadores/indicadores-axis-labels.spec.ts @@ -0,0 +1,230 @@ +import { abbreviateCategories, categoryMinimumWidth } from './indicadores-axis-labels'; +import { FigureSelection, PlotlyFigure } from './indicadores.models'; +import { figurePresentation } from './indicadores.presentation'; +import { BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE, READABLE_VISUAL_PROFILE } from './indicadores-visual-profile'; + +const selection: FigureSelection = { dominio: 'tea', indicador: 'synthetic', figura: 'fig_c1_grupos', tema: 'claro' }; +const long = 'Fármaco de riesgo para el neurodesarrollo'; +const hover = '2025-S1
%{x}
%{y:.1f}% (%{customdata[0]} de %{customdata[1]})'; +function source(): PlotlyFigure { + return { data: [{ type: 'scatter', mode: 'markers', x: [long, 'Otra'], y: [20, null], + customdata: [[2, 10], [null, 'SUPRIMIDO']], error_y: { array: [5, null] }, hovertemplate: hover, + future: { keep: true } }], layout: { xaxis: { type: 'category', categoryorder: 'array', categoryarray: [long, 'Otra'], future: 7 }, + yaxis: { range: [0, 100] }, margin: { b: 150 }, annotations: [{ text: 'Nota desconocida', y: -0.3 }] }, + config: { displaylogo: false }, future: { keep: [null, 0] } }; +} +const present = (figure: PlotlyFigure) => figurePresentation(figure, selection, READABLE_VISUAL_PROFILE); +function freezeDeep(value: unknown) { + if (value && typeof value === 'object') { Object.values(value).forEach(freezeDeep); Object.freeze(value); } +} + +describe('UX-07C etiquetas de ejes', () => { + it('UX-07D reserva espacio para las cinco áreas cortas sin perder ticks ni modificar observaciones', () => { + const figure: PlotlyFigure = { data: [{ type: 'bar', name: 'Desarrollo adecuado', x: ['Cognoscitivo', 'Lingüístico', 'Físico', 'Socioemocional', 'Adaptativo'], y: [20, null, 0, 40, 60] }], + layout: { xaxis: {}, margin: { l: 60, r: 30 } } }; + const before = structuredClone(figure); freezeDeep(figure); + const result = figurePresentation(figure, { ...selection, figura: 'fig_c2_apiladas' }, READABLE_VISUAL_PROFILE, 253); + expect(result.minimumPlotWidth).toBeGreaterThan(253); + expect(result.figure.layout['xaxis']).toMatchObject({ type: 'category', tickmode: 'linear', dtick: 1, automargin: true }); + expect(result.figure.data).toEqual(before.data); expect(figure).toEqual(before); + expect(figurePresentation(figure, selection, BASE_VISUAL_PROFILE, 253).minimumPlotWidth).toBeUndefined(); + expect(figurePresentation(figure, { ...selection, dominio: 'cacu' }, READABLE_VISUAL_PROFILE, 253).minimumPlotWidth).toBeUndefined(); + expect(figurePresentation(figure, selection, READABLE_VISUAL_PROFILE, result.minimumPlotWidth).minimumPlotWidth).toBe(result.minimumPlotWidth); + }); + it('UX-07D mantiene todos los pares semestre/área con un mínimo estable y sin ticks simples', () => { + const figure: PlotlyFigure = { data: [{ type: 'bar', x: [Array(5).fill('2025-S1').concat(Array(5).fill('2025-S2')), + ['Cognoscitivo', 'Lingüístico', 'Físico', 'Socioemocional', 'Adaptativo', 'Cognoscitivo', 'Lingüístico', 'Físico', 'Socioemocional', 'Adaptativo']], y: Array(10).fill(null) }], layout: { xaxis: {} } }; + const before = structuredClone(figure); + const result = figurePresentation(figure, { ...selection, figura: 'fig_c2_apiladas' }, READABLE_VISUAL_PROFILE, 253); + expect(result.minimumPlotWidth).toBeGreaterThan(253); + expect(result.figure.layout['xaxis']).toEqual({}); expect(result.figure.data).toEqual(before.data); + expect(figure).toEqual(before); + }); + it('UX-07D no reserva ancho en estructuras desconocidas, ejes numéricos, notas sin reconocer o dimensiones fijas', () => { + const base: PlotlyFigure = { data: [{ type: 'bar', x: ['A', 'B', 'C'], y: [0, null, 20] }], layout: { xaxis: { type: 'category' } } }; + for (const layout of [{ width: 700 }, { autosize: false }, { xaxis2: {} }, { annotations: [{ text: 'Advertencia desconocida' }] }, { xaxis: { type: 'date' } }, { template: { layout: { xaxis: { tickvals: ['A'] } } } }]) { + expect(categoryMinimumWidth({ ...base, layout: { ...base.layout, ...layout } })).toBeUndefined(); + } + expect(categoryMinimumWidth({ ...base, data: [{ type: 'box', x: ['A', 'B', 'C'], y: [0, null, 20] }] })).toBeUndefined(); + expect(categoryMinimumWidth({ ...base, frames: [{}] })).toBeUndefined(); + }); + it('deja las etiquetas cortas intactas y abrevia por palabras sólo las extensas', () => { + expect([...abbreviateCategories(['Corta', long], 22)]).toEqual([['Corta', 'Corta'], [long, 'Fármaco de riesgo…']]); + const result = present(source()); + expect(result.figure.layout['xaxis']).toMatchObject({ tickvals: [long, 'Otra'], ticktext: ['Fármaco de riesgo…', 'Otra'], + categoryarray: [long, 'Otra'], categoryorder: 'array', future: 7, automargin: true }); + expect(result.categoryLabels).toEqual([{ axis: 'x', original: long, abbreviated: 'Fármaco de riesgo…' }]); + }); + it('sin etiquetas extensas no crea ticks ni cambia el hover', () => { + const figure = source(); figure.data[0]['x'] = ['Corta', 'Otra']; figure.layout['xaxis'] = { type: 'category' }; + expect(present(figure).figure.data).toEqual(figure.data); + expect(present(figure).figure.layout['xaxis']).toEqual(figure.layout['xaxis']); + expect(present(figure).categoryLabels).toEqual([]); + }); + it('conserva etiquetas completas cuando hay ancho suficiente y abrevia al estrechar la misma figura', () => { + const figure = source(), before = structuredClone(figure); + const spacious = figurePresentation(figure, selection, READABLE_VISUAL_PROFILE, 1400); + expect(spacious.categoryLabels).toEqual([]); expect(spacious.figure.data).toEqual(before.data); + expect(spacious.figure.layout['xaxis']).toEqual(before.layout['xaxis']); + expect(figurePresentation(figure, selection, READABLE_VISUAL_PROFILE, 320).categoryLabels).toHaveLength(1); + expect(figurePresentation(figure, selection, { axisLabels: { enabled: true, preserveWhenFits: false } }, 1400).categoryLabels).toHaveLength(1); + expect(figure).toEqual(before); + }); + it('acota la ampliación tipográfica opcional en tarjetas estrechas sin cambiar la fuente original ni el perfil amplio', () => { + const figure = source(); figure.layout['font'] = { size: 13, future: true }; + const profile = { ...DEMO_VISUAL_PROFILE, ...READABLE_VISUAL_PROFILE }; + expect(figurePresentation(figure, selection, profile, 270).figure.layout['font']).toMatchObject({ size: 12, future: true }); + expect(figurePresentation(figure, selection, profile, 646).figure.layout['font']).toMatchObject({ size: 15 }); + expect(figure.layout['font']).toEqual({ size: 13, future: true }); + }); + it('las colisiones y las abreviaciones iguales a otra categoría vuelven al original', () => { + const a = 'Fármaco de riesgo para el neurodesarrollo', b = 'Fármaco de riesgo para otra condición'; + const labels = abbreviateCategories([a, b, 'Fármaco de riesgo…'], 22); + expect([...labels.values()]).toEqual([a, b, 'Fármaco de riesgo…']); + expect(new Set(labels.values()).size).toBe(labels.size); + }); + it('deduplica la correspondencia sin retirar puntos duplicados', () => { + const figure = source(); figure.data[0]['x'] = [long, long]; + const result = present(figure); + expect(result.categoryLabels).toHaveLength(1); + expect(result.figure.data[0]['x']).toEqual([long, long]); + expect((result.figure.layout['xaxis'] as Record)['tickvals']).toEqual([long, 'Otra']); + }); + it('conserva grafemas Unicode, acentos, símbolos y palabras indivisibles', () => { + const value = 'Área 👩🏽‍⚕️ y comunicación extensa'; + expect(abbreviateCategories([value], 12).get(value)).toBe('Área 👩🏽‍⚕️ y…'); + const word = 'Neurodesarrollosuperextenso'; + expect(abbreviateCategories([word], 10).get(word)).toBe(word); + expect(abbreviateCategories([word], 10, false).get(word)).toBe('Neurodesa…'); + const symbol = 'Área α ± lenguaje y comunicación'; + expect(abbreviateCategories([symbol], 12).get(symbol)).toBe('Área α ±…'); + }); + it('preserva profundamente el original, datos, customdata, anotaciones, configuración y atributos desconocidos', () => { + const figure = source(), before = structuredClone(figure); freezeDeep(figure); + const result = present(figure); + expect(figure).toEqual(before); + const { hovertemplate: ignored, ...observations } = result.figure.data[0]; + const { hovertemplate: originalHover, ...originalObservations } = before.data[0]; + expect(observations).toEqual(originalObservations); + expect(result.figure.data[0]).not.toBe(figure.data[0]); + expect(result.figure.layout['annotations']).toEqual(before.layout['annotations']); + expect(result.figure.layout['margin']).toEqual(before.layout['margin']); + expect(result.figure.config).toEqual(before.config); expect(result.figure['future']).toEqual(before['future']); + }); + it('restituye exclusivamente la categoría en hover y conserva porcentajes, intervalos y conteos', () => { + const figure = source(); figure.data[0]['hovertemplate'] = hover.replace('', '
IC %{error_y.array}'); + const result = present(figure); + expect(result.figure.data[0]['hovertemplate']).toEqual([long, 'Otra'].map(label => + (figure.data[0]['hovertemplate'] as string).replace('%{x}', label))); + expect(figure.data[0]['hovertemplate']).toContain('%{x}'); + }); + it('conserva símbolos de reemplazo y ampersands como texto literal en el hover', () => { + const figure = source(), label = 'Área $& y salud & comunicación extensa'; + figure.data[0]['x'] = [label, 'Otra']; + expect((present(figure).figure.data[0]['hovertemplate'] as string[])[0]).toBe(hover.replace('%{x}', () => label.replaceAll('&', '&'))); + }); + it.each([NaN, 0, 7, 81, 20.5])('opciones inválidas conservan los ejes: %s', maxCharacters => { + const figure = source(); + const result = figurePresentation(figure, selection, { axisLabels: { enabled: true, maxCharacters } }); + expect(result.figure.data).toEqual(figure.data); expect(result.categoryLabels).toEqual([]); + }); + it('conserva plantillas por punto, hovertext, hoverinfo y contenido suprimido sin exponer valores', () => { + const figure = source(); figure.data[0]['hovertemplate'] = [hover, '%{x}
dato suprimido (conteo bajo)']; + figure.data[0]['hovertext'] = ['Observación publicada', 'SUPRIMIDO']; figure.data[0]['hoverinfo'] = 'text'; + const result = present(figure).figure.data[0]; + expect((result['hovertemplate'] as string[])[1]).toBe('Otra
dato suprimido (conteo bajo)'); + expect((result['hovertemplate'] as string[])[1]).not.toMatch(/customdata|%\{y|20|0 %/); + expect(result['hovertext']).toEqual(figure.data[0]['hovertext']); expect(result['customdata']).toEqual(figure.data[0]['customdata']); + expect(result['hoverinfo']).toBe('text'); expect(result['y']).toEqual([20, null]); + }); + it.each([undefined, '%{x:.2f}
%{y}', '%{customdata[0]}', ['%{x}'], ['%{x}', null]])('fallback de hover desconocido o incompatible: %j', template => { + const figure = source(); figure.data[0]['hovertemplate'] = template; + expect(present(figure).figure.data).toEqual(figure.data); + expect(present(figure).figure.layout['xaxis']).toEqual(figure.layout['xaxis']); + expect(present(figure).categoryLabels).toEqual([]); + }); + it.each(['linear', 'date', 'log', 'multicategory'])('no adapta un eje simple declarado %s', type => { + const figure = source(); figure.layout['xaxis'] = { type }; + expect(present(figure).figure.data).toEqual(figure.data); + expect(present(figure).figure.layout['xaxis']).toEqual({ type }); + }); + it.each(['2025-01', '2025-S1', '2025-10-14T14:00:00', 'Primer semestre del año 2025', '1234567890123456789012345'])('no abrevia fechas, periodos ni texto numérico: %s', label => { + expect(abbreviateCategories([label], 8).get(label)).toBe(label); + }); + it.each([{ ticktext: ['Alias'] }, { tickmode: 'auto' }, { labelalias: { [long]: 'Alias' } }, { range: [0, 2] }, + { showticklabels: false }, { tickprefix: 'Grupo: ' }, { matches: 'x2' }])('respeta ticks/semántica explícita del eje: %j', axis => { + const figure = source(); figure.layout['xaxis'] = { type: 'category', ...axis }; + expect(present(figure).figure.layout['xaxis']).toEqual(figure.layout['xaxis']); + }); + it('respeta ticks heredados de una plantilla y una orientación publicada', () => { + const figure = source(); figure.layout['template'] = { layout: { xaxis: { ticktext: ['Alias'] } } }; + expect(present(figure).categoryLabels).toEqual([]); + delete figure.layout['template']; (figure.layout['xaxis'] as Record)['tickangle'] = 30; + expect(present(figure).figure.layout['xaxis']).toMatchObject({ tickangle: 30 }); + }); + it('soporta barras horizontales sin cambiar categorías Y ni valores X', () => { + const figure: PlotlyFigure = { data: [{ type: 'bar', orientation: 'h', y: [long], x: [0], customdata: [null], + hovertemplate: '%{y}
%{x:.1f}%' }], layout: { yaxis: { type: 'category' } } }; + const result = present(figure); + expect(result.figure.layout['yaxis']).toMatchObject({ ticktext: ['Fármaco de riesgo…'], tickvals: [long] }); + expect(result.figure.data[0]['x']).toEqual([0]); expect(result.figure.data[0]['y']).toEqual([long]); + expect(result.figure.data[0]['hovertemplate']).toEqual([long + '
%{x:.1f}%']); + }); + it('multicategoría conserva niveles, periodos, agrupación, hover y reserva de margen', () => { + const figure = source(); figure.data[0]['type'] = 'bar'; figure.data[0]['x'] = [['2025-S1', '2025-S2'], [long, long]]; + figure.layout['xaxis'] = { type: 'multicategory', future: true }; + const result = present(figure); + expect(result.figure.data).toEqual(figure.data); expect(result.categoryLabels).toEqual([]); + expect(result.figure.layout['xaxis']).toEqual({ type: 'multicategory', future: true, automargin: true, tickfont: { size: 11 } }); + expect(result.figure.layout['margin']).toEqual(figure.layout['margin']); + const preserve = figurePresentation(figure, selection, { axisLabels: { enabled: true, multicategory: 'preserve' } }); + expect(preserve.figure.layout['xaxis']).toEqual(figure.layout['xaxis']); + }); + it.each([{ levels: [['2025-S1'], [long, long]] }, { levels: [['Grupo', 'Grupo'], [long, long]] }, + { levels: [['2025-S1', '2025-S2'], [long, long], ['a', 'b']] }])('preserva multicategorías no validadas: %j', ({ levels }) => { + const figure = source(); figure.data[0]['x'] = levels; figure.layout['xaxis'] = { type: 'multicategory' }; + expect(present(figure).figure.layout['xaxis']).toEqual(figure.layout['xaxis']); + expect(present(figure).figure.data).toEqual(figure.data); + }); + it.each(['pie', 'box', 'heatmap', 'future'])('conserva familias incompatibles: %s', type => { + const figure = source(); figure.data[0]['type'] = type; + expect(present(figure).categoryLabels).toEqual([]); expect(present(figure).figure.data).toEqual(figure.data); + }); + it('conserva frames/menús/subplots y no infiere identidades o HTML', () => { + for (const extra of [{ frames: [{ name: 'f', data: [{ x: [long] }], future: 3 }] }, + { layout: { ...source().layout, updatemenus: [] } }, { layout: { ...source().layout, xaxis2: {} } }]) { + const figure = { ...source(), ...extra }, before = structuredClone(figure); + expect(present(figure).figure.data).toEqual(before.data); expect(present(figure).figure.frames).toEqual(before.frames); + expect(present(figure).categoryLabels).toEqual([]); + } + for (const label of ['Texto extenso publicado', 'Área & texto extenso', 'Área %{customdata} muy extensa']) { + const figure = source(); figure.data[0]['x'] = [label, 'Otra']; + expect(present(figure).categoryLabels).toEqual([]); + } + }); + it('revierte al perfil base desde el original y combina el perfil de demostración sin acumulación', () => { + const figure = source(), original = structuredClone(figure); + const compact = present(figure); compact.figure.data[0]['x'] = ['mutación del runtime']; + const restored = figurePresentation(figure, selection, BASE_VISUAL_PROFILE); + expect(restored.figure.data).toEqual(original.data); expect(restored.categoryLabels).toEqual([]); + expect(restored.figure.layout['xaxis']).toEqual(original.layout['xaxis']); + const demo = figurePresentation(figure, selection, { ...DEMO_VISUAL_PROFILE, ...READABLE_VISUAL_PROFILE }); + expect(demo.figure.layout['paper_bgcolor']).toBe('#f2f7fc'); expect(demo.categoryLabels).toHaveLength(1); + expect(figure).toEqual(original); + }); + it('extrae el pie TEA sin perder el mapa de categorías ni alterar anotaciones desconocidas', () => { + const figure = source(); figure.layout['annotations'] = [{ + text: 'Nota sintética.
Base depurada del proyecto TEA · Centro Médico ISSSTELEÓN – UANL · Fecha de corte: 2025-08-01
Uso exclusivo de investigación. No usar para decisiones clínicas.', + xref: 'paper', yref: 'paper', x: 0, y: -0.22, xanchor: 'left', yanchor: 'top', align: 'left', showarrow: false, font: { size: 11 }, + }]; + const result = present(figure); + expect(result.footnotes).toHaveLength(1); expect(result.figure.layout['annotations']).toEqual([]); + expect(result.categoryLabels[0].original).toBe(long); + }); + it.each(['cacu', 'cama'] as const)('mantiene la adaptación mensual %s con el perfil legible', dominio => { + const figure: PlotlyFigure = { data: [{ type: 'scatter', mode: 'markers', x: ['2025-03', '2025-01'], y: [null, 0], hovertemplate: hover }], layout: {} }; + const result = figurePresentation(figure, { ...selection, dominio, figura: 'fig_c1_puntos', tipoPeriodo: 'mes' }, READABLE_VISUAL_PROFILE); + expect(result.figure.layout['xaxis']).toMatchObject({ categoryarray: ['2025-01', '2025-03'], ticktext: ['2025-01', '2025-03'] }); + expect(result.figure.data).toEqual(figure.data); expect(result.categoryLabels).toEqual([]); + }); +}); diff --git a/src/app/features/indicadores/indicadores-axis-labels.ts b/src/app/features/indicadores/indicadores-axis-labels.ts new file mode 100644 index 0000000..42de694 --- /dev/null +++ b/src/app/features/indicadores/indicadores-axis-labels.ts @@ -0,0 +1,191 @@ +import { PlotlyFigure } from './indicadores.models'; +import { AxisLabelOptions } from './indicadores-visual-profile'; + +export interface CategoryLabel { + readonly axis: 'x' | 'y'; + readonly abbreviated: string; + readonly original: string; +} + +const graphemes = new Intl.Segmenter('es', { granularity: 'grapheme' }); +const characters = (text: string) => [...graphemes.segment(text)].map(part => part.segment); +function record(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} +function plainLabel(value: unknown): value is string { + return typeof value === 'string' && value.trim().length > 0 + && !/[<>]|&(?:#\d+|#x[\da-f]+|[a-z][\da-z]*);|%\{/i.test(value); +} +function temporalOrNumeric(value: string): boolean { + // Conservative: published years, dates, semester/month codes and numeric text. + return /(?:^|\D)\d{4}(?:\D|$)/u.test(value) || /^[\d\s.,+−\-/%:]+$/u.test(value) + || /^(?:S[12]|T[1-4]|Q[1-4]|\d{1,2}[-/]\d{1,2})$/iu.test(value); +} + +/** A collision falls back to the original; identical categories share one label. */ +export function abbreviateCategories(values: readonly string[], limit: number, preferWords = true): Map { + const originals = [...new Set(values)]; + const labels = new Map(originals.map(value => { + if (temporalOrNumeric(value) || characters(value).length <= limit) return [value, value]; + let prefix = characters(value).slice(0, limit - 1).join(''); + if (preferWords && !/^\s/u.test(characters(value)[limit - 1] ?? '')) { + const boundary = prefix.search(/\s+\S*$/u); + if (boundary < 1) return [value, value]; // Do not split an indivisible word. + prefix = prefix.slice(0, boundary); + } + return [value, prefix.trimEnd() + '…']; + })); + const counts = new Map(); + for (const label of labels.values()) counts.set(label, (counts.get(label) ?? 0) + 1); + for (const [original, label] of labels) { + if ((counts.get(label) ?? 0) > 1 || (label !== original && labels.has(label))) labels.set(original, original); + } + return labels; +} + +function templates(trace: Record, coordinate: 'x' | 'y', size: number): string[] | undefined { + const template = trace['hovertemplate']; + const list = typeof template === 'string' ? Array(size).fill(template) + : Array.isArray(template) && template.length === size ? template : undefined; + // Do not reconstruct default hovers, formatted coordinates, expressions, or + // templates whose category is in a different field. Preserve those axes. + return list?.every(text => typeof text === 'string' && text.includes(`%{${coordinate}}`) + && !text.includes(`%{${coordinate}:`) && !text.includes(`%{${coordinate}|`)) ? list : undefined; +} + +// Keep dense categories readable inside the existing keyboard-scrollable plot +// viewport. The minimum is independent of the measured host width, preventing +// ResizeObserver feedback when the host grows to this minimum. +export function categoryMinimumWidth(figure: PlotlyFigure): number | undefined { + const published = figure.layout['xaxis']; + const template = figure.layout['template']; + const templateLayout = record(template) && record(template['layout']) ? template['layout'] : {}; + const axis = { ...(record(templateLayout['xaxis']) ? templateLayout['xaxis'] : {}), ...(record(published) ? published : {}) }; + if ((published !== undefined && !record(published)) || (axis['type'] !== undefined && !['category', 'multicategory'].includes(String(axis['type']))) + || figure.frames?.length || figure.layout['width'] !== undefined || figure.layout['autosize'] === false + || ['annotations', 'shapes', 'images', 'sliders', 'updatemenus'].some(key => { + const value = figure.layout[key]; return value !== undefined && (!Array.isArray(value) || value.length > 0); + }) || Object.keys(figure.layout).some(key => /^[xy]axis\d+$/.test(key)) + || ['tickvals', 'ticktext', 'tickmode', 'dtick', 'tick0', 'range', 'matches', 'overlaying', 'ticklabelstep'].some(key => axis[key] !== undefined) + || !figure.data.length) return undefined; + const multi = figure.data.some(trace => Array.isArray(trace['x']) && trace['x'].some(Array.isArray)); + if ((multi && axis['type'] === 'category') || (!multi && axis['type'] === 'multicategory')) return undefined; + const positions: string[] = []; + for (const trace of figure.data) { + if (!['scatter', 'bar'].includes(String(trace['type'])) || trace['orientation'] === 'h' + || ['transforms', 'xsrc', 'ysrc'].some(key => trace[key] !== undefined) + || (trace['xaxis'] !== undefined && trace['xaxis'] !== 'x') || (trace['yaxis'] !== undefined && trace['yaxis'] !== 'y') + || !Array.isArray(trace['x']) || !Array.isArray(trace['y'])) return undefined; + const x = trace['x'] as unknown[], y = trace['y'] as unknown[]; + if (y.some(value => value !== null && typeof value !== 'number')) return undefined; + if (multi) { + if (trace['type'] !== 'bar' || x.length !== 2 || !x.every(Array.isArray) + || x.some(level => level.length !== y.length) || !(x[0] as unknown[]).every(value => typeof value === 'string' && /^\d{4}-S[12]$/.test(value)) + || !(x[1] as unknown[]).every(plainLabel)) return undefined; + (x[0] as string[]).forEach((period, index) => positions.push(JSON.stringify([period, (x[1] as string[])[index]]))); + } else { + if (x.length !== y.length || !x.every(plainLabel) || x.some(temporalOrNumeric)) return undefined; + positions.push(...x as string[]); + } + } + const count = new Set(positions).size; + if (count < 3) return undefined; + const font = record(figure.layout['font']) ? figure.layout['font'] : {}; + const tickfont = record(axis['tickfont']) ? axis['tickfont'] : font; + const size = typeof tickfont['size'] === 'number' ? tickfont['size'] : 12; + const legend = record(figure.layout['legend']) ? figure.layout['legend'] : {}; + const legendWidth = figure.layout['showlegend'] === false || legend['orientation'] === 'h' ? 0 + : Math.max(0, ...figure.data.filter(trace => trace['showlegend'] !== false).map(trace => + characters(String(trace['name'] ?? '')).length * 7 + 48)); + const margin = record(figure.layout['margin']) ? figure.layout['margin'] : {}; + return Math.ceil(count * Math.max(20, size * 1.8) + legendWidth + + (typeof margin['l'] === 'number' ? margin['l'] : 80) + + (typeof margin['r'] === 'number' ? margin['r'] : 80)); +} + +/** Mutates only the independent presentation clone supplied by figurePresentation. */ +export function applyAxisLabels(figure: PlotlyFigure, options?: AxisLabelOptions, availableWidth?: number): CategoryLabel[] { + const result: CategoryLabel[] = []; + const limit = options?.maxCharacters ?? 22; + if (!options?.enabled || !Number.isInteger(limit) || limit < 8 || limit > 80 || figure.frames?.length + || figure.layout['updatemenus'] !== undefined || figure.layout['sliders'] !== undefined) return result; + // Multiple/linked axes and subplots require an explicit mapping contract. + if (Object.keys(figure.layout).some(key => /^[xy]axis\d+$/.test(key))) return result; + for (const coordinate of ['x', 'y'] as const) { + const axisKey = `${coordinate}axis`, other = coordinate === 'x' ? 'y' : 'x'; + const published = figure.layout[axisKey]; + if (published !== undefined && !record(published)) continue; + const axis = record(published) ? published : {}; + const templateLayout = record(figure.layout['template']) ? figure.layout['template']['layout'] : undefined; + const templateAxis = record(templateLayout) && record(templateLayout[axisKey]) ? templateLayout[axisKey] : {}; + const effective = { ...templateAxis, ...axis }; + if (['tickvals', 'ticktext', 'tickmode', 'labelalias', 'tickformat', 'tickprefix', 'ticksuffix', 'dtick', 'tick0', + 'ticklabelstep', 'range', 'matches', 'overlaying', 'ticklabelindex'].some(key => effective[key] !== undefined) + || effective['showticklabels'] === false) continue; + const traces = figure.data; + if (!traces.length || traces.some(trace => !['scatter', 'bar'].includes(String(trace['type'])) + || (trace[axisKey] !== undefined && trace[axisKey] !== coordinate) + || ['transforms', 'hovertemplatesrc', `${coordinate}src`].some(key => trace[key] !== undefined) + || !Array.isArray(trace[coordinate]) || !Array.isArray(trace[other]) + || (trace[other] as unknown[]).some(value => value !== null && typeof value !== 'number'))) continue; + const arrays = traces.map(trace => trace[coordinate] as unknown[]); + const fits = (values: readonly string[], count: number): boolean => { + if (coordinate !== 'x' || options.preserveWhenFits === false || !Number.isFinite(availableWidth) || !count) return false; + const margin = record(figure.layout['margin']) ? figure.layout['margin'] : {}; + const font = record(effective['tickfont']) ? effective['tickfont'] + : record(figure.layout['font']) ? figure.layout['font'] : {}; + const fontSize = typeof font['size'] === 'number' ? font['size'] : 12; + const textWidth = (text: string) => characters(text).reduce((size, char) => size + + fontSize * (/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Extended_Pictographic}]/u.test(char) ? 1.1 : 0.58), 0); + const legend = record(figure.layout['legend']) ? figure.layout['legend'] : {}; + const legendSize = figure.layout['showlegend'] === false || legend['orientation'] === 'h' ? 0 + : Math.max(0, ...traces.filter(trace => trace['showlegend'] !== false).map(trace => + textWidth(String(trace['name'] ?? '')) + 40)); + const width = availableWidth! - (typeof margin['l'] === 'number' ? margin['l'] : 80) + - (typeof margin['r'] === 'number' ? margin['r'] : 80) - legendSize; + // A conservative estimate with padding; no SVG measurements or font loads. + return values.every(value => textWidth(value) + 16 <= width / count); + }; + const multi = arrays.some(values => values.some(Array.isArray)); + if (multi) { + // Plotly 4.1.2 does not safely map tickvals/ticktext to both levels. + // Keep every published coordinate, grouping, period and hover unchanged. + if (coordinate !== 'x' || options.multicategory !== 'fit' || traces.some(trace => trace['type'] !== 'bar') + || (effective['type'] !== undefined && effective['type'] !== 'multicategory') + || arrays.some((levels, i) => levels.length !== 2 || !levels.every(Array.isArray) + || (levels[0] as unknown[]).length !== (levels[1] as unknown[]).length + || (levels[0] as unknown[]).length !== (traces[i][other] as unknown[]).length + || !(levels[0] as unknown[]).every(value => typeof value === 'string' && /^\d{4}-S[12]$/.test(value)) + || !(levels[1] as unknown[]).every(plainLabel)) + || !arrays.some(levels => (levels[1] as string[]).some(value => characters(value).length > limit))) continue; + if (fits(arrays.flatMap(levels => levels[1] as string[]), Math.max(...arrays.map(levels => (levels[1] as string[]).length)))) continue; + const font = record(effective['tickfont']) ? effective['tickfont'] : {}; + figure.layout[axisKey] = { ...axis, automargin: true, + tickfont: { ...font, size: Math.min(typeof font['size'] === 'number' ? font['size'] : 12, 11) } }; + continue; + } + if ((effective['type'] !== undefined && effective['type'] !== 'category') + || arrays.some((values, i) => values.length !== (traces[i][other] as unknown[]).length || !values.every(plainLabel))) continue; + const order = effective['categoryarray']; + if (order !== undefined && (!Array.isArray(order) || !order.every(plainLabel))) continue; + const values = [...new Set([...(Array.isArray(order) ? order as string[] : []), ...arrays.flat() as string[]])]; + if (fits(values, values.length)) continue; + const labels = abbreviateCategories(values, limit, options.preferWords ?? true); + if (![...labels].some(([original, label]) => original !== label)) continue; + const hoverTemplates = traces.map((trace, i) => templates(trace, coordinate, arrays[i].length)); + if (hoverTemplates.some(value => value === undefined)) continue; + // Only the bare coordinate token changes, per point. All statistical and + // suppression tokens/text remain exactly as published; no customdata added. + traces.forEach((trace, i) => { + trace['hovertemplate'] = hoverTemplates[i]!.map((template, j) => template.replaceAll( + `%{${coordinate}}`, () => (arrays[i][j] as string).replaceAll('&', '&'))); + }); + figure.layout[axisKey] = { ...axis, type: 'category', tickmode: 'array', tickvals: values, + ticktext: values.map(value => labels.get(value)!), automargin: true, + ...(effective['tickangle'] === undefined ? { tickangle: coordinate === 'x' ? -60 : 0 } : {}) }; + for (const [original, abbreviated] of labels) { + if (original !== abbreviated) result.push({ axis: coordinate, original, abbreviated }); + } + } + return result; +} diff --git a/src/app/features/indicadores/indicadores-catalog-contract.spec.ts b/src/app/features/indicadores/indicadores-catalog-contract.spec.ts new file mode 100644 index 0000000..29da740 --- /dev/null +++ b/src/app/features/indicadores/indicadores-catalog-contract.spec.ts @@ -0,0 +1,22 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { IndicadoresService } from './indicadores.service'; +describe('UX-05B contrato de figuras del catálogo', () => { + it.each([{ figuras: [] }, { figuras: ['f'] }, { figuras: ['f', 'g'] }])('acepta figuras publicadas $figuras', ({ figuras }) => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + const http = TestBed.inject(HttpTestingController); + let actual: unknown; + TestBed.inject(IndicadoresService).catalogo('tea').subscribe(value => actual = value); + const items = [{ id: 'i', titulo: 'I', contrato: 'C1', figuras, tipos_periodo: ['mes'] }]; + http.expectOne('/tea/indicadores').flush(items); expect(actual).toEqual(items); http.verify(); + }); + it('rechaza figuras duplicadas dentro de un indicador', () => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + const http = TestBed.inject(HttpTestingController); + let error: unknown; let emitted = false; + TestBed.inject(IndicadoresService).catalogo('tea').subscribe({ next: () => emitted = true, error: e => error = e }); + http.expectOne('/tea/indicadores').flush([{ id: 'i', titulo: 'I', contrato: 'C1', figuras: ['f', 'f'], tipos_periodo: ['mes'] }]); + expect(error).toBeInstanceOf(Error); expect(emitted).toBe(false); http.verify(); + }); +}); diff --git a/src/app/features/indicadores/indicadores-figure-labels.spec.ts b/src/app/features/indicadores/indicadores-figure-labels.spec.ts new file mode 100644 index 0000000..1e6db48 --- /dev/null +++ b/src/app/features/indicadores/indicadores-figure-labels.spec.ts @@ -0,0 +1,28 @@ +import { figureDisplayName } from './indicadores-figure-labels'; + +describe('UX-07A nombres de representaciones', () => { + it.each([ + ['fig_c1_grupos', 'Grupos'], + ['fig_c1_puntos', 'Puntos'], + ['fig_c2_apiladas', 'Barras apiladas'], + ['fig_c2_barras', 'Barras'], + ['fig_c2_donas', 'Donas'], + ['fig_c3r_caja', 'Caja de cuartiles'], + ])('presenta %s como %s', (id, label) => { + expect(figureDisplayName(id, [id])).toBe(label); + }); + + it('no infiere tipos por prefijo y distingue opciones desconocidas en orden de publicación', () => { + const figures = ['fig_c1_grupos', 'fig_c1_futura', 'fig_c2_futura']; + const snapshot = [...figures]; + expect(figureDisplayName(figures[1], figures)).toBe('Representación 2'); + expect(figureDisplayName(figures[2], figures)).toBe('Representación 3'); + expect(figureDisplayName(figures[1], [...figures])).toBe('Representación 2'); + expect(figures).toEqual(snapshot); + }); + + it('no usa propiedades heredadas ni revela IDs ajenos al catálogo', () => { + expect(figureDisplayName('constructor', ['constructor'])).toBe('Representación 1'); + expect(figureDisplayName('sin_publicar', [])).toBe('Representación adicional'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-figure-labels.ts b/src/app/features/indicadores/indicadores-figure-labels.ts new file mode 100644 index 0000000..46c48dd --- /dev/null +++ b/src/app/features/indicadores/indicadores-figure-labels.ts @@ -0,0 +1,17 @@ +// Presentation labels for representations confirmed in the published catalog. +// Exact IDs remain the option values and HTTP identities; never infer a type +// from a prefix. Unknown options keep a neutral label in publication order. +const FIGURE_LABELS: Readonly> = { + fig_c1_grupos: 'Grupos', + fig_c1_puntos: 'Puntos', + fig_c2_apiladas: 'Barras apiladas', + fig_c2_barras: 'Barras', + fig_c2_donas: 'Donas', + fig_c3r_caja: 'Caja de cuartiles', +}; + +export function figureDisplayName(figureId: string, publishedFigures: readonly string[]): string { + if (Object.hasOwn(FIGURE_LABELS, figureId)) return FIGURE_LABELS[figureId]; + const index = publishedFigures.indexOf(figureId); + return index >= 0 ? `Representación ${index + 1}` : 'Representación adicional'; +} diff --git a/src/app/features/indicadores/indicadores-global-filters.spec.ts b/src/app/features/indicadores/indicadores-global-filters.spec.ts new file mode 100644 index 0000000..ff3e0bf --- /dev/null +++ b/src/app/features/indicadores/indicadores-global-filters.spec.ts @@ -0,0 +1,166 @@ +import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing'; +import { Component } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { By } from '@angular/platform-browser'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { IndicadorFigureCard } from './indicador-figure-card'; +import { Indicador, TipoPeriodo } from './indicadores.models'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; + +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) +class ChartStub {} +const item = (id: string, types: TipoPeriodo[] = ['semestre', 'mes']): Indicador => + ({ id, titulo: id, contrato: 'C1', figuras: ['f'], tipos_periodo: types }); +describe('D.2 integración de autoridad global y consumidores', () => { + let fixture: ReturnType>; + let page: IndicadoresPage; + let http: HttpTestingController; + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] }); + TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController); + }); + afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); + function load(items = [item('a'), item('b')], domain = 'tea') { + http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); + } + function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } + function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); } + function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; } + function open(index = 0) { cards()[index].setVisible(true); fixture.detectChanges(); } + function request(id: string) { return http.expectOne(r => r.url.endsWith('/' + id + '/figuras/f')); } + function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [42, null, 0] }], layout: {} })); fixture.detectChanges(); } + function draft(tipo: TipoPeriodo, periods: string[]) { + const control = editor(); control.changeTipo(tipo); control.changeMode('manual'); + for (const period of periods) { control.year = period.slice(0, 4); control.unit = period.slice(5); control.add(); } + } + function apply() { page.applyFilters(); fixture.detectChanges(); } + + it('Aplicar Todos inicial equivalente no cambia el filtro gráfico ni repite su HTTP', () => { + http.expectOne('/tea/indicadores').flush([]); + page.changeDominio('cacu'); load(undefined, 'cacu'); open(); respond(); + const applied = page.filters!.applied, before = panels()[0].result(); + expect(page.initialKpiPresentation).toBe(true); + apply(); + expect(page.initialKpiPresentation).toBe(false); expect(page.filters!.applied).toBe(applied); + expect(applied.revision).toBe(0); expect(panels()[0].result()).toBe(before); http.expectNone(() => true); + }); + + it.each(['tea', 'cacu', 'cama'] as const)('un editor general de %s sin KPI no publicados ni HTTP inicial', domain => { + if (domain !== 'tea') { http.expectOne('/tea/indicadores'); page.changeDominio(domain); } + load(undefined, domain); + expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1); + const sections = fixture.nativeElement.querySelectorAll('.dashboard > section') as NodeListOf; + expect(sections[0].textContent).toContain('Filtros generales de ' + page.domainLabels[domain]); + expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')).toHaveLength(3); + expect(sections[2].getAttribute('aria-labelledby')).toBe('graphic-section-title'); + expect(page.filters!.applied.selection.mode).toBe('todos'); + expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(false); + http.expectNone(() => true); + }); + it('edición y vacío no consultan ni cambian el resultado vigente', () => { + load(); open(); respond(); const result = panels()[0].result(); + editor().changeMode('manual'); apply(); expect(page.filters!.applied.revision).toBe(0); + expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true); + draft('semestre', ['2025-S1']); fixture.detectChanges(); + expect(panels()[0].result()).toBe(result); expect(page.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true); + }); + it('aplicar actualiza todas las activadas sin abrir pendientes ni KPI', () => { + load([item('a'), item('b'), item('c')]); open(0); open(1); respond(); + const before = cards(); draft('semestre', ['2025-S1']); apply(); + expect(cards()).toEqual(before); expect(cards()[2].visible).toBe(false); + const requests = http.match(r => r.url.includes('/figuras/')); expect(requests).toHaveLength(2); + for (const r of requests) { expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush({ data: [], layout: {} }); } + expect(page.filters!.applied.revision).toBe(1); expect(panels().every(p => p.applied === page.filters!.applied)).toBe(true); + http.expectNone(() => true); + }); + it('aplicación equivalente conserva revisión, consumidores, hosts y resultados', () => { + load(); open(); respond(); draft('semestre', ['2025-S1', '2025-S2']); apply(); respond(); + const panel = panels()[0], result = panel.result(), chart = fixture.nativeElement.querySelector('app-plotly-chart'), applied = page.filters!.applied; + editor().select(['2025-S2', '2025-S1']); apply(); + expect(page.filters!.applied).toBe(applied); expect(panel.result()).toBe(result); + expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); expect(panels()[0]).toBe(panel); http.expectNone(() => true); + }); + it('tarjeta activada después recibe el último aplicado y solo su primera consulta', () => { + load(); draft('semestre', ['2025-S2']); apply(); http.expectNone(() => true); + cards()[1].setVisible(true); fixture.detectChanges(); + const r = request('b'); expect(r.request.params.get('periodos')).toBe('2025-S2'); r.flush({ data: [], layout: {} }); + cards()[1].setVisible(true); fixture.detectChanges(); http.expectNone(() => true); + }); + it('fuera del viewport difiere aplicado y al volver usa revisión vigente', () => { + load(); open(); respond(); const panel = panels()[0]; + cards()[0].setVisible(false); fixture.detectChanges(); draft('semestre', ['2025-S1']); apply(); + expect(fixture.debugElement.query(By.directive(IndicadorFigurePanel)).componentInstance).toBe(panel); expect(panel.result().status).toBe('deferred'); http.expectNone(() => true); + open(); const r = request('a'); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush({ data: [], layout: {} }); + }); + it('restaurada abierta espera visibilidad y usa revisión vigente al activarse', () => { + load(); open(); respond(); page.changeDominio('cacu'); load(undefined, 'cacu'); + page.changeDominio('tea'); load(); + expect(cards()[0].visible).toBe(false); draft('semestre', ['2025-S1']); apply(); http.expectNone(() => true); + cards()[0].setVisible(true); fixture.detectChanges(); + expect(panels()[0].applied.revision).toBe(1); const r = request('a'); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush({ data: [], layout: {} }); + }); + it('mensual compartido consulta compatibles y retira resultado anterior del incompatible', () => { + load([item('a', ['semestre']), item('b')]); open(0); open(1); respond(); + const panel = panels()[0], host = fixture.nativeElement.querySelector('app-plotly-chart'); + draft('mes', ['2025-01']); apply(); + expect(panel.result().status).toBe('incompatible'); expect(panel.result().figure).toBeUndefined(); + http.expectNone(r => r.url.includes('/a/figuras/')); const r = request('b'); + expect(r.request.params.get('periodos')).toBe('2025-01'); expect(r.request.params.has('tipoPeriodo')).toBe(false); + expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('granularidad mes'); + expect((host as HTMLElement).parentElement!.hidden).toBe(true); + r.flush({ data: [], layout: {} }); + expect(fixture.nativeElement.textContent).not.toContain('Todos los meses'); + }); + it('incompatibilidad cancela solicitud pendiente y no queda cargando', () => { + load([item('a', ['semestre']), item('b')]); open(); const old = request('a'); + draft('mes', ['2025-01']); apply(); expect(old.cancelled).toBe(true); expect(panels()[0].result().status).toBe('incompatible'); + expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); http.expectNone(() => true); + }); + it('dos revisiones cancelan respuestas anteriores y carga oculta resultado previo conservando host', () => { + load(); open(); respond(); const host = fixture.nativeElement.querySelector('app-plotly-chart'); + draft('semestre', ['2025-S1']); apply(); const old = request('a'); + expect(panels()[0].result().figure).toBeUndefined(); expect((host as HTMLElement).parentElement!.hidden).toBe(true); + editor().year = '2025'; editor().unit = 'S2'; editor().add(); apply(); const current = request('a'); + expect(old.cancelled).toBe(true); current.flush({ data: [{ y: [7] }], layout: {} }); fixture.detectChanges(); + expect(panels()[0].result().figure!.data[0]['y']).toEqual([7]); expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(host); + expect((host as HTMLElement).parentElement!.hidden).toBe(false); + }); + it('404 y reintento individual usan aplicado vigente y conservan borrador y otra figura', () => { + load(); open(0); open(1); respond(); draft('semestre', ['2025-S1']); apply(); + request('a').flush('private', { status: 404, statusText: 'Not Found' }); request('b').flush({ data: [{ y: [0, null] }], layout: {} }); + const other = panels()[1].result(); editor().select([]); panels()[0].requestFigure(); + const retry = request('a'); expect(retry.request.params.get('periodos')).toBe('2025-S1'); + retry.flush({ data: [], layout: {} }); expect(panels()[1].result()).toBe(other); expect(editor().entry.draft.mode).toBe('empty'); + }); + it('dominio durante carga cancela saliente y restaura borrador separado del aplicado', () => { + load(); open(); respond(); draft('semestre', ['2025-S1']); apply(); const outgoing = request('a'); + editor().year = '2025'; editor().unit = 'S2'; editor().add(); page.changeDominio('cacu'); fixture.detectChanges(); + expect(outgoing.cancelled).toBe(true); load(undefined, 'cacu'); expect(page.filters!.applied.selection.mode).toBe('todos'); + draft('mes', ['2026-01']); apply(); page.changeDominio('tea'); load(); + expect(editor().selectedPeriods).toEqual(['2025-S1', '2025-S2']); expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2025-S1'] }); + expect(cards()[0].visible).toBe(false); + http.match(r => r.url.endsWith('/datos')).filter(r => !r.cancelled).forEach(r => r.flush('missing', { status: 404, statusText: 'Not Found' })); + http.expectNone(() => true); + }); + it('catálogo nuevo revalida sin recortar ni sustituir mensual aplicado', () => { + load(); draft('mes', ['2025-01']); apply(); open(); respond(); + page.retryCatalog(); fixture.detectChanges(); load([item('a', ['semestre'])]); + expect(page.filters!.applied.tipo).toBe('mes'); expect(page.filters!.applied.revision).toBe(1); + cards()[0].setVisible(true); fixture.detectChanges(); + expect(panels()[0].result().status).toBe('incompatible'); http.expectNone(() => true); + expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true); + editor().changeTipo('semestre'); apply(); request('a').flush({ data: [], layout: {} }); expect(page.filters!.applied.revision).toBe(2); + }); + it('orden del catálogo no permite simular Todos mensual', () => { + load([item('a', ['mes', 'semestre'])]); open(); expect(panels()[0].result().status).toBe('incompatible'); http.expectNone(() => true); + draft('mes', ['2025-01']); apply(); request('a').flush({ data: [], layout: {} }); + }); +}); diff --git a/src/app/features/indicadores/indicadores-http.ts b/src/app/features/indicadores/indicadores-http.ts new file mode 100644 index 0000000..58d1fe3 --- /dev/null +++ b/src/app/features/indicadores/indicadores-http.ts @@ -0,0 +1,10 @@ +import { HttpErrorResponse } from '@angular/common/http'; + +export function httpMessage(error: unknown, catalog = false): string { + if (!(error instanceof HttpErrorResponse)) return 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.'; + if (error.status === 0) return 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.'; + if (error.status === 400) return 'El servicio rechazó los parámetros. Revisa los periodos y la selección.'; + if (error.status === 404) return catalog ? 'El catálogo no está disponible.' : 'La figura o los reportes no están disponibles para esta selección.'; + if (error.status >= 500) return 'El servicio encontró un error interno. Intenta nuevamente más tarde.'; + return 'No se pudo completar la solicitud. Intenta nuevamente.'; +} diff --git a/src/app/features/indicadores/indicadores-identities.spec.ts b/src/app/features/indicadores/indicadores-identities.spec.ts new file mode 100644 index 0000000..a1cbf7f --- /dev/null +++ b/src/app/features/indicadores/indicadores-identities.spec.ts @@ -0,0 +1,9 @@ +import { figureIdentity, indicatorIdentity, identityElementId } from './indicadores-identities'; +describe('UX-05B identidades', () => { + it('separa dominios, indicadores y figuras sin colisiones por delimitadores', () => { + const ids = [indicatorIdentity('tea', 'a/b'), indicatorIdentity('cacu', 'a/b'), figureIdentity('tea', 'a/b', 'c'), figureIdentity('tea', 'a', 'b/c'), figureIdentity('tea', 'a', 'á')]; + expect(new Set(ids).size).toBe(ids.length); + expect(new Set(ids.map(identityElementId)).size).toBe(ids.length); + expect(ids.map(identityElementId).every(id => /^[a-z0-9-]+$/.test(id))).toBe(true); + }); +}); diff --git a/src/app/features/indicadores/indicadores-identities.ts b/src/app/features/indicadores/indicadores-identities.ts new file mode 100644 index 0000000..fdfcb61 --- /dev/null +++ b/src/app/features/indicadores/indicadores-identities.ts @@ -0,0 +1,12 @@ +import { Dominio } from './indicadores.models'; + +// JSON tuples preserve identity even when published IDs contain separators. +export function indicatorIdentity(domain: Dominio, indicator: string): string { + return JSON.stringify([domain, indicator]); +} +export function figureIdentity(domain: Dominio, indicator: string, figure: string): string { + return JSON.stringify([domain, indicator, figure]); +} +export function identityElementId(identity: string): string { + return 'indicadores-' + Array.from(identity, char => char.codePointAt(0)!.toString(16)).join('-'); +} diff --git a/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts b/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts new file mode 100644 index 0000000..a7675bc --- /dev/null +++ b/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts @@ -0,0 +1,145 @@ +import { KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi'; +import { IndicadorDatos } from './indicadores.models'; + +// /cama/indicadores//datos?periodos=2025-S2 as WebApi served it (oct 2026) over a CaMa base +// mounted by dev-data (n = 300, semilla 7, referencia 2026-01-01), trimmed to what the card reads. +// Since indicadores_kit v0.6.2 the catalog has no plain B4 (only 4A, 4B and 4C). +const DATOS_2025_S2: Record = { + "cama_birads_456_paciente": { + "id": "cama_birads_456_paciente", + "contrato": "C2", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S2" + ], + "categorias": { + "B4A": {}, + "B4B": {}, + "B4C": {}, + "B5": {}, + "B6": {}, + "SIN_DATO": {} + }, + "filas": [ + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "B4A", + "n": 9, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "B4B", + "n": 0, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "B4C", + "n": 4, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "B5", + "n": 18, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "B6", + "n": 0, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "SIN_DATO", + "n": 0, + "orden": 6, + "suprimido": 0 + } + ] + }, + "cama_confirmacion_birads45": { + "id": "cama_confirmacion_birads45", + "contrato": "C1", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S2" + ], + "categorias": {}, + "filas": [ + { + "periodo": "2025-S2", + "grupo": "total", + "estrato": null, + "numerador": 22, + "denominador": 33, + "valor": 66.6666666667, + "ic_bajo": 49.6078942936, + "ic_alto": 80.2497724059, + "suprimido": 0, + "n_sin_evento": 11, + "n_excluido": 0 + } + ] + }, + "cama_dias_toma_diagnostico": { + "id": "cama_dias_toma_diagnostico", + "contrato": "C3r", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S2" + ], + "categorias": {}, + "filas": [ + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "n": 25, + "mediana": 42.0, + "q1": 24.0, + "q3": 76.0, + "n_sin_evento": 0, + "n_excluido": 58, + "suprimido": 0, + "unidad": "dias" + } + ] + } +}; + +describe('KPI de CaMa con respuestas reales de WebApi', () => { + const applied = { tipo: 'semestre' as const, selection: { mode: 'explicit' as const, periodos: ['2025-S2'] as [string] }, revision: 0 }; + const result = (index: number) => kpiResult(DATOS_2025_S2[KPI_BY_DOMAIN.cama[index].id], KPI_BY_DOMAIN.cama[index], 'cama', applied); + + it('pacientes evaluadas con BI-RADS 4, 5 y 6: la suma de sus categorías', () => { + expect(result(0)).toEqual(expect.objectContaining({ state: 'Disponible', value: 31 })); + }); + it('tasa de confirmación histopatológica: el valor del C1', () => { + expect(result(1)).toEqual(expect.objectContaining({ state: 'Disponible', value: '66.7' })); + expect(result(1).info).toBe('22 de 33 mastografías BI-RADS 4 y 5 con reporte de biopsia.'); + }); + it('tiempo de tamizaje a diagnóstico: la mediana del C3r', () => { + expect(result(2).state).toBe('Disponible'); + expect(result(2).info).toContain('El horizonte de 180 días es provisional.'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-kpi-queries.ts b/src/app/features/indicadores/indicadores-kpi-queries.ts new file mode 100644 index 0000000..e173597 --- /dev/null +++ b/src/app/features/indicadores/indicadores-kpi-queries.ts @@ -0,0 +1,23 @@ +import { inject, Injectable } from '@angular/core'; +import { Observable, shareReplay } from 'rxjs'; +import { Dominio, IndicadorDatos, TipoPeriodo } from './indicadores.models'; +import { IndicadoresService } from './indicadores.service'; +import { IndicadoresRequests } from './indicadores-requests'; + +@Injectable({ providedIn: 'root' }) +export class IndicadoresKpiQueries { + private readonly service = inject(IndicadoresService); + private readonly requests = inject(IndicadoresRequests); + // Only resolved KPI payloads survive navigation. Errors and cancelled requests reset. + private readonly cache = new Map>(); + datos(domain: Dominio, id: string, tipo: TipoPeriodo, period: string) { + const key = JSON.stringify([domain, id, tipo, period]); + let request = this.cache.get(key); + if (!request) { + request = this.requests.run(() => this.service.datos(domain, id, tipo, [period])).pipe( + shareReplay({ bufferSize: 1, refCount: true })); + this.cache.set(key, request); + } + return request; + } +} diff --git a/src/app/features/indicadores/indicadores-kpi.spec.ts b/src/app/features/indicadores/indicadores-kpi.spec.ts new file mode 100644 index 0000000..0d1f655 --- /dev/null +++ b/src/app/features/indicadores/indicadores-kpi.spec.ts @@ -0,0 +1,62 @@ +import { KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi'; +import { GlobalApplied } from './indicadores-memory'; +import { Dominio, IndicadorDatos } from './indicadores.models'; +const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 0 }; +const total = { periodo: '2025-S1', grupo: 'TOTAL', estrato: null, suprimido: 0 }; +function data(domain: Dominio, index: number, filas: Record[]): IndicadorDatos { + const d = KPI_BY_DOMAIN[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: Object.fromEntries(filas.filter(row => typeof row['categoria'] === 'string').map(row => [row['categoria'], {}])), filas }; +} +describe.each(['tea', 'cacu', 'cama'] as const)('KPI %s', domain => { + const c1Group = domain === 'tea' ? 'TOTAL' : 'total'; + const run = (index: number, rows: Record[]) => kpiResult(data(domain, index, rows), KPI_BY_DOMAIN[domain][index], domain, applied); + it('C2 suma categorías disjuntas del único TOTAL incluyendo SIN_DATO y cero', () => { + expect(run(0, [{ ...total, categoria: 'A', n: 5 }, { ...total, categoria: 'SIN_DATO', n: 0 }]).value).toBe(5); + expect(run(0, [{ ...total, categoria: 'A', n: 0 }]).value).toBe(0); + }); + it('C1 consume porcentaje sin recalcular y muestra numerador y denominador', () => { + const result = run(1, [{ ...total, grupo: c1Group, valor: 33.36, numerador: 2, denominador: 6 }]); + expect(result.value).toBe('33.4'); expect(result.info).toContain('2 de 6'); + expect(run(1, [{ ...total, grupo: c1Group, valor: 0, numerador: 0, denominador: 6 }]).value).toBe('0.0'); + }); + it('C3r conserva mediana cero y Q1/Q3, referencia provisional solo en CaCu y CaMa', () => { + const result = run(2, [{ ...total, mediana: 0, n: 5, q1: 0, q3: 7, unidad: 'dias' }]); + expect(result.value).toBe(0); expect(result.info).toContain('0 a 7 días'); + if (domain === 'tea') expect(result.info).not.toContain('provisional'); else expect(result.info).toContain('provisional'); + }); + it.each([0, 1, 2])('suprimido en %s oculta cualquier cifra', index => { + expect(run(index, [{ ...total, grupo: index === 1 ? c1Group : 'TOTAL', categoria: 'A', n: 5, valor: 100, mediana: 7, suprimido: 2 }])).toEqual({ state: 'Dato oculto por tamaño' }); + }); + it.each([0, 1, 2])('nulos en %s no se convierten en cero', index => { + const result = run(index, [{ ...total, grupo: index === 1 ? c1Group : 'TOTAL', categoria: 'A', n: null, valor: null, mediana: null }]); + expect(result.value).toBeUndefined(); expect(result.state).toBe('Sin valor disponible'); + }); + it('no suma grupos superpuestos, estratos ni categorías duplicadas', () => { + for (const rows of [[{ ...total, categoria: 'A', n: 5 }, { ...total, grupo: 'OTHER', categoria: 'A', n: 5 }], + [{ ...total, categoria: 'A', n: 5 }, { ...total, categoria: 'A', n: 5 }], [{ ...total, categoria: 'A', n: 5, estrato: 'edad' }]]) { + expect(run(0, rows).state).toBe('Selección no consolidable'); + } + }); + it('Todos con reporte con varios periodos es no consolidable, aun si uno no tiene filas', () => { + const d = data(domain, 0, [{ ...total, categoria: 'A', n: 5 }]); d.periodos.push('2025-S2'); + expect(kpiResult(d, KPI_BY_DOMAIN[domain][0], domain, { ...applied, selection: { mode: 'todos' } }).state).toBe('Selección no consolidable'); + }); + it('sin filas tiene estado explícito y contrato equivocado no produce cifra', () => { + expect(run(0, []).state).toBe('Sin filas utilizables'); const d = data(domain, 0, []); d.contrato = 'C1'; + expect(kpiResult(d, KPI_BY_DOMAIN[domain][0], domain, applied).state).toBe('Error de contrato'); + }); +}); + +it('categorías incompletas nunca producen un total parcial', () => { + const d = data('cacu', 0, [{ ...total, categoria: 'A', n: 5 }]); d['categorias'] = { A: {}, B: {} }; + expect(kpiResult(d, KPI_BY_DOMAIN.cacu[0], 'cacu', applied).value).toBeUndefined(); +}); + +it('TEA usa sus tres indicadores destacados y su grupo C1 es TOTAL', () => { + expect(KPI_BY_DOMAIN.tea.map(d => [d.id, d.contrato])).toEqual([ + ['M23_pacientes_evaluados', 'C2'], ['M24_confirmacion_diagnostico', 'C1'], ['M25_dias_mchat_diagnostico', 'C3r']]); + const d = data('tea', 1, [{ ...total, grupo: 'TOTAL', valor: 50, numerador: 3, denominador: 6 }]); + expect(kpiResult(d, KPI_BY_DOMAIN.tea[1], 'tea', applied)).toEqual({ state: 'Disponible', value: '50.0', + info: '3 de 6 pacientes con nota médica con diagnóstico CIE-10 F84.0.' }); + expect(kpiResult(data('tea', 1, [{ ...total, grupo: 'total', valor: 50, numerador: 3, denominador: 6 }]), KPI_BY_DOMAIN.tea[1], 'tea', applied).state) + .toBe('Selección no consolidable'); +}); diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts new file mode 100644 index 0000000..b8bc560 --- /dev/null +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -0,0 +1,80 @@ +import { Dominio, IndicadorDatos } from './indicadores.models'; +import { GlobalApplied } from './indicadores-memory'; + +export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; } +// Provisional (oct 2026): titles are copied by hand from the `title` of each indicator's TOML +// in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories +// (patients), not the distribution. If a TOML title changes, change it here too, until the +// cards read the `titulo` that the API already sends. +export const KPI_BY_DOMAIN: Record = { + tea: [ + { id: 'M23_pacientes_evaluados', title: 'Total de pacientes evaluados', contrato: 'C2', unit: 'pacientes' }, + { id: 'M24_confirmacion_diagnostico', title: 'Porcentaje de confirmación diagnóstica', contrato: 'C1', unit: '%' }, + { id: 'M25_dias_mchat_diagnostico', title: 'Tiempo de aplicación de M-CHAT (psicología) a diagnóstico positivo', contrato: 'C3r', unit: 'días (mediana)' }, + ], + cacu: [ + { id: 'cacu_eu7', title: 'Pacientes evaluadas', contrato: 'C2', unit: 'pacientes' }, + { id: 'cacu_eu13', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%' }, + { id: 'cacu_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' }, + ], + cama: [ + { id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 y 6', contrato: 'C2', unit: 'pacientes' }, + { id: 'cama_confirmacion_birads45', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%' }, + { id: 'cama_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' }, + ], +}; +// C1 rows of CaCu/CaMa carry the linkId `total`; TEA's ficha names its single group `TOTAL`. +const C1_GROUP: Record = { tea: 'TOTAL', cacu: 'total', cama: 'total' }; +const C1_INFO: Record string> = { + tea: (n, d) => `${n} de ${d} pacientes con nota médica con diagnóstico CIE-10 F84.0.`, + cacu: (n, d) => `${n} de ${d} pacientes con lesión de alto grado o mayor en biopsia.`, + cama: (n, d) => `${n} de ${d} mastografías BI-RADS 4 y 5 con reporte de biopsia.`, +}; +const C3R_INFO: Record string> = { + tea: (n, q1, q3) => `${n} pacientes; Q1 a Q3: ${q1} a ${q3} días.`, + cacu: (n, q1, q3) => `${n} citologías; Q1 a Q3: ${q1} a ${q3} días. El horizonte de 180 días es provisional.`, + cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días. El horizonte de 180 días es provisional.`, +}; +export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; } +const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); +const count = (v: unknown): v is number => finite(v) && Number.isSafeInteger(v) && v >= 0; +const unscoped = { state: 'Selección no consolidable', info: 'Elige un único periodo. No hay una regla aprobada para consolidar periodos, grupos o estratos.' }; + +// C2 definitions count each patient once per period, in disjoint categories of TOTAL. +// C1/C3r publish a single total row. Never combine totals, strata, or periods. +export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domain: Dominio, applied: GlobalApplied): KpiResult { + if (data.id !== definition.id || data.contrato !== definition.contrato || data.tipo_periodo !== applied.tipo) { + return { state: 'Error de contrato', info: 'Los datos recibidos no corresponden al indicador o periodo aplicado.' }; + } + if (!data.periodos.length && !data.filas.length) return { state: 'Sin filas utilizables' }; + if (data.periodos.length !== 1 || new Set(data.filas.map(row => row['periodo'])).size > 1) return unscoped; + const period = data.periodos[0]; + if (applied.selection.mode === 'explicit' && (applied.selection.periodos.length !== 1 || applied.selection.periodos[0] !== period)) return unscoped; + const rows = data.filas; + if (!rows.length) return { state: 'Sin filas utilizables' }; + const group = definition.contrato === 'C1' ? C1_GROUP[domain] : 'TOTAL'; + if (rows.some(row => row['periodo'] !== period || row['grupo'] !== group || row['estrato'] != null)) return unscoped; + if (definition.contrato !== 'C2' && rows.length !== 1) return unscoped; + if (rows.some(row => finite(row['suprimido']) && row['suprimido'] !== 0)) return { state: 'Dato oculto por tamaño' }; + if (rows.some(row => row['suprimido'] !== 0)) return { state: 'Sin filas utilizables', info: 'No se puede determinar el estado de supresión.' }; + const empty = { state: 'Sin valor disponible' }; + const row = rows[0]; + if (definition.contrato === 'C2') { + const categories = rows.map(row => row['categoria']); + if (categories.some(c => typeof c !== 'string' || !c) || new Set(categories).size !== categories.length) return unscoped; + const catalog = data['categorias']; + if (!catalog || typeof catalog !== 'object' || Array.isArray(catalog)) return { state: 'Error de contrato', info: 'Falta el catálogo de categorías para verificar el total.' }; + const expected = Object.keys(catalog); + if (expected.length !== categories.length || expected.some(c => !categories.includes(c))) return { state: 'Sin filas utilizables', info: 'Las categorías recibidas no permiten verificar un total completo.' }; + if (!rows.every(row => count(row['n']))) return empty; + const value = rows.reduce((sum, row) => sum + (row['n'] as number), 0); + if (!count(value)) return empty; + return { state: 'Disponible', value, info: 'Conteo de pacientes únicos en el periodo.' }; + } + if (definition.contrato === 'C1') { + if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty; + return { state: 'Disponible', value: row['valor'].toFixed(1), info: C1_INFO[domain](row['numerador'], row['denominador']) }; + } + if (!finite(row['mediana']) || !count(row['n']) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty; + return { state: 'Disponible', value: row['mediana'], info: C3R_INFO[domain](row['n'], row['q1'], row['q3']) }; +} diff --git a/src/app/features/indicadores/indicadores-memory.spec.ts b/src/app/features/indicadores/indicadores-memory.spec.ts new file mode 100644 index 0000000..8ef623b --- /dev/null +++ b/src/app/features/indicadores/indicadores-memory.spec.ts @@ -0,0 +1,103 @@ +import { TestBed } from '@angular/core/testing'; +import { TipoPeriodo } from './indicadores.models'; +import { applyGlobal, domainTypes, filterCompatibility, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory'; + +describe('D.2 memoria global por dominio', () => { + let memory: IndicadoresMemory; + beforeEach(() => { TestBed.configureTestingModule({}); memory = TestBed.inject(IndicadoresMemory); }); + it.each(['tea', 'cacu', 'cama'] as const)('inicia %s con Todos y revisión cero', domain => { + const state = memory.restoreGlobal(domain, ['semestre', 'mes']); + expect(state.applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 }); + expect(state.editors.mes?.draft.mode).toBe('empty'); expect(pending(state)).toBe(false); + }); + it('guarda y restaura borrador y aplicado con copias defensivas', () => { + const state = memory.restoreGlobal('tea', ['semestre', 'mes']); + state.tipo = 'mes'; state.editors.mes = { added: ['2025-01'], draft: { mode: 'explicit', periodos: ['2025-01'] } }; + memory.saveGlobal('tea', state); state.editors.mes.added.push('2025-02'); + const restored = memory.restoreGlobal('tea', ['semestre', 'mes']); + expect(restored.editors.mes?.added).toEqual(['2025-01']); expect(restored.applied.tipo).toBe('semestre'); + restored.editors.mes!.added.length = 0; + expect(memory.restoreGlobal('tea', ['semestre', 'mes']).editors.mes?.added).toEqual(['2025-01']); + }); + it('aísla los tres dominios sin tomar selecciones de figuras', () => { + const state = memory.restoreGlobal('tea', ['semestre']); + state.editors.semestre = { added: ['2025-S1'], draft: { mode: 'explicit', periodos: ['2025-S1'] } }; + applyGlobal(state, ['semestre']); memory.saveGlobal('tea', state); + for (const domain of ['cacu', 'cama'] as const) expect(memory.restoreGlobal(domain, ['semestre']).applied.selection.mode).toBe('todos'); + }); + it('mantiene figura por dominio e indicador y tema independiente', () => { + memory.rememberFigure('tea', 'i', 'f'); memory.rememberFigure('cacu', 'i', 'g'); + expect(memory.figure('tea', 'i')).toBe('f'); expect(memory.figure('cacu', 'i')).toBe('g'); + expect(memory.figure('cama', 'i')).toBeUndefined(); + memory.rememberTheme('cacu', 'oscuro'); expect(memory.theme('cacu')).toBe('oscuro'); expect(memory.theme('tea')).toBe('claro'); + }); + it('nueva instancia reinicia memoria sin almacenamiento persistente', () => { + const read = vi.spyOn(Storage.prototype, 'getItem'), write = vi.spyOn(Storage.prototype, 'setItem'); + memory.rememberTheme('tea', 'oscuro'); + const saved = memory.restoreGlobal('tea', ['semestre', 'mes']); + saved.tipo = 'mes'; saved.editors.mes!.draft = { mode: 'explicit', periodos: ['2025-01'] }; + applyGlobal(saved, ['semestre', 'mes']); memory.saveGlobal('tea', saved); + const fresh = new IndicadoresMemory(); + expect(fresh.theme('tea')).toBe('claro'); + expect(fresh.restoreGlobal('tea', ['semestre']).applied.revision).toBe(0); + expect(read).not.toHaveBeenCalled(); expect(write).not.toHaveBeenCalled(); read.mockRestore(); write.mockRestore(); + }); + it('preserva selección ante pérdida de capacidades y explica incompatibilidad', () => { + const state = memory.restoreGlobal('cacu', ['semestre', 'mes']); + state.tipo = 'mes'; state.editors.mes = { added: ['2025-01'], draft: { mode: 'explicit', periodos: ['2025-01'] } }; + applyGlobal(state, ['semestre', 'mes']); memory.saveGlobal('cacu', state); + const restored = memory.restoreGlobal('cacu', ['semestre']); + expect(restored.applied).toEqual(state.applied); expect(restored.tipo).toBe('mes'); + expect(filterCompatibility(restored.applied, ['semestre']).compatible).toBe(false); + }); + it('deduplica por semántica, incluido orden de periodos, sin incrementar revisión', () => { + const state = memory.restoreGlobal('tea', ['semestre']); + state.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] }; + expect(applyGlobal(state, ['semestre'])).toBe(true); const applied = state.applied; + state.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2', '2025-S1'] }; + expect(applyGlobal(state, ['semestre'])).toBe(false); expect(state.applied).toBe(applied); expect(applied.revision).toBe(1); + }); + it('rechaza vacío sin sustituirlo por Todos', () => { + const state = memory.restoreGlobal('tea', ['semestre']); state.editors.semestre!.draft = { mode: 'empty' }; + expect(applyGlobal(state, ['semestre'])).toBe(false); expect(state.applied.revision).toBe(0); + }); + it('oferta unión publicada ordenada sin inventar capacidades', () => { + expect(domainTypes([{ id: 'i', titulo: 'I', contrato: 'C1', figuras: ['f'], tipos_periodo: ['mes', 'semestre'] }])).toEqual(['semestre', 'mes']); + expect(domainTypes([])).toEqual([]); + }); + it.each([{ types: [] }, { types: ['semestre'] }, { types: ['mes', 'semestre'] }] as { types: TipoPeriodo[] }[])('adapter explica incompatibilidad mensual Todos con %j', ({ types }) => { + expect(filterCompatibility({ tipo: 'mes', selection: { mode: 'todos' }, revision: 1 }, types).compatible).toBe(false); + }); + it('adapter no transforma ni recorta y requiere primera granularidad para Todos', () => { + const applied: GlobalFilterState['applied'] = { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-01', '2025-02'] }, revision: 1 }; + const snapshot = JSON.stringify(applied); + expect(filterCompatibility(applied, ['semestre', 'mes']).compatible).toBe(true); + expect(filterCompatibility(applied, ['semestre']).compatible).toBe(false); expect(JSON.stringify(applied)).toBe(snapshot); + expect(filterCompatibility({ tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 }, ['mes', 'semestre']).compatible).toBe(false); + }); +}); +describe('UX-04 selección discriminada', () => { + it('permite Todos solo en el primer tipo publicado', () => { + expect(validDraft({ mode: 'todos' }, 'semestre', ['semestre', 'mes'])).toBe(true); + expect(validDraft({ mode: 'todos' }, 'mes', ['semestre', 'mes'])).toBe(false); + expect(validDraft({ mode: 'todos' }, 'mes', ['mes', 'semestre'])).toBe(false); + }); + it.each([ + ['semestre', ['2025-S1']], ['semestre', ['0001-S1', '9999-S2']], + ['mes', ['2025-01']], ['mes', ['2025-01', '2025-12']], + ] as [TipoPeriodo, [string, ...string[]]][])('acepta explícitos %s %j', (tipo, periodos) => { + expect(validDraft({ mode: 'explicit', periodos }, tipo, ['semestre', 'mes'])).toBe(true); + }); + it.each([ + ['semestre', ['0000-S1']], ['mes', ['2025-00']], ['mes', ['2025-13']], + ['semestre', ['2025-S3']], ['mes', ['2025-01', '2025-S1']], ['mes', ['2025-01', '2025-01']], + ['semestre', ['2025-S1', '2025-S1']], ['mes', [' 2025-01']], + ] as [TipoPeriodo, [string, ...string[]]][])('rechaza explícitos %s %j', (tipo, periodos) => { + expect(validDraft({ mode: 'explicit', periodos }, tipo, ['semestre', 'mes'])).toBe(false); + }); + it('bloquea vacío, incluso un arreglo vacío forzado en tiempo de ejecución', () => { + expect(validDraft({ mode: 'empty' }, 'semestre', ['semestre'])).toBe(false); + expect(validDraft({ mode: 'explicit', periodos: [] as unknown as [string, ...string[]] }, 'semestre', ['semestre'])).toBe(false); + expect(validDraft({ mode: 'explicit', periodos: ['2025-01'] }, 'mes', ['semestre'])).toBe(false); + }); +}); diff --git a/src/app/features/indicadores/indicadores-memory.ts b/src/app/features/indicadores/indicadores-memory.ts new file mode 100644 index 0000000..7c0c764 --- /dev/null +++ b/src/app/features/indicadores/indicadores-memory.ts @@ -0,0 +1,103 @@ +import { Injectable, signal } from '@angular/core'; +import { Dominio, Indicador, parsePeriodos, Tema, TipoPeriodo } from './indicadores.models'; + +export type PeriodDraft = + | { mode: 'todos' } + | { mode: 'empty' } + | { mode: 'explicit'; periodos: [string, ...string[]] }; +export type AppliedPeriods = Exclude; +export interface PeriodEditor { added: string[]; draft: PeriodDraft; } +export interface FilterState { + tipo: TipoPeriodo; + editors: Partial>; + applied?: { tipo: TipoPeriodo; selection: AppliedPeriods }; +} +export interface GlobalApplied { tipo: TipoPeriodo; selection: AppliedPeriods; revision: number; } +export interface GlobalFilterState extends FilterState { applied: GlobalApplied; } +export function newEditor(tipo: TipoPeriodo, first: TipoPeriodo): PeriodEditor { + return { added: [], draft: tipo === 'semestre' && tipo === first ? { mode: 'todos' } : { mode: 'empty' } }; +} +export function validDraft(draft: PeriodDraft, tipo: TipoPeriodo, types: TipoPeriodo[]): draft is AppliedPeriods { + if (!types.includes(tipo) || draft.mode === 'empty') return false; + if (draft.mode === 'todos') return tipo === 'semestre' && tipo === types[0]; + const parsed = parsePeriodos(draft.periodos.join(','), tipo); + return parsed !== null && parsed.length === draft.periodos.length + && parsed.every((p, i) => p === draft.periodos[i]); +} +export function describePeriods(tipo: TipoPeriodo, draft: PeriodDraft): string { + return draft.mode === 'todos' ? 'Todos con reporte (semestres)' + : draft.mode === 'empty' ? 'Sin periodos seleccionados' : draft.periodos.join(', '); +} +export function selectionKey(applied: Pick): string { + return JSON.stringify([applied.tipo, applied.selection.mode, + applied.selection.mode === 'explicit' ? [...applied.selection.periodos].sort() : []]); +} +export function pending(state: FilterState): boolean { + const draft = state.editors[state.tipo]?.draft; + return !state.applied || !draft || draft.mode === 'empty' + || selectionKey(state.applied) !== selectionKey({ tipo: state.tipo, selection: draft }); +} +export function domainTypes(items: readonly Indicador[]): TipoPeriodo[] { + return (['semestre', 'mes'] as const).filter(tipo => items.some(item => item.tipos_periodo.includes(tipo))); +} +export type Compatibility = { compatible: true } | { compatible: false; reason: string }; +// Published capabilities only; this adapter never changes a selection or probes HTTP. +// Future consumers may use the same capability list without defining a KPI contract here. +export function filterCompatibility(applied: GlobalApplied | undefined, types: readonly TipoPeriodo[]): Compatibility { + if (!types.length) return { compatible: false, reason: 'El catálogo no declara capacidades temporales suficientes para consultar.' }; + if (!applied) return { compatible: false, reason: 'No hay un filtro general aplicado.' }; + if (!types.includes(applied.tipo)) return { compatible: false, reason: 'Esta figura no admite la granularidad ' + applied.tipo + ' del filtro general.' }; + const mode = applied.selection.mode; + if (!validDraft(applied.selection, applied.tipo, [...types])) return { compatible: false, reason: mode === 'todos' + ? 'Todos con reporte requiere semestre como primera granularidad publicada. Para meses elige periodos explícitos.' + : 'Los periodos del filtro general no son válidos para esta granularidad.' }; + return { compatible: true }; +} +export function applyGlobal(state: GlobalFilterState, types: TipoPeriodo[]): boolean { + const draft = state.editors[state.tipo]?.draft; + if (!draft || !validDraft(draft, state.tipo, types) || !pending(state)) return false; + state.applied = { tipo: state.tipo, selection: structuredClone(draft), revision: state.applied.revision + 1 }; + return true; +} + +@Injectable({ providedIn: 'root' }) +export class IndicadoresMemory { + private readonly manuallyApplied = new Set(); + initialKpiPresentation(domain: Dominio) { return !this.manuallyApplied.has(domain); } + finishInitialKpiPresentation(domain: Dominio) { this.manuallyApplied.add(domain); } + private readonly pinnedIndicators = signal>(new Set()); + isPinned(domain: Dominio, indicador: string) { + return this.pinnedIndicators().has(JSON.stringify([domain, indicador])); + } + togglePinned(domain: Dominio, indicador: string) { + const key = JSON.stringify([domain, indicador]); + this.pinnedIndicators.update(current => { + const next = new Set(current); + if (next.has(key)) next.delete(key); else next.add(key); + return next; + }); + } + private readonly themes = new Map(); + private readonly figures = new Map(); + figure(domain: Dominio, indicador: string) { return this.figures.get(JSON.stringify([domain, indicador])); } + rememberFigure(domain: Dominio, indicador: string, figure: string) { + this.figures.set(JSON.stringify([domain, indicador]), figure); + } + private readonly filters = new Map(); + theme(domain: Dominio): Tema { return this.themes.get(domain) ?? 'claro'; } + rememberTheme(domain: Dominio, tema: Tema) { this.themes.set(domain, tema); } + saveGlobal(domain: Dominio, state: GlobalFilterState) { + this.filters.set(domain, structuredClone(state)); + } + restoreGlobal(domain: Dominio, types: TipoPeriodo[]): GlobalFilterState { + const stored = this.filters.get(domain); + const state: GlobalFilterState = stored ? structuredClone(stored) : { + tipo: 'semestre', editors: { semestre: newEditor('semestre', 'semestre') }, + applied: { tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 }, + }; + for (const tipo of types) state.editors[tipo] ??= newEditor(tipo, 'semestre'); + // Preserve an application whose capabilities changed: consumers explain incompatibility, + // rather than silently replacing or trimming the user's temporal selection. + return state; + } +} diff --git a/src/app/features/indicadores/indicadores-navigation.spec.ts b/src/app/features/indicadores/indicadores-navigation.spec.ts new file mode 100644 index 0000000..c2cb052 --- /dev/null +++ b/src/app/features/indicadores/indicadores-navigation.spec.ts @@ -0,0 +1,112 @@ +import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing'; +import { Component } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter, Router } from '@angular/router'; +import { RouterTestingHarness } from '@angular/router/testing'; +import { By } from '@angular/platform-browser'; +import { routes } from '../../app.routes'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadorFigureCard } from './indicador-figure-card'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { PlotlyFigure } from './indicadores.models'; +import { syntheticCatalogs } from './indicadores.synthetic-fixtures'; + +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) +class ChartStub { figure?: PlotlyFigure; } + +describe('UX-04 navegación Angular', () => { + let http: HttpTestingController; + async function setup() { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] }); + TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + http = TestBed.inject(HttpTestingController); + return RouterTestingHarness.create(); + } + function load(domain: 'tea' | 'cacu' | 'cama', harness: RouterTestingHarness) { + http.expectOne('/' + domain + '/indicadores').flush(syntheticCatalogs[domain]); + harness.detectChanges(); + const page = harness.routeDebugElement!.componentInstance as IndicadoresPage; + vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); + const card = harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard; + if (!card.visible) { card.setVisible(true); harness.detectChanges(); } + const req = http.expectOne(r => r.url.includes('/figuras/')); + req.flush({ data: [{ y: [0, null] }], layout: {} }); + return req; + } + afterEach(() => { http.verify(); vi.unstubAllGlobals(); }); + it.each(['tea', 'cacu', 'cama'] as const)('navegación %s mantiene tres enlaces, estado, decoración y foco independiente', async domain => { + const harness = await setup(); + await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage); + load(domain, harness); harness.detectChanges(); + const links = Array.from(harness.routeNativeElement!.querySelectorAll('nav a')) as HTMLAnchorElement[]; + expect(links.map(a => a.textContent?.trim())).toEqual(['TEA', 'CaCu', 'CaMa']); + expect(links.map(a => a.getAttribute('href'))).toEqual(['/indicadores/tea', '/indicadores/cacu', '/indicadores/cama']); + const selected = links.find(a => a.getAttribute('aria-current') === 'page')!; + expect(selected.getAttribute('href')).toBe('/indicadores/' + domain); + expect(links.filter(a => a.hasAttribute('aria-current'))).toHaveLength(1); + // Check the compiled CSSOM rule against the actual encapsulated element. + // jsdom's computed link decoration can remain stale after aria-current changes. + const activeRule = Array.from(document.styleSheets).flatMap(sheet => Array.from(sheet.cssRules)) + .find((rule): rule is CSSStyleRule => rule instanceof CSSStyleRule + && rule.selectorText.includes('[aria-current=') && selected.matches(rule.selectorText))!; + expect(activeRule).toBeTruthy(); + expect(activeRule.style.getPropertyValue('text-decoration')).toBe('none'); + expect(activeRule.style.getPropertyValue('font-weight')).toBe('700'); + expect(activeRule.style.getPropertyValue('background')).toBe('var(--issste-accent)'); + for (const link of links) { + expect(link.tabIndex).toBe(0); + link.focus(); expect(document.activeElement).toBe(link); + const key = new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }); + link.dispatchEvent(key); expect(key.defaultPrevented).toBe(false); + expect(selected.getAttribute('aria-current')).toBe('page'); + } + http.expectNone(() => true); + }); + it('mantiene la ruta, restaura borradores y reconsulta la aplicación entre TEA/CaCu/CaMa', async () => { + const harness = await setup(); + const tea = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage); + load('tea', harness); harness.detectChanges(); + const control = harness.routeDebugElement!.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; + control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add(); + (harness.routeDebugElement!.componentInstance as IndicadoresPage).applyFilters(); harness.detectChanges(); + http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); + control.year = '2025'; control.unit = 'S2'; control.add(); + await harness.navigateByUrl('/indicadores/cacu', IndicadoresPage); load('cacu', harness); + await harness.navigateByUrl('/indicadores/cama', IndicadoresPage); load('cama', harness); + const restored = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage); + const req = load('tea', harness); + expect(req.request.params.get('periodos')).toBe('2025-S1'); + expect((harness.routeDebugElement!.componentInstance as IndicadoresPage).filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S1', '2025-S2'] }); + expect(TestBed.inject(Router).url).toBe('/indicadores/tea'); + }); + it('un nuevo arranque conserva la URL de entrada y reinicia indicador, tema y filtros', async () => { + let harness = await setup(); + const page = await harness.navigateByUrl('/indicadores/cacu', IndicadoresPage); + load('cacu', harness); harness.detectChanges(); + page.changeTema('oscuro'); harness.detectChanges(); + http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); + const control = harness.routeDebugElement!.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; + control.changeTipo('mes'); control.year = '2025'; control.unit = '01'; control.add(); + (harness.routeDebugElement!.componentInstance as IndicadoresPage).applyFilters(); harness.detectChanges(); + http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); + const url = TestBed.inject(Router).url; + http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush('missing', { status: 404, statusText: 'Not Found' })); + http.verify(); TestBed.resetTestingModule(); + harness = await setup(); + const restarted = await harness.navigateByUrl(url, IndicadoresPage); + const req = load('cacu', harness); + expect(TestBed.inject(Router).url).toBe('/indicadores/cacu'); + expect((harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard).visible).toBe(true); + expect(restarted.tema).toBe('claro'); + expect((harness.routeDebugElement!.componentInstance as IndicadoresPage).filters?.tipo).toBe('semestre'); + expect((harness.routeDebugElement!.componentInstance as IndicadoresPage).filters?.editors.mes?.draft.mode).toBe('empty'); + expect(req.request.params.has('periodos')).toBe(false); + expect(req.request.params.get('tema')).toBe('claro'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html new file mode 100644 index 0000000..73e9689 --- /dev/null +++ b/src/app/features/indicadores/indicadores-page.html @@ -0,0 +1,82 @@ +
+
+ Dominio {{ domainLabels[dominio] }} · Investigación +

Dashboard de indicadores

+

Explora las figuras de indicadores {{ domainLabels[dominio] }} generadas por el servicio de reportes.

+
+ + + @if (!catalogLoading() && filters; as state) { +
+

Filtros generales de {{ domainLabels[dominio] }}

+

La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.

+ +
+ } + @let kpis = availableKpis; + @if (kpis.length) { +
+

Indicadores destacados

+

La vista inicial busca el último dato visible de cada indicador. Al aplicar Todos con reporte se toma el último reporte disponible. Un periodo explícito consulta ese periodo; varios periodos no se consolidan.

+
+ @for (definition of kpis; track dominio + ':' + definition.id) { + + } +
+
+ } + +
+
+

Indicadores gráficos

+ @if (!catalogLoading() && !catalogError() && catalog().length) { +

{{ catalog().length }} indicadores publicados

+ } +
+ @if (catalogLoading()) { + +

Cargando catálogo de indicadores…

+ } @else if (catalogError()) { +

{{ catalogError() }}

+
+ } @else if (!catalog().length) { +

No hay indicadores disponibles en el catálogo.

+
+ } @else { + @if (searchVisible()) { + +

+ @if (searchResults().active) { + @if (searchResults().count) { + {{ searchResults().count }} coincidencias de {{ catalog().length }} indicadores. Todos permanecen disponibles. + } @else { + No se encontraron coincidencias. El catálogo completo permanece disponible; los indicadores fijados aparecen primero. + } + } +

+ } +
+ @for (item of searchResults().items; track cardIdentity(item)) { + + } +
+ } +
+
diff --git a/src/app/features/indicadores/indicadores-page.scss b/src/app/features/indicadores/indicadores-page.scss new file mode 100644 index 0000000..5671583 --- /dev/null +++ b/src/app/features/indicadores/indicadores-page.scss @@ -0,0 +1,60 @@ +// `flex: 1` is our own app shell's convention for a workspace route's root +// component (`.app-main` is a flex row, see connect-page/governance-page's +// own `:host`) -- not present upstream, whose shell lays this out differently. +:host { display: block; flex: 1; min-width: 0; } +.dashboard { max-width: 1440px; margin: 0 auto; min-width: 0; container: dashboard / inline-size; } +h1 { font: var(--mat-sys-headline-large); font-family: var(--issste-font-heading); font-weight: 700; margin: .65rem 0; } +header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; } +.domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); } +.state { padding: 1.25rem; margin: 0; } +.section-title { font-family: var(--issste-font-heading); font-size: 1.5rem; line-height: 1.3; margin: 0; overflow-wrap: anywhere; } +.section-description { color: var(--issste-text-secondary); margin: var(--issste-space-2) 0 var(--issste-space-4); overflow-wrap: anywhere; } +.kpi-section, .graphic-section { min-width: 0; } +.graphic-section { margin-top: var(--issste-space-6); padding-top: var(--issste-space-6); border-top: 1px solid var(--issste-border); } +.kpi-grid, .catalog-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); } +.catalog-grid { align-items: start; } +.catalog-grid > app-indicador-catalog-card { min-width: 0; margin: 0; } +.catalog-heading { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); } +.catalog-count { margin: 0 0 0 auto; text-align: right; color: var(--issste-text-secondary); overflow-wrap: anywhere; } +.catalog-search { display: flex; justify-content: flex-end; margin-top: var(--issste-space-4); } +.catalog-search mat-form-field { width: 100%; min-width: 0; max-width: 32rem; } +.catalog-search button { width: 48px; height: 48px; } +.catalog-search button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: -3px; } +// Keep search semantics; Material supplies the single accessible clear control. +.catalog-search input::-webkit-search-cancel-button { -webkit-appearance: none; appearance: none; } +.search-result { color: var(--mat-sys-on-surface-variant); font: var(--mat-sys-body-medium); text-align: right; + overflow-wrap: anywhere; margin: var(--issste-space-2) 0 var(--issste-space-4); } +@container dashboard (min-width: 600px) { .kpi-grid { grid-template-columns: repeat(min(2, var(--kpi-count)), minmax(0, 1fr)); } } +@container dashboard (min-width: 1304px) { .catalog-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } } + +nav { + display: flex; + flex-wrap: wrap; + gap: var(--issste-space-2); + padding: var(--issste-space-2); + justify-content: center; + margin: var(--issste-space-4) 0; + border-radius: var(--issste-radius); +} +nav a { + flex: 0 1 6rem; + max-width: 10rem; + color: var(--issste-text); + border: 1px solid var(--issste-border); + background: var(--issste-surface); + min-height: 44px; + border-radius: var(--issste-radius); +} +nav a[aria-current='page'] { + background: var(--issste-accent); + font-weight: 700; + text-decoration: none; +} +@media (max-width: 550px) { + h1 { font-size: var(--mat-sys-headline-medium-size); line-height: var(--mat-sys-headline-medium-line-height); } + nav { gap: var(--issste-space-2); padding-inline: 0; } +} + +.global-filters { margin-block: var(--issste-space-6); padding: clamp(.75rem, 2vw, 1.5rem); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); min-width: 0; } + +@container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } } diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts new file mode 100644 index 0000000..65f04e7 --- /dev/null +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -0,0 +1,328 @@ +import { periodAvailabilityProvider } from './indicadores-periodos.testing'; +import { Component } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { By } from '@angular/platform-browser'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; +import { IndicadorFigureCard } from './indicador-figure-card'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { MatSelect } from '@angular/material/select'; +import { NgModel } from '@angular/forms'; +import { IndicadoresMemory } from './indicadores-memory'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { Indicador, PlotlyFigure } from './indicadores.models'; +import { syntheticCatalogs } from './indicadores.synthetic-fixtures'; + +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) +class ChartStub { figure?: PlotlyFigure; } +const item: Indicador = { id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre', 'mes'] }; +const second: Indicador = { ...item, id: 'i2', titulo: 'Dos', figuras: ['g'] }; +describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { + let fixture: ReturnType>; + let page: IndicadoresPage; + let http: HttpTestingController; + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider] }); + TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => { http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush('missing', { status: 404, statusText: 'Not Found' })); fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); + function load(items: Indicador[] = [item, second], domain = 'tea') { + http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); + } + function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } + function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); } + function toggle(index = 0) { cards()[index].setVisible(true); fixture.detectChanges(); } + function request(figure: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + figure)); } + function flushAll() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: {} })); fixture.detectChanges(); } + function kpiMissing() { http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush('missing', { status: 404, statusText: 'Not Found' })); fixture.detectChanges(); } + function control(index = 0) { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))[index].componentInstance as IndicadorPeriodFilters; } + + it('KPI-DYNAMIC TEA muestra sus tres destacados sin consultar datos fuera del catálogo', () => { + load(); + expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores destacados'); + expect(Array.from(fixture.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card h3')).map(h => (h as HTMLElement).textContent)) + .toEqual(['Total de pacientes evaluados', 'Porcentaje de confirmación diagnóstica', 'Tiempo de aplicación de M-CHAT (psicología) a diagnóstico positivo']); + http.expectNone(r => r.url.endsWith('/datos')); + }); + it('KPI-DYNAMIC distingue carga, error y catálogo vacío confirmado', () => { + fixture.detectChanges(); + expect(page.catalogLoading()).toBe(true); + expect(fixture.nativeElement.textContent).toContain('Cargando catálogo'); + expect(fixture.nativeElement.textContent).not.toContain('No hay indicadores disponibles'); + http.expectOne('/tea/indicadores').flush('private', { status: 500, statusText: 'Error' }); fixture.detectChanges(); + expect(page.catalogError()).toBeTruthy(); + expect(fixture.nativeElement.querySelector('[role="alert"]')).toBeTruthy(); + expect(fixture.nativeElement.textContent).not.toContain('No hay indicadores disponibles'); + page.retryCatalog(); fixture.detectChanges(); load([]); + expect(page.catalogLoading()).toBe(false); expect(page.catalogError()).toBe(''); + expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); + expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')).toHaveLength(3); + http.expectNone(() => true); + }); + it('D.1 separa secciones y conserva tarjetas, orden, identidades y figuras dentro del grid', () => { + load(); const before = cards(); + const grid = fixture.nativeElement.querySelector('.catalog-grid') as HTMLElement; + expect(getComputedStyle(grid).display).toBe('grid'); + expect(grid.children).toHaveLength(2); + expect(Array.from(grid.children).every(host => host.tagName === 'APP-INDICADOR-CATALOG-CARD')).toBe(true); + const sections = fixture.nativeElement.querySelectorAll('.dashboard > section') as NodeListOf; + expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'kpi-section-title', 'graphic-section-title']); + expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('2 indicadores publicados'); + expect(getComputedStyle(fixture.nativeElement.querySelector('.catalog-count')).textAlign).toBe('right'); + toggle(0); toggle(1); flushAll(); + expect(Array.from(grid.children).map(host => host.querySelectorAll('app-indicador-figure-panel').length)).toEqual([1, 1]); + expect(panels().map(panel => panel.figuraId)).toEqual(['f1', 'g']); + expect(cards()).toEqual(before); expect(cards().every(card => card.visible)).toBe(true); + http.expectNone(() => true); + }); + it('D.3.A muestra identidad, selector y skeleton sin control de expansión ni HTTP', () => { + load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card'); + expect(host.querySelector('h2').textContent).toBe('Uno'); + expect(host.querySelector('header button')).toBeNull(); + expect(host.querySelector('mat-select')).toBeTruthy(); + expect(host.querySelector('.figure-skeleton').textContent).toContain('pendiente'); + expect(host.textContent).not.toContain('Contrato C1'); + expect(host.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas'); + http.expectNone(() => true); + }); + it('D.3.A conserva encabezado y contenido al salir del viewport', () => { + load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card'); + const header = host.querySelector('header'); toggle(); flushAll(); + const panel = panels()[0]; cards()[0].setVisible(false); fixture.detectChanges(); + expect(host.querySelector('header')).toBe(header); expect(panels()[0]).toBe(panel); + expect(host.querySelector('.catalog-metadata')).toBeTruthy(); http.expectNone(() => true); + }); + it('UX-06C: conserva título largo completo y el control separado de la identidad', () => { + const title = 'Distribución de indicadores con un título extenso y múltiples palabras para revisión responsive'; + load([{ ...item, titulo: title }, second]); + const header = fixture.nativeElement.querySelector('app-indicador-catalog-card header') as HTMLElement; + expect(header.querySelector('h2')?.textContent).toBe(title); + expect(header.querySelector('.card-identity button')).toBeNull(); + expect(header.querySelector('button')).toBeNull(); + expect(fixture.nativeElement.querySelector('.pin-toggle').getAttribute('aria-label')).toContain(title); + http.expectNone(() => true); + }); + it('UX-06B conserva una navegación con rutas y estado activo en los tres dominios', () => { + const domains = ['tea', 'cacu', 'cama'] as const; + for (const domain of domains) { + if (domain !== 'tea') page.changeDominio(domain); + load([], domain); + const navs = fixture.nativeElement.querySelectorAll('nav') as NodeListOf; + expect(navs).toHaveLength(1); + expect(navs[0].getAttribute('aria-label')).toBe('Dominios de indicadores'); + const links = Array.from(navs[0].querySelectorAll('a')); + expect(links.map(link => link.textContent?.trim())).toEqual(['TEA', 'CaCu', 'CaMa']); + expect(links.map(link => link.getAttribute('href'))).toEqual(domains.map(d => '/indicadores/' + d)); + expect(links.filter(link => link.getAttribute('aria-current') === 'page')).toHaveLength(1); + expect(links[domains.indexOf(domain)].getAttribute('aria-current')).toBe('page'); + expect(cards()).toHaveLength(0); + http.expectNone(() => true); + } + }); + + it('UX-06D retira el selector visual, inicia claro y conserva oscuro sin recargar catálogo', async () => { + load(); + await fixture.whenStable(); fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('.global-filters mat-select')).toBeTruthy(); + expect(fixture.nativeElement.textContent).not.toContain('Tema del dominio'); + expect(page.tema).toBe('claro'); + page.changeTema('oscuro'); fixture.detectChanges(); + expect(page.tema).toBe('oscuro'); + expect(cards().every(card => !card.visible)).toBe(true); + http.expectNone(() => true); + }); + it.each([0, 1, 2, 18, 37])('catálogo de %i conserva orden y no consulta figuras inicialmente', count => { + const items = Array.from({ length: count }, (_, i) => ({ ...item, id: 'id-' + i })); + load(items); + expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id)); + expect(cards().every(c => !c.visible)).toBe(true); + expect(panels()).toHaveLength(0); http.expectNone(r => r.url.includes('/figuras/')); + if (!count) expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); + }); + it('activar visibilidad consulta exactamente una vez la primera figura publicada', () => { + load([item]); toggle(); expect(cards()[0].visible).toBe(true); expect(panels()).toHaveLength(1); + request('f1').flush({ data: [], layout: {} }); + fixture.detectChanges(); fixture.detectChanges(); http.expectNone(() => true); + }); + it('volver al dominio espera nueva visibilidad sin memoria de cierre', () => { + load([item]); toggle(); flushAll(); + fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); + load([item]); expect(cards()[0].visible).toBe(false); http.expectNone(() => true); + }); + it('indicador sin figuras informa y no consulta HTTP', () => { + load([{ ...item, figuras: [] }]); toggle(); expect(cards()[0].visible).toBe(true); + expect(fixture.nativeElement.textContent).toContain('no tiene figuras disponibles'); + expect(panels()).toHaveLength(0); http.expectNone(() => true); + }); + it('varias tarjetas y figuras abiertas mantienen solicitudes concurrentes independientes', () => { + load(); toggle(0); const a = request('f1'); toggle(1); const c = request('g'); + expect(a.cancelled).toBe(false); + c.flush({ data: [{ y: [3] }], layout: {} }); + a.flush({ data: [{ y: [1] }], layout: {} }); + expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [3]]); + expect(cards().every(c => c.visible)).toBe(true); + }); + it('retirar una tarjeta cancela solo su solicitud y destruye su panel', () => { + load(); toggle(); toggle(1); const a = request('f1'), c = request('g'); + page.catalog.set([second]); fixture.detectChanges(); + expect(a.cancelled).toBe(true); expect(c.cancelled).toBe(false); + expect(() => a.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); + expect(panels()).toHaveLength(1); c.flush({ data: [{ y: [3] }], layout: {} }); + expect(panels()[0].result().figure?.data[0]['y']).toEqual([3]); + }); + it('404 y reintento afectan solo una figura y 200 sin puntos sigue siendo resultado', () => { + load(); toggle(); toggle(1); const a = request('f1'), b = request('g'); + a.flush('private', { status: 404, statusText: 'Not Found' }); + b.flush({ data: [{ y: [null] }], layout: {} }); fixture.detectChanges(); + expect(panels()[0].result().status).toBe('error'); expect(panels()[1].result().status).toBe('ready'); + expect(fixture.nativeElement.textContent).toContain('No hay valores visibles'); + panels()[0].requestFigure(); request('f1').flush({ data: [], layout: {} }); http.expectNone(() => true); + }); + it('un único borrador actualiza todas las figuras y tema usa aplicado', () => { + load([item]); toggle(); flushAll(); const a = control(); + expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1); + a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add(); http.expectNone(() => true); + page.applyFilters(); fixture.detectChanges(); + const appliedA = request('f1'); + expect(appliedA.request.params.get('periodos')).toBe('2025-S1'); + appliedA.flush({ data: [], layout: {} }); kpiMissing(); a.year = '2025'; a.unit = 'S2'; a.add(); + page.changeTema('oscuro'); fixture.detectChanges(); + const themedA = request('f1'); + expect(themedA.request.params.get('periodos')).toBe('2025-S1'); + expect(themedA.request.params.get('tema')).toBe('oscuro'); expect(a.selectedPeriods).toEqual(['2025-S1', '2025-S2']); + themedA.flush({ data: [], layout: {} }); + }); + it('UX-06D expandir metodología conserva panel, figura y borrador sin generar HTTP', () => { + load([{ ...item, contrato: 'C2', figuras: ['fig_c2_apiladas'] }]); toggle(); flushAll(); + const panel = panels()[0], chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance; + const filters = control(); + filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add(); + const draft = structuredClone(filters.entry.draft), applied = structuredClone(page.filters!.applied); + const result = panel.result(); + const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement; + for (let i = 0; i < 2; i++) { + button.click(); fixture.detectChanges(); + expect(button.getAttribute('aria-expanded')).toBe(i === 0 ? 'true' : 'false'); + expect(panels()[0]).toBe(panel); expect(panel.result()).toBe(result); + expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(chart); + expect(filters.entry.draft).toEqual(draft); expect(page.filters!.applied).toEqual(applied); + http.expectNone(() => true); + } + }); + it('salir y volver al viewport conserva borrador, aplicado y resultado sin HTTP redundante', () => { + load([item]); toggle(); flushAll(); const a = control(); a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add(); + page.applyFilters(); fixture.detectChanges(); flushAll(); kpiMissing(); a.year = '2025'; a.unit = 'S2'; a.add(); + cards()[0].setVisible(false); fixture.detectChanges(); toggle(); + expect(control()).toBe(a); expect(control().selectedPeriods).toEqual(['2025-S1', '2025-S2']); + http.expectNone(() => true); + }); + it('tema solo consulta paneles visibles, cancela los anteriores y no repite el mismo tema', () => { + load(); toggle(); const a = request('f1'); + page.changeTema('oscuro'); fixture.detectChanges(); expect(a.cancelled).toBe(true); + const darkA = request('f1'); + expect(darkA.request.params.get('tema')).toBe('oscuro'); http.expectNone(r => r.url.endsWith('/g')); + darkA.flush({ data: [], layout: {} }); + page.changeTema('oscuro'); fixture.detectChanges(); http.expectNone(() => true); + toggle(1); const later = request('g'); expect(later.request.params.get('tema')).toBe('oscuro'); later.flush({ data: [], layout: {} }); + }); + it('salir del dominio cancela paneles y catálogos obsoletos', () => { + load(); toggle(); const a = request('f1'); + page.changeDominio('cacu'); fixture.detectChanges(); expect(a.cancelled).toBe(true); + const oldCatalog = http.expectOne('/cacu/indicadores'); page.changeDominio('cama'); fixture.detectChanges(); + expect(oldCatalog.cancelled).toBe(true); load(syntheticCatalogs.cama, 'cama'); flushAll(); + expect(() => oldCatalog.flush(syntheticCatalogs.cacu)).toThrow(); expect(page.dominio).toBe('cama'); + }); + it('restaura representación y tema de dominio sin aplicar borrador pendiente', () => { + load(); toggle(); flushAll(); control().changeMode('manual'); + page.changeTema('oscuro'); fixture.detectChanges(); flushAll(); + page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu'); toggle(); flushAll(); + toggle(); page.changeDominio('tea'); fixture.detectChanges(); load(); + expect(cards()[0].visible).toBe(false); expect(cards()[1].visible).toBe(false); + expect(page.tema).toBe('oscuro'); expect(cards()[0].visible).toBe(false); http.expectNone(() => true); + toggle(); const a = request('f1'); expect(a.request.params.has('periodos')).toBe(false); + expect(control().entry.draft.mode).toBe('empty'); a.flush({ data: [], layout: {} }); + page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu'); + expect(cards()[0].visible).toBe(false); expect(page.tema).toBe('claro'); http.expectNone(() => true); + }); + it('identidades estables conservan componentes al reordenar el catálogo', () => { + load(); toggle(); flushAll(); const card = cards()[0], panel = panels()[0]; + page.catalog.set([second, item]); fixture.detectChanges(); + expect(cards()[1]).toBe(card); expect(panels()[0]).toBe(panel); http.expectNone(() => true); + }); + it('identidad eliminada no se monta aunque exista preferencia anterior', () => { + TestBed.inject(IndicadoresMemory).rememberFigure('tea', 'removed', 'f1'); + load([second]); expect(cards().map(c => c.indicador.id)).toEqual(['i2']); flushAll(); + }); + it('controles permanentes conservan IDs únicos y foco al salir del viewport', () => { + load(); toggle(); flushAll(); + const input = fixture.nativeElement.querySelector('app-indicador-catalog-card .methodology-toggle'); + input.focus(); cards()[0].setVisible(false); fixture.detectChanges(); expect(document.activeElement).toBe(input); + const ids = Array.from(fixture.nativeElement.querySelectorAll('[id]') as NodeListOf).map(e => e.id); + expect(new Set(ids).size).toBe(ids.length); + expect(fixture.nativeElement.querySelector('app-indicador-catalog-card header button')).toBeNull(); + }); + it('copia de presentación y gráficos independientes conservan JSON binario, notas, ceros y nulos', () => { + load(); toggle(0); toggle(1); const raw = { data: [{ y: { dtype: 'f8', bdata: 'AAAAAAAAAAA=' }, customdata: [[0, null]] }], layout: { annotations: [{ text: 'Nota' }] } }; + const before = JSON.stringify(raw); request('f1').flush(raw); request('g').flush({ data: [{ y: [0, null] }], layout: {} }); fixture.detectChanges(); + expect(JSON.stringify(raw)).toBe(before); expect(panels()[0].result().figure).toEqual(raw); + const charts = fixture.debugElement.queryAll(By.directive(ChartStub)); expect(charts).toHaveLength(2); + expect(charts[0].componentInstance.figure).not.toBe(charts[1].componentInstance.figure); + expect(panels()[0].result().presentationFigure).not.toBe(raw); + expect(fixture.nativeElement.textContent).not.toContain('reportes no están disponibles'); + }); + it.each(['cacu', 'cama'] as const)('preserva advertencias y filtros mensuales de %s', domain => { + load([]); page.changeDominio(domain); load(syntheticCatalogs[domain], domain); toggle(); flushAll(); + const c = control(); c.changeTipo('mes'); c.year = '2025'; c.unit = '01'; c.add(); http.expectNone(() => true); + page.applyFilters(); fixture.detectChanges(); const r = http.expectOne(r => r.url.includes('/figuras/')); + expect(r.request.params.get('periodos')).toBe('2025-01'); r.flush({ data: [{ y: [0, null] }], layout: {} }); fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('no entregan intervalos Wilson efectivos'); + expect(fixture.nativeElement.textContent).toContain('suprimidos no representan tasas observadas de 0 %'); + }); + it('catálogo error, reintento y vacío no dejan paneles', () => { + http.expectOne('/tea/indicadores').flush('private', { status: 500, statusText: 'Error' }); fixture.detectChanges(); + expect(page.catalogError()).toContain('error interno'); expect(fixture.nativeElement.textContent).not.toContain('private'); + page.retryCatalog(); load([]); expect(panels()).toHaveLength(0); + }); + it.each(['M02_sexo', 'K01_evaluacion_3_meses'])('UX-04A: %s conserva selección vacía estable al reabrir sin escrituras ni HTTP redundantes', async id => { + load(syntheticCatalogs.tea); + const index = cards().findIndex(c => c.indicador.id === id); + toggle(index); flushAll(); + const c = control(); c.changeMode('manual'); fixture.detectChanges(); await fixture.whenStable(); + expect(c.canApply).toBe(false); http.expectNone(() => true); + c.year = '2025'; c.unit = 'S1'; c.add(); c.select([]); fixture.detectChanges(); await fixture.whenStable(); + toggle(index); toggle(index); flushAll(); await fixture.whenStable(); + expect(control().entry.draft.mode).toBe('empty'); expect(control().state.applied?.selection.mode).toBe('todos'); + const state = panels()[0].result(); const saves = vi.spyOn(TestBed.inject(IndicadoresMemory), 'saveGlobal'); + const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!; + const writes = vi.spyOn(select.injector.get(NgModel).control, 'setValue'); + for (let i = 0; i < 3; i++) { + select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable(); + expect(select.componentInstance.panelOpen).toBe(true); + select.componentInstance.close(); fixture.detectChanges(); await fixture.whenStable(); + } + expect(writes).not.toHaveBeenCalled(); expect(saves).not.toHaveBeenCalled(); + expect(panels()[0].result()).toBe(state); http.expectNone(() => true); + }); + it('UX-06D retira solo el aviso general del catálogo', () => { + load(); expect(fixture.nativeElement.querySelector('.notice')).toBeNull(); + expect(fixture.nativeElement.textContent).not.toContain('Uso exclusivo de investigación. No usar para decisiones clínicas.'); + }); + it('IDs distintos con el mismo título y figura conservan paneles y etiquetas independientes', () => { + load([{ ...item, figuras: ['f1'] }, { ...second, titulo: item.titulo, figuras: ['f1'] }]); + toggle(0); toggle(1); + const a = http.expectOne(r => r.url.endsWith('/i1/figuras/f1')); + const b = http.expectOne(r => r.url.endsWith('/i2/figuras/f1')); + a.flush({ data: [{ y: [1] }], layout: {} }); b.flush({ data: [{ y: [2] }], layout: {} }); fixture.detectChanges(); + const buttons = fixture.nativeElement.querySelectorAll('app-indicador-catalog-card mat-select') as NodeListOf; + expect(panels()[0].titleId).not.toBe(panels()[1].titleId); + expect(buttons[0].tabIndex).toBe(-1); expect(buttons[1].tabIndex).toBe(-1); + expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [2]]); + }); +}); diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts new file mode 100644 index 0000000..90fbfdc --- /dev/null +++ b/src/app/features/indicadores/indicadores-page.ts @@ -0,0 +1,274 @@ +import { DOCUMENT } from '@angular/common'; +import { afterEveryRender, afterNextRender, ChangeDetectorRef, Component, DestroyRef, ElementRef, Injector, inject, computed, signal, viewChild, viewChildren } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { ActivatedRoute, RouterLink } from '@angular/router'; +import { FormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCardModule } from '@angular/material/card'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { MatIconModule } from '@angular/material/icon'; +import { MatSelectModule } from '@angular/material/select'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs'; +import { Dominio, DOMINIOS, isDominio, Indicador, Tema } from './indicadores.models'; +import { IndicadoresService } from './indicadores.service'; +import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, validDraft } from './indicadores-memory'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { KPI_BY_DOMAIN } from './indicadores-kpi'; +import { IndicadorKpiPanel } from './indicador-kpi-panel'; +import { indicatorIdentity } from './indicadores-identities'; +import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos'; +import { httpMessage } from './indicadores-http'; + +@Component({ + selector: 'app-indicadores-page', + imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorPeriodFilters], + templateUrl: './indicadores-page.html', + styleUrl: './indicadores-page.scss', +}) +export class IndicadoresPage { + private readonly document = inject(DOCUMENT); + private readonly element = inject>(ElementRef); + private readonly injector = inject(Injector); + private readonly searchInput = viewChild>('searchInput'); + private readonly graphicCards = viewChildren(IndicadorCatalogCard); + private readonly observedRegions = new Map(); + private renderedCards: readonly IndicadorCatalogCard[] = []; + private visibilityObserver?: IntersectionObserver; + private sizeObserver?: ResizeObserver; + private readonly sizeTargets = new Set(); + private frame?: number; + private stickyHeight = -1; + private visibilityDestroyed = false; + private readonly viewportChanged = () => this.visibilityChanged(); + + visibilityChanged() { + this.queueVisibility(); + } + private queueVisibility() { + const browser = this.document.defaultView; + if (this.visibilityDestroyed || !this.visibilityObserver || !browser || this.frame !== undefined) return; + this.frame = browser.requestAnimationFrame(() => { + this.frame = undefined; + this.evaluateVisibility(); + }); + } + private clearVisibility() { + this.visibilityObserver?.disconnect(); + this.visibilityObserver = undefined; + this.observedRegions.clear(); + this.renderedCards = []; + if (this.frame !== undefined) this.document.defaultView?.cancelAnimationFrame(this.frame); + this.frame = undefined; + } + private syncVisibility() { + if (this.visibilityDestroyed || !this.document.defaultView) return; + const cards = this.graphicCards(); + if (typeof IntersectionObserver === 'undefined') { + for (const card of cards) card.setVisible(true); + return; + } + const orderChanged = cards.length !== this.renderedCards.length || cards.some((card, i) => card !== this.renderedCards[i]); + this.renderedCards = [...cards]; + this.refreshVisibilityObserver(); + let changed = orderChanged; + for (const [region, card] of this.observedRegions) { + if (!cards.includes(card) || card.visibilityRegion?.nativeElement !== region) { + this.visibilityObserver?.unobserve(region); + this.observedRegions.delete(region); + changed = true; + } + } + for (const card of cards) { + const region = card.visibilityRegion?.nativeElement; + if (region && !this.observedRegions.has(region)) { + this.observedRegions.set(region, card); + this.visibilityObserver?.observe(region); + changed = true; + } + } + if (typeof ResizeObserver !== 'undefined') { + this.sizeObserver ??= new ResizeObserver(this.viewportChanged); + const targets = [this.document.querySelector('.institutional-header'), this.element.nativeElement.querySelector('.catalog-grid')] + .filter((target): target is Element => target !== null); + for (const target of this.sizeTargets) { + if (!targets.includes(target)) { this.sizeObserver.unobserve(target); this.sizeTargets.delete(target); } + } + for (const target of targets) { + if (!this.sizeTargets.has(target)) { this.sizeTargets.add(target); this.sizeObserver.observe(target); } + } + } + if (changed) this.visibilityChanged(); + } + private refreshVisibilityObserver() { + const height = Math.max(0, this.document.querySelector('.institutional-header')?.getBoundingClientRect().bottom ?? 0); + if (this.visibilityObserver && Math.abs(height - this.stickyHeight) < 1) return; + this.stickyHeight = height; + this.visibilityObserver?.disconnect(); + const observer = new IntersectionObserver(entries => { + // Callbacks from a replaced observer or retired target cannot authorize activation. + if (this.visibilityDestroyed || this.visibilityObserver !== observer) return; + if (entries.some(entry => this.observedRegions.has(entry.target))) this.queueVisibility(); + }, { root: null, rootMargin: `-${height}px 0px 200px 0px`, threshold: 0 }); + this.visibilityObserver = observer; + for (const region of this.observedRegions.keys()) observer.observe(region); + } + private evaluateVisibility() { + const browser = this.document.defaultView; + if (!browser || this.visibilityDestroyed || !this.visibilityObserver) return; + this.refreshVisibilityObserver(); + const width = browser.innerWidth, height = browser.innerHeight; + // Reread connected graphic regions after scroll/reorder; old observer rectangles + // cannot activate a card that has since moved outside the current viewport. + for (const card of this.renderedCards) { + const region = card.visibilityRegion?.nativeElement; + if (!region || card.dominio !== this.dominio || !region.isConnected) continue; + const rect = region.getBoundingClientRect(); + card.setVisible(rect.width > 0 && rect.height > 0 && rect.right > 0 + && rect.left < width && rect.bottom > this.stickyHeight && rect.top < height + 200); + } + this.changeDetector.markForCheck(); + } + clearSearch() { + this.changeSearchQuery(''); + this.searchInput()?.nativeElement.focus({ preventScroll: true }); + } + changeSearchQuery(query: string) { + this.preserveCardFocus(); + this.searchQuery.set(query); + } + isPinned(item: Indicador) { return this.memory.isPinned(this.dominio, item.id); } + togglePinned(item: Indicador) { + this.preserveCardFocus(); + this.memory.togglePinned(this.dominio, item.id); + } + private preserveCardFocus() { + const focused = this.document.activeElement; + if (focused instanceof HTMLElement && this.element.nativeElement.contains(focused) + && focused.closest('app-indicador-catalog-card')) { + // Moving a retained view can blur its control. Restore only that connected control, + // without overriding focus deliberately assigned elsewhere during the update. + afterNextRender(() => { + if (focused.isConnected && this.document.activeElement === this.document.body) { + focused.focus({ preventScroll: true }); + } + }, { injector: this.injector }); + } + } + private readonly changeDetector = inject(ChangeDetectorRef); + private readonly service = inject(IndicadoresService); + private readonly periodService = inject(IndicadoresPeriodos); + private readonly availabilityRequests = new Subject(); + readonly availability = signal(emptyAvailability()); + private readonly memory = inject(IndicadoresMemory); + private readonly destroyRef = inject(DestroyRef); + private readonly route = inject(ActivatedRoute, { optional: true }); + readonly dominios = DOMINIOS; + dominio: Dominio = 'tea'; + readonly domainLabels: Record = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' }; + readonly kpisByDomain = KPI_BY_DOMAIN; + kpiIndicator(id: string) { return this.catalog().find(item => item.id === id); } + get availableKpis() { return this.kpisByDomain[this.dominio]; } + get initialKpiPresentation() { return !!this.availableKpis.length && this.memory.initialKpiPresentation(this.dominio); } + private readonly catalogRequests = new Subject(); + readonly catalog = signal([]); + readonly searchQuery = signal(''); + readonly searchVisible = computed(() => this.catalog().length >= 5); + readonly searchResults = computed(() => { + const items = this.catalog(); + const query = this.normalizeSearch(this.searchQuery()); + const prioritize = (group: Indicador[]) => [ + ...group.filter(item => this.isPinned(item)), + ...group.filter(item => !this.isPinned(item)), + ]; + if (!query) return { items: prioritize(items), active: false, count: 0 }; + const matches: Indicador[] = []; + const remaining: Indicador[] = []; + for (const item of items) { + const matchesQuery = [item.titulo, item.id].some(value => this.normalizeSearch(value).includes(query)); + (matchesQuery ? matches : remaining).push(item); + } + return { items: [...prioritize(matches), ...prioritize(remaining)], active: true, count: matches.length }; + }); + private normalizeSearch(value: string) { + return value.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase().trim(); + } + readonly catalogLoading = signal(true); + readonly catalogError = signal(''); + tema: Tema = 'claro'; + filters?: GlobalFilterState; + readonly filterTypes = computed(() => domainTypes(this.catalog())); + retryAvailability() { this.availabilityRequests.next(); } + filtersEdited() { if (this.filters) this.memory.saveGlobal(this.dominio, this.filters); } + applyFilters() { + this.evaluateVisibility(); + if (!this.filters) return; + const draft = this.filters.editors[this.filters.tipo]?.draft; + if (!draft || !validDraft(draft, this.filters.tipo, this.filterTypes())) return; + const initial = this.initialKpiPresentation; + this.memory.finishInitialKpiPresentation(this.dominio); + if (!applyGlobal(this.filters, this.filterTypes()) && !initial) return; + this.filtersEdited(); + this.changeDetector.markForCheck(); + } + cardIdentity(item: Indicador) { return indicatorIdentity(this.dominio, item.id); } + constructor() { + afterEveryRender(() => this.syncVisibility()); + const browser = this.document.defaultView; + if (typeof IntersectionObserver !== 'undefined') { + browser?.addEventListener('scroll', this.viewportChanged, { passive: true }); + browser?.addEventListener('resize', this.viewportChanged); + } + this.destroyRef.onDestroy(() => { + this.filtersEdited(); + this.visibilityDestroyed = true; + this.clearVisibility(); + this.sizeObserver?.disconnect(); + this.sizeTargets.clear(); + browser?.removeEventListener('scroll', this.viewportChanged); + browser?.removeEventListener('resize', this.viewportChanged); + }); + const initialDomain: unknown = this.route?.snapshot.data['dominio']; + if (isDominio(initialDomain)) this.dominio = initialDomain; + this.tema = this.memory.theme(this.dominio); + this.availabilityRequests.pipe(switchMap(() => { + this.availability.set(emptyAvailability()); + return this.periodService.dominio(this.dominio, this.catalog()); + }), takeUntilDestroyed(this.destroyRef)).subscribe(state => this.availability.set(state)); + this.catalogRequests.pipe(startWith(undefined), switchMap(() => { + this.clearVisibility(); + this.catalogLoading.set(true); + this.catalogError.set(''); + this.catalog.set([]); + this.availabilityRequests.next(); + return this.service.catalogo(this.dominio).pipe(map(items => ({ items, error: '' })), + catchError(error => of({ items: [] as Indicador[], error: httpMessage(error, true) }))); + }), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => { + this.catalogLoading.set(false); + this.filters = items.length ? this.memory.restoreGlobal(this.dominio, domainTypes(items)) : undefined; + this.catalog.set(items); + this.filtersEdited(); + this.catalogError.set(error); + this.availabilityRequests.next(); + }); + } + changeDominio(dominio: Dominio) { + if (!isDominio(dominio) || dominio === this.dominio) return; + this.searchQuery.set(''); + this.filtersEdited(); + this.filters = undefined; + this.dominio = dominio; + this.tema = this.memory.theme(dominio); + this.catalogRequests.next(); + } + retryCatalog() { this.catalogRequests.next(); } + changeTema(tema: Tema) { + if ((tema !== 'claro' && tema !== 'oscuro') || tema === this.tema) return; + this.evaluateVisibility(); + this.tema = tema; + this.memory.rememberTheme(this.dominio, tema); + this.changeDetector.markForCheck(); + } +} diff --git a/src/app/features/indicadores/indicadores-periodos-integration.spec.ts b/src/app/features/indicadores/indicadores-periodos-integration.spec.ts new file mode 100644 index 0000000..a02b251 --- /dev/null +++ b/src/app/features/indicadores/indicadores-periodos-integration.spec.ts @@ -0,0 +1,124 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { By } from '@angular/platform-browser'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadorKpiPanel } from './indicador-kpi-panel'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { KPI_BY_DOMAIN } from './indicadores-kpi'; +import { Dominio, IndicadorDatos } from './indicadores.models'; + +describe('P0.1 selección publicada y último periodo por KPI', () => { + let fixture: ReturnType>, http: HttpTestingController; + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController); + http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); }); + const payload = (id: string, periods: string[]) => ({ id, periodos: periods.map(periodo => ({ periodo, tipo: periodo.includes('-S') ? 'semestre' : 'mes' })) }); + function catalog(domain: Dominio) { + fixture.componentInstance.changeDominio(domain); fixture.detectChanges(); + http.expectOne('/' + domain + '/indicadores').flush(KPI_BY_DOMAIN[domain].map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }))); + fixture.detectChanges(); + return http.match(r => r.url.endsWith('/periodos')); + } + function load(domain: Dominio, periods: string[][]) { + catalog(domain).forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN[domain][i].id, periods[i]))); + fixture.detectChanges(); + } + function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel); } + function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; } + function data(index: number, domain: Dominio, period: string, suppressed = false): IndicadorDatos { + const d = KPI_BY_DOMAIN[domain][index]; + return { id: d.id, contrato: d.contrato, tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], categorias: { A: {} }, filas: [{ + periodo: period, grupo: index === 1 ? 'total' : 'TOTAL', estrato: null, categoria: 'A', + n: 0, valor: 0, numerador: 0, denominador: 5, mediana: 0, q1: 0, q3: 0, unidad: 'dias', suprimido: suppressed ? 1 : 0, + }] }; + } + function flushDatos(domain: Dominio, suppressed = false) { + const requests = http.match(r => r.url.endsWith('/datos')); + requests.forEach(r => { + const index = KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')); + r.flush(data(index, domain, r.request.params.get('periodos')!, suppressed)); + }); + fixture.detectChanges(); return requests; + } + it.each(['cacu', 'cama'] as const)('%s usa últimos periodos propios, conserva ceros y no altera Todos aplicado', domain => { + load(domain, [['2026-S1', '2024-S2', '2025-S2'], ['2025-S1', '2026-S2', '2025-12'], ['2025-S2', '2024-S1']]); + const requests = flushDatos(domain); + expect(requests.map(r => r.request.params.get('periodos'))).toEqual(['2026-S1', '2026-S2', '2025-S2']); + expect(panels().map(p => p.temporalReference)).toEqual(['2026-S1', '2026-S2', '2025-S2']); + expect(panels().map(p => p.result().value)).toEqual([0, '0.0', 0]); + expect(fixture.componentInstance.filters!.applied.selection).toEqual({ mode: 'todos' }); + expect(fixture.componentInstance.filters!.applied.revision).toBe(0); + fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true); + }); + it('tras Aplicar Todos, supresión del último no busca periodos anteriores ni sustituye cifras', () => { + load('cacu', Array(3).fill(['2024-S1', '2026-S2', '2025-S2'])); + const initial = http.match(r => r.url.endsWith('/datos')); + fixture.componentInstance.applyFilters(); fixture.detectChanges(); + expect(initial.every(r => r.cancelled)).toBe(true); + const requests = flushDatos('cacu', true); + expect(requests.every(r => r.request.params.get('periodos') === '2026-S2')).toBe(true); + expect(panels().every(p => p.result().state === 'Dato oculto por tamaño' && p.result().value === undefined)).toBe(true); + expect(panels().every(p => p.temporalReference === '2026-S2')).toBe(true); http.expectNone(() => true); + }); + it('sin reportes en una tarjeta no consulta datos y no impide las otras', () => { + load('cama', [[], ['2025-S2'], ['2025-S1']]); const requests = flushDatos('cama'); + expect(requests).toHaveLength(2); expect(panels()[0].result().state).toBe('Sin reportes disponibles'); + expect(panels()[0].result().value).toBeUndefined(); + }); + it('multiselección mensual edita sin HTTP; un periodo consulta y varios no consolidan', async () => { + load('cacu', Array(3).fill(['2026-S2', '2025-02', '2025-10', '2026-01'])); flushDatos('cacu'); + const control = editor(); control.changeTipo('mes'); control.select(['2025-10']); fixture.detectChanges(); + expect(control.options).toEqual(['2026-01', '2025-10', '2025-02']); + expect(fixture.nativeElement.querySelector('.period-builder')).toBeNull(); + expect(fixture.nativeElement.textContent).toContain('Existe reporte en al menos un indicador'); + expect(fixture.componentInstance.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true); + fixture.componentInstance.applyFilters(); fixture.detectChanges(); + const single = flushDatos('cacu'); expect(single).toHaveLength(3); + expect(single.every(r => r.request.params.get('periodos') === '2025-10')).toBe(true); + control.select(['2025-10', '2025-02']); fixture.detectChanges(); http.expectNone(() => true); + fixture.componentInstance.applyFilters(); fixture.detectChanges(); + expect(panels().every(p => p.result().state === 'Selección no consolidable' && p.result().value === undefined)).toBe(true); + http.expectNone(() => true); + control.select(['2025-02', '2025-10']); fixture.componentInstance.applyFilters(); fixture.detectChanges(); + http.expectNone(() => true); + await fixture.whenStable(); + }); + it('error de disponibilidad ofrece reintento sin sustituir la selección y conserva éxitos en caché', () => { + const requests = catalog('cacu'); + requests[0].flush('private', { status: 503, statusText: 'Unavailable' }); + requests.slice(1).forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN.cacu[i + 1].id, ['2025-S2']))); + fixture.detectChanges(); flushDatos('cacu'); + expect(panels()[0].result().state).toBe('Error de disponibilidad'); + expect(fixture.nativeElement.textContent).toContain('No se pudo completar la consulta'); + expect(fixture.nativeElement.textContent).not.toContain('private'); + const control = editor(); control.changeMode('manual'); control.select(['2025-S2']); + expect(control.canApply).toBe(false); + fixture.componentInstance.retryAvailability(); fixture.detectChanges(); + const retry = http.expectOne('/cacu/indicadores/cacu_eu7/periodos'); + http.expectNone(r => r.url.endsWith('/periodos')); + retry.flush(payload('cacu_eu7', ['2025-S2'])); fixture.detectChanges(); flushDatos('cacu'); + expect(fixture.componentInstance.filters!.applied.selection.mode).toBe('todos'); + }); + it('cambio de dominio cancela inventarios y evita opciones o valores obsoletos', () => { + const outgoing = catalog('cacu'); const incoming = catalog('cama'); + expect(outgoing.every(r => r.cancelled)).toBe(true); + expect(() => outgoing[0].flush(payload('cacu_eu7', ['2099-S2']))).toThrow(); + incoming.forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN.cama[i].id, ['2025-S1']))); + fixture.detectChanges(); const requests = flushDatos('cama'); + expect(requests.every(r => r.request.url.startsWith('/cama/') && r.request.params.get('periodos') === '2025-S1')).toBe(true); + expect(editor().options).toEqual(['2025-S1']); + }); + it('error y catálogo vacío no inventan opciones ni consultas KPI', () => { + fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); + http.expectOne('/cacu/indicadores').flush('private', { status: 500, statusText: 'Error' }); fixture.detectChanges(); + expect(fixture.componentInstance.catalogError()).toBeTruthy(); http.expectNone(() => true); + fixture.componentInstance.retryCatalog(); http.expectOne('/cacu/indicadores').flush([]); fixture.detectChanges(); + expect(fixture.componentInstance.availability().options.semestre).toEqual([]); http.expectNone(() => true); + }); +}); diff --git a/src/app/features/indicadores/indicadores-periodos.spec.ts b/src/app/features/indicadores/indicadores-periodos.spec.ts new file mode 100644 index 0000000..7dc3808 --- /dev/null +++ b/src/app/features/indicadores/indicadores-periodos.spec.ts @@ -0,0 +1,83 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { Indicador, TipoPeriodo } from './indicadores.models'; +import { IndicadoresPeriodos, parseAvailability, PeriodAvailability, sortedPeriods } from './indicadores-periodos'; + +const item = (id: string, tipos_periodo: TipoPeriodo[] = ['semestre', 'mes']): Indicador => ({ id, titulo: id, contrato: 'C1', figuras: [], tipos_periodo }); +const payload = (id: string, periods: string[]) => ({ id, version: 'test', periodos: periods.map(periodo => ({ periodo, tipo: periodo.includes('-S') ? 'semestre' : 'mes', report_id: 1 })) }); +describe('P0.1 inventarios publicados de periodos', () => { + let service: IndicadoresPeriodos, http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + service = TestBed.inject(IndicadoresPeriodos); http = TestBed.inject(HttpTestingController); + }); + afterEach(() => http.verify()); + it('une coberturas diferentes, deduplica y separa mes/semestre con orden numérico', () => { + let result!: PeriodAvailability; + service.dominio('cacu', [item('a'), item('b')]).subscribe(value => result = value); + http.expectOne('/cacu/indicadores/a/periodos').flush(payload('a', ['2025-S1', '2026-S2', '2025-S1', '2025-02', '2025-10'])); + http.expectOne('/cacu/indicadores/b/periodos').flush(payload('b', ['2024-S2', '2025-10', '2026-01'])); + expect(result.status).toBe('ready'); + expect(result.options).toEqual({ semestre: ['2026-S2', '2025-S1', '2024-S2'], mes: ['2026-01', '2025-10', '2025-02'] }); + expect(result.byIndicator['b'].some(p => p.periodo === '2026-S2')).toBe(false); + }); + it('respeta capacidades individuales y no mezcla dominios en caché', () => { + let result!: PeriodAvailability; + service.dominio('tea', [item('a', ['semestre'])]).subscribe(value => result = value); + http.expectOne('/tea/indicadores/a/periodos').flush(payload('a', ['2025-S1', '2025-01'])); + expect(result.options.mes).toEqual([]); + service.dominio('cama', [item('a')]).subscribe(); + http.expectOne('/cama/indicadores/a/periodos').flush(payload('a', [])); + }); + it('limita a cuatro consultas simultáneas y cancela también la cola', () => { + const sub = service.dominio('tea', Array.from({ length: 9 }, (_, i) => item('i' + i))).subscribe(); + const first = http.match(r => r.url.endsWith('/periodos')); expect(first).toHaveLength(4); + first[0].flush(payload('i0', [])); + const next = http.expectOne('/tea/indicadores/i4/periodos'); + sub.unsubscribe(); + expect(first.slice(1).every(r => r.cancelled)).toBe(true); expect(next.cancelled).toBe(true); + http.expectNone(r => r.url.includes('/i5/')); + }); + it('reutiliza inventarios exitosos sin HTTP y reintenta únicamente errores sin publicar unión parcial', () => { + let result!: PeriodAvailability; + service.dominio('cacu', [item('a'), item('b')]).subscribe(value => result = value); + http.expectOne('/cacu/indicadores/a/periodos').flush(payload('a', ['2025-S1'])); + http.expectOne('/cacu/indicadores/b/periodos').flush('private', { status: 503, statusText: 'Unavailable' }); + expect(result.status).toBe('error'); expect(result.options.semestre).toEqual([]); + expect(result.errors['b']).not.toContain('private'); expect(result.byIndicator['a']).toHaveLength(1); + service.dominio('cacu', [item('a'), item('b')]).subscribe(value => result = value); + http.expectNone('/cacu/indicadores/a/periodos'); + http.expectOne('/cacu/indicadores/b/periodos').flush(payload('b', ['2025-S2'])); + expect(result.options.semestre).toEqual(['2025-S2', '2025-S1']); + service.dominio('cacu', [item('a'), item('b')]).subscribe(); http.expectNone(() => true); + }); + it('un inventario cancelado no entrega respuestas obsoletas ni se conserva como éxito', () => { + const delivered = vi.fn(); + const sub = service.dominio('tea', [item('a')]).subscribe(delivered); + const old = http.expectOne('/tea/indicadores/a/periodos'); sub.unsubscribe(); + expect(old.cancelled).toBe(true); expect(delivered).not.toHaveBeenCalled(); + expect(() => old.flush(payload('a', ['2025-S1']))).toThrow(); + service.dominio('tea', [item('a')]).subscribe(delivered); + http.expectOne('/tea/indicadores/a/periodos').flush(payload('a', [])); + expect(delivered).toHaveBeenCalledOnce(); + }); + it('catálogo vacío y lista vacía son éxito sin periodos inventados', () => { + let result!: PeriodAvailability; + service.dominio('tea', []).subscribe(value => result = value); + expect(result.status).toBe('ready'); expect(result.options.semestre).toEqual([]); http.expectNone(() => true); + service.dominio('tea', [item('a')]).subscribe(value => result = value); + http.expectOne('/tea/indicadores/a/periodos').flush(payload('a', [])); + expect(result.byIndicator['a']).toEqual([]); + }); + it.each([ + null, { id: 'wrong', periodos: [] }, { id: 'a' }, payload('a', ['2025-13']), + { id: 'a', periodos: [{ periodo: '2025-S1', tipo: 'mes' }] }, + ])('rechaza respuestas inválidas sin inventar disponibilidad: %j', value => { + expect(() => parseAvailability(value, 'a')).toThrow(); + }); + it('ordena cambios de año y unidades sin usar el orden accidental', () => { + expect(sortedPeriods(['2026-S1', '2025-S2', '2026-S2'])).toEqual(['2026-S2', '2026-S1', '2025-S2']); + expect(sortedPeriods(['2025-02', '2024-12', '2025-10', '2026-01'])).toEqual(['2026-01', '2025-10', '2025-02', '2024-12']); + }); +}); diff --git a/src/app/features/indicadores/indicadores-periodos.testing.ts b/src/app/features/indicadores/indicadores-periodos.testing.ts new file mode 100644 index 0000000..5cee482 --- /dev/null +++ b/src/app/features/indicadores/indicadores-periodos.testing.ts @@ -0,0 +1,23 @@ +import { NEVER, of } from 'rxjs'; +import { Indicador } from './indicadores.models'; +import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos'; +import { IndicadoresKpiQueries } from './indicadores-kpi-queries'; + +// Existing figure/search/visibility suites isolate their HTTP from availability. +// The new P0.1 suites exercise the real availability HTTP separately. +export const periodAvailabilityProvider = { + provide: IndicadoresPeriodos, + useValue: { dominio: (_domain: unknown, catalog: Indicador[]) => { + const state = emptyAvailability('ready'); + for (const tipo of ['semestre', 'mes'] as const) { + state.options[tipo] = [2024, 2025, 2026].flatMap(year => + (tipo === 'semestre' ? ['S1', 'S2'] : Array.from({ length: 12 }, (_, i) => String(i + 1).padStart(2, '0'))).map(unit => year + '-' + unit)); + } + for (const item of catalog) state.byIndicator[item.id] = item.tipos_periodo.flatMap(tipo => state.options[tipo].map(periodo => ({ tipo, periodo }))); + return of(state); + } }, +}; + +// Figure/search/visibility suites also isolate their HTTP from the KPI panels, +// which every domain (TEA included) now renders. KPI suites use the real queries. +export const kpiQueriesProvider = { provide: IndicadoresKpiQueries, useValue: { datos: () => NEVER } }; diff --git a/src/app/features/indicadores/indicadores-periodos.ts b/src/app/features/indicadores/indicadores-periodos.ts new file mode 100644 index 0000000..f5fca93 --- /dev/null +++ b/src/app/features/indicadores/indicadores-periodos.ts @@ -0,0 +1,79 @@ +import { inject, Injectable } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; +import { catchError, from, map, mergeMap, Observable, of, shareReplay, toArray } from 'rxjs'; +import { Dominio, Indicador, parsePeriodos, requireDominio, TipoPeriodo } from './indicadores.models'; +import { httpMessage } from './indicadores-http'; +import { IndicadoresRequests } from './indicadores-requests'; + +export interface AvailablePeriod { periodo: string; tipo: TipoPeriodo; } +export interface PeriodAvailability { + status: 'loading' | 'ready' | 'error'; + byIndicator: Record; + options: Record; + errors: Record; +} +export function emptyAvailability(status: PeriodAvailability['status'] = 'loading'): PeriodAvailability { + return { status, byIndicator: {}, options: { semestre: [], mes: [] }, errors: {} }; +} +// Numeric year/unit comparison, independent of server order and report generation date. +export function periodOrder(period: string): number { + return Number(period.slice(0, 4)) * 12 + (period.includes('-S') ? Number(period.slice(6)) * 6 : Number(period.slice(5))); +} +export function sortedPeriods(periods: readonly string[]): string[] { + return [...new Set(periods)].sort((a, b) => periodOrder(b) - periodOrder(a)); +} +function record(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} +export function parseAvailability(value: unknown, id: string): AvailablePeriod[] { + if (!record(value) || value['id'] !== id || !Array.isArray(value['periodos'])) throw new Error('Respuesta de periodos inválida'); + const unique = new Map(); + for (const row of value['periodos']) { + if (!record(row) || (row['tipo'] !== 'semestre' && row['tipo'] !== 'mes') + || typeof row['periodo'] !== 'string' || parsePeriodos(row['periodo'], row['tipo'])?.[0] !== row['periodo']) { + throw new Error('Respuesta de periodos inválida'); + } + unique.set(row['periodo'], { periodo: row['periodo'], tipo: row['tipo'] }); + } + return [...unique.values()].sort((a, b) => periodOrder(b.periodo) - periodOrder(a.periodo)); +} +@Injectable({ providedIn: 'root' }) +export class IndicadoresPeriodos { + private readonly http = inject(HttpClient); + private readonly requests = inject(IndicadoresRequests); + // Successful inventories live only in memory. Errors reset; cancelled HTTP is not cached. + private readonly cache = new Map>(); + periodos(domain: Dominio, id: string) { + const dominio = requireDominio(domain); + const key = JSON.stringify([dominio, id]); + let request = this.cache.get(key); + if (!request) { + request = this.requests.run(() => this.http.get(`/${dominio}/indicadores/${encodeURIComponent(id)}/periodos`)).pipe( + map(value => parseAvailability(value, id)), shareReplay({ bufferSize: 1, refCount: true })); + this.cache.set(key, request); + } + return request; + } + dominio(domain: Dominio, catalog: readonly Indicador[]): Observable { + return from(catalog).pipe( + mergeMap(item => this.periodos(domain, item.id).pipe( + map(periods => ({ id: item.id, periods: periods.filter(p => item.tipos_periodo.includes(p.tipo)), error: '' })), + catchError(error => of({ id: item.id, periods: [] as AvailablePeriod[], error: httpMessage(error) }))), 4), + toArray(), + map(results => { + const state = emptyAvailability('ready'); + for (const result of results) { + if (result.error) state.errors[result.id] = result.error; + else state.byIndicator[result.id] = result.periods; + } + state.status = Object.keys(state.errors).length ? 'error' : 'ready'; + // Do not publish an incomplete union as a successful inventory. + if (state.status === 'ready') { + for (const tipo of ['semestre', 'mes'] as const) { + state.options[tipo] = sortedPeriods(Object.values(state.byIndicator).flat().filter(p => p.tipo === tipo).map(p => p.periodo)); + } + } + return state; + })); + } +} diff --git a/src/app/features/indicadores/indicadores-pinning.spec.ts b/src/app/features/indicadores/indicadores-pinning.spec.ts new file mode 100644 index 0000000..8906a5e --- /dev/null +++ b/src/app/features/indicadores/indicadores-pinning.spec.ts @@ -0,0 +1,131 @@ +import { periodAvailabilityProvider } from './indicadores-periodos.testing'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { By } from '@angular/platform-browser'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; +import { IndicadoresMemory } from './indicadores-memory'; +import { Indicador } from './indicadores.models'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; + +const items: Indicador[] = ['Edad', 'Evaluación inicial', 'Sexo', 'Seguimiento', 'Evaluación final'].map((titulo, i) => ({ + id: 'i' + i, titulo, contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'], +})); + +describe('UX-06E.D.3.B fijación temporal', () => { + let fixture: ReturnType>; + let page: IndicadoresPage; + let http: HttpTestingController; + const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } }; + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + runtime.react.mockReset().mockResolvedValue(undefined); runtime.purge.mockReset(); runtime.Plots.resize.mockReset().mockResolvedValue(undefined); + vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, + { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); + create(); load(); + }); + afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); + function create() { fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController); } + function load(domain = 'tea') { http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); } + function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } + function card(id: string) { return cards().find(c => c.indicador.id === id)!; } + function ids() { return cards().map(c => c.indicador.id); } + function button(id: string): HTMLButtonElement { return card(id).host.nativeElement.querySelector('.pin-toggle')!; } + async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); } + async function pin(id: string) { button(id).click(); fixture.detectChanges(); await settle(); } + function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [1] }], layout: {} })); fixture.detectChanges(); } + + it('fija y desfija con control nativo, texto, estado accesible y sin HTTP', async () => { + const control = button('i3'); + expect(control.type).toBe('button'); expect(control.tabIndex).toBe(0); + expect(control.textContent).toContain('Fijar indicador'); expect(control.getAttribute('aria-pressed')).toBe('false'); + expect(control.getAttribute('aria-label')).toContain('Fijar indicador'); + for (const key of ['Enter', ' ']) { + const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); + control.dispatchEvent(event); expect(event.defaultPrevented).toBe(false); + } + await pin('i3'); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']); + expect(button('i3')).toBe(control); expect(control.getAttribute('aria-pressed')).toBe('true'); + expect(control.textContent).toContain('Desfijar indicador'); expect(control.getAttribute('aria-label')).toContain('Desfijar indicador'); + await pin('i3'); expect(ids()).toEqual(items.map(i => i.id)); expect(control.getAttribute('aria-pressed')).toBe('false'); + http.expectNone(() => true); + }); + it('varios fijados conservan orden del catálogo, independientemente del orden de clics', async () => { + const original = page.catalog(), snapshot = JSON.stringify(original); + await pin('i4'); await pin('i2'); await pin('i0'); + expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']); + await pin('i2'); expect(ids()).toEqual(['i0', 'i4', 'i1', 'i2', 'i3']); + await pin('i2'); expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']); + expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); http.expectNone(() => true); + }); + it('coincidencias preceden a los fijados no coincidentes y la fijación resuelve cada grupo', async () => { + await pin('i3'); await pin('i4'); + page.changeSearchQuery(' EVALUACION '); fixture.detectChanges(); await settle(); + expect(ids()).toEqual(['i4', 'i1', 'i3', 'i0', 'i2']); + expect(page.searchResults().count).toBe(2); expect(page.searchResults().active).toBe(true); + await pin('i1'); expect(ids()).toEqual(['i1', 'i4', 'i3', 'i0', 'i2']); + expect(cards()).toHaveLength(items.length); http.expectNone(() => true); + }); + it('limpiar mediante el buscador restaura fijados primero y mantiene foco', async () => { + await pin('i3'); page.changeSearchQuery('Edad'); fixture.detectChanges(); await settle(); + expect(ids()[0]).toBe('i0'); + fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle(); + expect(page.searchQuery()).toBe(''); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']); + expect(document.activeElement).toBe(fixture.nativeElement.querySelector('.catalog-search input')); http.expectNone(() => true); + }); + it('búsqueda sin coincidencias conserva todo el catálogo con prioridad de fijados', async () => { + await pin('i2'); page.changeSearchQuery('inexistente'); fixture.detectChanges(); await settle(); + expect(ids()).toEqual(['i2', 'i0', 'i1', 'i3', 'i4']); expect(page.searchResults().count).toBe(0); + expect(fixture.nativeElement.textContent).toContain('El catálogo completo permanece disponible'); http.expectNone(() => true); + }); + it('memoria independiente por dominio y persistente al recrear la página', async () => { + await pin('i3'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id)); + await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual(items.map(i => i.id)); + await pin('i4'); page.changeDominio('cacu'); load('cacu'); expect(ids()[0]).toBe('i1'); + page.changeDominio('tea'); load(); expect(ids()[0]).toBe('i3'); + fixture.destroy(); create(); load(); expect(ids()[0]).toBe('i3'); http.expectNone(() => true); + }); + it('no usa Storage y una nueva memoria reinicia la fijación', async () => { + const read = vi.spyOn(Storage.prototype, 'getItem'), write = vi.spyOn(Storage.prototype, 'setItem'); + await pin('i2'); expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i2')).toBe(true); + expect(new IndicadoresMemory().isPinned('tea', 'i2')).toBe(false); + expect(read).not.toHaveBeenCalled(); expect(write).not.toHaveBeenCalled(); http.expectNone(() => true); + }); + it('mover la tarjeta conserva foco en su botón existente', async () => { + const control = button('i4'); control.focus(); await pin('i4'); + expect(control.isConnected).toBe(true); expect(document.activeElement).toBe(control); + await pin('i4'); expect(document.activeElement).toBe(control); http.expectNone(() => true); + }); + it('preserva figura seleccionada, estado de visibilidad, panel y host Plotly', async () => { + card('i3').setVisible(true); fixture.detectChanges(); respond(); await settle(); + card('i3').selectFigure('g'); fixture.detectChanges(); respond(); await settle(); + + const before = cards(), panel = fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance; + const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart; + const host = chart.host.nativeElement, result = panel.result(), applied = page.filters!.applied; + const reacts = runtime.react.mock.calls.length, purges = runtime.purge.mock.calls.length; + for (const id of ['i3', 'i1', 'i3']) { + await pin(id); + for (const c of before) expect(card(c.indicador.id)).toBe(c); + expect(card('i3').visible).toBe(true); expect(card('i3').selectedFigure).toBe('g'); expect(card('i3').visible).toBe(true); + expect(card('i1').visible).toBe(false); + expect(fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance).toBe(panel); + expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance).toBe(chart); + expect(chart.host.nativeElement).toBe(host); expect(panel.result()).toBe(result); expect(page.filters!.applied).toBe(applied); + http.expectNone(() => true); + } + expect(runtime.react).toHaveBeenCalledTimes(reacts); expect(runtime.purge).toHaveBeenCalledTimes(purges); + }); + it('mover un panel cargando conserva su petición sin cancelar ni duplicar', async () => { + card('i4').setVisible(true); fixture.detectChanges(); const request = http.expectOne(r => r.url.endsWith('/i4/figuras/f')); + const panel = fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance; + await pin('i4'); expect(request.cancelled).toBe(false); + expect(fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance).toBe(panel); http.expectNone(() => true); + request.flush({ data: [{ y: [7] }], layout: {} }); await settle(); expect(panel.result().figure.data[0].y).toEqual([7]); + }); +}); diff --git a/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts b/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts new file mode 100644 index 0000000..51019e9 --- /dev/null +++ b/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts @@ -0,0 +1,102 @@ +import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { By } from '@angular/platform-browser'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; + +describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () => { + let fixture: ReturnType>; + let http: HttpTestingController; + const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } }; + const disconnects: ReturnType[] = []; + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + vi.resetAllMocks(); disconnects.length = 0; + runtime.react.mockResolvedValue(undefined); runtime.Plots.resize.mockResolvedValue(undefined); + vi.stubGlobal('ResizeObserver', class { + disconnect = vi.fn(); unobserve = vi.fn(); + // Material outline labels also observe size; track only Plotly hosts here. + observe = vi.fn((target: Element) => { if (target.classList.contains('plot')) disconnects.push(this.disconnect); }); + }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider, + { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); + fixture = TestBed.createComponent(IndicadoresPage); + vi.spyOn(fixture.componentInstance as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController); + http.expectOne('/tea/indicadores').flush([{ id: 'i', titulo: 'I', contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'] }, { id: 'j', titulo: 'J', contrato: 'C1', figuras: ['g'], tipos_periodo: ['semestre'] }]); + fixture.detectChanges(); + for (const entry of fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard))) (entry.componentInstance as IndicadorCatalogCard).setVisible(true); + fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); }); + async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); } + function respond() { + http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: { annotations: [{ text: 'Nota' }] } })); + fixture.detectChanges(); + } + it('dos gráficos poseen hosts y etiquetas independientes y purgan al contraer', async () => { + respond(); await settle(); const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart)); + expect(charts).toHaveLength(2); expect(runtime.react).toHaveBeenCalledTimes(2); + const hosts = charts.map(c => c.componentInstance.host.nativeElement); + expect(hosts[0]).not.toBe(hosts[1]); expect(hosts[0].getAttribute('aria-label')).toBe('tea · i · f'); + expect(hosts[1].getAttribute('aria-label')).toBe('tea · j · g'); + const card = fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard; + fixture.componentInstance.catalog.set(fixture.componentInstance.catalog().slice(1)); fixture.detectChanges(); + expect(runtime.purge).toHaveBeenCalledWith(hosts[0]); + expect(runtime.purge).not.toHaveBeenCalledWith(hosts[1]); + expect(disconnects[0]).toHaveBeenCalledTimes(1); expect(disconnects[1]).not.toHaveBeenCalled(); + expect(fixture.debugElement.queryAll(By.directive(PlotlyChart))).toHaveLength(1); + }); + it('cambiar representación purga el host saliente y conserva el host del otro indicador', async () => { + respond(); await settle(); + const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart)); + const outgoing = charts[0].componentInstance.host.nativeElement; + const other = charts[1].componentInstance.host.nativeElement; + const card = fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard; + card.selectFigure('g'); fixture.detectChanges(); + expect(runtime.purge).toHaveBeenCalledWith(outgoing); expect(runtime.purge).not.toHaveBeenCalledWith(other); + http.expectOne(r => r.url.endsWith('/i/figuras/g')).flush({ data: [{ y: [3] }], layout: {} }); await settle(); + const current = fixture.debugElement.queryAll(By.directive(PlotlyChart)); + expect(current[0].componentInstance.host.nativeElement).not.toBe(outgoing); + expect(current[1].componentInstance.host.nativeElement).toBe(other); + expect(runtime.react.mock.calls.filter(c => c[0] === other)).toHaveLength(1); + }); + it('un error de renderizado y su reintento no afectan la otra instancia', async () => { + runtime.react.mockRejectedValueOnce(new Error('render')); + respond(); await settle(); const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart)); + expect(charts[0].componentInstance.status()).toBe('error'); expect(charts[1].componentInstance.status()).toBe('ready'); + const otherHost = charts[1].componentInstance.host.nativeElement; + charts[0].componentInstance.retry(); await settle(); + expect(charts[0].componentInstance.status()).toBe('ready'); expect(charts[1].componentInstance.status()).toBe('ready'); + expect(runtime.react.mock.calls.filter(c => c[0] === otherHost)).toHaveLength(1); http.expectNone(() => true); + }); + it('destruir la página desconecta y purga todas las instancias salientes', async () => { + respond(); await settle(); fixture.destroy(); + expect(runtime.purge).toHaveBeenCalledTimes(2); expect(disconnects).toHaveLength(2); + for (const disconnect of disconnects) expect(disconnect).toHaveBeenCalledTimes(1); + }); + it('D.2 conserva hosts reales ocultando resultados anteriores durante carga e incompatibilidad', async () => { + respond(); await settle(); + const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart)); + const hosts = charts.map(c => c.componentInstance.host.nativeElement); + const page = fixture.componentInstance; + page.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S1'] }; + page.applyFilters(); fixture.detectChanges(); + expect(fixture.debugElement.queryAll(By.directive(PlotlyChart)).map(c => c.componentInstance)).toEqual(charts.map(c => c.componentInstance)); + for (const host of hosts) expect(host.closest('[hidden]')).toBeTruthy(); + expect(runtime.purge).not.toHaveBeenCalled(); + respond(); await settle(); + for (const host of hosts) expect(host.closest('[hidden]')).toBeNull(); + expect(fixture.debugElement.queryAll(By.directive(PlotlyChart)).map(c => c.componentInstance.host.nativeElement)).toEqual(hosts); + // Published capability change is evaluated by each existing consumer. + const current = page.catalog()[0]; + page.catalog.set(page.catalog().map(item => ({ ...item, tipos_periodo: ['mes'] }))); fixture.detectChanges(); await settle(); + for (const host of hosts) expect(host.closest('[hidden]')).toBeTruthy(); + expect(fixture.nativeElement.querySelectorAll('.incompatible')).toHaveLength(2); + expect(runtime.purge).not.toHaveBeenCalled(); http.expectNone(() => true); + }); +}); diff --git a/src/app/features/indicadores/indicadores-requests.ts b/src/app/features/indicadores/indicadores-requests.ts new file mode 100644 index 0000000..f96a7db --- /dev/null +++ b/src/app/features/indicadores/indicadores-requests.ts @@ -0,0 +1,35 @@ +import { Injectable } from '@angular/core'; +import { defer, finalize, Observable, Subscription } from 'rxjs'; + +// Shared by availability and KPI data; figure requests retain their existing lifecycle. +@Injectable({ providedIn: 'root' }) +export class IndicadoresRequests { + private active = 0; + private readonly queue: (() => void)[] = []; + run(request: () => Observable): Observable { + return new Observable(subscriber => { + let started = false; + let subscription: Subscription | undefined; + const start = () => { + started = true; + this.active++; + subscription = defer(request).pipe(finalize(() => { + this.active--; + this.drain(); + })).subscribe(subscriber); + }; + if (this.active < 4) start(); + else this.queue.push(start); + return () => { + if (!started) { + const index = this.queue.indexOf(start); + if (index >= 0) this.queue.splice(index, 1); + } + subscription?.unsubscribe(); + }; + }); + } + private drain() { + while (this.active < 4 && this.queue.length) this.queue.shift()!(); + } +} diff --git a/src/app/features/indicadores/indicadores-search.spec.ts b/src/app/features/indicadores/indicadores-search.spec.ts new file mode 100644 index 0000000..ad8db27 --- /dev/null +++ b/src/app/features/indicadores/indicadores-search.spec.ts @@ -0,0 +1,224 @@ +import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { By } from '@angular/platform-browser'; +import { NgModel } from '@angular/forms'; +import { MatSelect } from '@angular/material/select'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { IndicadoresMemory } from './indicadores-memory'; +import { Indicador } from './indicadores.models'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; + +const items: Indicador[] = [ + { id: 'A01', titulo: 'Edad', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] }, + { id: 'B02', titulo: 'Evaluación inicial', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] }, + { id: 'M02_sexo', titulo: 'Distribución por sexo', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] }, + { id: 'D04', titulo: 'Seguimiento', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] }, + { id: 'E05', titulo: 'Evaluación final', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] }, +]; + +describe('UX-05C búsqueda local y partición estable', () => { + let fixture: ReturnType>; + let page: IndicadoresPage; + let http: HttpTestingController; + const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } }; + const disconnect = vi.fn(); + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + vi.resetAllMocks(); runtime.react.mockResolvedValue(undefined); runtime.Plots.resize.mockResolvedValue(undefined); + vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = disconnect; }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider, + { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); + fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); }); + function load(catalog = items, domain = 'tea') { + http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges(); + } + function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } + function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); } + function filters() { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters)).map(e => e.componentInstance as IndicadorPeriodFilters); } + function charts() { return fixture.debugElement.queryAll(By.directive(PlotlyChart)).map(e => e.componentInstance as PlotlyChart); } + function input(): HTMLInputElement { return fixture.nativeElement.querySelector('.catalog-search input'); } + async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); } + async function search(value: string) { + input().value = value; input().dispatchEvent(new Event('input', { bubbles: true })); fixture.detectChanges(); await settle(); + } + function respond() { + http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: {} })); fixture.detectChanges(); + } + function request(id: string) { return http.expectOne(r => r.url.endsWith('/' + id + '/figuras/f')); } + + it.each([0, 1, 4, 5, 18, 37])('muestra búsqueda exclusivamente desde cinco: catálogo de %i', count => { + load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i }))); + expect(!!input()).toBe(count >= 5); expect(cards()).toHaveLength(count); + expect(cards().every(c => !c.visible)).toBe(true); + http.expectNone(() => true); + if (!count) expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); + }); + it.each([ + ['sexo', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1], + ['M02', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1], + ['tribuci', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1], + ['SEXO', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1], + ['evaluacion', ['B02', 'E05', 'A01', 'M02_sexo', 'D04'], 2], + [' EVALUACIÓN ', ['B02', 'E05', 'A01', 'M02_sexo', 'D04'], 2], + ['imposible', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0], + ['', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0], + [' ', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0], + ])('consulta %s preserva todos los objetos y el catálogo original', async (query, ids, count) => { + load(); const original = page.catalog(), snapshot = JSON.stringify(original), before = cards(); + await search(query as string); + expect(cards().map(c => c.indicador.id)).toEqual(ids); + expect(page.searchResults().count).toBe(count); expect(page.searchResults().active).toBe(!!(query as string).trim()); + expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); + for (const card of cards()) { + expect(card).toBe(before.find(c => c.indicador.id === card.indicador.id)); + expect(card.indicador).toBe(original.find(i => i.id === card.indicador.id)); expect(card.visible).toBe(false); + } + if (query === 'imposible') expect(fixture.nativeElement.textContent).toContain('El catálogo completo permanece disponible'); + if (!(query as string).trim()) expect(fixture.nativeElement.querySelector('#catalog-search-result').textContent.trim()).toBe(''); + http.expectNone(() => true); + }); + it('D.1 mantiene KPI fuera de la búsqueda y del recuento y utiliza un único suffix Material', async () => { + load(); await settle(); + const kpis = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')); + const field = fixture.nativeElement.querySelector('.catalog-search mat-form-field') as HTMLElement; + const clear = field.querySelector('button')!; + expect(clear.hasAttribute('matIconSuffix')).toBe(true); + expect(clear.closest('.mat-mdc-form-field-icon-suffix')).toBeTruthy(); + expect(fixture.nativeElement.querySelectorAll('.catalog-search button')).toHaveLength(1); + expect(input().type).toBe('search'); + for (const query of ['sexo', 'Indicador destacado', '']) { + await search(query); + expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card'))).toEqual(kpis); + expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('5 indicadores publicados'); + expect(cards()).toHaveLength(5); + } + http.expectNone(() => true); + }); + it('escritura y limpieza mantienen foco, cursor, etiqueta y ayudas sin HTTP', async () => { + load(); await settle(); const field = input(); field.focus(); await search('sexo'); + expect(document.activeElement).toBe(field); expect(field.value).toBe('sexo'); + field.setSelectionRange(2, 2); fixture.detectChanges(); await settle(); expect(field.selectionStart).toBe(2); expect(field.selectionEnd).toBe(2); + expect(field.labels?.[0].textContent).toContain('Buscar indicadores'); + for (const id of field.getAttribute('aria-describedby')!.split(' ')) expect(document.getElementById(id)).toBeTruthy(); + expect(fixture.nativeElement.querySelector('#catalog-search-result').getAttribute('aria-live')).toBeNull(); + const clear = fixture.nativeElement.querySelector('.catalog-search button') as HTMLButtonElement; + expect(clear.getAttribute('aria-label')).toBe('Limpiar búsqueda'); clear.focus(); expect(document.activeElement).toBe(clear); clear.click(); fixture.detectChanges(); await settle(); + expect(page.searchQuery()).toBe(''); expect(field.value).toBe(''); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id)); + expect(clear.disabled).toBe(true); expect(input()).toBe(field); expect(document.activeElement).toBe(field); + await search('edad'); field.setSelectionRange(2, 2); expect(document.activeElement).toBe(field); expect(field.selectionStart).toBe(2); + http.expectNone(() => true); + }); + it('botón nativo iconográfico conserva nombre, semántica, tamaño y estado sin HTTP', async () => { + load(); await settle(); + const clear = fixture.nativeElement.querySelector('.catalog-search button') as HTMLButtonElement; + expect(clear.type).toBe('button'); expect(clear.disabled).toBe(true); + expect(clear.getAttribute('aria-label')).toBe('Limpiar búsqueda'); + const icon = clear.querySelector('mat-icon')!; + expect(icon.textContent).toBe('close'); expect(icon.getAttribute('aria-hidden')).toBe('true'); + expect(clear.textContent).not.toContain('Limpiar'); + expect(getComputedStyle(clear).width).toBe('48px'); expect(getComputedStyle(clear).height).toBe('48px'); + await search('sexo'); expect(clear.disabled).toBe(false); expect(clear.tabIndex).toBe(0); + // jsdom does not synthesize native keyboard activation. Verify that keys remain + // available to the browser; Enter/Space activation is a Chrome acceptance check. + for (const key of ['Enter', ' ']) { + const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); + clear.dispatchEvent(event); expect(event.defaultPrevented).toBe(false); + } + clear.focus(); clear.click(); fixture.detectChanges(); await settle(); + expect(document.activeElement).toBe(input()); expect(clear.disabled).toBe(true); + http.expectNone(() => true); + }); + it('tres tarjetas abiertas conservan paneles, borrador/aplicado, Forms, memoria y hosts Plotly sin react/purge', async () => { + load(); cards().slice(0, 3).forEach(c => c.setVisible(true)); fixture.detectChanges(); respond(); await settle(); + const beforeCards = cards(), beforePanels = panels(), beforeFilters = filters(), beforeCharts = charts(); + const c = beforeFilters[0]; c.changeMode('manual'); c.year = '2025'; c.unit = 'S1'; c.add(); + page.applyFilters(); fixture.detectChanges(); respond(); await settle(); + c.year = '2025'; c.unit = 'S2'; c.add(); c.year = '2026'; + fixture.detectChanges(); await settle(); + const states = beforePanels.map(p => p.applied), results = beforePanels.map(p => p.result()); + const titleIds = beforePanels.map(p => p.titleId); + expect(new Set(titleIds).size).toBe(beforePanels.length); + const snapshots = states.map(s => JSON.stringify(s)), hosts = beforeCharts.map(c => c.host.nativeElement); + const selects = fixture.debugElement.queryAll(By.directive(MatSelect)).filter(e => e.componentInstance.multiple); + const writes = selects.map(e => vi.spyOn(e.injector.get(NgModel).control, 'setValue')); + const memory = TestBed.inject(IndicadoresMemory), saves = vi.spyOn(memory, 'saveGlobal'), restores = vi.spyOn(memory, 'restoreGlobal'); + const reacts = runtime.react.mock.calls.length; + const helps = [...fixture.nativeElement.querySelectorAll('.methodology-toggle')] as HTMLButtonElement[]; + expect(helps).toHaveLength(5); + const helpIds = helps.map(button => button.getAttribute('aria-controls')!); + expect(new Set(helpIds).size).toBe(5); + for (const id of helpIds) expect(document.getElementById(id)?.hidden).toBe(true); + helps[0].click(); fixture.detectChanges(); await settle(); + expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false', 'false', 'false']); + expect(helpIds.map(id => document.getElementById(id)?.hidden)).toEqual([false, true, true, true, true]); + for (const query of ['sexo', 'evaluacion', '']) { + if (query) await search(query); + else { fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle(); } + for (const card of beforeCards) expect(cards().find(c => c.indicador.id === card.indicador.id)).toBe(card); + for (const panel of beforePanels) expect(panels().find(p => p.indicador.id === panel.indicador.id)).toBe(panel); + beforeFilters.forEach(c => expect(filters().find(f => f.state === c.state)).toBe(c)); + beforeCharts.forEach(c => expect(charts().find(chart => chart.host.nativeElement === c.host.nativeElement)).toBe(c)); + } + expect(cards()).toEqual(beforeCards); expect(beforeCards.slice(0, 3).every(c => c.visible)).toBe(true); + for (const button of helps) expect(button.isConnected).toBe(true); + expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false', 'false', 'false']); + helps[0].click(); fixture.detectChanges(); await settle(); + expect(document.getElementById(helpIds[0])?.hidden).toBe(true); + expect(panels()).toEqual(beforePanels); expect(filters()).toEqual(beforeFilters); expect(charts()).toEqual(beforeCharts); + expect(beforePanels.map(p => p.titleId)).toEqual(titleIds); + for (const id of titleIds) { + const heading = document.getElementById(id)!; + expect(heading.tagName).toBe('H3'); expect(heading.parentElement!.getAttribute('aria-labelledby')).toBe(id); + } + beforePanels.forEach((p, i) => { expect(p.applied).toBe(states[i]); expect(JSON.stringify(p.applied)).toBe(snapshots[i]); expect(p.result()).toBe(results[i]); }); + beforeCharts.forEach((c, i) => expect(c.host.nativeElement).toBe(hosts[i])); + expect(c.year).toBe('2026'); expect(c.unit).toBe('S2'); expect(c.selectedPeriods).toEqual(['2025-S1', '2025-S2']); + for (const write of writes) expect(write).not.toHaveBeenCalled(); + expect(saves).not.toHaveBeenCalled(); expect(restores).not.toHaveBeenCalled(); + expect(runtime.react).toHaveBeenCalledTimes(reacts); expect(runtime.purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled(); + http.expectNone(() => true); + }); + it('reordenar conserva un panel cargando y otro con error; completar y reintentar siguen siendo independientes', async () => { + load(); cards().slice(0, 3).forEach(c => c.setVisible(true)); fixture.detectChanges(); + const before = panels(), a = request('A01'), b = request('B02'), c = request('M02_sexo'); + b.flush('private', { status: 404, statusText: 'Not Found' }); c.flush({ data: [{ y: [3] }], layout: {} }); await settle(); + await search('sexo'); expect(a.cancelled).toBe(false); expect(before[0].result().status).toBe('loading'); expect(before[1].result().status).toBe('error'); + expect(panels()).toEqual([before[2], before[0], before[1]]); http.expectNone(() => true); + a.flush({ data: [{ y: [1] }], layout: {} }); await settle(); expect(before[0].result().figure?.data[0]['y']).toEqual([1]); + const other = before[2].result(); before[1].requestFigure(); request('B02').flush({ data: [{ y: [2] }], layout: {} }); + expect(before[2].result()).toBe(other); await search(''); expect(panels()).toEqual(before); http.expectNone(() => true); + }); + it('reordenar el catálogo conserva foco en el selector global existente', async () => { + load(); cards()[2].setVisible(true); fixture.detectChanges(); respond(); await settle(); + filters()[0].changeMode('manual'); fixture.detectChanges(); await settle(); + const field = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-period-filters mat-select') as NodeListOf).at(-1)!; + field.focus(); expect(document.activeElement).toBe(field); + page.changeSearchQuery('sexo'); fixture.detectChanges(); await settle(); + expect(document.activeElement).toBe(field); expect(field.isConnected).toBe(true); + page.changeSearchQuery(''); fixture.detectChanges(); await settle(); expect(document.activeElement).toBe(field); + http.expectNone(() => true); + }); + it('cambiar de dominio limpia búsqueda y volver conserva figura y borrador mediante memoria existente', async () => { + load(); cards()[2].setVisible(true); fixture.detectChanges(); respond(); await settle(); + filters()[0].changeMode('manual'); filters()[0].year = '2025'; filters()[0].unit = 'S1'; filters()[0].add(); + await search('sexo'); page.changeDominio('cacu'); fixture.detectChanges(); expect(page.searchQuery()).toBe(''); + load([{ ...items[0], figuras: [] }], 'cacu'); expect(input()).toBeNull(); expect(cards()[0].visible).toBe(false); + page.changeDominio('tea'); fixture.detectChanges(); load(); expect(page.searchQuery()).toBe(''); + expect(cards().map(c => c.visible)).toEqual([false, false, false, false, false]); + http.expectNone(() => true); cards()[2].setVisible(true); fixture.detectChanges(); + const r = request('M02_sexo'); expect(r.request.params.has('periodos')).toBe(false); r.flush({ data: [], layout: {} }); + expect(filters()[0].selectedPeriods).toEqual(['2025-S1']); + await search('sexo'); fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); load(); respond(); + expect(page.searchQuery()).toBe(''); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id)); + }); +}); diff --git a/src/app/features/indicadores/indicadores-visibility.spec.ts b/src/app/features/indicadores/indicadores-visibility.spec.ts new file mode 100644 index 0000000..5aacf8e --- /dev/null +++ b/src/app/features/indicadores/indicadores-visibility.spec.ts @@ -0,0 +1,221 @@ +import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing'; +import { Component } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { By } from '@angular/platform-browser'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { IndicadorFigureCard } from './indicador-figure-card'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { IndicadoresMemory } from './indicadores-memory'; +import { Indicador } from './indicadores.models'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; + +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) +class ChartStub {} +const items: Indicador[] = Array.from({ length: 5 }, (_, i) => ({ + id: 'i' + i, titulo: 'Indicador ' + i, contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'], +})); + +// jsdom geometry and browser notifications are explicit, independent inputs. +class IntersectionControl { + static instances: IntersectionControl[] = []; + readonly targets = new Set(); + observe = vi.fn((target: Element) => this.targets.add(target)); + unobserve = vi.fn((target: Element) => this.targets.delete(target)); + disconnect = vi.fn(() => this.targets.clear()); + constructor(readonly callback: IntersectionObserverCallback, readonly options: IntersectionObserverInit) { + IntersectionControl.instances.push(this); + } + emit(target: Element, isIntersecting = true) { + this.callback([{ target, isIntersecting, intersectionRatio: isIntersecting ? 1 : 0 } as IntersectionObserverEntry], this as unknown as IntersectionObserver); + } +} +class ResizeControl { + static instances: ResizeControl[] = []; + readonly targets = new Set(); + observe = vi.fn((target: Element) => this.targets.add(target)); + unobserve = vi.fn((target: Element) => this.targets.delete(target)); + disconnect = vi.fn(() => this.targets.clear()); + constructor(readonly callback: ResizeObserverCallback) { ResizeControl.instances.push(this); } + emit() { this.callback([], this as unknown as ResizeObserver); } +} + +describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => { + let fixture: ReturnType>; + let page: IndicadoresPage; + let http: HttpTestingController; + let memory: IndicadoresMemory; + let sticky: HTMLElement; + let geometry: WeakMap; + let frames: Map; + let sequence: number; + const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } }; + function rect(top: number, left = 0, width = 600, height = 80): DOMRect { + return { x: left, y: top, top, left, width, height, right: left + width, bottom: top + height, toJSON: () => ({}) } as DOMRect; + } + beforeEach(() => { + IntersectionControl.instances = []; ResizeControl.instances = []; + geometry = new WeakMap(); frames = new Map(); sequence = 0; + vi.stubGlobal('IntersectionObserver', IntersectionControl); vi.stubGlobal('ResizeObserver', ResizeControl); + vi.stubGlobal('innerWidth', 1440); vi.stubGlobal('innerHeight', 800); + vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => { frames.set(++sequence, callback); return sequence; }); + vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(id => { frames.delete(id); }); + vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function(this: Element) { return geometry.get(this) ?? rect(0, 0, 0, 0); }); + sticky = document.createElement('header'); sticky.className = 'institutional-header'; document.body.append(sticky); + geometry.set(sticky, rect(0, 0, 1440, 100)); + runtime.react.mockReset().mockResolvedValue(undefined); runtime.purge.mockReset(); runtime.Plots.resize.mockReset().mockResolvedValue(undefined); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider, + { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); + TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + create(); + }); + function create() { + fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; + http = TestBed.inject(HttpTestingController); memory = TestBed.inject(IndicadoresMemory); + } + afterEach(() => { fixture.destroy(); sticky.remove(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); + function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } + function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); } + async function render() { fixture.detectChanges(); await fixture.whenStable(); } + async function load(catalog = items, domain = 'tea') { + http.expectOne('/' + domain + '/indicadores').flush(catalog); await render(); + positions(cards().map((_, i) => [1000 + i * 200, 0])); + } + function positions(values: number[][]) { + cards().forEach((card, i) => { + geometry.set(card.host.nativeElement, rect(values[i][0], values[i][1])); + geometry.set(card.visibilityRegion!.nativeElement, rect(values[i][0], values[i][1], 600, 620)); + }); + } + function observer() { return IntersectionControl.instances.at(-1)!; } + async function frame() { + const callbacks = [...frames.values()]; frames.clear(); callbacks.forEach(callback => callback(0)); await render(); + } + async function confirm() { await frame(); await frame(); } + function notify(index = 0, intersects = true) { observer().emit(cards()[index].visibilityRegion!.nativeElement, intersects); } + function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [1] }], layout: {} })); } + async function idle() { + for (let i = 0; i < 6 && frames.size; i++) await frame(); + expect(frames.size).toBe(0); + } + + it.each([{ domain: 'tea', count: 18 }, { domain: 'cacu', count: 8 }] as const)('%s no descarga todas las figuras al abrir', async ({ domain, count }) => { + if (domain !== 'tea') { http.expectOne('/tea/indicadores'); page.changeDominio(domain); } + await load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'i' + i })), domain); + await idle(); expect(cards()).toHaveLength(count); expect(panels()).toHaveLength(count); + expect(panels().every(p => p.result().status === 'deferred')).toBe(true); http.expectNone(() => true); + expect(fixture.nativeElement.querySelectorAll('app-indicador-catalog-card header button')).toHaveLength(0); + expect(fixture.nativeElement.querySelectorAll('.figure-skeleton')).toHaveLength(count); + positions(cards().map((_, i) => [i < 2 ? 200 : 1200 + i * 1000, i === 1 ? 650 : 0])); notify(); await confirm(); + const requests = http.match(r => r.url.includes('/figuras/')); expect(requests).toHaveLength(2); + requests.forEach(r => r.flush({ data: [{ y: [1] }], layout: {} })); await render(); await idle(); http.expectNone(() => true); + }); + it('observa regiones gráficas permanentemente con margen de anticipación y sticky', async () => { + await load(); await idle(); + expect(observer().options).toEqual({ root: null, threshold: 0, rootMargin: '-100px 0px 200px 0px' }); + expect([...observer().targets]).toEqual(cards().map(c => c.visibilityRegion!.nativeElement)); + positions([[900, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); respond(); await render(); + expect(observer().targets.size).toBe(5); expect(panels()[0].result().status).toBe('ready'); + expect(fixture.nativeElement.querySelectorAll('.figure-skeleton')).toHaveLength(4); + }); + it('salir y volver conserva panel, resultado y selección sin HTTP redundante', async () => { + await load(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); respond(); await render(); + const panel = panels()[0], result = panel.result(); + positions([[-1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(0, false); await idle(); + expect(cards()[0].visible).toBe(false); expect(panels()[0]).toBe(panel); expect(panel.result()).toBe(result); + positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await idle(); + expect(panel.result()).toBe(result); http.expectNone(() => true); + }); + it('filtro fuera de vista conserva host y consulta únicamente el último aplicado al regresar', async () => { + await load(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); respond(); await render(); + const panel = panels()[0], chart = fixture.nativeElement.querySelector('app-plotly-chart'); + positions([[-1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); window.dispatchEvent(new Event('scroll')); await idle(); + const filters = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; + filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add(); page.applyFilters(); await render(); + filters.year = '2025'; filters.unit = 'S2'; filters.add(); page.applyFilters(); page.changeTema('oscuro'); await render(); await idle(); + expect(panels()[0]).toBe(panel); expect(panel.result().status).toBe('deferred'); + expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); http.expectNone(() => true); + positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); + const request = http.expectOne(r => r.url.includes('/i0/figuras/')); + expect(request.request.params.get('periodos')).toBe('2025-S1,2025-S2'); expect(request.request.params.get('tema')).toBe('oscuro'); + request.flush({ data: [{ y: [2] }], layout: {} }); await render(); notify(); await idle(); http.expectNone(() => true); + }); + it('aplicar antes del frame de scroll relee geometría y cancela petición obsoleta sin nueva descarga', async () => { + await load(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); + const old = http.expectOne(r => r.url.includes('/i0/figuras/')); + positions([[-1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); window.dispatchEvent(new Event('scroll')); + page.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S1'] }; page.applyFilters(); await render(); + expect(old.cancelled).toBe(true); expect(panels()[0].result().status).toBe('deferred'); http.expectNone(() => true); + expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); await idle(); + }); + it('cambio rápido de representación cancela saliente y fuera de vista difiere seleccionada', async () => { + await load([{ ...items[0], figuras: ['f', 'g', 'h'] }]); positions([[200, 0]]); notify(); await confirm(); + const old = http.expectOne(r => r.url.endsWith('/figuras/f')); cards()[0].selectFigure('g'); await render(); + expect(old.cancelled).toBe(true); const next = http.expectOne(r => r.url.endsWith('/figuras/g')); + cards()[0].selectFigure('h'); await render(); expect(next.cancelled).toBe(true); + http.expectOne(r => r.url.endsWith('/figuras/h')).flush({ data: [], layout: {} }); await render(); + expect(panels()).toHaveLength(1); positions([[-1000, 0]]); notify(0, false); await idle(); + cards()[0].selectFigure('g'); await render(); http.expectNone(() => true); expect(panels()[0].result().status).toBe('deferred'); + positions([[200, 0]]); notify(); await confirm(); http.expectOne(r => r.url.endsWith('/figuras/g')).flush({ data: [], layout: {} }); + }); + it('fijación y búsqueda conservan componentes y descartan callbacks con geometría antigua', async () => { + await load(); const before = cards(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); + const target = before[0].visibilityRegion!.nativeElement; notify(); page.togglePinned(items[4]); await render(); + page.changeSearchQuery('Indicador 3'); await render(); positions(cards().map((_, i) => [1200 + i * 1000, 0])); + observer().emit(target); await idle(); http.expectNone(() => true); + expect(cards()[0]).toBe(before[3]); expect(cards()[1]).toBe(before[4]); expect(cards().every(c => before.includes(c))).toBe(true); + positions(cards().map((_, i) => [i === 0 ? 200 : 1200 + i * 1000, 0])); notify(); await confirm(); + http.expectOne(r => r.url.includes('/i3/figuras/')).flush({ data: [], layout: {} }); await render(); + expect(cards()[0].selectedFigure).toBe('f'); + }); + it.each([{ data: [], layout: {} }, { data: [{ y: [null, null] }], layout: { annotations: [{ text: 'Valores ocultos por supresión.' }] } }])('resultado vacío o suprimido termina skeleton y conserva JSON: %j', async figure => { + await load([items[0]]); positions([[200, 0]]); notify(); await confirm(); + http.expectOne(r => r.url.includes('/figuras/')).flush(figure); await render(); + expect(panels()[0].result().status).toBe('ready'); expect(panels()[0].result().figure).toEqual(figure); + expect(fixture.nativeElement.querySelector('.figure-skeleton')).toBeNull(); expect(fixture.nativeElement.textContent).toContain('No hay valores visibles'); + if (figure.layout.annotations) expect(panels()[0].result().figure?.layout['annotations']).toEqual(figure.layout.annotations); + }); + it('error HTTP termina skeleton y reintenta sólo la figura visible', async () => { + await load([items[0]]); positions([[200, 0]]); notify(); await confirm(); + http.expectOne(r => r.url.includes('/figuras/')).flush('private', { status: 503, statusText: 'Unavailable' }); await render(); + expect(panels()[0].result().status).toBe('error'); expect(fixture.nativeElement.querySelector('.figure-skeleton')).toBeNull(); + panels()[0].requestFigure(); respond(); await render(); expect(panels()[0].result().status).toBe('ready'); + }); + it('fallback sin IntersectionObserver muestra las figuras sin interacción manual', async () => { + http.expectOne('/tea/indicadores'); fixture.destroy(); vi.stubGlobal('IntersectionObserver', undefined); create(); + await load([items[0]]); respond(); await render(); expect(panels()[0].result().status).toBe('ready'); + expect(fixture.nativeElement.querySelector('app-indicador-catalog-card header button')).toBeNull(); http.expectNone(() => true); + }); + it('dominio cancela solicitudes, desobserva tarjetas retiradas e ignora callback antiguo', async () => { + await load(); const oldObserver = observer(), retired = cards()[0].visibilityRegion!.nativeElement; + page.catalog.set(items.slice(1)); await render(); expect(oldObserver.unobserve).toHaveBeenCalledWith(retired); + oldObserver.emit(retired); await idle(); http.expectNone(() => true); + positions([[200, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await confirm(); + const request = http.expectOne(r => r.url.includes('/figuras/')); + page.changeDominio('cama'); await load([items[0]], 'cama'); expect(request.cancelled).toBe(true); + expect(oldObserver.disconnect).toHaveBeenCalled(); oldObserver.emit(retired); await idle(); http.expectNone(() => true); + }); + it('destrucción desconecta observers, cancela frame y vuelve inocuos callbacks tardíos', async () => { + await load(); const active = observer(), target = cards()[0].visibilityRegion!.nativeElement; + notify(); const pending = [...frames.keys()]; fixture.destroy(); + expect(active.disconnect).toHaveBeenCalled(); expect(ResizeControl.instances.some(o => o.disconnect.mock.calls.length)).toBe(true); + expect(pending.some(id => vi.mocked(window.cancelAnimationFrame).mock.calls.some(call => call[0] === id))).toBe(true); + const remaining = frames.size; active.emit(target); window.dispatchEvent(new Event('scroll')); expect(frames.size).toBe(remaining); + }); + it('hosts Plotly permanecen montados fuera de vista y se purgan al destruir', async () => { + http.expectOne('/tea/indicadores'); fixture.destroy(); TestBed.resetTestingModule(); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); create(); + await load([items[0]]); positions([[200, 0]]); notify(); await confirm(); respond(); await render(); + for (let i = 0; i < 12; i++) await Promise.resolve(); await render(); + const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart, host = chart.host.nativeElement; + expect(runtime.react).toHaveBeenCalledTimes(1); positions([[-1000, 0]]); notify(0, false); await idle(); + expect(chart.host.nativeElement).toBe(host); expect(runtime.purge).not.toHaveBeenCalled(); + positions([[200, 0]]); notify(); await idle(); expect(runtime.react).toHaveBeenCalledTimes(1); http.expectNone(() => true); + fixture.destroy(); expect(runtime.purge).toHaveBeenCalledWith(host); + }); +}); diff --git a/src/app/features/indicadores/indicadores-visual-profile.spec.ts b/src/app/features/indicadores/indicadores-visual-profile.spec.ts new file mode 100644 index 0000000..0dc955b --- /dev/null +++ b/src/app/features/indicadores/indicadores-visual-profile.spec.ts @@ -0,0 +1,228 @@ +import { FigureSelection, PlotlyFigure } from './indicadores.models'; +import { figurePresentation } from './indicadores.presentation'; +import { BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE } from './indicadores-visual-profile'; +import { syntheticFigures } from './indicadores.synthetic-fixtures'; + +const selection: FigureSelection = { dominio: 'tea', indicador: 'synthetic', figura: 'fig_c1_grupos', tema: 'claro' }; +const footer = { + text: 'Explicación sintética. Los valores suprimidos no son cero.
Base depurada del proyecto TEA · Centro Médico ISSSTELEÓN – UANL · Fecha de corte: 2025-08-01
Uso exclusivo de investigación. No usar para decisiones clínicas.', + xref: 'paper', yref: 'paper', x: 0, y: -0.22, xanchor: 'left', yanchor: 'top', + align: 'left', showarrow: false, font: { size: 11, color: '#52514e' }, +}; +function freezeDeep(value: unknown) { + if (value && typeof value === 'object') { + Object.values(value).forEach(freezeDeep); + Object.freeze(value); + } +} +function original(): PlotlyFigure { + return { + data: [{ type: 'bar', x: [['2025-S1', '2025-S2'], ['Área extensa de ejemplo', 'Otra área']], y: [null, 0], + marker: { color: ['gray', 'blue'] }, customdata: [[null, 'SUPRIMIDO'], [0, 10]], future: { untouched: true } }], + layout: { title: 'Título', xaxis: { type: 'multicategory', future: 17 }, yaxis: { range: [0, 100] }, + font: { future: 2 }, margin: { b: 150, future: 3 }, annotations: [structuredClone(footer)], future: { keep: true } }, + config: { staticPlot: false }, future: { keep: [1, null] }, + }; +} +describe('UX-07B perfiles y pies metodológicos', () => { + it('deriva desde el original congelado, preserva íntegramente trazas, frames y atributos desconocidos', () => { + const source = original(); source.frames = [{ name: 'frame', data: [{ y: [null, 0] }], layout: { annotations: [footer] }, future: 9 }]; + const before = structuredClone(source); freezeDeep(source); + const result = figurePresentation(source, selection, DEMO_VISUAL_PROFILE); + expect(source).toEqual(before); + expect(result.figure.data).toEqual(before.data); expect(result.figure.data).not.toBe(source.data); + expect(result.figure.frames).toEqual(before.frames); expect(result.figure.frames).not.toBe(source.frames); + expect(result.figure.config).toEqual(before.config); expect(result.figure['future']).toEqual(before['future']); + expect(result.figure.layout['future']).toEqual(before.layout['future']); + expect(result.figure.layout['xaxis']).toMatchObject({ type: 'multicategory', future: 17 }); + expect(result.figure.layout['font']).toMatchObject({ future: 2 }); + expect(result.figure.layout['margin']).toMatchObject({ b: 150, future: 3 }); + expect(result.footnotes).toEqual([]); // An animated annotation could otherwise reappear. + expect(result.figure.layout['annotations']).toEqual(before.layout['annotations']); + }); + it('aplica y revierte el perfil sin acumular estilos ni mutaciones del runtime', () => { + const source = original(), snapshot = structuredClone(source); + const base = figurePresentation(source, selection); + const demo = figurePresentation(source, selection, DEMO_VISUAL_PROFILE); + expect(demo.figure.layout).toMatchObject({ paper_bgcolor: '#f2f7fc', plot_bgcolor: '#ffffff', height: 640, + font: { family: 'Arial, sans-serif', size: 15 }, xaxis: { type: 'multicategory', showgrid: true, gridcolor: '#c6d7e8' } }); + demo.figure.data[0]['y'] = [999]; demo.figure.layout['annotations'] = [{ text: 'runtime' }]; + expect(figurePresentation(source, selection, BASE_VISUAL_PROFILE)).toEqual(base); + expect(source).toEqual(snapshot); + }); + it('extrae sólo el pie reconocido, preserva texto y orden sin duplicarlo en Plotly', () => { + const source = original(); const annotation = { text: 'Meta', x: 1, y: 90 }; + const second = { ...footer, text: footer.text.replace('Explicación sintética.', 'Segunda explicación.') }; + source.layout['annotations'] = [footer, annotation, second]; + const result = figurePresentation(source, selection); + expect(result.footnotes).toEqual([footer.text.replaceAll('
', '\n'), second.text.replaceAll('
', '\n')]); + expect(result.figure.layout['annotations']).toEqual([annotation]); + expect(source.layout['annotations']).toEqual([footer, annotation, second]); + expect(result.figure.layout['margin']).toEqual(source.layout['margin']); + }); + it.each([ + { xref: 'x' }, { yref: 'y' }, { y: -0.23 }, { x: 0.1 }, { showarrow: true }, + { xanchor: 'center' }, { yanchor: 'bottom' }, { align: 'center' }, { opacity: 0.4 }, + { font: { size: 11, future: true } }, { text: 'Nota desconocida' }, + { text: footer.text.replace('Explicación sintética.', 'Explicación sintética.') }, + { text: footer.text.replace('Explicación sintética.', '<script>') }, + { text: footer.text.replace('Explicación sintética.', '') }, + ])('conserva anotaciones ambiguas o marcado no trasladable: %j', change => { + const source = original(); source.layout['annotations'] = [{ ...footer, ...change }]; + const result = figurePresentation(source, selection); + expect(result.footnotes).toEqual([]); expect(result.figure.layout['annotations']).toEqual(source.layout['annotations']); + }); + it.each([{ dominio: 'cacu' as const }, { figura: 'fig_c3r_cajas' }, { dominio: undefined }])('no infiere familias ni dominios: %j', change => { + const source = original(); const result = figurePresentation(source, { ...selection, ...change }); + expect(result.footnotes).toEqual([]); expect(result.figure.layout['annotations']).toEqual(source.layout['annotations']); + }); + it.each([{ data: [] }, { data: [{ y: [null, null], customdata: ['SUPRIMIDO', 'SIN_DATO'] }] }, { data: [{ y: [0, NaN, null] }] }])('preserva vacíos, supresión, nulos y cero: %j', ({ data }) => { + const source = { ...original(), data }; const snapshot = structuredClone(source); + expect(figurePresentation(source, selection, DEMO_VISUAL_PROFILE).figure.data).toEqual(snapshot.data); + expect(source).toEqual(snapshot); + }); + it('admite saltos br equivalentes y conserva cada línea sin trim ni HTML', () => { + const source = original(); const text = footer.text.replaceAll('
', '
'); + source.layout['annotations'] = [{ ...footer, text }]; + expect(figurePresentation(source, selection).footnotes).toEqual([footer.text.replaceAll('
', '\n')]); + }); + it('reconoce los tres pies de fixtures sintéticos existentes sin alterar los datos', () => { + const tea = syntheticFigures.filter(item => item.name.startsWith('tea')); + expect(tea).toHaveLength(3); + for (const item of tea) { + const result = figurePresentation(item.figure, selection); + expect(result.footnotes).toHaveLength(1); + const annotations = item.figure.layout['annotations'] as { text: string }[]; + expect(result.footnotes[0]).toBe(annotations[0].text.replaceAll('
', '\n')); + expect(result.figure.layout['annotations']).toEqual([]); expect(result.figure.data).toEqual(item.figure.data); + } + }); + it('respeta dimensiones fijas y no crea ejes para figuras que no los publican', () => { + const source = { data: [], layout: { width: 800, height: 400, autosize: false } }; + const result = figurePresentation(source, selection, DEMO_VISUAL_PROFILE); + expect(result.figure.layout).toMatchObject({ width: 800, height: 400, autosize: false }); + expect(result.figure.layout['xaxis']).toBeUndefined(); + }); + it('reduce sólo la reserva conocida de un eje simple con automargin efectivo', () => { + const source = original(); source.data = [{ type: 'bar', x: ['Grupo'], y: [0] }]; + source.layout['xaxis'] = { type: 'category', automargin: true }; + expect(figurePresentation(source, selection).figure.layout['margin']).toMatchObject({ b: 80, future: 3 }); + expect(source.layout['margin']).toMatchObject({ b: 150 }); + for (const change of [{ xaxis: { type: 'multicategory', automargin: true } }, { legend: { y: -0.2 } }, + { legend: { orientation: 'h' } }, { legend: { y: 0, yanchor: 'top' } }, + { shapes: [] }, { xaxis2: { automargin: true } }, { height: 620 }, { xaxis: { type: 'category' } }]) { + expect(figurePresentation({ ...source, layout: { ...source.layout, ...change } }, selection).figure.layout['margin']).toMatchObject({ b: 150 }); + } + }); + it.each(['cacu', 'cama'] as const)('conserva adaptación mensual de %s con ambos perfiles', dominio => { + const source: PlotlyFigure = { data: [{ type: 'scatter', mode: 'markers', x: ['2025-03', '2025-01'], y: [null, 0] }], layout: { xaxis: { future: true } } }; + for (const profile of [BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE]) { + const result = figurePresentation(source, { ...selection, dominio, figura: 'fig_c1_puntos', tipoPeriodo: 'mes' }, profile); + expect(result.figure.layout['xaxis']).toMatchObject({ type: 'category', categoryarray: ['2025-01', '2025-03'], ticktext: ['2025-01', '2025-03'], automargin: true, future: true }); + expect(result.figure.data).toEqual(source.data); + } + }); +}); + +describe('UX-07D.2 pies documentales de familias verificadas', () => { + const note = { ...footer, text: 'Fuente: ejemplo sintético.' }; + const donutTotal = { text: '12', xref: 'paper', yref: 'paper', x: 0.5, y: 0.5, + showarrow: false, font: { size: 18, color: '#000000' } }; + const selected = (dominio: 'tea' | 'cacu' | 'cama', figura = 'fig_c2_barras'): FigureSelection => + ({ ...selection, dominio, figura }); + const figure = (annotations: unknown[] = [note]): PlotlyFigure => ({ + data: [{ type: 'bar', x: ['Categoría íntegra'], y: [null, 0], customdata: ['SUPRIMIDO', 'SIN_DATO'], + hovertemplate: '%{x}: %{y}', marker: { color: 'gray' }, future: { untouched: true } }], + layout: { margin: { b: 150 }, annotations, future: { untouched: true } }, + config: { displaylogo: false }, future: { unchanged: true }, + }); + it.each(['cacu', 'cama'] as const)('extrae pies de barras, donas y cajas %s con la firma completa', dominio => { + for (const id of ['fig_c2_barras', 'fig_c2_donas', 'fig_c3r_caja']) { + const source = figure([donutTotal, note]); + const result = figurePresentation(source, selected(dominio, id)); + expect(result.footnotes).toEqual([note.text]); + expect(result.figure.layout['annotations']).toEqual([donutTotal]); + expect(result.figure.data).toEqual(source.data); + expect(result.figure.layout['margin']).toEqual({ b: 150 }); + } + }); + it.each(['fig_c2_barras', 'fig_c2_donas'])('amplía TEA %s conservando su firma de fuente e investigación', id => { + expect(figurePresentation(figure([donutTotal, footer]), selected('tea', id)).footnotes) + .toEqual([footer.text.replaceAll('
', '\n')]); + expect(figurePresentation(figure(), selected('tea', id)).footnotes).toEqual([]); + }); + it.each(['Fuente: X.', 'Nota: ' + 'Texto extenso. '.repeat(100), 'Primera\n\nSegunda
Tercera
Cuarta', + ' Fuente: A & B · «Sin dato» ≤ 5 — 日本語\n '])('preserva texto independientemente de longitud o saltos: %s', text => { + const result = figurePresentation(figure([{ ...note, text }]), selected('cama')); + expect(result.footnotes).toEqual([text.replace(//gi, '\n')]); + expect(result.figure.layout['annotations']).toEqual([]); + }); + it.each([ + { text: 'Nota' }, { text: '' }, { text: '<img>' }, + { text: 'Fuente' }, { text: 'Texto & más' }, + { text: ' \n ' }, { text: 17 }, { xref: 'x' }, { yref: 'y' }, { yref: 'y domain' }, + { y: -0.23 }, { x: 0.5 }, { y: 0.5 }, { showarrow: true }, { ax: 0, ay: 20 }, + { xanchor: 'center' }, { yanchor: 'bottom' }, { align: 'center' }, { opacity: 0.5 }, + { visible: false }, { name: 'unknown' }, { font: { size: 11, future: true } }, + ])('conserva en Plotly marcado, geometría o atributos incompatibles: %j', change => { + const source = figure([{ ...note, ...change }]); + for (const domain of ['cacu', 'cama'] as const) { + const result = figurePresentation(source, selected(domain)); + expect(result.footnotes).toEqual([]); + expect(result.figure.layout['annotations']).toEqual(source.layout['annotations']); + } + }); + it('particiona cada ocurrencia una sola vez, en orden, conservando anotaciones internas', () => { + const internal = [{ text: 'Dato', xref: 'x', yref: 'y', x: 1, y: 3, showarrow: false }, + { text: 'Observación', x: 1, y: 3, showarrow: true }, donutTotal, + { text: 'Larga\n'.repeat(100), xref: 'paper', yref: 'paper', y: -0.22 }]; + const annotations = [note, internal[0], { ...note, text: 'Segunda
línea' }, ...internal.slice(1), note]; + const source = figure(annotations), before = structuredClone(source); freezeDeep(source); + const result = figurePresentation(source, selected('cacu')); + expect(result.footnotes).toEqual([note.text, 'Segunda\nlínea', note.text]); + expect(result.figure.layout['annotations']).toEqual(internal); + expect(result.footnotes.length + internal.length).toBe(annotations.length); + expect(source).toEqual(before); expect(result.figure.data).toEqual(before.data); + expect(result.figure.config).toEqual(before.config); expect(result.figure['future']).toEqual(before['future']); + expect(result.figure.layout['future']).toEqual(before.layout['future']); + }); + it('conserva animaciones, plantilla, ejes multicategoría y atributos desconocidos', () => { + const source = figure(); source.frames = [{ name: 'frame', layout: { annotations: [note] }, future: 1 }]; + source.layout['template'] = { layout: { annotations: [note] } }; + source.layout['xaxis'] = { type: 'multicategory', future: 3 }; + const result = figurePresentation(source, selected('cama')); + expect(result.footnotes).toEqual([]); expect(result.figure.frames).toEqual(source.frames); + expect(result.figure.layout['annotations']).toEqual([note]); + expect(result.figure.layout['template']).toEqual(source.layout['template']); + expect(result.figure.layout['xaxis']).toEqual(source.layout['xaxis']); + }); + it('no impone nuevas reducciones de márgenes ni cambia multicategoría al extraer', () => { + const source = figure(); source.layout['xaxis'] = { type: 'multicategory', automargin: true }; + source.layout['legend'] = { orientation: 'h', y: -0.3 }; source.layout['height'] = 620; + const result = figurePresentation(source, selected('cama')); + expect(result.footnotes).toEqual([note.text]); + expect(result.figure.layout['xaxis']).toEqual(source.layout['xaxis']); + expect(result.figure.layout['margin']).toEqual(source.layout['margin']); + expect(result.figure.layout['legend']).toEqual(source.layout['legend']); + expect(result.figure.layout['height']).toBe(620); + }); + it('no inventa pies para figuras sin notas ni familias desconocidas', () => { + expect(figurePresentation(figure([]), selected('cacu')).footnotes).toEqual([]); + const source = figure(); + for (const id of ['fig_c1_puntos', 'fig_desconocida']) { + const result = figurePresentation(source, selected('cacu', id)); + expect(result.footnotes).toEqual([]); expect(result.figure.layout['annotations']).toEqual([note]); + } + }); + it('deriva las mismas notas desde el original al alternar perfiles y anchos', () => { + const source = figure(), snapshot = structuredClone(source); + for (const profile of [BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE, BASE_VISUAL_PROFILE]) { + for (const width of [230, 320, 768, 1440]) { + const result = figurePresentation(source, selected('cama'), profile, width); + expect(result.footnotes).toEqual([note.text]); + expect(result.figure.data).toEqual(snapshot.data); + } + } + expect(source).toEqual(snapshot); + }); +}); diff --git a/src/app/features/indicadores/indicadores-visual-profile.ts b/src/app/features/indicadores/indicadores-visual-profile.ts new file mode 100644 index 0000000..4cfb857 --- /dev/null +++ b/src/app/features/indicadores/indicadores-visual-profile.ts @@ -0,0 +1,31 @@ +// Presentation preferences. Trace colours retain their published semantic roles. +export interface AxisLabelOptions { + readonly enabled: boolean; + readonly maxCharacters?: number; + readonly preferWords?: boolean; + readonly preserveWhenFits?: boolean; + readonly multicategory?: 'preserve' | 'fit'; +} + +export interface FigureVisualProfile { + readonly axisLabels?: AxisLabelOptions; + readonly paperBackground?: string; + readonly plotBackground?: string; + readonly font?: Readonly<{ family?: string; size?: number; color?: string }>; + readonly margin?: Readonly<{ l?: number; r?: number; t?: number; b?: number; pad?: number }>; + readonly grid?: Readonly<{ color?: string; visible?: boolean }>; + readonly minimumHeight?: number; +} + +// Base keeps the received styling plus the dashboard's existing adaptations. +export const BASE_VISUAL_PROFILE: FigureVisualProfile = Object.freeze({}); +export const READABLE_VISUAL_PROFILE: FigureVisualProfile = Object.freeze({ + axisLabels: Object.freeze({ enabled: true, maxCharacters: 22, preferWords: true, preserveWhenFits: true, multicategory: 'fit' }), +}); +export const DEMO_VISUAL_PROFILE: FigureVisualProfile = Object.freeze({ + paperBackground: '#f2f7fc', plotBackground: '#ffffff', + font: Object.freeze({ family: 'Arial, sans-serif', size: 15, color: '#17324d' }), + margin: Object.freeze({ t: 30, pad: 8 }), + grid: Object.freeze({ color: '#c6d7e8', visible: true }), + minimumHeight: 640, +}); diff --git a/src/app/features/indicadores/indicadores.models.spec.ts b/src/app/features/indicadores/indicadores.models.spec.ts new file mode 100644 index 0000000..87c0c28 --- /dev/null +++ b/src/app/features/indicadores/indicadores.models.spec.ts @@ -0,0 +1,59 @@ +import { hasNoVisibleValues, parsePeriodos } from './indicadores.models'; + +describe('Periodos y visibilidad conservadora', () => { + it('normaliza espacios y duplicados sin inventar periodos', () => { + expect(parsePeriodos('2025-S1, 2025-S2,2025-S1')).toEqual(['2025-S1', '2025-S2']); + expect(parsePeriodos('1900-S2')).toEqual(['1900-S2']); + }); + it.each(['', '2025', '25-S1', '2025-S3', '2025-S1,', '2025-s1', '2025-S1 2025-S2'])('rechaza %s', value => { + expect(parsePeriodos(value)).toBeNull(); + }); + it('detecta trazos vacíos, nulos y cajas sin mediana', () => { + expect(hasNoVisibleValues({ data: [], layout: {} })).toBe(true); + expect(hasNoVisibleValues({ data: [{ type: 'scatter', y: [null] }, { type: 'bar', y: [] }, { type: 'box', median: [null] }], layout: {} })).toBe(true); + }); + it('conserva cero, supresión y medianas válidas como valores visibles', () => { + expect(hasNoVisibleValues({ data: [{ y: [0] }], layout: {} })).toBe(false); + expect(hasNoVisibleValues({ data: [{ type: 'box', median: [10] }], layout: {} })).toBe(false); + }); + it('no declara vacíos los formatos desconocidos o binarios', () => { + expect(hasNoVisibleValues({ data: [{ y: { bdata: 'AAAA', dtype: 'f8' } }], layout: {} })).toBe(false); + expect(hasNoVisibleValues({ data: [{ type: 'heatmap', z: [] }], layout: {} })).toBe(false); + }); +}); + +it('deduplica meses en orden estable y valida el calendario sin mezclar tipos', () => { + expect(parsePeriodos('2025-12, 2025-01,2025-12', 'mes')).toEqual(['2025-12', '2025-01']); + for (const value of ['', '2025-00', '2025-13', '2025-1', '2025-S1', '2025-01,2025-S1']) { + expect(parsePeriodos(value, 'mes')).toBeNull(); + } + expect(parsePeriodos('2025-S1,2025-01', 'semestre')).toBeNull(); +}); +it('no interpreta NaN ni null como porcentajes cero', () => { + expect(hasNoVisibleValues({ data: [{ y: [NaN, null] }], layout: {} })).toBe(true); +}); + +it.each(['0000-S1', '0000-S2', '10000-S1'])('rechaza año fuera de rango %s', value => { + expect(parsePeriodos(value)).toBeNull(); +}); +it.each(['0000-01', '10000-01', '2025-00', '2025-13'])('rechaza mes o año fuera de rango %s', value => { + expect(parsePeriodos(value, 'mes')).toBeNull(); +}); +it('acepta extremos canónicos de año', () => { + expect(parsePeriodos('0001-S1,9999-S2')).toEqual(['0001-S1', '9999-S2']); + expect(parsePeriodos('0001-01,9999-12', 'mes')).toEqual(['0001-01', '9999-12']); +}); + +it.each([ + [{ type: 'bar', orientation: 'h', x: [null], y: ['grupo'] }, true], + [{ type: 'bar', orientation: 'h', x: [0], y: ['grupo'] }, false], + [{ type: 'bar', y: [null], x: ['grupo'] }, true], + [{ type: 'bar', y: [0] }, false], + [{ type: 'pie', values: [null] }, true], + [{ type: 'pie', values: [0] }, false], + [{ type: 'pie', values: { bdata: 'AAAA' } }, false], + [{ type: 'bar', orientation: 'unknown', y: [null] }, false], + [{ type: 'bar', y: ['unknown'] }, false], +])('interpreta magnitudes de forma conservadora %j', (trace, empty) => { + expect(hasNoVisibleValues({ data: [trace as Record], layout: {} })).toBe(empty); +}); diff --git a/src/app/features/indicadores/indicadores.models.ts b/src/app/features/indicadores/indicadores.models.ts new file mode 100644 index 0000000..3cb1bea --- /dev/null +++ b/src/app/features/indicadores/indicadores.models.ts @@ -0,0 +1,60 @@ +export const DOMINIOS = ['tea', 'cacu', 'cama'] as const; +export type Dominio = typeof DOMINIOS[number]; +export type TipoPeriodo = 'semestre' | 'mes'; +export function isDominio(value: unknown): value is Dominio { + return typeof value === 'string' && DOMINIOS.some(domain => domain === value); +} +export function requireDominio(value: unknown): Dominio { + if (!isDominio(value)) throw new Error('Dominio no permitido'); + return value; +} +export interface Indicador { + id: string; + titulo: string; + contrato: string; + figuras: string[]; + tipos_periodo: TipoPeriodo[]; +} + +// Keep the complete HTTP figure, including future attributes and interpretation notes. +export interface PlotlyFigure { + data: Record[]; + layout: Record; + frames?: Record[]; + config?: Record; + [key: string]: unknown; +} +export type Tema = 'claro' | 'oscuro'; +export interface FigureSelection { dominio?: Dominio; tipoPeriodo?: TipoPeriodo; indicador: string; figura: string; tema: Tema; periodos?: string[]; } + +export function parsePeriodos(value: string, tipo: TipoPeriodo = 'semestre'): string[] | null { + if (tipo !== 'semestre' && tipo !== 'mes') return null; + const parts = value.split(',').map(part => part.trim()); + return parts.length && parts.every(part => part.slice(0, 4) !== '0000' && (tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(part)) + ? [...new Set(parts)] : null; +} + +// Only assert emptiness for known traces with ordinary arrays. Unknown/binary +// representations remain indeterminate; never infer counts or suppression causes. +export function hasNoVisibleValues(figure: PlotlyFigure): boolean { + return figure.data.every(trace => { + if (trace['visible'] === false || trace['visible'] === 'legendonly') return true; + const type = trace['type'] ?? 'scatter'; + const values = type === 'box' ? trace['median'] ?? trace['y'] + : type === 'bar' ? (trace['orientation'] === 'h' ? trace['x'] : trace['orientation'] === undefined || trace['orientation'] === 'v' ? trace['y'] : undefined) + : type === 'pie' ? trace['values'] + : type === 'scatter' ? trace['y'] : undefined; + if (!Array.isArray(values)) return false; + return values.every(value => value === null || value === undefined || (typeof value === 'number' && !Number.isFinite(value))); + }); +} + +export interface IndicadorDatos { + id: string; + contrato: string; + tipo_periodo: TipoPeriodo; + periodos: string[]; + filas: Record[]; + notas?: string[]; + [key: string]: unknown; +} diff --git a/src/app/features/indicadores/indicadores.presentation.spec.ts b/src/app/features/indicadores/indicadores.presentation.spec.ts new file mode 100644 index 0000000..4e22749 --- /dev/null +++ b/src/app/features/indicadores/indicadores.presentation.spec.ts @@ -0,0 +1,45 @@ +import { figureTitle, presentationFigure } from './indicadores.presentation'; +import { FigureSelection, PlotlyFigure } from './indicadores.models'; + +const selection: FigureSelection = { dominio: 'cacu', figura: 'fig_c1_puntos', indicador: 'x', tipoPeriodo: 'mes', tema: 'claro' }; +const monthly: PlotlyFigure = { + data: [{ type: 'scatter', mode: 'markers', x: ['2025-03', '2025-01', '2025-02'], y: [100, null, 0], customdata: [[1, 1], [null, null], [0, 1]] }], + layout: { title: { text: 'Título completo
con contexto', font: { size: 18 } }, xaxis: { gridcolor: 'gray' }, annotations: [{ text: 'Nota' }] }, + frames: [{ name: 'original' }], config: { displayModeBar: true }, future: { preserved: true }, +}; +describe('Dashboard presentation', () => { + it.each(['cacu', 'cama'] as const)('ordena ticks mensuales de %s sin cambiar observaciones ni HTTP', dominio => { + const original = structuredClone(monthly); + const adapted = presentationFigure(monthly, { ...selection, dominio }); + expect(monthly).toEqual(original); + expect(adapted.data).toEqual(original.data); + expect(adapted.data).not.toBe(monthly.data); + expect(adapted.frames).toEqual(original.frames); + expect(adapted.config).toEqual(original.config); + expect(adapted['future']).toEqual(original['future']); + expect(adapted.layout['annotations']).toEqual(original.layout['annotations']); + expect(adapted.layout['xaxis']).toEqual({ gridcolor: 'gray', type: 'category', categoryorder: 'array', categoryarray: ['2025-01', '2025-02', '2025-03'], tickmode: 'array', tickvals: ['2025-01', '2025-02', '2025-03'], ticktext: ['2025-01', '2025-02', '2025-03'], tickangle: 0, automargin: true }); + expect(figureTitle(monthly, 'catálogo')).toBe('Título completo
con contexto'); + expect(adapted.layout['title']).toEqual({ text: '', font: { size: 18 } }); + }); + it.each(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c3r_caja'])('preserva ejes y trazas de %s', figura => { + const adapted = presentationFigure(monthly, { ...selection, figura }); + expect(adapted.layout['xaxis']).toEqual(monthly.layout['xaxis']); + expect(adapted.data).toEqual(monthly.data); + }); + it('conserva semestres, TEA, representaciones binarias y figuras vacías', () => { + for (const input of [monthly, { data: [], layout: {} }, { data: [{ type: 'scatter', mode: 'markers', x: ['2025-S1', '2025-S2'], y: { dtype: 'f8', bdata: 'AAAAAAAAVEAAAAAAAABJQA==' } }], layout: { xaxis: { type: 'category' } } }] as PlotlyFigure[]) { + const original = structuredClone(input); + for (const request of [{ ...selection, tipoPeriodo: 'semestre' as const }, { ...selection, dominio: 'tea' as const }, selection]) { + const adapted = presentationFigure(input, request); + expect(adapted.data).toEqual(original.data); + if (input !== monthly || request !== selection) expect(adapted.layout['xaxis']).toEqual(original.layout['xaxis']); + } + expect(input).toEqual(original); + } + }); + it('conserva títulos string y usa catálogo cuando no hay título', () => { + expect(figureTitle({ data: [], layout: { title: 'Título completo' } }, 'fallback')).toBe('Título completo'); + expect(figureTitle({ data: [], layout: { title: { text: '' } } }, 'Catálogo')).toBe('Catálogo'); + }); +}); diff --git a/src/app/features/indicadores/indicadores.presentation.ts b/src/app/features/indicadores/indicadores.presentation.ts new file mode 100644 index 0000000..0b5bd89 --- /dev/null +++ b/src/app/features/indicadores/indicadores.presentation.ts @@ -0,0 +1,161 @@ +import { FigureSelection, PlotlyFigure } from './indicadores.models'; +import { BASE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visual-profile'; +import { applyAxisLabels, categoryMinimumWidth, CategoryLabel } from './indicadores-axis-labels'; + +export interface FigurePresentation { + figure: PlotlyFigure; + // Plain text, including original line breaks; never an HTML fragment. + footnotes: readonly string[]; + categoryLabels: readonly CategoryLabel[]; + minimumPlotWidth?: number; +} + +const TEA_FOOTER_FIGURES = new Set(['fig_c1_grupos', 'fig_c1_puntos', 'fig_c2_apiladas', 'fig_c3r_caja']); +// Verified published families share the complete documentary footer geometry. +// Donut totals (paper 0.5, 0.5), data labels and callouts do not match it. +const DISTRIBUTION_FOOTER_FIGURES = new Set(['fig_c2_barras', 'fig_c2_donas', 'fig_c3r_caja']); +const FOOTER_KEYS = new Set(['text', 'xref', 'yref', 'x', 'y', 'xanchor', 'yanchor', 'align', 'showarrow', 'font']); +function record(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function footerText(annotation: unknown, selection: FigureSelection): string | undefined { + const tea = selection.dominio === 'tea'; + const verifiedFamily = tea + ? TEA_FOOTER_FIGURES.has(selection.figura) || DISTRIBUTION_FOOTER_FIGURES.has(selection.figura) + : (selection.dominio === 'cacu' || selection.dominio === 'cama') && DISTRIBUTION_FOOTER_FIGURES.has(selection.figura); + if (!verifiedFamily || !record(annotation) + || Object.keys(annotation).some(key => !FOOTER_KEYS.has(key)) + || annotation['xref'] !== 'paper' || annotation['yref'] !== 'paper' + || annotation['x'] !== 0 || annotation['y'] !== -0.22 + || annotation['xanchor'] !== 'left' || annotation['yanchor'] !== 'top' + || annotation['align'] !== 'left' || annotation['showarrow'] !== false + || !record(annotation['font']) || annotation['font']['size'] !== 11 + || Object.keys(annotation['font']).some(key => !['size', 'color'].includes(key)) + || typeof annotation['text'] !== 'string') return undefined; + const text = annotation['text'].replace(//gi, '\n'); + // Rich markup, encoded markup, links and unknown formatting stay in Plotly. + if (!text.trim() || /[<>]|&(?:#\d+|#x[\da-f]+|[a-z][\da-z]*);/i.test(text)) return undefined; + // CaCu/CaMa publish plain documentary text in this exact exterior slot. + // No length threshold, keywords or indicator-name inference is involved. + if (!tea) return text; + // Retain UX-07B's additional TEA source/restriction guarantees. + const lines = text.split('\n'); + if (lines.length < 3 || !lines[0].trim() + || !/^Base depurada del proyecto TEA · Centro Médico ISSSTELEÓN – UANL · Fecha de corte: \d{4}-\d{2}-\d{2}$/.test(lines.at(-2)!) + || lines.at(-1) !== 'Uso exclusivo de investigación. No usar para decisiones clínicas.') return undefined; + return text; +} + +function applyVisualProfile(figure: PlotlyFigure, profile: FigureVisualProfile, availableWidth?: number) { + const layout = figure.layout; + if (profile.paperBackground !== undefined) layout['paper_bgcolor'] = profile.paperBackground; + if (profile.plotBackground !== undefined) layout['plot_bgcolor'] = profile.plotBackground; + if (profile.font) { + // A larger inherited legend/tick font can hide multicategory labels on + // narrow cards. Bound only the optional profile enlargement, not the source. + const narrowCategories = profile.axisLabels?.enabled && availableWidth !== undefined && availableWidth > 0 && availableWidth < 360 + && record(layout['xaxis']) && ['category', 'multicategory'].includes(String(layout['xaxis']['type'])) + && figure.data.every(trace => ['scatter', 'bar'].includes(String(trace['type']))); + layout['font'] = { ...(record(layout['font']) ? layout['font'] : {}), ...profile.font, + ...(narrowCategories && profile.font.size !== undefined && profile.font.size > 12 ? { size: 12 } : {}) }; + } + if (profile.margin) layout['margin'] = { ...(record(layout['margin']) ? layout['margin'] : {}), ...profile.margin }; + if (profile.grid) { + for (const key of Object.keys(layout).filter(key => /^[xy]axis\d*$/.test(key))) { + const axis = layout[key]; + if (!record(axis)) continue; + layout[key] = { ...axis, + ...(profile.grid.color !== undefined ? { gridcolor: profile.grid.color } : {}), + ...(profile.grid.visible !== undefined ? { showgrid: profile.grid.visible } : {}), + }; + } + } + // Respect fixed-size figures and animated layouts. No width feedback loop. + if (profile.minimumHeight !== undefined && Number.isFinite(profile.minimumHeight) && profile.minimumHeight > 0 + && !figure.frames?.length && layout['autosize'] !== false && layout['width'] === undefined + && (layout['height'] === undefined || typeof layout['height'] === 'number')) { + layout['height'] = Math.max(typeof layout['height'] === 'number' ? layout['height'] : 620, profile.minimumHeight); + } +} + +function relaxFooterMargin(figure: PlotlyFigure) { + const layout = figure.layout, axis = layout['xaxis'], margin = layout['margin']; + const template = layout['template']; + const templateLayout = record(template) ? template['layout'] : undefined; + const templateAxis = record(templateLayout) ? templateLayout['xaxis'] : undefined; + const legend = layout['legend']; + // Only the known footer reserve on a single, automatic Cartesian axis. + // Multicategory ticks, lower legends and other paper objects keep their space. + if (!record(axis) || !record(margin) || margin['b'] !== 150 + || (axis['automargin'] !== true && !(record(templateAxis) && templateAxis['automargin'] === true)) + || axis['type'] === 'multicategory' || figure.data.some(trace => !['scatter', 'bar', 'box'].includes(String(trace['type'])) + || (Array.isArray(trace['x']) && trace['x'].some(Array.isArray))) + || Object.keys(layout).some(key => /^[xy]axis[1-9]\d*$/.test(key)) + || ['shapes', 'images', 'sliders', 'updatemenus'].some(key => layout[key] !== undefined) + || (record(legend) && (legend['orientation'] === 'h' || (typeof legend['y'] === 'number' && legend['y'] <= 0))) + || layout['autosize'] === false || layout['width'] !== undefined || layout['height'] !== undefined) return; + layout['margin'] = { ...margin, b: 80 }; +} + +export function figureTitle(figure: PlotlyFigure, fallback: string): string { + const title = figure.layout['title']; + if (typeof title === 'string' && title.trim()) return title; + if (title && typeof title === 'object' && 'text' in title + && typeof title.text === 'string' && title.text.trim()) return title.text; + return fallback; +} + +// Adapt only the dashboard copy; HTTP figures and all observations stay intact. +export function figurePresentation(original: PlotlyFigure, selection: FigureSelection, + profile: FigureVisualProfile = BASE_VISUAL_PROFILE, availableWidth?: number): FigurePresentation { + const figure = structuredClone(original); + const title = figure.layout['title']; + figure.layout['title'] = title && typeof title === 'object' ? { ...title, text: '' } : { text: '' }; + if ((selection.dominio === 'cacu' || selection.dominio === 'cama') + && selection.figura === 'fig_c1_puntos' && selection.tipoPeriodo === 'mes' + && figure.data.length > 0 + && figure.data.every(trace => trace['type'] === 'scatter' && trace['mode'] === 'markers' + && Array.isArray(trace['x']) && trace['x'].length > 0 + && trace['x'].every(x => typeof x === 'string' && /^[0-9]{4}-(0[1-9]|1[0-2])$/.test(x)))) { + const periods = [...new Set(figure.data.flatMap(trace => trace['x'] as string[]))].sort(); + figure.layout['xaxis'] = { + ...(figure.layout['xaxis'] as Record | undefined), + type: 'category', categoryorder: 'array', categoryarray: periods, + tickmode: 'array', tickvals: periods, ticktext: periods, + tickangle: 0, automargin: true, + }; + } + const footnotes: string[] = []; + const annotations = figure.layout['annotations']; + // Frames may reintroduce annotations. Keep animated figures entirely in Plotly. + if (!figure.frames?.length && Array.isArray(annotations)) { + figure.layout['annotations'] = annotations.filter(annotation => { + const text = footerText(annotation, selection); + if (text === undefined) return true; + footnotes.push(text); + return false; + }); + // Only the previously verified TEA reserve can be relaxed. Newly supported + // families keep their margins, legends, colorbars and fixed dimensions. + if (footnotes.length && selection.dominio === 'tea' && TEA_FOOTER_FIGURES.has(selection.figura) + && (figure.layout['annotations'] as unknown[]).length === 0) relaxFooterMargin(figure); + } + applyVisualProfile(figure, profile, availableWidth); + const minimumPlotWidth = profile.axisLabels?.enabled && Number.isFinite(availableWidth) && availableWidth! > 0 + && selection.dominio === 'tea' && ['fig_c1_grupos', 'fig_c2_apiladas'].includes(selection.figura) + ? categoryMinimumWidth(figure) : undefined; + const categoryLabels = applyAxisLabels(figure, profile.axisLabels, availableWidth); + if (minimumPlotWidth !== undefined && !categoryLabels.length + && figure.data.every(trace => Array.isArray(trace['x']) && !trace['x'].some(Array.isArray))) { + figure.layout['xaxis'] = { ...(record(figure.layout['xaxis']) ? figure.layout['xaxis'] : {}), + type: 'category', tickmode: 'linear', dtick: 1, automargin: true }; + } + return { figure, footnotes, categoryLabels, minimumPlotWidth }; +} + +// Compatibility for existing consumers that only need the Plotly copy. +export function presentationFigure(original: PlotlyFigure, selection: FigureSelection, + profile: FigureVisualProfile = BASE_VISUAL_PROFILE): PlotlyFigure { + return figurePresentation(original, selection, profile).figure; +} diff --git a/src/app/features/indicadores/indicadores.service.spec.ts b/src/app/features/indicadores/indicadores.service.spec.ts new file mode 100644 index 0000000..96c363c --- /dev/null +++ b/src/app/features/indicadores/indicadores.service.spec.ts @@ -0,0 +1,120 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { Dominio } from './indicadores.models'; +import { syntheticCatalogs, syntheticFigures } from './indicadores.synthetic-fixtures'; +import { IndicadoresService } from './indicadores.service'; + +describe('IndicadoresService HTTP', () => { + let service: IndicadoresService; + let http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + service = TestBed.inject(IndicadoresService); + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => http.verify()); + + it.each(['tea', 'cacu', 'cama'] as const)('lee catálogo sintético dinámico de %s y sus tipos publicados', dominio => { + service.catalogo(dominio).subscribe(items => { + expect(items).toEqual(syntheticCatalogs[dominio]); + expect(items.length).toBe(dominio === 'tea' ? 18 : 1); + expect(items[0].tipos_periodo).toEqual(dominio === 'tea' ? ['semestre'] : ['semestre', 'mes']); + }); + http.expectOne(`/${dominio}/indicadores`).flush(syntheticCatalogs[dominio]); + }); + it.each(['tea', 'cacu', 'cama'] as const)('usa la URL de figura del dominio %s', dominio => { + service.figura({ dominio, indicador: 'i', figura: 'f', tema: 'oscuro', tipoPeriodo: dominio === 'tea' ? 'semestre' : 'mes', periodos: [dominio === 'tea' ? '2025-S1' : '2025-01'] }).subscribe(); + const req = http.expectOne(r => r.url === `/${dominio}/indicadores/i/figuras/f`); + expect(req.request.params.get('periodos')).toBe(dominio === 'tea' ? '2025-S1' : '2025-01'); + req.flush({ data: [], layout: {} }); + }); + it('rechaza dominios arbitrarios y periodos mezclados antes de HTTP', () => { + expect(() => service.catalogo('otro' as Dominio)).toThrow('Dominio no permitido'); + expect(() => service.figura({ dominio: '../otro' as Dominio, indicador: 'i', figura: 'f', tema: 'claro' })).toThrow(); + for (const periodos of [['2025-01', '2025-S1'], ['2025-13'], ['2025-00']]) { + expect(() => service.figura({ indicador: 'i', figura: 'f', tema: 'claro', periodos })).toThrow(); + } + http.expectNone(() => true); + }); + it.each([{ tipos_periodo: undefined }, { tipos_periodo: [] }, { tipos_periodo: ['anual'] }, { tipos_periodo: ['mes', 'mes'] }])('rechaza tipos de periodo inválidos $tipos_periodo', ({ tipos_periodo }) => { + let error: unknown; + service.catalogo('cacu').subscribe({ error: value => error = value }); + http.expectOne('/cacu/indicadores').flush([{ ...syntheticCatalogs.cacu[0], tipos_periodo }]); + expect(error).toBeInstanceOf(Error); + }); + it.each(syntheticFigures)('conserva el JSON sintético $name con arrays, nulos, anotaciones y bdata', ({ figure }) => { + service.figura({ indicador: 'i', figura: 'f', tema: 'claro' }).subscribe(value => expect(value).toEqual(figure)); + http.expectOne(r => r.url.includes('/figuras/')).flush(figure); + }); + it('consume un arreglo directo sin hardcodear catálogo', () => { + const data = [{ id: 'prueba', titulo: 'Título', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre'] }]; + let actual: unknown; + service.catalogo().subscribe(value => actual = value); + http.expectOne('/tea/indicadores').flush(data); + expect(actual).toEqual(data); + }); + it('acepta catálogo vacío y rechaza envelope inesperado', () => { + service.catalogo().subscribe(value => expect(value).toEqual([])); + http.expectOne('/tea/indicadores').flush([]); + let error: unknown; + service.catalogo().subscribe({ error: value => error = value }); + http.expectOne('/tea/indicadores').flush({ items: [] }); + expect(error).toBeInstanceOf(Error); + }); + it('codifica segmentos y omite periodos en Todos', () => { + service.figura({ indicador: 'a/b ü', figura: 'f?#', tema: 'claro' }).subscribe(); + const request = http.expectOne(req => req.url === '/tea/indicadores/a%2Fb%20%C3%BC/figuras/f%3F%23'); + expect(request.request.method).toBe('GET'); + expect(request.request.params.get('tema')).toBe('claro'); + expect(request.request.params.has('periodos')).toBe(false); + request.flush({ data: [], layout: {} }); + }); + it('envía semestres y conserva atributos desconocidos, nulos y notas', () => { + const figure = { data: [{ y: [null, 0], customdata: [null] }], layout: { annotations: [{ text: 'Uso exclusivo de investigación' }] }, extension: { future: true }, frames: [] }; + service.figura({ indicador: 'i', figura: 'f', tema: 'oscuro', periodos: ['2025-S1', '2025-S2'] }) + .subscribe(value => expect(value).toEqual(figure)); + const request = http.expectOne(req => req.url.endsWith('/i/figuras/f')); + expect(request.request.params.get('periodos')).toBe('2025-S1,2025-S2'); + expect(request.request.params.get('tema')).toBe('oscuro'); + request.flush(figure); + }); + it('rechaza una figura estructuralmente inválida', () => { + let error: unknown; + service.figura({ indicador: 'i', figura: 'f', tema: 'claro' }).subscribe({ error: value => error = value }); + http.expectOne(req => req.url.endsWith('/i/figuras/f')).flush({ data: null, layout: {} }); + expect(error).toBeInstanceOf(Error); + }); +}); + +describe('UX-04 validación defensiva HTTP', () => { + it('bloquea explícitos vacíos antes de construir una petición', () => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + const service = TestBed.inject(IndicadoresService); + const http = TestBed.inject(HttpTestingController); + expect(() => service.figura({ indicador: 'i', figura: 'f', tema: 'claro', periodos: [] })).toThrow('Selección explícita vacía'); + for (const periodos of [['0000-S1'], ['0000-01'], ['10000-01']]) { + expect(() => service.figura({ indicador: 'i', figura: 'f', tema: 'claro', periodos })).toThrow(); + } + http.expectNone(() => true); http.verify(); + }); +}); + +describe('contrato datos exclusivo de KPI', () => { + beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] })); + it('envía sólo periodos explícitos sin granularidad ni tema y conserva filas y notas', () => { + const http = TestBed.inject(HttpTestingController); let result: unknown; + TestBed.inject(IndicadoresService).datos('cacu', 'cacu_eu7', 'mes', ['2025-01']).subscribe(v => result = v); + const req = http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu7/datos'); + expect(req.request.params.keys()).toEqual(['periodos']); expect(req.request.params.get('periodos')).toBe('2025-01'); + const payload = { id: 'cacu_eu7', contrato: 'C2', tipo_periodo: 'mes', periodos: ['2025-01'], filas: [{ n: null, suprimido: 1 }], notas: ['Nota'] }; + req.flush(payload); expect(result).toEqual(payload); http.verify(); + }); + it('Todos omite periodos y rechaza respuesta de otro indicador', () => { + const http = TestBed.inject(HttpTestingController); let error: unknown; + TestBed.inject(IndicadoresService).datos('cama', 'cama_eu38a', 'semestre').subscribe({ error: e => error = e }); + const req = http.expectOne('/cama/indicadores/cama_eu38a/datos'); expect(req.request.params.keys()).toEqual([]); + req.flush({ id: 'otro', contrato: 'C3r', tipo_periodo: 'semestre', periodos: [], filas: [] }); + expect(error).toBeInstanceOf(Error); http.verify(); + }); +}); diff --git a/src/app/features/indicadores/indicadores.service.ts b/src/app/features/indicadores/indicadores.service.ts new file mode 100644 index 0000000..47fe164 --- /dev/null +++ b/src/app/features/indicadores/indicadores.service.ts @@ -0,0 +1,66 @@ +import { inject, Injectable } from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; +import { map } from 'rxjs'; +import { Dominio, IndicadorDatos, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio } from './indicadores.models'; + +function record(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} +@Injectable({ providedIn: 'root' }) +export class IndicadoresService { + private readonly http = inject(HttpClient); + catalogo(dominio: Dominio = 'tea') { + const domain = requireDominio(dominio); + return this.http.get(`/${domain}/indicadores`).pipe(map(value => { + if (!Array.isArray(value) || !value.every(item => record(item) + && typeof item['id'] === 'string' && item['id'].trim().length > 0 && typeof item['titulo'] === 'string' + && typeof item['contrato'] === 'string' && Array.isArray(item['figuras']) + && item['figuras'].every((figure: unknown) => typeof figure === 'string' && figure.trim().length > 0) + && new Set(item['figuras']).size === item['figuras'].length + && Array.isArray(item['tipos_periodo']) && item['tipos_periodo'].length > 0 + && item['tipos_periodo'].every((tipo: unknown) => tipo === 'semestre' || tipo === 'mes') + && new Set(item['tipos_periodo']).size === item['tipos_periodo'].length)) { + throw new Error('Respuesta de catálogo inválida'); + } + if (new Set(value.map(item => item['id'])).size !== value.length) throw new Error('IDs de catálogo duplicados'); + return value as Indicador[]; + })); + } + datos(dominio: Dominio, indicador: string, tipo: 'semestre' | 'mes', periodos?: string[]) { + const domain = requireDominio(dominio); + if (periodos && (!periodos.length || parsePeriodos(periodos.join(','), tipo) === null)) { + throw new Error('Periodos inválidos'); + } + let params = new HttpParams(); + if (periodos) params = params.set('periodos', [...new Set(periodos)].join(',')); + return this.http.get(`/${domain}/indicadores/${encodeURIComponent(indicador)}/datos`, { params }).pipe(map(value => { + if (!record(value) || value['id'] !== indicador || typeof value['contrato'] !== 'string' + || !['mes', 'semestre'].includes(value['tipo_periodo'] as string) + || !Array.isArray(value['periodos']) || !value['periodos'].every(p => typeof p === 'string') + || !Array.isArray(value['filas']) || !value['filas'].every(record) + || (value['notas'] !== undefined && (!Array.isArray(value['notas']) || !value['notas'].every(n => typeof n === 'string')))) { + throw new Error('Respuesta de datos inválida'); + } + return value as unknown as IndicadorDatos; + })); + } + figura(selection: FigureSelection) { + const dominio = requireDominio(selection.dominio ?? 'tea'); + if (selection.periodos !== undefined) { + if (!selection.periodos.length) throw new Error('Selección explícita vacía'); + const text = selection.periodos.join(','); + const tipos = selection.tipoPeriodo ? [selection.tipoPeriodo] : (['semestre', 'mes'] as const); + if (!tipos.some(tipo => parsePeriodos(text, tipo) !== null)) { + throw new Error('Periodos inválidos o de tipos mezclados'); + } + } + let params = new HttpParams().set('tema', selection.tema); + if (selection.periodos?.length) params = params.set('periodos', [...new Set(selection.periodos.map(periodo => periodo.trim()))].join(',')); + const url = `/${dominio}/indicadores/${encodeURIComponent(selection.indicador)}/figuras/${encodeURIComponent(selection.figura)}`; + return this.http.get(url, { params }).pipe(map(value => { + if (!record(value) || !Array.isArray(value['data']) || !value['data'].every(record) + || !record(value['layout'])) throw new Error('Respuesta de figura inválida'); + return value as unknown as PlotlyFigure; + })); + } +} diff --git a/src/app/features/indicadores/indicadores.synthetic-fixtures.ts b/src/app/features/indicadores/indicadores.synthetic-fixtures.ts new file mode 100644 index 0000000..d43c35d --- /dev/null +++ b/src/app/features/indicadores/indicadores.synthetic-fixtures.ts @@ -0,0 +1,4654 @@ +// Synthetic HTTP-only extracts from G7D.2B query_data.json. +// Source SHA256: 9b04eb5350b73171a7fac5ae498a34712781a598c0a1e6d50a55112587fbdd09 +import { Dominio, Indicador, PlotlyFigure } from './indicadores.models'; + +export const syntheticCatalogs: Record = { + "tea": [ + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "K01_evaluacion_3_meses", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Evaluaci\u00f3n iniciada a \u2264 3 meses de la referencia" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "K02_evaluacion_auditiva", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Evaluaci\u00f3n auditiva realizada" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "K03_evaluacion_desarrollo", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Evaluaci\u00f3n del desarrollo realizada" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "K04_ados2_eeg_30_dias", + "tipos_periodo": [ + "semestre" + ], + "titulo": "ADOS-2 y EEG a \u2264 30 d\u00edas" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "K05_eeg_20_minutos", + "tipos_periodo": [ + "semestre" + ], + "titulo": "EEG con \u2265 20 min de registro" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "K06_eeg_utilizable", + "tipos_periodo": [ + "semestre" + ], + "titulo": "EEG utilizable para el an\u00e1lisis" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "K07_eeg_fotoestimulacion", + "tipos_periodo": [ + "semestre" + ], + "titulo": "EEG con fotoestimulaci\u00f3n" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "K08_eeg_sueno", + "tipos_periodo": [ + "semestre" + ], + "titulo": "EEG con sue\u00f1o registrado" + }, + { + "contrato": "C2", + "figuras": [ + "fig_c2_apiladas" + ], + "id": "M02_sexo", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Sexo" + }, + { + "contrato": "C3r", + "figuras": [ + "fig_c3r_caja" + ], + "id": "M04_dias_entrevista_ados2", + "tipos_periodo": [ + "semestre" + ], + "titulo": "D\u00edas de la entrevista inicial al ADOS-2" + }, + { + "contrato": "C2", + "figuras": [ + "fig_c2_apiladas" + ], + "id": "M05_resultado_mchat", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Resultado del M-CHAT" + }, + { + "contrato": "C2", + "figuras": [ + "fig_c2_apiladas" + ], + "id": "M10_clasificacion_ados2_ventana", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Clasificaci\u00f3n del ADOS-2 por ventana" + }, + { + "contrato": "C2", + "figuras": [ + "fig_c2_apiladas" + ], + "id": "M12_perfil_ramos", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Perfil de desarrollo por \u00e1rea (Ramos)" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "M12b_sospecha_rgd", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Sospecha de retraso global del desarrollo" + }, + { + "contrato": "C2", + "figuras": [ + "fig_c2_apiladas" + ], + "id": "M15_grado_hipoacusia", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Grado de hipoacusia" + }, + { + "contrato": "C2", + "figuras": [ + "fig_c2_apiladas" + ], + "id": "M17_apgar_5min", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Apgar a los cinco minutos" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "M18_ingreso_ucin", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Ingreso a cuidados intensivos neonatales" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "M19_antecedentes_maternos", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Antecedentes maternos m\u00e1s frecuentes" + } + ], + "cacu": [ + { + "contrato": "C1", + "figuras": [ + "fig_c1_puntos" + ], + "id": "cacu_eu8", + "tipos_periodo": [ + "semestre", + "mes" + ], + "titulo": "Tasa de referencia a repetir citolog\u00eda" + } + ], + "cama": [ + { + "contrato": "C1", + "figuras": [ + "fig_c1_puntos" + ], + "id": "cama_eu8", + "tipos_periodo": [ + "semestre", + "mes" + ], + "titulo": "Proporci\u00f3n de ex\u00e1menes t\u00e9cnicamente aceptables" + } + ] +}; + +export const syntheticFigures: { name: string; figure: PlotlyFigure }[] = [ + { + "name": "tea_C1", + "figure": { + "data": [ + { + "customdata": [ + [ + 4, + 4 + ], + [ + 1, + 3 + ], + [ + 5, + 7 + ] + ], + "error_y": { + "array": [ + -1.4210854715202004e-14, + 45.90070678588425, + 20.349536246500236 + ], + "arrayminus": [ + 48.989084039692145, + 27.184138931240252, + 35.53512647546602 + ], + "color": "#2a78d6", + "thickness": 2, + "type": "data" + }, + "hovertemplate": "2025-S1
%{x}
%{y:.1f}% (%{customdata[0]} de %{customdata[1]})", + "marker": { + "color": "#2a78d6", + "line": { + "color": "#fcfcfb", + "width": 2 + }, + "size": 10 + }, + "mode": "markers", + "name": "2025-S1", + "showlegend": true, + "x": [ + "16 a 23 meses", + "24 a 30 meses", + "Total" + ], + "y": [ + 100.0, + 33.33333333333333, + 71.42857142857143 + ], + "type": "scatter" + }, + { + "customdata": [], + "error_y": { + "array": [], + "arrayminus": [], + "color": "#eb6834", + "thickness": 2, + "type": "data" + }, + "hovertemplate": "2025-S2
%{x}
%{y:.1f}% (%{customdata[0]} de %{customdata[1]})", + "marker": { + "color": "#eb6834", + "line": { + "color": "#fcfcfb", + "width": 2 + }, + "size": 10 + }, + "mode": "markers", + "name": "2025-S2", + "showlegend": true, + "x": [], + "y": [], + "type": "scatter" + } + ], + "layout": { + "template": { + "data": { + "histogram2dcontour": [ + { + "type": "histogram2dcontour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "choropleth": [ + { + "type": "choropleth", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "histogram2d": [ + { + "type": "histogram2d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "heatmap": [ + { + "type": "heatmap", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "contourcarpet": [ + { + "type": "contourcarpet", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "contour": [ + { + "type": "contour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "surface": [ + { + "type": "surface", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "mesh3d": [ + { + "type": "mesh3d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "scatter": [ + { + "fillpattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + }, + "type": "scatter" + } + ], + "parcoords": [ + { + "type": "parcoords", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolargl": [ + { + "type": "scatterpolargl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "bar": [ + { + "error_x": { + "color": "#2a3f5f" + }, + "error_y": { + "color": "#2a3f5f" + }, + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "bar" + } + ], + "scattergeo": [ + { + "type": "scattergeo", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolar": [ + { + "type": "scatterpolar", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "histogram": [ + { + "marker": { + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "histogram" + } + ], + "scattergl": [ + { + "type": "scattergl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatter3d": [ + { + "type": "scatter3d", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattermap": [ + { + "type": "scattermap", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterternary": [ + { + "type": "scatterternary", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattercarpet": [ + { + "type": "scattercarpet", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "carpet": [ + { + "aaxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "baxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "type": "carpet" + } + ], + "table": [ + { + "cells": { + "fill": { + "color": "#EBF0F8" + }, + "line": { + "color": "white" + } + }, + "header": { + "fill": { + "color": "#C8D4E3" + }, + "line": { + "color": "white" + } + }, + "type": "table" + } + ], + "barpolar": [ + { + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "barpolar" + } + ], + "pie": [ + { + "automargin": true, + "type": "pie" + } + ] + }, + "layout": { + "autotypenumbers": "strict", + "colorway": [ + "#636efa", + "#EF553B", + "#00cc96", + "#ab63fa", + "#FFA15A", + "#19d3f3", + "#FF6692", + "#B6E880", + "#FF97FF", + "#FECB52" + ], + "font": { + "color": "#2a3f5f" + }, + "hovermode": "closest", + "hoverlabel": { + "align": "left" + }, + "paper_bgcolor": "white", + "plot_bgcolor": "#E5ECF6", + "polar": { + "bgcolor": "#E5ECF6", + "angularaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "radialaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "ternary": { + "bgcolor": "#E5ECF6", + "aaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "baxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "caxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "coloraxis": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "colorscale": { + "sequential": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "sequentialminus": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "diverging": [ + [ + 0, + "#8e0152" + ], + [ + 0.1, + "#c51b7d" + ], + [ + 0.2, + "#de77ae" + ], + [ + 0.3, + "#f1b6da" + ], + [ + 0.4, + "#fde0ef" + ], + [ + 0.5, + "#f7f7f7" + ], + [ + 0.6, + "#e6f5d0" + ], + [ + 0.7, + "#b8e186" + ], + [ + 0.8, + "#7fbc41" + ], + [ + 0.9, + "#4d9221" + ], + [ + 1, + "#276419" + ] + ] + }, + "xaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "yaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "scene": { + "xaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "yaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "zaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + } + }, + "shapedefaults": { + "line": { + "color": "#2a3f5f" + } + }, + "annotationdefaults": { + "arrowcolor": "#2a3f5f", + "arrowhead": 0, + "arrowwidth": 1 + }, + "geo": { + "bgcolor": "white", + "landcolor": "#E5ECF6", + "subunitcolor": "white", + "showland": true, + "showlakes": true, + "lakecolor": "white" + }, + "title": { + "x": 0.05 + } + } + }, + "xaxis": { + "type": "category", + "categoryorder": "array", + "categoryarray": [ + "16 a 23 meses", + "24 a 30 meses", + "31 a 36 meses", + "Total" + ], + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + }, + "yaxis": { + "range": [ + 0, + 100 + ], + "ticksuffix": "%", + "title": { + "text": "porcentaje" + }, + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + }, + "scattermode": "group", + "font": { + "color": "#0b0b0b", + "family": "system-ui, -apple-system, sans-serif" + }, + "margin": { + "l": 60, + "r": 30, + "t": 50, + "b": 150 + }, + "title": { + "text": "Evaluaci\u00f3n iniciada a \u2264 3 meses de la referencia" + }, + "paper_bgcolor": "#fcfcfb", + "plot_bgcolor": "#fcfcfb", + "annotations": [ + { + "align": "left", + "font": { + "color": "#52514e", + "size": 11 + }, + "showarrow": false, + "text": "Indicador de calidad para el hospital; no forma parte del tablero del m\u00e9dico. Est\u00e1ndar: inicio de la evaluaci\u00f3n diagn\u00f3stica a \u2264 3 meses de la referencia (NICE QS51, enunciado 1).
Base depurada del proyecto TEA \u00b7 Centro M\u00e9dico ISSSTELE\u00d3N \u2013 UANL \u00b7 Fecha de corte: 2025-08-01
Uso exclusivo de investigaci\u00f3n. No usar para decisiones cl\u00ednicas.", + "x": 0, + "xanchor": "left", + "xref": "paper", + "y": -0.22, + "yanchor": "top", + "yref": "paper" + } + ] + } + } + }, + { + "name": "cacu_C1", + "figure": { + "data": [ + { + "hovertemplate": "%{x}
dato suprimido (conteo bajo)", + "marker": { + "color": "#c3c2b7", + "size": 10, + "symbol": "x" + }, + "mode": "markers", + "name": "suprimido", + "showlegend": false, + "x": [ + "2025-S1", + "2025-S2" + ], + "y": [ + 0, + 0 + ], + "type": "scatter" + } + ], + "layout": { + "template": { + "data": { + "histogram2dcontour": [ + { + "type": "histogram2dcontour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "choropleth": [ + { + "type": "choropleth", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "histogram2d": [ + { + "type": "histogram2d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "heatmap": [ + { + "type": "heatmap", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "contourcarpet": [ + { + "type": "contourcarpet", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "contour": [ + { + "type": "contour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "surface": [ + { + "type": "surface", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "mesh3d": [ + { + "type": "mesh3d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "scatter": [ + { + "fillpattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + }, + "type": "scatter" + } + ], + "parcoords": [ + { + "type": "parcoords", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolargl": [ + { + "type": "scatterpolargl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "bar": [ + { + "error_x": { + "color": "#2a3f5f" + }, + "error_y": { + "color": "#2a3f5f" + }, + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "bar" + } + ], + "scattergeo": [ + { + "type": "scattergeo", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolar": [ + { + "type": "scatterpolar", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "histogram": [ + { + "marker": { + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "histogram" + } + ], + "scattergl": [ + { + "type": "scattergl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatter3d": [ + { + "type": "scatter3d", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattermap": [ + { + "type": "scattermap", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterternary": [ + { + "type": "scatterternary", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattercarpet": [ + { + "type": "scattercarpet", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "carpet": [ + { + "aaxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "baxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "type": "carpet" + } + ], + "table": [ + { + "cells": { + "fill": { + "color": "#EBF0F8" + }, + "line": { + "color": "white" + } + }, + "header": { + "fill": { + "color": "#C8D4E3" + }, + "line": { + "color": "white" + } + }, + "type": "table" + } + ], + "barpolar": [ + { + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "barpolar" + } + ], + "pie": [ + { + "automargin": true, + "type": "pie" + } + ] + }, + "layout": { + "autotypenumbers": "strict", + "colorway": [ + "#636efa", + "#EF553B", + "#00cc96", + "#ab63fa", + "#FFA15A", + "#19d3f3", + "#FF6692", + "#B6E880", + "#FF97FF", + "#FECB52" + ], + "font": { + "color": "#2a3f5f" + }, + "hovermode": "closest", + "hoverlabel": { + "align": "left" + }, + "paper_bgcolor": "white", + "plot_bgcolor": "#E5ECF6", + "polar": { + "bgcolor": "#E5ECF6", + "angularaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "radialaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "ternary": { + "bgcolor": "#E5ECF6", + "aaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "baxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "caxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "coloraxis": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "colorscale": { + "sequential": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "sequentialminus": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "diverging": [ + [ + 0, + "#8e0152" + ], + [ + 0.1, + "#c51b7d" + ], + [ + 0.2, + "#de77ae" + ], + [ + 0.3, + "#f1b6da" + ], + [ + 0.4, + "#fde0ef" + ], + [ + 0.5, + "#f7f7f7" + ], + [ + 0.6, + "#e6f5d0" + ], + [ + 0.7, + "#b8e186" + ], + [ + 0.8, + "#7fbc41" + ], + [ + 0.9, + "#4d9221" + ], + [ + 1, + "#276419" + ] + ] + }, + "xaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "yaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "scene": { + "xaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "yaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "zaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + } + }, + "shapedefaults": { + "line": { + "color": "#2a3f5f" + } + }, + "annotationdefaults": { + "arrowcolor": "#2a3f5f", + "arrowhead": 0, + "arrowwidth": 1 + }, + "geo": { + "bgcolor": "white", + "landcolor": "#E5ECF6", + "subunitcolor": "white", + "showland": true, + "showlakes": true, + "lakecolor": "white" + }, + "title": { + "x": 0.05 + } + } + }, + "yaxis": { + "range": [ + 0, + 100 + ], + "ticksuffix": "%", + "title": { + "text": "porcentaje" + }, + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + }, + "font": { + "color": "#0b0b0b", + "family": "system-ui, -apple-system, sans-serif" + }, + "margin": { + "l": 60, + "r": 30, + "t": 50, + "b": 50 + }, + "title": { + "text": "Tasa de referencia a repetir citolog\u00eda" + }, + "paper_bgcolor": "#fcfcfb", + "plot_bgcolor": "#fcfcfb", + "xaxis": { + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + } + } + } + }, + { + "name": "cama_C1", + "figure": { + "data": [ + { + "customdata": { + "dtype": "i1", + "bdata": "BAU=", + "shape": "1, 2" + }, + "error_y": { + "array": { + "dtype": "f8", + "bdata": "AAAAAAAA+H8=" + }, + "arrayminus": { + "dtype": "f8", + "bdata": "AAAAAAAA+H8=" + }, + "color": "#2a78d6", + "thickness": 2, + "type": "data" + }, + "hovertemplate": "%{x}
%{y:.1f}% (%{customdata[0]} de %{customdata[1]})", + "marker": { + "color": "#2a78d6", + "size": 10 + }, + "mode": "markers", + "name": "valor", + "showlegend": false, + "x": [ + "2025-S1" + ], + "y": { + "dtype": "f8", + "bdata": "AAAAAAAAVEA=" + }, + "type": "scatter" + }, + { + "hovertemplate": "%{x}
dato suprimido (conteo bajo)", + "marker": { + "color": "#c3c2b7", + "size": 10, + "symbol": "x" + }, + "mode": "markers", + "name": "suprimido", + "showlegend": false, + "x": [ + "2025-S2" + ], + "y": [ + 0 + ], + "type": "scatter" + } + ], + "layout": { + "template": { + "data": { + "histogram2dcontour": [ + { + "type": "histogram2dcontour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "choropleth": [ + { + "type": "choropleth", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "histogram2d": [ + { + "type": "histogram2d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "heatmap": [ + { + "type": "heatmap", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "contourcarpet": [ + { + "type": "contourcarpet", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "contour": [ + { + "type": "contour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "surface": [ + { + "type": "surface", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "mesh3d": [ + { + "type": "mesh3d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "scatter": [ + { + "fillpattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + }, + "type": "scatter" + } + ], + "parcoords": [ + { + "type": "parcoords", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolargl": [ + { + "type": "scatterpolargl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "bar": [ + { + "error_x": { + "color": "#2a3f5f" + }, + "error_y": { + "color": "#2a3f5f" + }, + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "bar" + } + ], + "scattergeo": [ + { + "type": "scattergeo", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolar": [ + { + "type": "scatterpolar", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "histogram": [ + { + "marker": { + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "histogram" + } + ], + "scattergl": [ + { + "type": "scattergl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatter3d": [ + { + "type": "scatter3d", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattermap": [ + { + "type": "scattermap", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterternary": [ + { + "type": "scatterternary", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattercarpet": [ + { + "type": "scattercarpet", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "carpet": [ + { + "aaxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "baxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "type": "carpet" + } + ], + "table": [ + { + "cells": { + "fill": { + "color": "#EBF0F8" + }, + "line": { + "color": "white" + } + }, + "header": { + "fill": { + "color": "#C8D4E3" + }, + "line": { + "color": "white" + } + }, + "type": "table" + } + ], + "barpolar": [ + { + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "barpolar" + } + ], + "pie": [ + { + "automargin": true, + "type": "pie" + } + ] + }, + "layout": { + "autotypenumbers": "strict", + "colorway": [ + "#636efa", + "#EF553B", + "#00cc96", + "#ab63fa", + "#FFA15A", + "#19d3f3", + "#FF6692", + "#B6E880", + "#FF97FF", + "#FECB52" + ], + "font": { + "color": "#2a3f5f" + }, + "hovermode": "closest", + "hoverlabel": { + "align": "left" + }, + "paper_bgcolor": "white", + "plot_bgcolor": "#E5ECF6", + "polar": { + "bgcolor": "#E5ECF6", + "angularaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "radialaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "ternary": { + "bgcolor": "#E5ECF6", + "aaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "baxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "caxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "coloraxis": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "colorscale": { + "sequential": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "sequentialminus": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "diverging": [ + [ + 0, + "#8e0152" + ], + [ + 0.1, + "#c51b7d" + ], + [ + 0.2, + "#de77ae" + ], + [ + 0.3, + "#f1b6da" + ], + [ + 0.4, + "#fde0ef" + ], + [ + 0.5, + "#f7f7f7" + ], + [ + 0.6, + "#e6f5d0" + ], + [ + 0.7, + "#b8e186" + ], + [ + 0.8, + "#7fbc41" + ], + [ + 0.9, + "#4d9221" + ], + [ + 1, + "#276419" + ] + ] + }, + "xaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "yaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "scene": { + "xaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "yaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "zaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + } + }, + "shapedefaults": { + "line": { + "color": "#2a3f5f" + } + }, + "annotationdefaults": { + "arrowcolor": "#2a3f5f", + "arrowhead": 0, + "arrowwidth": 1 + }, + "geo": { + "bgcolor": "white", + "landcolor": "#E5ECF6", + "subunitcolor": "white", + "showland": true, + "showlakes": true, + "lakecolor": "white" + }, + "title": { + "x": 0.05 + } + } + }, + "yaxis": { + "range": [ + 0, + 100 + ], + "ticksuffix": "%", + "title": { + "text": "porcentaje" + }, + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + }, + "font": { + "color": "#0b0b0b", + "family": "system-ui, -apple-system, sans-serif" + }, + "margin": { + "l": 60, + "r": 30, + "t": 50, + "b": 50 + }, + "title": { + "text": "Proporci\u00f3n de ex\u00e1menes t\u00e9cnicamente aceptables" + }, + "paper_bgcolor": "#fcfcfb", + "plot_bgcolor": "#fcfcfb", + "xaxis": { + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + } + } + } + }, + { + "name": "tea_C2", + "figure": { + "data": [ + { + "customdata": [ + 5, + 0 + ], + "hovertemplate": "Femenino
%{x}
%{y:.1f}% (%{customdata})", + "marker": { + "color": "#E0A030", + "line": { + "color": "#fcfcfb", + "width": 2 + } + }, + "name": "Femenino", + "x": [ + [ + "2025-S1", + "2025-S2" + ], + [ + "Cohorte", + "Cohorte" + ] + ], + "y": [ + 45.45454545454545, + null + ], + "type": "bar" + }, + { + "customdata": [ + 4, + 0 + ], + "hovertemplate": "Masculino
%{x}
%{y:.1f}% (%{customdata})", + "marker": { + "color": "#2F6DB3", + "line": { + "color": "#fcfcfb", + "width": 2 + } + }, + "name": "Masculino", + "x": [ + [ + "2025-S1", + "2025-S2" + ], + [ + "Cohorte", + "Cohorte" + ] + ], + "y": [ + 36.36363636363637, + null + ], + "type": "bar" + }, + { + "customdata": [ + 1, + 0 + ], + "hovertemplate": "Indeterminado
%{x}
%{y:.1f}% (%{customdata})", + "marker": { + "color": "#8A9199", + "line": { + "color": "#fcfcfb", + "width": 2 + } + }, + "name": "Indeterminado", + "x": [ + [ + "2025-S1", + "2025-S2" + ], + [ + "Cohorte", + "Cohorte" + ] + ], + "y": [ + 9.090909090909092, + null + ], + "type": "bar" + }, + { + "customdata": [ + 1, + 0 + ], + "hovertemplate": "Sin dato
%{x}
%{y:.1f}% (%{customdata})", + "marker": { + "color": "#C9CDD2", + "line": { + "color": "#fcfcfb", + "width": 2 + } + }, + "name": "Sin dato", + "x": [ + [ + "2025-S1", + "2025-S2" + ], + [ + "Cohorte", + "Cohorte" + ] + ], + "y": [ + 9.090909090909092, + null + ], + "type": "bar" + } + ], + "layout": { + "template": { + "data": { + "histogram2dcontour": [ + { + "type": "histogram2dcontour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "choropleth": [ + { + "type": "choropleth", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "histogram2d": [ + { + "type": "histogram2d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "heatmap": [ + { + "type": "heatmap", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "contourcarpet": [ + { + "type": "contourcarpet", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "contour": [ + { + "type": "contour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "surface": [ + { + "type": "surface", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "mesh3d": [ + { + "type": "mesh3d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "scatter": [ + { + "fillpattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + }, + "type": "scatter" + } + ], + "parcoords": [ + { + "type": "parcoords", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolargl": [ + { + "type": "scatterpolargl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "bar": [ + { + "error_x": { + "color": "#2a3f5f" + }, + "error_y": { + "color": "#2a3f5f" + }, + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "bar" + } + ], + "scattergeo": [ + { + "type": "scattergeo", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolar": [ + { + "type": "scatterpolar", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "histogram": [ + { + "marker": { + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "histogram" + } + ], + "scattergl": [ + { + "type": "scattergl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatter3d": [ + { + "type": "scatter3d", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattermap": [ + { + "type": "scattermap", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterternary": [ + { + "type": "scatterternary", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattercarpet": [ + { + "type": "scattercarpet", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "carpet": [ + { + "aaxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "baxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "type": "carpet" + } + ], + "table": [ + { + "cells": { + "fill": { + "color": "#EBF0F8" + }, + "line": { + "color": "white" + } + }, + "header": { + "fill": { + "color": "#C8D4E3" + }, + "line": { + "color": "white" + } + }, + "type": "table" + } + ], + "barpolar": [ + { + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "barpolar" + } + ], + "pie": [ + { + "automargin": true, + "type": "pie" + } + ] + }, + "layout": { + "autotypenumbers": "strict", + "colorway": [ + "#636efa", + "#EF553B", + "#00cc96", + "#ab63fa", + "#FFA15A", + "#19d3f3", + "#FF6692", + "#B6E880", + "#FF97FF", + "#FECB52" + ], + "font": { + "color": "#2a3f5f" + }, + "hovermode": "closest", + "hoverlabel": { + "align": "left" + }, + "paper_bgcolor": "white", + "plot_bgcolor": "#E5ECF6", + "polar": { + "bgcolor": "#E5ECF6", + "angularaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "radialaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "ternary": { + "bgcolor": "#E5ECF6", + "aaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "baxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "caxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "coloraxis": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "colorscale": { + "sequential": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "sequentialminus": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "diverging": [ + [ + 0, + "#8e0152" + ], + [ + 0.1, + "#c51b7d" + ], + [ + 0.2, + "#de77ae" + ], + [ + 0.3, + "#f1b6da" + ], + [ + 0.4, + "#fde0ef" + ], + [ + 0.5, + "#f7f7f7" + ], + [ + 0.6, + "#e6f5d0" + ], + [ + 0.7, + "#b8e186" + ], + [ + 0.8, + "#7fbc41" + ], + [ + 0.9, + "#4d9221" + ], + [ + 1, + "#276419" + ] + ] + }, + "xaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "yaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "scene": { + "xaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "yaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "zaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + } + }, + "shapedefaults": { + "line": { + "color": "#2a3f5f" + } + }, + "annotationdefaults": { + "arrowcolor": "#2a3f5f", + "arrowhead": 0, + "arrowwidth": 1 + }, + "geo": { + "bgcolor": "white", + "landcolor": "#E5ECF6", + "subunitcolor": "white", + "showland": true, + "showlakes": true, + "lakecolor": "white" + }, + "title": { + "x": 0.05 + } + } + }, + "legend": { + "traceorder": "normal" + }, + "barmode": "stack", + "yaxis": { + "range": [ + 0, + 100 + ], + "ticksuffix": "%", + "title": { + "text": "porcentaje" + }, + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + }, + "font": { + "color": "#0b0b0b", + "family": "system-ui, -apple-system, sans-serif" + }, + "margin": { + "l": 60, + "r": 30, + "t": 50, + "b": 150 + }, + "title": { + "text": "Sexo" + }, + "paper_bgcolor": "#fcfcfb", + "plot_bgcolor": "#fcfcfb", + "xaxis": { + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + }, + "annotations": [ + { + "align": "left", + "font": { + "color": "#52514e", + "size": 11 + }, + "showarrow": false, + "text": "Sexo registrado en el expediente del ni\u00f1o. \u00abSin dato\u00bb: el expediente no lo consigna.
Base depurada del proyecto TEA \u00b7 Centro M\u00e9dico ISSSTELE\u00d3N \u2013 UANL \u00b7 Fecha de corte: 2025-08-01
Uso exclusivo de investigaci\u00f3n. No usar para decisiones cl\u00ednicas.", + "x": 0, + "xanchor": "left", + "xref": "paper", + "y": -0.22, + "yanchor": "top", + "yref": "paper" + } + ] + } + } + }, + { + "name": "tea_C3r", + "figure": { + "data": [ + { + "customdata": [ + 7 + ], + "hovertemplate": "2025-S1
%{x}
n = %{customdata}", + "line": { + "width": 2 + }, + "lowerfence": [ + 23.5 + ], + "marker": { + "color": "#2a78d6" + }, + "median": [ + 45.0 + ], + "name": "2025-S1", + "q1": [ + 23.5 + ], + "q3": [ + 55.0 + ], + "showlegend": true, + "upperfence": [ + 55.0 + ], + "x": [ + "Entrevista inicial \u2192 ADOS-2" + ], + "type": "box" + } + ], + "layout": { + "template": { + "data": { + "histogram2dcontour": [ + { + "type": "histogram2dcontour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "choropleth": [ + { + "type": "choropleth", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "histogram2d": [ + { + "type": "histogram2d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "heatmap": [ + { + "type": "heatmap", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "contourcarpet": [ + { + "type": "contourcarpet", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "contour": [ + { + "type": "contour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "surface": [ + { + "type": "surface", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "mesh3d": [ + { + "type": "mesh3d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "scatter": [ + { + "fillpattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + }, + "type": "scatter" + } + ], + "parcoords": [ + { + "type": "parcoords", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolargl": [ + { + "type": "scatterpolargl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "bar": [ + { + "error_x": { + "color": "#2a3f5f" + }, + "error_y": { + "color": "#2a3f5f" + }, + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "bar" + } + ], + "scattergeo": [ + { + "type": "scattergeo", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolar": [ + { + "type": "scatterpolar", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "histogram": [ + { + "marker": { + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "histogram" + } + ], + "scattergl": [ + { + "type": "scattergl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatter3d": [ + { + "type": "scatter3d", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattermap": [ + { + "type": "scattermap", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterternary": [ + { + "type": "scatterternary", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattercarpet": [ + { + "type": "scattercarpet", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "carpet": [ + { + "aaxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "baxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "type": "carpet" + } + ], + "table": [ + { + "cells": { + "fill": { + "color": "#EBF0F8" + }, + "line": { + "color": "white" + } + }, + "header": { + "fill": { + "color": "#C8D4E3" + }, + "line": { + "color": "white" + } + }, + "type": "table" + } + ], + "barpolar": [ + { + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "barpolar" + } + ], + "pie": [ + { + "automargin": true, + "type": "pie" + } + ] + }, + "layout": { + "autotypenumbers": "strict", + "colorway": [ + "#636efa", + "#EF553B", + "#00cc96", + "#ab63fa", + "#FFA15A", + "#19d3f3", + "#FF6692", + "#B6E880", + "#FF97FF", + "#FECB52" + ], + "font": { + "color": "#2a3f5f" + }, + "hovermode": "closest", + "hoverlabel": { + "align": "left" + }, + "paper_bgcolor": "white", + "plot_bgcolor": "#E5ECF6", + "polar": { + "bgcolor": "#E5ECF6", + "angularaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "radialaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "ternary": { + "bgcolor": "#E5ECF6", + "aaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "baxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "caxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "coloraxis": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "colorscale": { + "sequential": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "sequentialminus": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "diverging": [ + [ + 0, + "#8e0152" + ], + [ + 0.1, + "#c51b7d" + ], + [ + 0.2, + "#de77ae" + ], + [ + 0.3, + "#f1b6da" + ], + [ + 0.4, + "#fde0ef" + ], + [ + 0.5, + "#f7f7f7" + ], + [ + 0.6, + "#e6f5d0" + ], + [ + 0.7, + "#b8e186" + ], + [ + 0.8, + "#7fbc41" + ], + [ + 0.9, + "#4d9221" + ], + [ + 1, + "#276419" + ] + ] + }, + "xaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "yaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "scene": { + "xaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "yaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "zaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + } + }, + "shapedefaults": { + "line": { + "color": "#2a3f5f" + } + }, + "annotationdefaults": { + "arrowcolor": "#2a3f5f", + "arrowhead": 0, + "arrowwidth": 1 + }, + "geo": { + "bgcolor": "white", + "landcolor": "#E5ECF6", + "subunitcolor": "white", + "showland": true, + "showlakes": true, + "lakecolor": "white" + }, + "title": { + "x": 0.05 + } + } + }, + "yaxis": { + "title": { + "text": "d\u00edas" + }, + "rangemode": "tozero", + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + }, + "boxmode": "group", + "font": { + "color": "#0b0b0b", + "family": "system-ui, -apple-system, sans-serif" + }, + "margin": { + "l": 60, + "r": 30, + "t": 50, + "b": 150 + }, + "title": { + "text": "D\u00edas de la entrevista inicial al ADOS-2" + }, + "paper_bgcolor": "#fcfcfb", + "plot_bgcolor": "#fcfcfb", + "xaxis": { + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + }, + "annotations": [ + { + "align": "left", + "font": { + "color": "#52514e", + "size": 11 + }, + "showarrow": false, + "text": "D\u00edas de la entrevista inicial de psicolog\u00eda a la aplicaci\u00f3n del ADOS-2. La caja va del primer al tercer cuartil y la l\u00ednea es la mediana; no se dibuja cada ni\u00f1o.
Base depurada del proyecto TEA \u00b7 Centro M\u00e9dico ISSSTELE\u00d3N \u2013 UANL \u00b7 Fecha de corte: 2025-08-01
Uso exclusivo de investigaci\u00f3n. No usar para decisiones cl\u00ednicas.", + "x": 0, + "xanchor": "left", + "xref": "paper", + "y": -0.22, + "yanchor": "top", + "yref": "paper" + } + ] + } + } + } +]; diff --git a/src/app/governance/api/governance.api.ts b/src/app/governance/api/governance.api.ts new file mode 100644 index 0000000..eaf7ce7 --- /dev/null +++ b/src/app/governance/api/governance.api.ts @@ -0,0 +1,108 @@ +import { HttpClient, HttpParams } from '@angular/common/http'; +import { Injectable, inject } from '@angular/core'; +import { Observable } from 'rxjs'; +import { + CohortExclusionsResponse, + CohortScenario, + CohortVersion, + ModelLineage, + ModelVersion, + PromotionCheck, + ReportField, + OcrJob, + OcrRowStatus, + OcrRowsResponse, + OcrRunSummary, +} from './governance.types'; + +/** `/governance/*`: model and cohort versions, artifacts, and the OCR review queue. */ +@Injectable({ providedIn: 'root' }) +export class GovernanceApi { + private readonly http = inject(HttpClient); + + /** `scenario` needs `domain`; `domain` alone matches every scenario of it; + * neither matches everything. */ + listModelVersions(filters: { domain?: string; scenario?: string } = {}): Observable<{ model_versions: ModelVersion[] }> { + return this.http.get<{ model_versions: ModelVersion[] }>('/governance/model-versions', { params: toParams(filters) }); + } + + /** 409 with `checks` when the version doesn't meet the promotion requirements. */ + promoteModelVersion(domain: string, scenario: string, version: string): Observable { + return this.http.post(`/governance/model-versions/${domain}/${scenario}/${version}/promote`, {}); + } + + retireModelVersion(domain: string, scenario: string, version: string): Observable { + return this.http.post(`/governance/model-versions/${domain}/${scenario}/${version}/retire`, {}); + } + + lineage(domain: string, scenario: string, version: string): Observable { + return this.http.get(`/governance/model-versions/${domain}/${scenario}/${version}/lineage`); + } + + checks(domain: string, scenario: string, version: string): Observable<{ ready: boolean; checks: PromotionCheck[] }> { + return this.http.get<{ ready: boolean; checks: PromotionCheck[] }>(`/governance/model-versions/${domain}/${scenario}/${version}/checks`); + } + + attachReports(domain: string, scenario: string, version: string, reports: Partial>): Observable { + return this.http.patch(`/governance/model-versions/${domain}/${scenario}/${version}/reports`, reports); + } + + /** Logs the file to the version's MLflow run. Browsing/downloading a + * logged artifact goes through the MLflow tracking server directly. */ + uploadArtifact(domain: string, scenario: string, version: string, kind: string, file: File): Observable { + const form = new FormData(); + form.append('file', file); + form.append('kind', kind); + return this.http.post(`/governance/model-versions/${domain}/${scenario}/${version}/artifacts`, form); + } + + listCohortScenarios(): Observable<{ scenarios: CohortScenario[] }> { + return this.http.get<{ scenarios: CohortScenario[] }>('/governance/cohort-scenarios'); + } + + buildCohortVersion(domain: string, scenario: string, description?: string): Observable { + return this.http.post('/governance/cohort-versions', { domain, scenario, ...(description ? { description } : {}) }); + } + + listCohortVersions(filters: { domain?: string; scenario?: string } = {}): Observable<{ cohort_versions: CohortVersion[] }> { + return this.http.get<{ cohort_versions: CohortVersion[] }>('/governance/cohort-versions', { params: toParams(filters) }); + } + + getCohortExclusions(cohortVersionId: number): Observable { + return this.http.get(`/governance/cohort-versions/${cohortVersionId}/exclusions`); + } + + listOcrJobs(): Observable<{ jobs: OcrJob[] }> { + return this.http.get<{ jobs: OcrJob[] }>('/governance/ocr/jobs'); + } + + listOcrRows(domain: string, entity: string, status: OcrRowStatus, limit = 100, offset = 0): Observable { + return this.http.get(`/governance/ocr/${domain}/${entity}/rows`, { + params: toParams({ status, limit, offset }), + }); + } + + runOcr(domain: string, entity: string): Observable { + return this.http.post('/governance/ocr/run', { domain, entity }); + } + + /** The stored PDF, wrapped by the caller in a `File` for the page viewer. */ + getOcrBlob(domain: string, entity: string, id: number): Observable { + return this.http.get(`/governance/ocr/${domain}/${entity}/${id}/blob`, { responseType: 'blob' }); + } + + correctOcrRow(domain: string, entity: string, id: number, values: Record, confianza?: number): Observable> { + return this.http.post>(`/governance/ocr/${domain}/${entity}/${id}/correct`, { + values, + ...(confianza !== undefined ? { confianza } : {}), + }); + } +} + +function toParams(filters: Record): HttpParams { + let params = new HttpParams(); + for (const [key, value] of Object.entries(filters)) { + if (value !== undefined && value !== null && value !== '') params = params.set(key, String(value)); + } + return params; +} diff --git a/src/app/governance/api/governance.types.ts b/src/app/governance/api/governance.types.ts new file mode 100644 index 0000000..a24512d --- /dev/null +++ b/src/app/governance/api/governance.types.ts @@ -0,0 +1,119 @@ +/** Shapes of the `/governance/*` JSON contract. */ +import { Domain } from '../../connect/api/api.types'; + +export type Environment = 'DEV' | 'PROD'; + +/** Derived from MLflow on every call, never stored. */ +export type ModelStatus = 'desarrollo' | 'candidata' | 'produccion' | 'retirada'; + +/** Training, versioning and artifact storage live in MLflow; `name` is + * `-` and `tags` carries our own promotion-relevant + * metadata (domain, scenario, environment, cohort_version_id, the three + * report URIs) — MLflow has no native columns for any of that. */ +export interface ModelVersion { + name: string; + version: string; + run_id: string; + tags: Partial>; + metrics: Record; + created_at: string; + status: ModelStatus; +} + +export type ReportField = 'technical_validation_report_uri' | 'clinical_validation_report_uri' | 'interpretability_report_uri'; + +export interface PromotionCheck { + code: string; + requirement: string; + passed: boolean; + detail: string; +} + +/** A logged artifact's path within the run, e.g. `ONNX_CHECKPOINT/model.onnx` + * — browsing/downloading the file itself goes through MLflow directly. */ +export type ArtifactPath = string; + +export interface ModelLineage { + model_version: ModelVersion; + cohort_version: CohortVersion | null; + cohort_exclusions: CohortExclusionCount[]; + artifacts: ArtifactPath[]; + predictions: number; + checks: PromotionCheck[]; +} + +export interface CohortScenario { + domain: string; + scenario: string; + criteria_version: string; + criteria: { code: string; reason_code: string; applicable_in_production: boolean }[]; +} + +export interface CohortVersion { + cohort_version_id: number; + domain: string; + scenario: string; + criteria_version: string; + version_hash: string; + source_table: string; + description: string | null; + n_source: number; + n_included: number; + created_at: string; +} + +export interface CohortExclusionCount { + cohort_exclusion_count_id: number; + cohort_version_id: number; + criterion_code: string; + reason_code: string; + count: number; + created_at: string; +} + +export interface CohortExclusionDetail { + cohort_exclusion_id: number; + cohort_version_id: number; + pac_id_hospital: string; + episodio_id: number | null; + criterion_code: string; + reason_code: string; + excluded_at: string; +} + +export interface CohortExclusionsResponse { + counts: CohortExclusionCount[]; + detail: CohortExclusionDetail[]; +} + +export interface OcrJob { + domain: Domain; + entity: string; + label: string; + result_fields: string[]; +} + +export type OcrRowStatus = 'review' | 'pending' | 'failed' | 'done' | 'all'; + +export interface OcrRow { + id: number; + pac_id_hospital: string | null; + values: Record; + confianza: number | null; + estatus: string | null; + requiere_revision: boolean | null; + metodo_principal: string | null; + metodo_alternativo: string | null; +} + +export interface OcrRowsResponse { + rows: OcrRow[]; + total: number; +} + +export interface OcrRunSummary { + processed: number; + skipped_already_done: number; + failed: number; + needs_review: number; +} diff --git a/src/app/governance/components/cohort-exclusions-dialog/cohort-exclusions-dialog.html b/src/app/governance/components/cohort-exclusions-dialog/cohort-exclusions-dialog.html new file mode 100644 index 0000000..8ea6992 --- /dev/null +++ b/src/app/governance/components/cohort-exclusions-dialog/cohort-exclusions-dialog.html @@ -0,0 +1,61 @@ +

Exclusiones · {{ data.cohort.scenario }} ({{ data.cohort.version_hash.slice(0, 12) }}…)

+ + @if (loading()) { + + } + @if (error(); as message) { + + } + + @if (!loading() && !error()) { +

Conteo por criterio

+ + + + + + + + + + + + + + + +
Criterio{{ row.criterion_code }}Razón{{ row.reason_code }}Conteo{{ row.count }}
+ @if (counts().length === 0) { +

Ningún episodio fue excluido al construir esta cohorte.

+ } + +

Bitácora por episodio

+ + + + + + + + + + + + + + + + + + + + + + + +
Paciente{{ row.pac_id_hospital }}Episodio{{ row.episodio_id ?? '—' }}Criterio{{ row.criterion_code }}Razón{{ row.reason_code }}Fecha{{ row.excluded_at | date: 'short' }}
+ } +
+ + + diff --git a/src/app/governance/components/cohort-exclusions-dialog/cohort-exclusions-dialog.scss b/src/app/governance/components/cohort-exclusions-dialog/cohort-exclusions-dialog.scss new file mode 100644 index 0000000..efeb530 --- /dev/null +++ b/src/app/governance/components/cohort-exclusions-dialog/cohort-exclusions-dialog.scss @@ -0,0 +1,32 @@ +.exclusions { + display: flex; + flex-direction: column; + gap: var(--space-2); + max-height: 70vh; + min-width: 560px; + + h3 { + font: var(--mat-sys-title-small); + margin: var(--space-3) 0 0; + } +} + +.exclusions__table { + width: 100%; +} + +.exclusions__alert { + color: var(--mat-sys-error); +} + +.exclusions__empty { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); + margin: 0; +} + +@media (max-width: 720px) { + .exclusions { + min-width: 0; + } +} diff --git a/src/app/governance/components/cohort-exclusions-dialog/cohort-exclusions-dialog.ts b/src/app/governance/components/cohort-exclusions-dialog/cohort-exclusions-dialog.ts new file mode 100644 index 0000000..5e502a1 --- /dev/null +++ b/src/app/governance/components/cohort-exclusions-dialog/cohort-exclusions-dialog.ts @@ -0,0 +1,51 @@ +import { DatePipe } from '@angular/common'; +import { Component, OnInit, inject, signal } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatTableModule } from '@angular/material/table'; +import { apiErrorMessage } from '../../../connect/api/api.types'; +import { GovernanceApi } from '../../api/governance.api'; +import { CohortExclusionCount, CohortExclusionDetail, CohortVersion } from '../../api/governance.types'; + +export interface CohortExclusionsDialogData { + cohort: CohortVersion; +} + +/** + * Exclusion counts per criterion for a cohort version, plus the + * per-episode log behind them. Both are written when the cohort is built; + * this dialog only displays them. + */ +@Component({ + selector: 'app-cohort-exclusions-dialog', + imports: [DatePipe, MatButtonModule, MatDialogModule, MatProgressBarModule, MatTableModule], + templateUrl: './cohort-exclusions-dialog.html', + styleUrl: './cohort-exclusions-dialog.scss', +}) +export class CohortExclusionsDialog implements OnInit { + readonly data = inject(MAT_DIALOG_DATA); + private readonly api = inject(GovernanceApi); + + readonly loading = signal(true); + readonly error = signal(null); + readonly counts = signal([]); + readonly detail = signal([]); + + readonly countColumns = ['criterion_code', 'reason_code', 'count']; + readonly detailColumns = ['pac_id_hospital', 'episodio_id', 'criterion_code', 'reason_code', 'excluded_at']; + + ngOnInit(): void { + this.api.getCohortExclusions(this.data.cohort.cohort_version_id).subscribe({ + next: ({ counts, detail }) => { + this.loading.set(false); + this.counts.set(counts); + this.detail.set(detail); + }, + error: (error) => { + this.loading.set(false); + this.error.set(apiErrorMessage(error, 'No se pudieron cargar las exclusiones.')); + }, + }); + } +} diff --git a/src/app/governance/components/cohort-versions-panel/cohort-versions-panel.html b/src/app/governance/components/cohort-versions-panel/cohort-versions-panel.html new file mode 100644 index 0000000..3e920e7 --- /dev/null +++ b/src/app/governance/components/cohort-versions-panel/cohort-versions-panel.html @@ -0,0 +1,79 @@ +
+
+ + @for (option of domains; track option.id) { + {{ option.label }} + } + + + + + @for (scenario of scenarios(); track scenario.domain + scenario.scenario) { + + } + + +
+ + @if (loading() || building()) { + + } + @if (loadError(); as error) { + + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Dominio · escenario{{ c.domain }} · {{ c.scenario }}Hash de versión{{ c.version_hash.slice(0, 16) }}…Criterio{{ c.criteria_version }}Participantes{{ c.n_included }} incluido(s) · {{ excludedCount(c) }} excluido(s) de {{ c.n_source }}Creada{{ c.created_at | date: 'short' }} + +
+ + @if (!loading() && cohorts().length === 0) { +

Aún no hay cohortes construidas para este filtro.

+ } +
diff --git a/src/app/governance/components/cohort-versions-panel/cohort-versions-panel.scss b/src/app/governance/components/cohort-versions-panel/cohort-versions-panel.scss new file mode 100644 index 0000000..7cdb37b --- /dev/null +++ b/src/app/governance/components/cohort-versions-panel/cohort-versions-panel.scss @@ -0,0 +1,45 @@ +.cohorts { + display: flex; + flex-direction: column; + gap: var(--space-3); +} + +.cohorts__toolbar { + align-items: center; + display: flex; + gap: var(--space-2); +} + +.cohorts__spacer { + flex: 1; +} + +.cohorts__alert { + align-items: center; + background: var(--mat-sys-error-container); + color: var(--mat-sys-on-error-container); + display: flex; + gap: var(--space-2); + margin: 0; + padding: var(--space-2) var(--space-3); +} + +.cohorts__table { + width: 100%; +} + +.cohorts__hash { + background: var(--mat-sys-surface-variant); + border-radius: 4px; + font-size: 12px; + padding: 2px 6px; +} + +.cohorts__empty { + align-items: center; + color: var(--mat-sys-on-surface-variant); + display: flex; + font: var(--mat-sys-body-small); + gap: var(--space-2); + margin: 0; +} diff --git a/src/app/governance/components/cohort-versions-panel/cohort-versions-panel.ts b/src/app/governance/components/cohort-versions-panel/cohort-versions-panel.ts new file mode 100644 index 0000000..7627807 --- /dev/null +++ b/src/app/governance/components/cohort-versions-panel/cohort-versions-panel.ts @@ -0,0 +1,110 @@ +import { DatePipe } from '@angular/common'; +import { Component, DestroyRef, OnInit, inject, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatButtonModule } from '@angular/material/button'; +import { MatButtonToggleModule } from '@angular/material/button-toggle'; +import { MatDialog } from '@angular/material/dialog'; +import { MatIconModule } from '@angular/material/icon'; +import { MatMenuModule } from '@angular/material/menu'; +import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatTableModule } from '@angular/material/table'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { DOMAINS } from '../../../connect/state/connect-workspace.store'; +import { apiErrorMessage } from '../../../connect/api/api.types'; +import { GovernanceApi } from '../../api/governance.api'; +import { CohortScenario, CohortVersion } from '../../api/governance.types'; +import { CohortExclusionsDialog, CohortExclusionsDialogData } from '../cohort-exclusions-dialog/cohort-exclusions-dialog'; + +/** + * Frozen, hashed cohort versions with their exclusion counts and log. + * Scenarios with a registered builder can produce a + * new version from here. + */ +@Component({ + selector: 'app-cohort-versions-panel', + imports: [ + DatePipe, + MatButtonModule, + MatButtonToggleModule, + MatIconModule, + MatMenuModule, + MatProgressBarModule, + MatSnackBarModule, + MatTableModule, + MatTooltipModule, + ], + templateUrl: './cohort-versions-panel.html', + styleUrl: './cohort-versions-panel.scss', +}) +export class CohortVersionsPanel implements OnInit { + private readonly api = inject(GovernanceApi); + private readonly dialog = inject(MatDialog); + private readonly destroyRef = inject(DestroyRef); + private readonly snackBar = inject(MatSnackBar); + + readonly domains = [{ id: null, label: 'Todos' }, ...DOMAINS.map((d) => ({ id: d.id as string | null, label: d.label }))]; + readonly domain = signal(null); + readonly cohorts = signal([]); + readonly loading = signal(false); + readonly loadError = signal(null); + readonly scenarios = signal([]); + readonly building = signal(false); + + readonly displayedColumns = ['scenario', 'version_hash', 'criteria_version', 'counts', 'created_at', 'acciones']; + + ngOnInit(): void { + this.reload(); + this.api.listCohortScenarios().subscribe({ next: ({ scenarios }) => this.scenarios.set(scenarios), error: () => this.scenarios.set([]) }); + } + + build(scenario: CohortScenario): void { + this.building.set(true); + this.api.buildCohortVersion(scenario.domain, scenario.scenario).subscribe({ + next: (cohort) => { + this.building.set(false); + this.snackBar.open(`Cohorte ${cohort.scenario} construida: ${cohort.n_included} de ${cohort.n_source} episodios.`, 'OK', { duration: 5000 }); + this.reload(); + }, + error: (error) => { + this.building.set(false); + this.snackBar.open(apiErrorMessage(error, 'No se pudo construir la cohorte.'), 'OK', { duration: 6000 }); + }, + }); + } + + setDomain(domain: string | null): void { + this.domain.set(domain); + this.reload(); + } + + reload(): void { + this.loading.set(true); + this.loadError.set(null); + this.api + .listCohortVersions(this.domain() ? { domain: this.domain()! } : {}) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: ({ cohort_versions }) => { + this.loading.set(false); + this.cohorts.set(cohort_versions); + }, + error: (error) => { + this.loading.set(false); + this.loadError.set(apiErrorMessage(error, 'No se pudieron cargar las versiones de cohorte.')); + }, + }); + } + + openExclusions(cohort: CohortVersion): void { + this.dialog.open(CohortExclusionsDialog, { + width: '720px', + maxWidth: '96vw', + data: { cohort }, + }); + } + + excludedCount(cohort: CohortVersion): number { + return cohort.n_source - cohort.n_included; + } +} diff --git a/src/app/governance/components/governance-page/governance-page.html b/src/app/governance/components/governance-page/governance-page.html new file mode 100644 index 0000000..bd1fa92 --- /dev/null +++ b/src/app/governance/components/governance-page/governance-page.html @@ -0,0 +1,26 @@ +
+ +
+ Análisis de información +

Gobernanza de modelos

+
+
+ + + +
+ +
+
+ +
+ +
+
+ +
+ +
+
+
+
diff --git a/src/app/governance/components/governance-page/governance-page.scss b/src/app/governance/components/governance-page/governance-page.scss new file mode 100644 index 0000000..44e6b77 --- /dev/null +++ b/src/app/governance/components/governance-page/governance-page.scss @@ -0,0 +1,59 @@ +:host { + display: flex; + flex: 1; + min-width: 0; +} + +.governance { + display: flex; + flex: 1; + flex-direction: column; + height: calc(100dvh - var(--site-header-height)); + min-width: 0; +} + +.governance__toolbar { + --mat-toolbar-container-background-color: var(--mat-sys-surface); + --mat-toolbar-standard-height: 68px; + border-bottom: 1px solid var(--mat-sys-outline-variant); + height: auto; + min-height: 68px; + padding: var(--space-2) var(--space-4); +} + +.governance__title { + display: flex; + flex-direction: column; + line-height: 1.1; + + h1 { + color: var(--color-primary); + font-family: var(--font-heading); + font-size: 26px; + font-weight: 700; + letter-spacing: -0.02em; + margin: 0; + } +} + +.governance__eyebrow { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-label-small); + letter-spacing: 0.1em; + text-transform: uppercase; +} + +.governance__tabs { + flex: 1; + min-height: 0; + + ::ng-deep .mat-mdc-tab-body-wrapper { + flex: 1; + } +} + +.governance__panel { + height: 100%; + overflow: auto; + padding: var(--space-4); +} diff --git a/src/app/governance/components/governance-page/governance-page.ts b/src/app/governance/components/governance-page/governance-page.ts new file mode 100644 index 0000000..fdd4f1f --- /dev/null +++ b/src/app/governance/components/governance-page/governance-page.ts @@ -0,0 +1,19 @@ +import { Component } from '@angular/core'; +import { MatTabsModule } from '@angular/material/tabs'; +import { MatToolbarModule } from '@angular/material/toolbar'; +import { CohortVersionsPanel } from '../cohort-versions-panel/cohort-versions-panel'; +import { ModelVersionsPanel } from '../model-versions-panel/model-versions-panel'; +import { OcrReviewPanel } from '../ocr-review-panel/ocr-review-panel'; + +/** + * The "Gobernanza de modelos" page (route `/gobernanza`): model versions, + * cohorts and the OCR review queue, one tab each. Every tab is a + * self-contained panel that loads its own data. + */ +@Component({ + selector: 'app-governance-page', + imports: [CohortVersionsPanel, MatTabsModule, MatToolbarModule, ModelVersionsPanel, OcrReviewPanel], + templateUrl: './governance-page.html', + styleUrl: './governance-page.scss', +}) +export class GovernancePage {} diff --git a/src/app/governance/components/model-status-chip/model-status-chip.ts b/src/app/governance/components/model-status-chip/model-status-chip.ts new file mode 100644 index 0000000..8be0a3a --- /dev/null +++ b/src/app/governance/components/model-status-chip/model-status-chip.ts @@ -0,0 +1,50 @@ +import { Component, computed, input } from '@angular/core'; +import { MatIconModule } from '@angular/material/icon'; +import { ModelStatus } from '../../api/governance.types'; + +const PRESENTATION: Record = { + desarrollo: { label: 'Desarrollo', icon: 'science' }, + candidata: { label: 'Candidata', icon: 'pending' }, + produccion: { label: 'En producción', icon: 'verified' }, + retirada: { label: 'Retirada', icon: 'history' }, +}; + +@Component({ + selector: 'app-model-status', + imports: [MatIconModule], + template: `{{ view().label }}`, + styles: ` + .status { + align-items: center; + border-radius: 999px; + display: inline-flex; + font: var(--mat-sys-label-medium); + gap: 4px; + padding: 2px 10px 2px 6px; + } + mat-icon { + font-size: 16px; + height: 16px; + width: 16px; + } + .status--desarrollo, + .status--retirada { + background: var(--mat-sys-surface-container-high); + color: var(--mat-sys-on-surface-variant); + } + .status--candidata { + background: var(--mat-sys-secondary-container); + color: var(--mat-sys-on-secondary-container); + } + .status--produccion { + background: var(--mat-sys-primary-container); + color: var(--mat-sys-on-primary-container); + } + `, +}) +export class ModelStatusChip { + readonly status = input.required(); + readonly view = computed(() => PRESENTATION[this.status()]); +} diff --git a/src/app/governance/components/model-version-dialog/model-version-dialog.html b/src/app/governance/components/model-version-dialog/model-version-dialog.html new file mode 100644 index 0000000..35fe3d8 --- /dev/null +++ b/src/app/governance/components/model-version-dialog/model-version-dialog.html @@ -0,0 +1,149 @@ +

+ {{ title }} + @if (lineage(); as l) { + + } +

+ + + @if (busy()) { + + } + @if (error(); as message) { + + } + + @if (lineage(); as l) { + @let v = l.model_version; +
+
+
Dominio · escenario
+
{{ v.tags.domain }} · {{ v.tags.scenario }}
+
Entorno
+
{{ v.tags.environment }}
+
Creada
+
{{ v.created_at | date: 'medium' }}
+ @if (v.tags.promovida_en) { +
Promovida
+
{{ v.tags.promovida_en | date: 'medium' }}
+ } +
Predicciones registradas
+
{{ l.predictions | number }}
+
+ @if (metrics(v).length) { +
+ @for (metric of metrics(v); track metric[0]) { +
{{ metric[0] }}
+
{{ metric[1] }}
+ } +
+ } +
+ +
+

Requisitos para producción

+
    + @for (check of l.checks; track $index) { +
  • + + {{ check.code }} + {{ check.requirement }} + @if (check.detail) { + {{ check.detail }} + } +
  • + } +
+
+ +
+

Cohorte de entrenamiento

+ @if (l.cohort_version; as cohort) { +

+ {{ cohort.domain }} · {{ cohort.scenario }} · criterio {{ cohort.criteria_version }} · + {{ cohort.n_included | number }} de {{ cohort.n_source | number }} episodios +

+

hash {{ cohort.version_hash.slice(0, 16) }}…

+ @if (l.cohort_exclusions.length) { +
    + @for (count of l.cohort_exclusions; track count.cohort_exclusion_count_id) { +
  • {{ count.criterion_code }} ({{ count.reason_code }}): {{ count.count | number }} excluidos
  • + } +
+ } + } @else { +

Sin cohorte enlazada.

+ } +
+ +
+

Artefactos

+

Guardados en la corrida de MLflow; ábrelos desde el servidor de MLflow.

+
    + @for (artifact of l.artifacts; track artifact) { +
  • + + {{ artifactKindOf(artifact) }} + {{ artifactName(artifact) }} +
  • + } @empty { +
  • Sin artefactos.
  • + } +
+
+ + Tipo + + @for (kind of artifactKinds; track kind.id) { + {{ kind.label }} + } + + + + +
+
+ +
+

Reportes de validación

+
+ + Pruebas técnicas (MLD-01) + + + + Validación clínica (MLD-01b) + + + + Interpretabilidad (MLD-03) + + + +
+
+ } +
+ + + + @if (lineage(); as l) { + @if (l.model_version.status === 'produccion') { + + } @else { + + } + } + diff --git a/src/app/governance/components/model-version-dialog/model-version-dialog.scss b/src/app/governance/components/model-version-dialog/model-version-dialog.scss new file mode 100644 index 0000000..f253247 --- /dev/null +++ b/src/app/governance/components/model-version-dialog/model-version-dialog.scss @@ -0,0 +1,113 @@ +.title { + align-items: center; + display: flex; + gap: var(--space-3); +} + +.content { + display: flex; + flex-direction: column; + gap: var(--space-4); + + h3 { + font: var(--mat-sys-title-small); + margin: 0 0 var(--space-2); + } + + p { + margin: 0 0 var(--space-1); + } +} + +.alert { + align-items: center; + color: var(--mat-sys-error); + display: flex; + gap: var(--space-2); +} + +.summary { + display: flex; + flex-wrap: wrap; + gap: var(--space-6, 24px); + + dl { + display: grid; + gap: var(--space-1) var(--space-3); + grid-template-columns: auto auto; + margin: 0; + } + + dt { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-label-medium); + } + + dd { + margin: 0; + } +} + +.checks, +.artifacts, +.exclusions { + display: flex; + flex-direction: column; + gap: var(--space-1); + list-style: none; + margin: 0; + padding: 0; + + li { + align-items: center; + display: flex; + flex-wrap: wrap; + gap: var(--space-2); + } +} + +.checks mat-icon { + color: var(--mat-sys-primary); +} + +.checks__fail mat-icon { + color: var(--mat-sys-error); +} + +.checks__code, +.artifacts__kind { + font: var(--mat-sys-label-medium); + min-width: 64px; +} + +.checks__detail, +.hash, +.muted { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); +} + +.hash { + font-family: monospace; +} + +.artifacts__name { + font-family: monospace; +} + +.upload { + align-items: center; + display: flex; + gap: var(--space-3); + margin-top: var(--space-2); +} + +.reports { + display: grid; + gap: var(--space-2); + grid-template-columns: 1fr; + + button { + justify-self: start; + } +} diff --git a/src/app/governance/components/model-version-dialog/model-version-dialog.ts b/src/app/governance/components/model-version-dialog/model-version-dialog.ts new file mode 100644 index 0000000..09960c0 --- /dev/null +++ b/src/app/governance/components/model-version-dialog/model-version-dialog.ts @@ -0,0 +1,167 @@ +import { DatePipe, DecimalPipe } from '@angular/common'; +import { Component, inject, signal } from '@angular/core'; +import { FormBuilder, ReactiveFormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatInputModule } from '@angular/material/input'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatSelectModule } from '@angular/material/select'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { Observable } from 'rxjs'; +import { apiErrorMessage } from '../../../connect/api/api.types'; +import { GovernanceApi } from '../../api/governance.api'; +import { ModelLineage, ModelVersion, PromotionCheck } from '../../api/governance.types'; +import { ModelStatusChip } from '../model-status-chip/model-status-chip'; + +export const ARTIFACT_KINDS: { id: string; label: string }[] = [ + { id: 'ONNX_CHECKPOINT', label: 'Checkpoint ONNX' }, + { id: 'MUESTREO', label: 'Muestreo' }, + { id: 'DATOS_FALTANTES', label: 'Datos faltantes' }, + { id: 'METODO_ANALITICO', label: 'Método analítico' }, + { id: 'BALANCE_CLASES', label: 'Balance de clases' }, + { id: 'CONFIANZA_SALIDA', label: 'Confianza de la salida' }, + { id: 'OTRO', label: 'Otro' }, +]; + +/** + * One model version: what it was trained on (cohort hash and exclusions), + * its artifacts and their integrity, its validation reports, and the + * checklist that must pass before it can serve predictions. Closes with + * `true` when the version changed. + */ +@Component({ + selector: 'app-model-version-dialog', + imports: [ + DatePipe, + DecimalPipe, + MatButtonModule, + MatDialogModule, + MatFormFieldModule, + MatIconModule, + MatInputModule, + MatProgressBarModule, + MatSelectModule, + MatTooltipModule, + ModelStatusChip, + ReactiveFormsModule, + ], + templateUrl: './model-version-dialog.html', + styleUrl: './model-version-dialog.scss', +}) +export class ModelVersionDialog { + private readonly api = inject(GovernanceApi); + private readonly dialogRef = inject>(MatDialogRef); + private readonly version = inject(MAT_DIALOG_DATA); + + readonly artifactKinds = ARTIFACT_KINDS; + readonly lineage = signal(null); + readonly busy = signal(false); + readonly error = signal(null); + private changed = false; + + readonly reports = inject(FormBuilder).nonNullable.group({ + technical_validation_report_uri: [''], + clinical_validation_report_uri: [''], + interpretability_report_uri: [''], + }); + readonly artifactKind = signal('ONNX_CHECKPOINT'); + + constructor() { + this.load(); + } + + private get domain(): string { + return this.version.tags.domain!; + } + + private get scenario(): string { + return this.version.tags.scenario!; + } + + get title(): string { + const v = this.lineage()?.model_version ?? this.version; + return `${v.name}:${v.version}`; + } + + ready(checks: PromotionCheck[]): boolean { + return checks.every((check) => check.passed); + } + + metrics(version: ModelVersion): [string, unknown][] { + return Object.entries(version.metrics ?? {}); + } + + artifactName(path: string): string { + return path.split('/').pop() ?? path; + } + + artifactKindOf(path: string): string { + return path.split('/')[0] ?? path; + } + + saveReports(): void { + const values = this.reports.getRawValue(); + this.run(this.api.attachReports(this.domain, this.scenario, this.version.version, { + technical_validation_report_uri: values.technical_validation_report_uri.trim() || null, + clinical_validation_report_uri: values.clinical_validation_report_uri.trim() || null, + interpretability_report_uri: values.interpretability_report_uri.trim() || null, + })); + } + + uploadArtifact(event: Event): void { + const input = event.target as HTMLInputElement; + const file = input.files?.[0]; + input.value = ''; + if (file) this.run(this.api.uploadArtifact(this.domain, this.scenario, this.version.version, this.artifactKind(), file)); + } + + promote(): void { + this.run(this.api.promoteModelVersion(this.domain, this.scenario, this.version.version)); + } + + retire(): void { + this.run(this.api.retireModelVersion(this.domain, this.scenario, this.version.version)); + } + + close(): void { + this.dialogRef.close(this.changed); + } + + private run(request: Observable): void { + this.busy.set(true); + this.error.set(null); + request.subscribe({ + next: () => { + this.changed = true; + this.load(); + }, + error: (error) => { + this.busy.set(false); + this.error.set(apiErrorMessage(error, 'La operación no se pudo completar.')); + }, + }); + } + + private load(): void { + this.busy.set(true); + this.api.lineage(this.domain, this.scenario, this.version.version).subscribe({ + next: (lineage) => { + this.lineage.set(lineage); + const tags = lineage.model_version.tags; + this.reports.setValue({ + technical_validation_report_uri: tags.technical_validation_report_uri ?? '', + clinical_validation_report_uri: tags.clinical_validation_report_uri ?? '', + interpretability_report_uri: tags.interpretability_report_uri ?? '', + }); + this.reports.markAsPristine(); + this.busy.set(false); + }, + error: (error) => { + this.busy.set(false); + this.error.set(apiErrorMessage(error, 'No se pudo cargar la versión.')); + }, + }); + } +} diff --git a/src/app/governance/components/model-versions-panel/model-versions-panel.html b/src/app/governance/components/model-versions-panel/model-versions-panel.html new file mode 100644 index 0000000..77b93d4 --- /dev/null +++ b/src/app/governance/components/model-versions-panel/model-versions-panel.html @@ -0,0 +1,79 @@ +
+
+ + @for (option of domains; track option.id) { + {{ option.label }} + } + + + +
+ + @if (loading()) { + + } + @if (loadError(); as error) { + + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versión +
{{ v.name }}:{{ v.version }}
+ @if (metrics(v).length) { + + @for (metric of metrics(v); track metric.key) { + {{ metric.key }}: {{ metric.value }} + } + + } +
Dominio · escenario{{ v.tags.domain }} · {{ v.tags.scenario }}Entorno + {{ v.tags.environment }} + Cohorte{{ v.tags.cohort_version_id ?? '— (sin enlazar)' }}EstatusCreada{{ v.created_at | date: 'short' }} + +
+ + @if (!loading() && versions().length === 0) { +

Aún no hay versiones entrenadas para este filtro.

+ } +
diff --git a/src/app/governance/components/model-versions-panel/model-versions-panel.scss b/src/app/governance/components/model-versions-panel/model-versions-panel.scss new file mode 100644 index 0000000..202edef --- /dev/null +++ b/src/app/governance/components/model-versions-panel/model-versions-panel.scss @@ -0,0 +1,72 @@ +.models { + display: flex; + flex-direction: column; + gap: var(--space-3); +} + +.models__toolbar { + align-items: center; + display: flex; + gap: var(--space-2); +} + +.models__spacer { + flex: 1; +} + +.models__alert { + align-items: center; + background: var(--mat-sys-error-container); + color: var(--mat-sys-on-error-container); + display: flex; + gap: var(--space-2); + margin: 0; + padding: var(--space-2) var(--space-3); +} + +.models__table { + width: 100%; +} + +.models__tag { + font-weight: 600; +} + +.models__env { + background: var(--mat-sys-surface-variant); + border-radius: 999px; + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-label-small); + padding: 2px 10px; +} + +.models__env--prod { + background: #d8f0da; + color: #1e5c25; +} + +.models__production { + align-items: center; + color: #1e5c25; + display: inline-flex; + gap: 4px; + + mat-icon { + font-size: 18px; + height: 18px; + width: 18px; + } +} + +.models__inactive { + color: var(--mat-sys-on-surface-variant); +} + +.models__empty { + align-items: center; + color: var(--mat-sys-on-surface-variant); + display: flex; + font: var(--mat-sys-body-small); + gap: var(--space-2); + margin: 0; +} diff --git a/src/app/governance/components/model-versions-panel/model-versions-panel.ts b/src/app/governance/components/model-versions-panel/model-versions-panel.ts new file mode 100644 index 0000000..ffc1d00 --- /dev/null +++ b/src/app/governance/components/model-versions-panel/model-versions-panel.ts @@ -0,0 +1,97 @@ +import { DatePipe } from '@angular/common'; +import { Component, DestroyRef, OnInit, inject, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatButtonModule } from '@angular/material/button'; +import { MatDialog } from '@angular/material/dialog'; +import { MatButtonToggleModule } from '@angular/material/button-toggle'; +import { MatChipsModule } from '@angular/material/chips'; +import { MatIconModule } from '@angular/material/icon'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; +import { MatTableModule } from '@angular/material/table'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { DOMAINS } from '../../../connect/state/connect-workspace.store'; +import { apiErrorMessage } from '../../../connect/api/api.types'; +import { GovernanceApi } from '../../api/governance.api'; +import { ModelVersion } from '../../api/governance.types'; +import { ModelStatusChip } from '../model-status-chip/model-status-chip'; +import { ModelVersionDialog } from '../model-version-dialog/model-version-dialog'; + +/** + * Every registered model version with its status (desarrollo, candidata, + * en producción, retirada). The detail dialog holds the promotion + * checklist, lineage, artifacts and reports. + */ +@Component({ + selector: 'app-model-versions-panel', + imports: [ + DatePipe, + MatButtonModule, + MatButtonToggleModule, + MatChipsModule, + MatIconModule, + MatProgressBarModule, + MatSnackBarModule, + MatTableModule, + MatTooltipModule, + ModelStatusChip, + ], + templateUrl: './model-versions-panel.html', + styleUrl: './model-versions-panel.scss', +}) +export class ModelVersionsPanel implements OnInit { + private readonly api = inject(GovernanceApi); + private readonly snackBar = inject(MatSnackBar); + private readonly dialog = inject(MatDialog); + private readonly destroyRef = inject(DestroyRef); + + readonly domains = [{ id: null, label: 'Todos' }, ...DOMAINS.map((d) => ({ id: d.id as string | null, label: d.label }))]; + readonly domain = signal(null); + readonly versions = signal([]); + readonly loading = signal(false); + readonly loadError = signal(null); + + readonly displayedColumns = ['version', 'scenario', 'environment', 'cohort_version_id', 'status', 'created_at', 'acciones']; + + ngOnInit(): void { + this.reload(); + } + + setDomain(domain: string | null): void { + this.domain.set(domain); + this.reload(); + } + + reload(): void { + this.loading.set(true); + this.loadError.set(null); + this.api + .listModelVersions(this.domain() ? { domain: this.domain()! } : {}) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: ({ model_versions }) => { + this.loading.set(false); + this.versions.set(model_versions); + }, + error: (error) => { + this.loading.set(false); + this.loadError.set(apiErrorMessage(error, 'No se pudieron cargar las versiones de modelo.')); + }, + }); + } + + open(version: ModelVersion): void { + this.dialog + .open(ModelVersionDialog, { data: version, width: '880px', maxWidth: '96vw', autoFocus: false }) + .afterClosed() + .subscribe((changed) => { + if (!changed) return; + this.snackBar.open(`${version.name}:${version.version} actualizada.`, 'OK', { duration: 3000 }); + this.reload(); + }); + } + + metrics(version: ModelVersion): { key: string; value: unknown }[] { + return Object.entries(version.metrics ?? {}).map(([key, value]) => ({ key, value })); + } +} diff --git a/src/app/governance/components/ocr-correction-dialog/ocr-correction-dialog.html b/src/app/governance/components/ocr-correction-dialog/ocr-correction-dialog.html new file mode 100644 index 0000000..6b01cf7 --- /dev/null +++ b/src/app/governance/components/ocr-correction-dialog/ocr-correction-dialog.html @@ -0,0 +1,43 @@ +

{{ data.title }}

+ +
+ +
+ + +
+ + + + diff --git a/src/app/governance/components/ocr-correction-dialog/ocr-correction-dialog.scss b/src/app/governance/components/ocr-correction-dialog/ocr-correction-dialog.scss new file mode 100644 index 0000000..4e0f27d --- /dev/null +++ b/src/app/governance/components/ocr-correction-dialog/ocr-correction-dialog.scss @@ -0,0 +1,57 @@ +.correction { + display: grid; + gap: var(--space-4); + grid-template-columns: minmax(0, 1fr) 300px; + max-height: 78vh; +} + +.correction__viewer { + min-width: 0; + overflow: auto; +} + +.correction__side { + display: flex; + flex-direction: column; + gap: var(--space-3); + overflow: auto; +} + +.correction__hint { + align-items: center; + color: var(--mat-sys-on-surface-variant); + display: flex; + font: var(--mat-sys-body-small); + gap: var(--space-2); + margin: 0; +} + +.correction__spinner { + flex: none; +} + +.correction__field { + border: 1px solid var(--mat-sys-outline-variant); + border-radius: var(--mat-sys-corner-medium); + padding: var(--space-2); +} + +.correction__field--active { + border-color: var(--color-primary); + box-shadow: inset 0 0 0 1px var(--color-primary); +} + +.correction__pick { + margin-bottom: var(--space-2); + width: 100%; +} + +.correction__input { + width: 100%; +} + +@media (max-width: 960px) { + .correction { + grid-template-columns: 1fr; + } +} diff --git a/src/app/governance/components/ocr-correction-dialog/ocr-correction-dialog.ts b/src/app/governance/components/ocr-correction-dialog/ocr-correction-dialog.ts new file mode 100644 index 0000000..112fae9 --- /dev/null +++ b/src/app/governance/components/ocr-correction-dialog/ocr-correction-dialog.ts @@ -0,0 +1,116 @@ +import { Component, computed, inject, signal } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatInputModule } from '@angular/material/input'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; +import { apiErrorMessage } from '../../../connect/api/api.types'; +import { PdfSourceApi } from '../../../connect/api/pdf-source.api'; +import { PdfPageViewer } from '../../../connect/components/pdf-page-viewer/pdf-page-viewer'; +import { DrawnRegionBox } from '../../../connect/components/pdf-page-viewer/region-draw-overlay.directive'; + +export interface OcrCorrectionField { + name: string; + label: string; +} + +export interface OcrCorrectionDialogData { + title: string; + /** The row's stored PDF, already fetched by the caller and wrapped as a browser File. */ + file: File; + fields: OcrCorrectionField[]; + currentValues: Record; +} + +export interface OcrCorrectionResult { + values: Record; +} + +/** + * Manual correction of an OCR row. The user picks a field and draws a box + * over its value on the stored PDF; the text read from that box fills an + * editable input. What gets saved is the input's value, so a bad read can + * be fixed by hand. + */ +@Component({ + selector: 'app-ocr-correction-dialog', + imports: [ + MatButtonModule, + MatDialogModule, + MatFormFieldModule, + MatIconModule, + MatInputModule, + MatProgressSpinnerModule, + MatSnackBarModule, + PdfPageViewer, + ], + templateUrl: './ocr-correction-dialog.html', + styleUrl: './ocr-correction-dialog.scss', +}) +export class OcrCorrectionDialog { + readonly data = inject(MAT_DIALOG_DATA); + private readonly dialogRef = inject>(MatDialogRef); + private readonly pdfApi = inject(PdfSourceApi); + private readonly snackBar = inject(MatSnackBar); + + readonly page = signal(1); + readonly pageCount = signal(1); + readonly activeField = signal(this.data.fields[0]?.name ?? null); + readonly extracting = signal(false); + + readonly values = signal>( + Object.fromEntries( + this.data.fields.map((field) => [ + field.name, + this.data.currentValues[field.name] == null ? '' : String(this.data.currentValues[field.name]), + ]), + ), + ); + + readonly canSave = computed(() => Object.values(this.values()).some((value) => value.trim() !== '')); + + constructor() { + this.pdfApi.detect(this.data.file).subscribe({ + next: (detection) => this.pageCount.set(detection.page_count || 1), + error: () => this.pageCount.set(1), + }); + } + + selectField(name: string): void { + this.activeField.set(name); + } + + setValue(name: string, value: string): void { + this.values.update((values) => ({ ...values, [name]: value })); + } + + onRegionDrawn(box: DrawnRegionBox): void { + const field = this.activeField(); + if (!field) return; + this.extracting.set(true); + this.pdfApi + .extractRegions(this.data.file, [{ target_field: field, page_numbers: [this.page()], bbox: [box.x0, box.y0, box.x1, box.y1] }], null) + .subscribe({ + next: (result) => { + this.extracting.set(false); + const extracted = result.rows[0]?.[field]; + if (extracted != null && String(extracted).trim() !== '') { + this.setValue(field, String(extracted)); + } else { + this.snackBar.open('No se encontró texto en la región marcada — edita el campo a mano.', 'OK', { duration: 4000 }); + } + }, + error: (error) => { + this.extracting.set(false); + this.snackBar.open(apiErrorMessage(error, 'No se pudo leer esa región.'), 'OK', { duration: 4000 }); + }, + }); + } + + save(): void { + const values = Object.fromEntries(Object.entries(this.values()).filter(([, value]) => value.trim() !== '')); + this.dialogRef.close({ values }); + } +} diff --git a/src/app/governance/components/ocr-review-panel/ocr-review-panel.html b/src/app/governance/components/ocr-review-panel/ocr-review-panel.html new file mode 100644 index 0000000..2092e90 --- /dev/null +++ b/src/app/governance/components/ocr-review-panel/ocr-review-panel.html @@ -0,0 +1,89 @@ +
+
+ @if (jobs().length) { + + @for (job of jobs(); track job.entity) { + {{ job.label }} + } + + } + + + + +
+ + + @for (option of statusOptions; track option.value) { + {{ option.label }} + } + + + @if (loading() || running()) { + + } + @if (loadError(); as error) { + + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Paciente{{ row.pac_id_hospital ?? '—' }}Valores extraídos + + @for (entry of rowValueEntries(row); track entry.field) { + {{ entry.field }}: {{ entry.value }} + } + + Confianza{{ row.confianza === null ? '—' : (row.confianza | number: '1.0-2') }}Estatus + + {{ row.estatus ?? 'PENDIENTE' }} + + @if (row.requiere_revision) { + + } + + +
+ + @if (!loading() && rows().length === 0) { +

No hay filas en este filtro.

+ } + +

{{ total() }} fila(s) en total.

+
diff --git a/src/app/governance/components/ocr-review-panel/ocr-review-panel.scss b/src/app/governance/components/ocr-review-panel/ocr-review-panel.scss new file mode 100644 index 0000000..da7e8d8 --- /dev/null +++ b/src/app/governance/components/ocr-review-panel/ocr-review-panel.scss @@ -0,0 +1,69 @@ +.ocr { + display: flex; + flex-direction: column; + gap: var(--space-3); +} + +.ocr__toolbar { + align-items: center; + display: flex; + flex-wrap: wrap; + gap: var(--space-2); +} + +.ocr__spacer { + flex: 1; +} + +.ocr__status { + flex-wrap: wrap; +} + +.ocr__alert { + align-items: center; + background: var(--mat-sys-error-container); + color: var(--mat-sys-on-error-container); + display: flex; + gap: var(--space-2); + margin: 0; + padding: var(--space-2) var(--space-3); +} + +.ocr__table { + width: 100%; +} + +.ocr__status-chip { + background: var(--mat-sys-surface-variant); + border-radius: 999px; + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-label-small); + padding: 2px 10px; + text-transform: uppercase; +} + +.ocr__status-chip--realizado { + background: #d8f0da; + color: #1e5c25; +} + +.ocr__status-chip--fallido { + background: var(--mat-sys-error-container); + color: var(--mat-sys-on-error-container); +} + +.ocr__review-flag { + color: #b8860b; + margin-left: var(--space-1); + vertical-align: middle; +} + +.ocr__empty, +.ocr__total { + align-items: center; + color: var(--mat-sys-on-surface-variant); + display: flex; + font: var(--mat-sys-body-small); + gap: var(--space-2); + margin: 0; +} diff --git a/src/app/governance/components/ocr-review-panel/ocr-review-panel.ts b/src/app/governance/components/ocr-review-panel/ocr-review-panel.ts new file mode 100644 index 0000000..47af1b7 --- /dev/null +++ b/src/app/governance/components/ocr-review-panel/ocr-review-panel.ts @@ -0,0 +1,182 @@ +import { DecimalPipe } from '@angular/common'; +import { Component, DestroyRef, OnInit, inject, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatButtonModule } from '@angular/material/button'; +import { MatButtonToggleModule } from '@angular/material/button-toggle'; +import { MatChipsModule } from '@angular/material/chips'; +import { MatDialog } from '@angular/material/dialog'; +import { MatIconModule } from '@angular/material/icon'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatTableModule } from '@angular/material/table'; +import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { apiErrorMessage } from '../../../connect/api/api.types'; +import { GovernanceApi } from '../../api/governance.api'; +import { OcrJob, OcrRow, OcrRowStatus } from '../../api/governance.types'; +import { + OcrCorrectionDialog, + OcrCorrectionDialogData, + OcrCorrectionResult, +} from '../ocr-correction-dialog/ocr-correction-dialog'; + +const STATUS_OPTIONS: { value: OcrRowStatus; label: string }[] = [ + { value: 'review', label: 'Requieren revisión' }, + { value: 'pending', label: 'Pendientes' }, + { value: 'failed', label: 'Fallidas' }, + { value: 'done', label: 'Completadas' }, + { value: 'all', label: 'Todas' }, +]; + +/** + * Review queue for OCR-derived fields. The toggle group picks the OCR job, + * the run button starts the automatic batch (rows already done are + * skipped), and "Corregir" opens `OcrCorrectionDialog` for one row. + */ +@Component({ + selector: 'app-ocr-review-panel', + imports: [ + DecimalPipe, + MatButtonModule, + MatButtonToggleModule, + MatChipsModule, + MatIconModule, + MatProgressBarModule, + MatSnackBarModule, + MatTableModule, + MatTooltipModule, + ], + templateUrl: './ocr-review-panel.html', + styleUrl: './ocr-review-panel.scss', +}) +export class OcrReviewPanel implements OnInit { + private readonly api = inject(GovernanceApi); + private readonly dialog = inject(MatDialog); + private readonly snackBar = inject(MatSnackBar); + private readonly destroyRef = inject(DestroyRef); + + readonly statusOptions = STATUS_OPTIONS; + readonly jobs = signal([]); + readonly selectedJob = signal(null); + readonly status = signal('review'); + readonly rows = signal([]); + readonly total = signal(0); + readonly loading = signal(false); + readonly running = signal(false); + readonly correctingId = signal(null); + readonly loadError = signal(null); + + /** The same for every job: each job's result fields render as chips in the "values" column. */ + readonly displayedColumns = ['pac_id_hospital', 'values', 'confianza', 'estatus', 'acciones']; + + rowValueEntries(row: OcrRow): { field: string; value: string }[] { + return Object.entries(row.values).map(([field, value]) => ({ field, value: this.valueOf(row, field) })); + } + + ngOnInit(): void { + this.api + .listOcrJobs() + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: ({ jobs }) => { + this.jobs.set(jobs); + if (jobs.length) this.selectJob(jobs[0]); + }, + error: (error) => this.loadError.set(apiErrorMessage(error, 'No se pudieron cargar los tipos de extracción OCR.')), + }); + } + + selectJob(job: OcrJob): void { + this.selectedJob.set(job); + this.reload(); + } + + setStatus(status: OcrRowStatus): void { + this.status.set(status); + this.reload(); + } + + reload(): void { + const job = this.selectedJob(); + if (!job) return; + this.loading.set(true); + this.loadError.set(null); + this.api.listOcrRows(job.domain, job.entity, this.status()).subscribe({ + next: ({ rows, total }) => { + this.loading.set(false); + this.rows.set(rows); + this.total.set(total); + }, + error: (error) => { + this.loading.set(false); + this.loadError.set(apiErrorMessage(error, 'No se pudieron cargar las filas.')); + }, + }); + } + + runOcr(): void { + const job = this.selectedJob(); + if (!job) return; + this.running.set(true); + this.api.runOcr(job.domain, job.entity).subscribe({ + next: (summary) => { + this.running.set(false); + this.snackBar.open( + `OCR: ${summary.processed} leída(s), ${summary.needs_review} por revisar, ${summary.failed} fallida(s), ${summary.skipped_already_done} ya hechas.`, + 'OK', + { duration: 5000 }, + ); + this.reload(); + }, + error: (error) => { + this.running.set(false); + const message = apiErrorMessage(error, 'No se pudo correr la extracción.'); + this.snackBar.open(message, 'OK', { duration: 5000 }); + }, + }); + } + + correct(row: OcrRow): void { + const job = this.selectedJob(); + if (!job) return; + this.correctingId.set(row.id); + this.api.getOcrBlob(job.domain, job.entity, row.id).subscribe({ + next: (blob) => { + this.correctingId.set(null); + const file = new File([blob], `${job.entity}-${row.id}.pdf`, { type: 'application/pdf' }); + this.dialog + .open(OcrCorrectionDialog, { + width: '1200px', + maxWidth: '98vw', + autoFocus: false, + disableClose: true, + data: { + title: `Corregir · ${job.label} · ${row.pac_id_hospital ?? 'fila ' + row.id}`, + file, + fields: job.result_fields.map((name) => ({ name, label: name })), + currentValues: row.values, + }, + }) + .afterClosed() + .subscribe((result) => { + if (!result || Object.keys(result.values).length === 0) return; + this.api.correctOcrRow(job.domain, job.entity, row.id, result.values).subscribe({ + next: () => { + this.snackBar.open('Corrección guardada.', 'OK', { duration: 3000 }); + this.reload(); + }, + error: (error) => this.snackBar.open(apiErrorMessage(error, 'No se pudo guardar la corrección.'), 'OK', { duration: 5000 }), + }); + }); + }, + error: (error) => { + this.correctingId.set(null); + this.snackBar.open(apiErrorMessage(error, 'No se pudo cargar el PDF de esta fila.'), 'OK', { duration: 5000 }); + }, + }); + } + + valueOf(row: OcrRow, field: string): string { + const value = row.values[field]; + return value === null || value === undefined || value === '' ? '—' : String(value); + } +} diff --git a/src/app/home.html b/src/app/home.html index 5e3b7ca..a98e3db 100644 --- a/src/app/home.html +++ b/src/app/home.html @@ -3,12 +3,22 @@

ISSSTELEON · Análisis de información

Analiza tu información

- Carga tus datos para procesarlos y consultar resultados de forma clara y sencilla. + Conecta archivos, bases de datos y documentos PDF, mapea sus columnas a la base del proyecto y carga datos validados.

- +
  1. diff --git a/src/app/home.scss b/src/app/home.scss index 9cabd3c..ca1bb9a 100644 --- a/src/app/home.scss +++ b/src/app/home.scss @@ -43,8 +43,17 @@ h1 { margin: 20px auto 30px; max-width: 560px; } +.home__actions { + align-items: center; + display: flex; + flex-wrap: wrap; + gap: 16px; + justify-content: center; +} + .home__action { align-items: center; + text-decoration: none; background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; @@ -82,6 +91,15 @@ h1 { color: #5f9ea0; margin: 0; } + +.home__action--secondary { + background: transparent; + border-color: #5f9ea0; +} + +.home__action--secondary:hover { + background: #f1f6f6; +} .steps { align-items: center; color: var(--color-text-secondary); diff --git a/src/app/home.ts b/src/app/home.ts index 7513f12..d77d5fd 100644 --- a/src/app/home.ts +++ b/src/app/home.ts @@ -1,27 +1,11 @@ -import { Component, inject } from '@angular/core'; -import { MatDialog, MatDialogModule } from '@angular/material/dialog'; +import { Component } from '@angular/core'; import { MatIconModule } from '@angular/material/icon'; -import { InformationUploadDialog } from './information-upload-dialog'; +import { RouterLink } from '@angular/router'; @Component({ - imports: [MatDialogModule, MatIconModule], + imports: [MatIconModule, RouterLink], selector: 'app-home', styleUrl: './home.scss', templateUrl: './home.html', }) -export class Home { - private readonly dialog = inject(MatDialog); - - openInformationDialog(): void { - if (this.dialog.openDialogs.length > 0) return; - - this.dialog.open(InformationUploadDialog, { - width: '800px', - maxWidth: 'calc(100vw - 32px)', - autoFocus: 'first-tabbable', - restoreFocus: true, - disableClose: true, - panelClass: 'information-upload-dialog-panel', - }); - } -} +export class Home {} diff --git a/src/app/information-upload-dialog.html b/src/app/information-upload-dialog.html deleted file mode 100644 index 2f13303..0000000 --- a/src/app/information-upload-dialog.html +++ /dev/null @@ -1,105 +0,0 @@ -
    -
    -

    Cargar información

    - -
    - -
      -
    1. - Fuente -
    2. -
    3. - Configuración -
    4. -
    5. - Confirmación -
    6. -
    - - @if (step() === 'source') { -

    Selecciona cómo deseas proporcionar los datos.

    -
    -
    - - -
    -
    - } @else if (step() === 'configuration' && source() === 'file') { -

    Selecciona los archivos que deseas procesar.

    -
    -
    - -

    Arrastra tus archivos aquí

    -

    Excel · CSV · JSON · PDF

    - - -
    - - @if (fileMessages().length > 0) { -
      - @for (message of fileMessages(); track $index) {
    • {{ message }}
    • } -
    - } - - @if (files().length > 0) { -
    -
    -

    Archivos seleccionados

    - {{ files().length }} -
    -
      - @for (file of files(); track file.name + ':' + file.size) { -
    • - - {{ file.name }} - {{ formatFileSize(file.size) }} - -
    • - } -
    -
    - } -
    - } @else if (step() === 'configuration') { -

    Configura la fuente seleccionada.

    -
    - -

    Conexión SQL

    -

    La configuración de la conexión se implementará en la siguiente fase.

    -
    - } @else { -

    Revisa el siguiente paso de la carga de información.

    -
    - -

    Confirmación

    -

    La confirmación de los archivos se implementará en la siguiente fase.

    -
    - } - -
    - -
    - @if (step() !== 'source') { - - } - @if (step() !== 'confirmation') { - - } -
    -
    -
    diff --git a/src/app/information-upload-dialog.scss b/src/app/information-upload-dialog.scss deleted file mode 100644 index 17bea23..0000000 --- a/src/app/information-upload-dialog.scss +++ /dev/null @@ -1,494 +0,0 @@ -:host { - display: block; -} - -.upload-dialog { - background: #fff; - color: #081839; - padding: 28px 32px 24px; -} -.upload-dialog__header { - align-items: flex-start; - display: flex; - gap: 20px; - justify-content: space-between; -} -.upload-dialog__header h2 { - font-family: var(--font-heading); - font-size: 30px; - line-height: 1.15; - margin: 0; -} -.upload-dialog__description { - color: #7a7a7a; - font-size: 15px; - line-height: 1.5; - margin: 14px 0 0; -} -.upload-dialog__close { - color: #596273; - margin: -8px -10px 0 0; -} -.upload-steps { - align-items: center; - border-bottom: 1px solid #e3e7df; - color: #7a7a7a; - display: flex; - justify-content: center; - list-style: none; - margin: 24px 0 0; - padding: 0 0 20px; -} -.upload-steps li { - align-items: center; - display: flex; - font-size: 13px; - gap: 8px; -} -.upload-steps li + li::before { - background: #dfe3dc; - content: ''; - height: 1px; - margin: 0 14px; - width: clamp(20px, 8vw, 70px); -} -.upload-steps__number { - align-items: center; - background: #f0f2ed; - border-radius: 50%; - display: inline-flex; - font-size: 12px; - height: 25px; - justify-content: center; - width: 25px; -} -.upload-steps__number mat-icon { - font-size: 16px; - height: 16px; - width: 16px; -} -.upload-steps__item--active { - color: #081839; - font-weight: 600; -} -.upload-steps__item--active .upload-steps__number { - background: #a8c243; - color: #081839; -} -.upload-steps__item--complete { - color: #71882b; -} -.upload-steps__item--complete .upload-steps__number { - background: #f0f3e8; - color: #71882b; -} -.upload-dialog__content { - padding: 18px 0 28px; -} -.source-options { - display: grid; - gap: 16px; - grid-template-columns: repeat(2, minmax(0, 1fr)); -} -.source-card { - align-items: center; - background: #fff; - border: 1px solid #e3e7df; - border-radius: 9px; - color: #081839; - cursor: pointer; - display: flex; - gap: 16px; - min-height: 126px; - padding: 20px; - position: relative; - text-align: left; - transition: - background-color 0.16s ease, - border-color 0.16s ease; -} -.source-card:hover { - background: #fafbf7; - border-color: #c7d49a; -} -.source-card:focus-visible, -.upload-dialog__close:focus-visible, -.file-row__remove:focus-visible, -.upload-action:focus-visible { - outline: 3px solid rgb(168 194 67 / 65%); - outline-offset: 2px; -} -.source-card--selected { - background: #fbfcf6; - border: 2px solid #a8c243; - padding: 19px; -} -.source-card__icon { - align-items: center; - background: #f0f3e8; - border-radius: 8px; - color: #71882b; - display: inline-flex; - flex: 0 0 46px; - height: 46px; - justify-content: center; -} -.source-card__copy { - display: grid; - gap: 6px; - min-width: 0; -} -.source-card__title { - font-size: 16px; - font-weight: 600; -} -.source-card__description { - color: #7a7a7a; - font-size: 13px; - line-height: 1.45; -} -.source-card__check { - color: #71882b; - margin-left: auto; -} -.configuration-placeholder { - align-items: center; - display: flex; - flex-direction: column; - justify-content: center; - min-height: 164px; - text-align: center; -} -.configuration-placeholder__icon { - align-items: center; - background: #f0f3e8; - border-radius: 50%; - color: #71882b; - display: inline-flex; - height: 48px; - justify-content: center; - width: 48px; -} -.configuration-placeholder h3 { - font-family: var(--font-heading); - font-size: 22px; - margin: 14px 0 6px; -} -.configuration-placeholder p { - color: #7a7a7a; - font-size: 14px; - line-height: 1.55; - margin: 0; - max-width: 460px; -} -.file-configuration { - padding-top: 18px; -} -.dropzone { - align-items: center; - background: #fcfdfb; - border: 1.5px dashed #cbd2c4; - border-radius: 10px; - display: flex; - flex-direction: column; - justify-content: center; - min-height: 244px; - padding: 24px; - text-align: center; - transition: - background-color 0.14s ease, - border-color 0.14s ease; -} -.dropzone--active { - background: #f5f8e9; - border-color: #a8c243; - border-style: solid; -} -.dropzone__icon { - color: #71882b; - font-size: 40px; - height: 40px; - width: 40px; -} -.dropzone__title { - font-size: 16px; - font-weight: 600; - margin: 14px 0 4px; -} -.dropzone__formats { - color: #7a7a7a; - font-size: 13px; - margin: 0 0 16px; -} -.select-files-button { - --mat-button-outlined-label-text-color: #081839; - --mat-button-outlined-outline-color: #d7dccf; - --mat-button-outlined-state-layer-color: transparent; - --mat-button-outlined-ripple-color: transparent; - background: #fff; - border: 1px solid var(--mat-button-outlined-outline-color); - transition: border-color 0.18s ease; -} -.upload-action--outlined:hover { - background: #f3f6e9; - border-color: #a8c243; -} -.upload-action--outlined:active { - background: #e8eed5; -} -.select-files-button mat-icon { - color: #5f9ea0; - margin: 0; -} -.visually-hidden { - clip: rect(0, 0, 0, 0); - clip-path: inset(50%); - height: 1px; - overflow: hidden; - position: absolute; - white-space: nowrap; - width: 1px; -} -.file-messages { - background: #fffaf0; - border: 1px solid #ead8a7; - border-radius: 7px; - color: #634d13; - font-size: 13px; - line-height: 1.45; - list-style: none; - margin: 12px 0 0; - padding: 10px 14px; -} -.file-messages li + li { - margin-top: 4px; -} -.selected-files { - margin-top: 20px; -} -.selected-files__header { - align-items: center; - display: flex; - gap: 10px; - justify-content: space-between; - margin-bottom: 8px; -} -.selected-files__header h3 { - font-size: 15px; - font-weight: 600; - margin: 0; -} -.selected-files__count { - align-items: center; - background: #f0f3e8; - border-radius: 20px; - color: #52651d; - display: inline-flex; - font-size: 12px; - font-weight: 600; - height: 25px; - justify-content: center; - min-width: 25px; - padding: 0 7px; -} -.selected-files__list { - border: 1px solid #e7eae3; - border-radius: 8px; - list-style: none; - margin: 0; - max-height: 220px; - overflow-y: auto; - padding: 0; -} -.file-row { - align-items: center; - display: grid; - gap: 10px; - grid-template-columns: 22px minmax(0, 1fr) auto 40px; - min-height: 54px; - padding: 6px 8px 6px 12px; -} -.file-row + .file-row { - border-top: 1px solid #eef0eb; -} -.file-row__icon { - color: #71882b; - font-size: 20px; - height: 20px; - width: 20px; -} -.file-row__name { - font-size: 13px; - min-width: 0; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} -.file-row__size { - color: #737b6b; - font-size: 12px; - white-space: nowrap; -} -.file-row__remove { - color: #596273; - height: 36px; - line-height: 36px; - width: 36px; -} -.upload-dialog__footer { - align-items: center; - border-top: 1px solid #e3e7df; - display: grid; - gap: 10px; - grid-template-columns: minmax(0, 1fr) auto; - padding-top: 18px; -} -.action-cancel { - justify-self: start; -} -.upload-dialog__navigation { - align-items: center; - display: flex; - gap: 10px; - justify-self: end; -} -.upload-action { - border-radius: 8px; - font: inherit; - font-weight: 600; - min-height: 44px; - padding: 10px 18px; - transition: background-color 0.18s ease; -} -.action-cancel, -.action-back { - --mat-button-text-state-layer-color: transparent; - --mat-button-text-ripple-color: transparent; -} -.action-cancel { - --mat-button-text-label-text-color: #fff; - background: #7a7a7a; -} -.action-cancel:hover { - background: #696969; -} -.action-cancel:active { - background: #5d5d5d; -} -.action-back { - --mat-button-text-label-text-color: #081839; - background: #fff; - border: 1px solid #d7dccf; -} -.action-back:hover { - background: #f3f6e9; - border-color: #a8c243; -} -.action-back:active { - background: #e8eed5; -} -.action-continue { - --mat-button-filled-container-color: #6f821c; - --mat-button-filled-label-text-color: #f7f9ef; - --mat-button-filled-state-layer-color: transparent; - --mat-button-filled-ripple-color: transparent; - min-width: 124px; -} -.action-continue:hover:not(:disabled) { - --mat-button-filled-container-color: #809625; -} -.action-continue:active:not(:disabled) { - --mat-button-filled-container-color: #607216; -} -.action-continue:disabled { - --mat-button-filled-disabled-container-color: #e8ecdf; - --mat-button-filled-disabled-label-text-color: #9da38f; - --mat-button-filled-disabled-state-layer-color: transparent; -} -@media (max-width: 600px) { - .upload-dialog { - padding: 22px 20px 18px; - } - .upload-dialog__header h2 { - font-size: 26px; - } - .upload-dialog__description { - font-size: 14px; - margin-top: 12px; - } - .upload-steps { - display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); - } - .upload-steps li { - flex-direction: column; - font-size: 11px; - gap: 4px; - text-align: center; - } - .upload-steps li + li::before { - display: none; - } - .upload-steps__number { - height: 22px; - width: 22px; - } - .source-options { - grid-template-columns: 1fr; - } - .source-card { - min-height: 94px; - padding: 16px; - } - .source-card--selected { - padding: 15px; - } - .upload-dialog__content { - padding: 20px 0; - } - .dropzone { - min-height: 220px; - padding: 20px 12px; - } - .file-row { - gap: 6px; - grid-template-columns: 20px minmax(0, 1fr) auto 36px; - padding-left: 8px; - } - .file-row__name { - font-size: 12px; - } - .file-row__size { - font-size: 11px; - } -} - -@media (max-width: 360px) { - .upload-dialog { - padding-inline: 16px; - } - .upload-steps li { - font-size: 10px; - } - .upload-dialog__footer { - gap: 4px; - } - .upload-dialog__navigation { - gap: 4px; - } - .action-cancel, - .action-back { - min-width: 56px; - padding-inline: 6px; - } - .action-continue { - min-width: 92px; - padding-inline: 10px; - } -} - -@media (max-width: 300px) { - .upload-dialog__footer { - grid-template-columns: minmax(0, 1fr); - } -} diff --git a/src/app/shared/plotly/plotly-chart.spec.ts b/src/app/shared/plotly/plotly-chart.spec.ts new file mode 100644 index 0000000..75b325d --- /dev/null +++ b/src/app/shared/plotly/plotly-chart.spec.ts @@ -0,0 +1,67 @@ +import { TestBed } from '@angular/core/testing'; +import { vi } from 'vitest'; +import { PlotlyChart } from './plotly-chart'; +import { PLOTLY_LOADER } from './plotly-runtime'; +const mocks = { load: vi.fn(), react: vi.fn(), purge: vi.fn(), resize: vi.fn() }; + +describe('PlotlyChart lifecycle', () => { + beforeEach(() => { + vi.resetAllMocks(); + mocks.react.mockResolvedValue(undefined); + mocks.resize.mockResolvedValue(undefined); + mocks.load.mockResolvedValue({ react: mocks.react, purge: mocks.purge, Plots: { resize: mocks.resize } }); + TestBed.configureTestingModule({ imports: [PlotlyChart], providers: [{ provide: PLOTLY_LOADER, useValue: mocks.load }] }); + }); + it('monta el host, actualiza inputs y desconecta ResizeObserver', async () => { + const disconnect = vi.fn(); const observe = vi.fn(); + vi.stubGlobal('ResizeObserver', class { observe = observe; disconnect = disconnect; }); + const fixture = TestBed.createComponent(PlotlyChart); + fixture.componentRef.setInput('figure', { data: [], layout: {} }); + fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); + expect(observe).toHaveBeenCalledWith(fixture.nativeElement.querySelector('.plot')); + expect(mocks.react).toHaveBeenCalledTimes(1); + fixture.componentRef.setInput('figure', { data: [{ y: [1] }], layout: {} }); + fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); + expect(mocks.react).toHaveBeenCalledTimes(2); + fixture.destroy(); expect(disconnect).toHaveBeenCalled(); expect(mocks.purge).toHaveBeenCalled(); + vi.unstubAllGlobals(); + }); + it('muestra error asíncrono y se recupera con reintento', async () => { + mocks.react.mockRejectedValueOnce(new Error('render failed')); + const fixture = TestBed.createComponent(PlotlyChart); + fixture.componentRef.setInput('figure', { data: [], layout: {} }); + fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('No se pudo representar'); + fixture.nativeElement.querySelector('button').click(); + await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); + expect(fixture.componentInstance.status()).toBe('ready'); fixture.destroy(); + }); + it('UX-07C comunica sólo cambios reales de ancho, agrupa notificaciones y cancela al destruir', async () => { + const frames: FrameRequestCallback[] = [], cancel = vi.fn(), disconnect = vi.fn(); + let notify!: ResizeObserverCallback; + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { frames.push(callback); return frames.length; }); + vi.stubGlobal('cancelAnimationFrame', cancel); + vi.stubGlobal('ResizeObserver', class { + constructor(callback: ResizeObserverCallback) { notify = callback; } + observe = vi.fn(); disconnect = disconnect; + }); + const fixture = TestBed.createComponent(PlotlyChart), widths: number[] = []; + fixture.componentInstance.widthChanged.subscribe(width => widths.push(width)); + fixture.componentRef.setInput('figure', { data: [], layout: {} }); fixture.detectChanges(); + const host = fixture.nativeElement.querySelector('.plot') as HTMLElement; + let width = 640; + vi.spyOn(host, 'getBoundingClientRect').mockImplementation(() => ({ width } as DOMRect)); + const resize = () => notify([], {} as ResizeObserver); + const flush = () => frames.splice(0).forEach(callback => callback(0)); + const pending = frames.length; // Angular may also schedule a render frame. + resize(); resize(); expect(frames).toHaveLength(pending); + flush(); expect(widths).toEqual([640]); + resize(); flush(); expect(widths).toEqual([640]); // Height-only notification. + width = 900; resize(); flush(); expect(widths).toEqual([640, 900]); + width = 0; resize(); flush(); expect(widths).toEqual([640, 900]); // Hidden host. + resize(); fixture.destroy(); expect(disconnect).toHaveBeenCalled(); expect(cancel).toHaveBeenCalled(); + vi.unstubAllGlobals(); + }); +}); + + diff --git a/src/app/shared/plotly/plotly-chart.ts b/src/app/shared/plotly/plotly-chart.ts new file mode 100644 index 0000000..e5015ab --- /dev/null +++ b/src/app/shared/plotly/plotly-chart.ts @@ -0,0 +1,76 @@ +import { AfterViewInit, Component, inject, ElementRef, Input, OnChanges, OnDestroy, output, signal, ViewChild } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { PlotlyFigure } from '../../features/indicadores/indicadores.models'; +import { PlotlyController } from './plotly-controller'; +import { PLOTLY_LOADER } from './plotly-runtime'; + +@Component({ + selector: 'app-plotly-chart', + imports: [MatButtonModule, MatProgressBarModule], + template: ` + @if (status() === 'loading') { } + @if (status() === 'error') { +

    No se pudo representar la figura. Puedes reintentar.

    +
    + } +
    + @if (showNotes && status() === 'ready' && notes.length) { +
    +

    Notas de la figura

    + @for (note of notes; track $index) {

    } +
    + } + `, + styles: `:host { display: block; min-width: 0; } .plot-viewport { min-width: 0; overflow-x: auto; } .plot-viewport:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } .plot { width: 100%; min-width: var(--plot-min-width, 0px); min-height: 620px; visibility: hidden; } [role=alert] { padding: 1rem; } .notes { padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; }`, +}) +export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { + @Input() showNotes = true; + @Input() label = 'Figura estadística'; + @Input({ required: true }) figure!: PlotlyFigure; + @ViewChild('host', { static: true }) host!: ElementRef; + readonly renderError = output(); + readonly widthChanged = output(); + readonly status = signal<'loading' | 'ready' | 'error'>('loading'); + get notes(): string[] { + const annotations = this.figure?.layout['annotations']; + if (!Array.isArray(annotations)) return []; + return annotations.flatMap(annotation => + annotation && typeof annotation.text === 'string' ? [annotation.text] : []); + } + private readonly loadPlotly = inject(PLOTLY_LOADER); + private controller?: PlotlyController; + private observer?: ResizeObserver; + private lastWidth = 0; + private widthFrame?: number; + private readonly windowResize = () => { + this.controller?.resize(); + if (this.widthFrame !== undefined) return; + this.widthFrame = requestAnimationFrame(() => { + this.widthFrame = undefined; + const width = Math.floor(this.host.nativeElement.getBoundingClientRect().width); + if (width > 0 && width !== this.lastWidth) { this.lastWidth = width; this.widthChanged.emit(width); } + }); + }; + ngAfterViewInit() { + this.controller = new PlotlyController(this.host.nativeElement, this.loadPlotly, state => { + this.status.set(state); + if (state === 'error') this.renderError.emit(); + }); + if (typeof ResizeObserver !== 'undefined') { + this.observer = new ResizeObserver(this.windowResize); + this.observer.observe(this.host.nativeElement); + } else window.addEventListener('resize', this.windowResize); + this.controller.setFigure(this.figure); + // Also supply the initial width in browsers without ResizeObserver. + this.windowResize(); + } + ngOnChanges() { if (this.figure) this.controller?.setFigure(this.figure); } + retry() { this.controller?.setFigure(this.figure); } + ngOnDestroy() { + this.observer?.disconnect(); + if (this.widthFrame !== undefined) cancelAnimationFrame(this.widthFrame); + window.removeEventListener('resize', this.windowResize); + this.controller?.destroy(); + } +} diff --git a/src/app/shared/plotly/plotly-controller.spec.ts b/src/app/shared/plotly/plotly-controller.spec.ts new file mode 100644 index 0000000..7d6e7cf --- /dev/null +++ b/src/app/shared/plotly/plotly-controller.spec.ts @@ -0,0 +1,198 @@ +import { syntheticFigures } from '../../features/indicadores/indicadores.synthetic-fixtures'; +import { vi } from 'vitest'; +import { PlotlyController } from './plotly-controller'; +import { PlotlyRuntime } from './plotly-runtime'; +import { PlotlyFigure } from '../../features/indicadores/indicadores.models'; +function deferred() { + let resolve!: (value?: unknown) => void; + let reject!: (reason?: unknown) => void; + const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); + return { promise, resolve, reject }; +} +async function settle() { for (let i = 0; i < 12; i++) await Promise.resolve(); } +const fig = (value: number): PlotlyFigure => ({ data: [{ type: 'scatter', y: [value, null] }], layout: { annotations: [{ text: 'No usar para decisiones clínicas' }] } }); +describe('PlotlyController async', () => { + let host: HTMLElement; + let plotly: PlotlyRuntime; + let state: ReturnType void>>; + let controller: PlotlyController; + beforeEach(() => { + host = document.createElement('div'); + plotly = { react: vi.fn().mockResolvedValue(undefined), purge: vi.fn(), Plots: { resize: vi.fn().mockResolvedValue(undefined) }, addFrames: vi.fn().mockResolvedValue(undefined), deleteFrames: vi.fn().mockResolvedValue(undefined) }; + state = vi.fn(); + controller = new PlotlyController(host, () => Promise.resolve(plotly), state); + }); + it('conserva valores y anotaciones, aislando mutaciones de Plotly', async () => { + const figure = fig(0); + vi.mocked(plotly.react).mockImplementation(async (_host, data) => { data[0]['y'] = [123]; }); + controller.setFigure(figure); await settle(); + expect(figure.data[0]['y']).toEqual([0, null]); + expect(plotly.react).toHaveBeenCalledWith(host, expect.any(Array), figure.layout, expect.objectContaining({ displaylogo: false })); + expect(host.style.visibility).toBe('visible'); + expect(state).toHaveBeenLastCalledWith('ready'); + }); + it('desactiva el envío externo sin alterar el JSON ni las opciones locales recibidas', async () => { + const figure: PlotlyFigure = { + ...fig(1), + config: { showSendToCloud: true, displaylogo: true, scrollZoom: true, doubleClick: 'reset+autosize' }, + frames: [{ name: 'uno', data: [{ y: [2, null] }] }], + }; + const original = JSON.stringify(figure); + controller.setFigure(figure); await settle(); + expect(plotly.react).toHaveBeenCalledWith(host, figure.data, figure.layout, { + responsive: false, displaylogo: false, showSendToCloud: false, + modeBarButtonsToRemove: ['sendChartToCloud'], scrollZoom: true, doubleClick: 'reset+autosize', + }); + expect(plotly.addFrames).toHaveBeenCalledWith(host, figure.frames); + expect(JSON.stringify(figure)).toBe(original); + }); + it('elige sólo la figura reciente si la importación sigue pendiente', async () => { + const load = deferred(); + controller = new PlotlyController(host, () => load.promise as Promise, state); + controller.setFigure(fig(1)); controller.setFigure(fig(2)); + load.resolve(plotly); await settle(); + expect(plotly.react).toHaveBeenCalledTimes(1); + expect(vi.mocked(plotly.react).mock.calls[0][1][0]['y']).toEqual([2, null]); + }); + it('serializa react y oculta completados obsoletos', async () => { + const old = deferred(); const latest = deferred(); + vi.mocked(plotly.react).mockReturnValueOnce(old.promise).mockReturnValueOnce(latest.promise); + controller.setFigure(fig(1)); await settle(); + controller.setFigure(fig(2)); + expect(plotly.react).toHaveBeenCalledTimes(1); + old.resolve(); await settle(); + expect(plotly.react).toHaveBeenCalledTimes(2); + expect(host.style.visibility).toBe('hidden'); + expect(state).not.toHaveBeenCalledWith('ready'); + latest.resolve(); await settle(); + expect(host.style.visibility).toBe('visible'); + expect(state).toHaveBeenLastCalledWith('ready'); + }); + it('ignora rechazo antiguo y representa la siguiente figura', async () => { + const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise); + controller.setFigure(fig(1)); await settle(); controller.setFigure(fig(2)); + pending.reject(new Error('old')); await settle(); + expect(state).not.toHaveBeenCalledWith('error'); + expect(state).toHaveBeenLastCalledWith('ready'); + }); + it('maneja error asíncrono y permite reintentar', async () => { + vi.mocked(plotly.react).mockRejectedValueOnce(new Error('failed')); + controller.setFigure(fig(1)); await settle(); + expect(state).toHaveBeenLastCalledWith('error'); + expect(host.style.visibility).toBe('hidden'); + controller.setFigure(fig(1)); await settle(); + expect(state).toHaveBeenLastCalledWith('ready'); + }); + it('maneja importación fallida y recupera el cargador', async () => { + const load = vi.fn().mockRejectedValueOnce(new Error()).mockResolvedValue(plotly); + controller = new PlotlyController(host, load, state); + controller.setFigure(fig(1)); await settle(); expect(state).toHaveBeenLastCalledWith('error'); + controller.setFigure(fig(1)); await settle(); expect(state).toHaveBeenLastCalledWith('ready'); + }); + it('purga al destruir y nuevamente tras terminar react pendiente', async () => { + const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise); + controller.setFigure(fig(1)); await settle(); + controller.destroy(); expect(plotly.purge).toHaveBeenCalledTimes(1); + pending.resolve(); await settle(); expect(plotly.purge).toHaveBeenCalledTimes(2); + expect(state).not.toHaveBeenCalledWith('ready'); + controller.setFigure(fig(2)); controller.resize(); await settle(); + expect(plotly.react).toHaveBeenCalledTimes(1); + expect(plotly.Plots.resize).not.toHaveBeenCalled(); + }); + it('no renderiza tras destruir durante la importación', async () => { + const pending = deferred(); controller = new PlotlyController(host, () => pending.promise as Promise, state); + controller.setFigure(fig(1)); controller.destroy(); pending.resolve(plotly); await settle(); + expect(plotly.react).not.toHaveBeenCalled(); expect(plotly.purge).toHaveBeenCalledWith(host); + }); + it('serializa resize y el siguiente react', async () => { + controller.setFigure(fig(1)); await settle(); + const resize = deferred(); vi.mocked(plotly.Plots.resize).mockReturnValueOnce(resize.promise); + controller.resize(); await settle(); controller.setFigure(fig(2)); + expect(plotly.react).toHaveBeenCalledTimes(1); + resize.resolve(); await settle(); expect(plotly.react).toHaveBeenCalledTimes(2); + }); + it('conserva frames y los retira al cambiar figura', async () => { + controller.setFigure({ ...fig(1), frames: [{ name: 'uno', data: [] }] }); await settle(); + expect(plotly.addFrames).toHaveBeenCalledWith(host, [{ name: 'uno', data: [] }]); + controller.setFigure(fig(2)); await settle(); + expect(plotly.deleteFrames).toHaveBeenCalledWith(host, [0]); + }); +}); + + +// Exercise the installed bundle in jsdom: no cloud action is clicked. +describe('PlotlyController con Plotly instalado', () => { + let runtime: PlotlyRuntime & { + version: string; + PlotSchema: { get(): { config: Record } }; + }; + beforeAll(async () => { + // jsdom has no canvas renderer; cartesian SVG only needs this import-time probe. + const canvas = vi.spyOn(HTMLCanvasElement.prototype, 'getContext') + .mockReturnValue({ measureText: () => ({ width: 0 }) } as unknown as CanvasRenderingContext2D); + try { + const module = await import('plotly.js-cartesian-dist-min'); + runtime = (module.default ?? module) as typeof runtime; + } finally { canvas.mockRestore(); } + }); + it('usa propiedades admitidas por el esquema de Plotly 4.1.2', () => { + expect(runtime.version).toBe('4.1.2'); + const config = runtime.PlotSchema.get().config; + expect(config['showSendToCloud'].valType).toBe('boolean'); + expect(config['displaylogo'].valType).toBe('boolean'); + expect(config['modeBarButtonsToRemove'].valType).toBe('any'); + }); + it.each([ + ['C1', { type: 'scatter', x: [1, 2], y: [3, 4] }], + ['C2', { type: 'bar', x: ['grupo'], y: [100] }], + ['C3r', { type: 'box', x: ['grupo'], q1: [23.5], median: [45], q3: [55], lowerfence: [23.5], upperfence: [55] }], + ])('genera la modebar %s sin envío externo y conserva zoom/pan/restauración', async (_contract, trace) => { + const host = document.createElement('div'); + document.body.append(host); + const figure: PlotlyFigure = { data: [trace], layout: { width: 600, height: 400 } }; + const original = JSON.stringify(figure); + let controller!: PlotlyController; + try { + await new Promise((resolve, reject) => { + controller = new PlotlyController(host, () => Promise.resolve(runtime), state => { + if (state === 'ready') resolve(); + if (state === 'error') reject(new Error('Plotly failed to render')); + }); + controller.setFigure(figure); + }); + const buttons = Array.from(host.querySelectorAll('.modebar-btn')); + const titles = buttons.map(button => button.getAttribute('data-title')); + expect(titles).not.toContain('Share chart...'); + expect(titles).toEqual(expect.arrayContaining(['Zoom', 'Pan', 'Zoom in', 'Zoom out', 'Autoscale', 'Reset axes', 'Download plot as a PNG'])); + expect(host.querySelector('.modebar a[href]')).toBeNull(); + const rendered = host as unknown as HTMLElement & { _fullLayout: { dragmode: string } }; + for (const [title, mode] of [['Pan', 'pan'], ['Zoom', 'zoom']]) { + buttons.find(button => button.getAttribute('data-title') === title)! + .dispatchEvent(new MouseEvent('click', { bubbles: true })); + await vi.waitFor(() => expect(rendered._fullLayout.dragmode).toBe(mode)); + } + expect(JSON.stringify(figure)).toBe(original); + } finally { + controller?.destroy(); host.remove(); + } + }); + it.each(syntheticFigures)('renderiza el JSON G7D.2B $name sin convertir nulos, IC ni bdata', async ({ figure }) => { + const host = document.createElement('div'); + document.body.append(host); + const original = JSON.stringify(figure); + let controller!: PlotlyController; + try { + await new Promise((resolve, reject) => { + controller = new PlotlyController(host, () => Promise.resolve(runtime), state => { + if (state === 'ready') resolve(); + if (state === 'error') reject(new Error('Plotly synthetic fixture failed')); + }); + controller.setFigure(figure); + }); + expect(host.querySelector('.main-svg')).not.toBeNull(); + expect(host.style.visibility).toBe('visible'); + expect(JSON.stringify(figure)).toBe(original); + } finally { controller?.destroy(); host.remove(); } + }); + +}); diff --git a/src/app/shared/plotly/plotly-controller.ts b/src/app/shared/plotly/plotly-controller.ts new file mode 100644 index 0000000..9ac0add --- /dev/null +++ b/src/app/shared/plotly/plotly-controller.ts @@ -0,0 +1,87 @@ +import { PlotlyFigure } from '../../features/indicadores/indicadores.models'; +import { PlotlyRuntime } from './plotly-runtime'; + +// One serialized queue owns the host. A completed stale operation cannot expose +// its graph or overwrite a newer react operation. Resize uses the same queue. +export class PlotlyController { + private desired?: PlotlyFigure; + private version = 0; + private rendered = -1; + private busy = false; + private destroyed = false; + private resizePending = false; + private plotly?: PlotlyRuntime; + private frameCount = 0; + constructor(private host: HTMLElement, private load: () => Promise, + private state: (state: 'loading' | 'ready' | 'error') => void) {} + + setFigure(figure: PlotlyFigure) { + if (this.destroyed) return; + this.desired = figure; + this.version++; + this.host.style.visibility = 'hidden'; + this.state('loading'); + void this.drain(); + } + resize() { + if (this.destroyed || this.rendered < 0) return; + this.resizePending = true; + void this.drain(); + } + destroy() { + this.destroyed = true; + this.host.style.visibility = 'hidden'; + this.plotly?.purge(this.host); + } + private async drain() { + if (this.busy || this.destroyed) return; + this.busy = true; + try { + this.plotly ??= await this.load(); + while (!this.destroyed && (this.rendered !== this.version || this.resizePending)) { + const version = this.version; + try { + if (this.rendered !== version && this.desired) { + // Plotly may mutate inputs; clone the complete JSON without changing values. + const figure = structuredClone(this.desired); + if (this.frameCount) await this.plotly.deleteFrames(this.host, Array.from({ length: this.frameCount }, (_, i) => i)); + this.frameCount = 0; + if (this.destroyed) break; + await this.plotly.react(this.host, figure.data, figure.layout, { + ...figure.config, responsive: false, displaylogo: false, + showSendToCloud: false, + modeBarButtonsToRemove: ['sendChartToCloud'], + }); + if (this.destroyed) break; + if (version !== this.version) continue; + if (figure.frames?.length) { + await this.plotly.addFrames(this.host, figure.frames); + this.frameCount = figure.frames.length; + } + if (this.destroyed) break; + if (version !== this.version) continue; + this.rendered = version; + this.host.style.visibility = 'visible'; + this.state('ready'); + } else { + this.resizePending = false; + await this.plotly.Plots.resize(this.host); + } + } catch { + if (this.destroyed) break; + if (version !== this.version) continue; + this.rendered = version; + this.resizePending = false; + this.host.style.visibility = 'hidden'; + this.state('error'); + } + } + } catch { + if (!this.destroyed) this.state('error'); + } finally { + this.busy = false; + // A pending react can recreate internal resources after the first purge. + if (this.destroyed) this.plotly?.purge(this.host); + } + } +} diff --git a/src/app/shared/plotly/plotly-runtime.spec.ts b/src/app/shared/plotly/plotly-runtime.spec.ts new file mode 100644 index 0000000..343db46 --- /dev/null +++ b/src/app/shared/plotly/plotly-runtime.spec.ts @@ -0,0 +1,23 @@ +import { vi } from 'vitest'; +import { loadPlotly } from './plotly-runtime'; + +it('carga una sola instancia oficial con el esquema requerido por C1/C2/C3r', async () => { + // No chart rendering in jsdom. Schema inspection only needs browser globals. + const canvas = vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null); + try { + const first = loadPlotly(); + expect(loadPlotly()).toBe(first); + const runtime = await first as unknown as { version: string; PlotSchema: { get(): any } }; + expect(runtime.version).toBe('4.1.2'); + const schema = runtime.PlotSchema.get(); + expect(schema.traces.scatter).toBeDefined(); + expect(schema.traces.bar).toBeDefined(); + expect(schema.traces.box).toBeDefined(); + expect(schema.traces.scatter.attributes.error_y).toBeDefined(); + expect(schema.layout.layoutAttributes.xaxis.type.values).toContain('multicategory'); + expect(schema.traces.scatter.layoutAttributes.scattermode.values).toContain('group'); + expect(schema.traces.box.layoutAttributes.boxmode.values).toContain('group'); + for (const key of ['q1', 'median', 'q3', 'lowerfence', 'upperfence']) expect(schema.traces.box.attributes[key]).toBeDefined(); + for (const key of ['annotations', 'template', 'paper_bgcolor', 'plot_bgcolor']) expect(schema.layout.layoutAttributes[key]).toBeDefined(); + } finally { canvas.mockRestore(); } +}); diff --git a/src/app/shared/plotly/plotly-runtime.ts b/src/app/shared/plotly/plotly-runtime.ts new file mode 100644 index 0000000..4179389 --- /dev/null +++ b/src/app/shared/plotly/plotly-runtime.ts @@ -0,0 +1,20 @@ +import { InjectionToken } from '@angular/core'; +import { PlotlyFigure } from '../../features/indicadores/indicadores.models'; + +// Narrow boundary for the official partial bundle, which ships without declarations. +export interface PlotlyRuntime { + react(host: HTMLElement, data: PlotlyFigure['data'], layout: PlotlyFigure['layout'], config: Record): Promise; + purge(host: HTMLElement): void; + Plots: { resize(host: HTMLElement): Promise }; + addFrames(host: HTMLElement, frames: Record[]): Promise; + deleteFrames(host: HTMLElement, indices: number[]): Promise; +} +let runtime: Promise | undefined; +export function loadPlotly(): Promise { + return runtime ??= import('plotly.js-cartesian-dist-min') + .then(module => (module.default ?? module) as unknown as PlotlyRuntime) + .catch(error => { runtime = undefined; throw error; }); +} + +export const PLOTLY_LOADER = new InjectionToken<() => Promise>('PLOTLY_LOADER', { providedIn: 'root', factory: () => loadPlotly }); + diff --git a/src/app/shared/plotly/plotly.d.ts b/src/app/shared/plotly/plotly.d.ts new file mode 100644 index 0000000..4c7c94a --- /dev/null +++ b/src/app/shared/plotly/plotly.d.ts @@ -0,0 +1 @@ +declare module 'plotly.js-cartesian-dist-min'; diff --git a/src/index.html b/src/index.html index cc672be..ddc2e22 100644 --- a/src/index.html +++ b/src/index.html @@ -9,7 +9,7 @@ diff --git a/src/styles.scss b/src/styles.scss index f91119b..f1f256c 100644 --- a/src/styles.scss +++ b/src/styles.scss @@ -1,4 +1,5 @@ @use '@angular/material' as mat; +@use './theme-colors' as brand; :root { --color-primary: #a8c243; @@ -10,15 +11,48 @@ --color-step: #f0f3e8; --font-body: 'Roboto', sans-serif; --font-heading: 'Rajdhani', 'Roboto Condensed', 'Arial Narrow', sans-serif; + --site-header-height: 72px; + + /* Spacing scale on a 4px grid. Use these for padding, margins and gaps + instead of one-off px values. */ + --space-1: 4px; + --space-2: 8px; + --space-3: 12px; + --space-4: 16px; + --space-5: 20px; + --space-6: 24px; + --space-7: 32px; + --space-8: 48px; + --space-9: 64px; + + /* Aliases for the `--issste-*` tokens the vendored `features/indicadores` + module (fork `dev`) is written against, so it can be pulled in byte- + identical rather than rewritten against our own naming. */ + --issste-text: var(--color-text); + --issste-text-secondary: var(--color-text-secondary); + --issste-background: var(--color-background); + --issste-surface: var(--color-surface); + --issste-border: var(--color-border); + --issste-accent: var(--color-primary); + --issste-font-heading: var(--font-heading); + --issste-font-body: var(--font-body); + --issste-space-2: var(--space-2); + --issste-space-3: var(--space-3); + --issste-space-4: var(--space-4); + --issste-space-6: var(--space-6); + --issste-radius: var(--mat-sys-corner-medium); } html { height: 100%; @include mat.theme( ( + // Brand palettes from _theme-colors.scss (lime #a8c243, teal #5f9ea0). + // Material picks accessible tones from them, so filled buttons use the + // darker olive rather than the raw lime. color: ( - primary: mat.$azure-palette, - tertiary: mat.$blue-palette, + primary: brand.$primary-palette, + tertiary: brand.$tertiary-palette, ), typography: Roboto, density: 0, @@ -41,7 +75,36 @@ body { box-sizing: border-box; } -.information-upload-dialog-panel .mat-mdc-dialog-surface { - border-radius: 12px; - padding: 0; +@media (max-width: 600px) { + :root { + --site-header-height: 64px; + } } + +/* CDK drag previews are appended to , outside any component's styles. */ +.drag-preview { + align-items: center; + background: var(--mat-sys-surface); + border: 1px solid var(--mat-sys-primary); + border-radius: var(--mat-sys-corner-small); + box-shadow: var(--mat-sys-level3); + color: var(--mat-sys-on-surface); + display: inline-flex; + font: var(--mat-sys-label-large); + gap: 8px; + max-width: 320px; + padding: 8px 12px; + white-space: nowrap; + + mat-icon { + color: var(--mat-sys-primary); + font-size: 18px; + height: 18px; + width: 18px; + } +} + +.cdk-drag-animating { + transition: transform 200ms cubic-bezier(0, 0, 0.2, 1); +} +