Compare commits

..

268 Commits

Author SHA1 Message Date
alberto 29d021b347 Merge pull request 'Gobernanza: results of one EDF and its ADOS-2 report without storing them; EEG sentence in the TEA summary' (#29) from feature/tea-eeg-analysis into dev 2026-11-23 12:28:00 -06:00
ulises 98e9b60e83 Gobernanza: view the results of one EDF and its ADOS-2 report without storing them, with Guardar como PDF 2026-11-23 12:26:19 -06:00
ulises 5061350dd8 TEA summary: the EEG sentence gives the number of studies not acceptable for an analysis 2026-11-23 12:26:19 -06:00
alberto eb887be447 Merge pull request 'Gobernanza: TEA · EEG tab with the whole baseline flow' (#28) from feature/tea-eeg-analysis into dev 2026-11-23 09:38:35 -06:00
ulises 0b22b3c309 Gobernanza: TEA · EEG tab with cluster check, reference data, training, baselines, reports, promotion, run monitor, analysis and result 2026-11-23 09:31:38 -06:00
Roberto Treviño Cervantes 6ade415f63 Merge dev into the CaMa survival record change 2026-11-23 00:10:03 -06:00
angel 5791928976 Merge pull request 'CaMa: etiquetas, secciones y pies de figura (verificación contra dev y título de Análisis de riesgos)' (#27) from fix/cama-etiquetas-secciones-20261122 into dev
Reviewed-on: #27
2026-11-22 23:53:48 -06:00
angel f4d1829cd3 Merge branch 'dev' into fix/cama-etiquetas-secciones-20261122 2026-11-22 23:52:56 -06:00
Roberto Treviño Cervantes 069cc459a4 CaMa survival record: the adjusted Kaplan-Meier is optional 2026-11-22 23:46:57 -06:00
Angel Capetillo Zavala 881c613744 fix(cama): title the risk analysis panel Análisis de riesgos 2026-11-22 23:41:31 -06:00
Roberto Treviño Cervantes be46429627 Merge dev into the CaMa consolidation branch 2026-11-22 23:31:20 -06:00
edgar 25f584c864 Merge pull request 'CaCu patient record and indicators: risk by follow-up status, screening route reading note, history panels' (#26) from feature/cacu-ficha-riesgo-gobernanza into dev
Reviewed-on: #26
2026-11-22 23:26:15 -06:00
edgar 561a5dde36 Merge dev into the CaCu risk record branch
dev already names the history tab «Trazabilidad» for the three domains, so its version of those files stays. CaCu's
diagnosis-to-treatment time keeps one presentation, its card: it has no figure of its own next to the screening
route chart.
2026-11-22 23:17:21 -06:00
edgar bf89099ce8 Merge pull request 'fix(cacu): ajustar trazabilidad y figuras disponibles' (#24) from fix/cacu-etiquetas-secciones-20261122 into feature/cacu-ficha-riesgo-gobernanza
Reviewed-on: #24
2026-11-22 22:57:36 -06:00
Angel Capetillo Zavala ff1f6758ba fix(cacu): ajustar trazabilidad y figuras disponibles 2026-11-22 22:27:49 -06:00
alberto f38a2c6bb4 Merge pull request 'TEA indicators: Resumen and Trazabilidad tabs, round help, series chips, shared colours' (#23) from feature/tea-eeg-analysis into dev
Reviewed-on: #23
2026-11-22 22:13:11 -06:00
ulises 40c19a6a1f Merge the TEA labels and sections branch into the TEA indicators branch 2026-11-22 22:11:34 -06:00
ulises 329c0891ae TEA indicators: Resumen and Trazabilidad tabs, round help buttons, series chips, shared colours, summary box, three-per-row grid and three-significant-digit EEG values 2026-11-22 22:01:50 -06:00
ulises 34c6f2af3a TEA seguimiento: the ADOS-2 relation panel reads the association's rows 2026-11-22 21:43:11 -06:00
Roberto Treviño Cervantes 7ab2567dc9 CaMa survival: the patient's own scenario, a menu only when she is in several 2026-11-22 21:38:43 -06:00
edgar 14d6875d9b Screening route: the reading note, condensed, folds into «Cómo leer» 2026-11-22 19:48:41 -06:00
edgar f82ce8cc38 Patient record: probability columns by follow-up status
The risk table shows only what the patient's follow-up status follows, as the follow-up table does: a case, her
survival; before colposcopy, LIEAG+ and cancer; after colposcopy or treatment, LIEAG+. Without a status every
column stays.
2026-11-22 19:41:39 -06:00
edgar 61867ff973 Patient risk: survival is 1 at 0 years, at the index date 2026-11-22 18:40:34 -06:00
edgar 8bca0fbcdf CaCu indicators: «Progresión por grupo de riesgo» withdrawn from the clinical figures 2026-11-22 18:39:22 -06:00
Roberto Treviño Cervantes ec8542de9f Seguimiento in place of Análisis de riesgos 2026-11-22 18:10:48 -06:00
Roberto Treviño Cervantes 29c9e6853b CaMa recurrence: the patient's own scenarios, without a cohort menu 2026-11-22 18:04:57 -06:00
Angel Capetillo Zavala b1ff6cadb2 fix(cama): ajustar títulos y pies de trazabilidad 2026-11-22 17:21:15 -06:00
Angel Capetillo Zavala 26285a87fa fix(cacu): ajustar trazabilidad y figuras clínicas 2026-11-22 16:55:16 -06:00
edgar f058f1f476 Screening route chart: it follows the page's period filter, with no filter of its own
The chart takes the page's period type and shows the newest of the periods the filter applies that has published
boxes (the newest with data when the filter applies every period), so it moves with the other indicators. Its own
period selector is gone; the period shown is written over the chart.
2026-11-22 16:30:01 -06:00
edgar 7f1e43bdc5 CaCu indicators: no «Tiempo de tamizaje a diagnóstico» figures next to the screening route chart
The route chart draws every time from the sample to each event, the cytology's result and the diagnosis included, so
the separate time figures repeated it. They come back only when the chart isn't shown (the catalog lacks one of its
measures).
2026-11-22 16:26:55 -06:00
Roberto Treviño Cervantes 5bf6af8ecf Revert "CaMa patient card: the SEER model's survival by clinical scenario beside the production model's"
This reverts commit dd356efb6b.
2026-11-22 16:12:44 -06:00
Angel Capetillo Zavala 253290ed6a fix(tea): ajustar indicadores, trazabilidad y etiquetas de riesgo 2026-11-22 16:04:04 -06:00
edgar ec5b8fde6b CaCu treatment time cards: no provisional notice under the value 2026-11-22 15:54:54 -06:00
edgar 2a36397fac CaCu history: the CIN2+ risk-band panel draws its measure
`CACU-RIESGO-BANDA` is published, so its panel reads it like the others; it counts the patients of the confirmed risk
batches, and is empty until one is confirmed. No CaCu history panel stays reserved.
2026-11-22 15:39:42 -06:00
edgar eada50d2ff CaCu history: the diagnosis-to-treatment time panel draws its measure
`CACU-DIAS-DIAGNOSTICO-TRATAMIENTO` is published with reports, so its panel reads it like the other active ones
instead of showing "Trabajo en desarrollo". The catalog fixture gains the measure as the WebApi serves it.
2026-11-22 15:38:55 -06:00
edgar 396902541d CaCu history: the screening-to-treatment time panel draws its measure
`CACU-DIAS-TOMA-TRATAMIENTO` is published with reports, so its panel reads it like the other active ones instead of
showing "Trabajo en desarrollo". The catalog fixture gains the measure as the WebApi serves it, and the panel specs
count the active and reserved panels from their lists.
2026-11-22 15:38:12 -06:00
edgar 68b5e927e7 CaCu follow-up table: the latest biopsy, and the probabilities of the status filtered
A column with each patient's latest biopsy. The probability columns follow the follow-up status chosen, its
scenario's models: a case shows survival, pre-colposcopy LIEAG+ and cancer, post-colposcopy and post-treatment
LIEAG+, every patient none. A horizon selector, and an order by the most recent study or one of the columns shown,
which the API applies to the whole list.
2026-11-22 15:04:13 -06:00
edgar 990cab0e37 Patient risk: probabilities in percent, survival as such, covariates, and one row per model
The table says its probabilities are percentages (0 to 100 %) with their 95 % interval, and its covariates under it.
A model whose estimand asks for its complement (survival from a probability of dying) shows 1 − p with its interval
swapped. "Riesgo acumulado" reads "probabilidad". The models' details are a table of one row per model, without
the version or the batch state.
2026-11-22 15:04:13 -06:00
edgar 39e1e3e094 Merge pull request 'Patient risk record and governance: one column per outcome, the model's estimand, single risk-batch decisions' (#21) from feature/cacu-ficha-riesgo-gobernanza into dev
Reviewed-on: #21
2026-11-22 13:48:07 -06:00
edgar 4e08bb8c4b Risk batches: one decision at a time, so a double click doesn't send it twice
(cherry picked from commit 88c1eb33be)
2026-11-22 09:47:11 -06:00
edgar 686580af81 Patient risk: a column per outcome, the index visit's sentence, and the model's details folded
The record reads every RiskAssessment of the patient. CaCu's table always has the LIEAG+ and cancer columns, each
risk with its interval in parentheses; a column with no current model says "No disponible", and one whose model
didn't estimate her says so, with the reason under the table. Another outcome (a survival model's death) shows only
when she has its risk, with its own index date in its header. The models' details fold under the table, without the
interval's method; the collapsible curves draw one line per outcome with the index date on the x axis, under a
sentence that words the index cytology's results and each outcome's risk at the longest common horizon.

(cherry picked from commit 73b88de0ca)
2026-11-22 09:47:11 -06:00
edgar 60c71bfc3d Governance: a version lists only the routines its run recorded
Not every model has each of the five routines, and the registry doesn't require them; the dialog showed the missing
ones as failures. It now lists the recorded ones and says so when there are none.

(cherry picked from commit b5bff7e0c6)
2026-11-22 09:47:11 -06:00
edgar ad4edbe2a1 Patient risk: what the model's number is, and its curve with the interval
The record reads the RiskAssessment's `estimando` extension and shows the quantity, the outcome, the index date and
the interval's method, and names the table's columns with the quantity and the horizons' unit. Below the table, a
collapsible curve of the risk at each horizon, with its interval as a band (or as error bars when a horizon lacks
one); Plotly is loaded only when it's opened.

(cherry picked from commit 6039e6b741)
2026-11-22 09:47:11 -06:00
angel 1af0c21291 Merge pull request 'feat(indicadores): consolidar Histórico CaCu y ajustes TEA/CaCu/CaMa' (#20) from feature/197-integracion-historico-cacu into dev
Reviewed-on: #20
2026-11-22 09:34:04 -06:00
Roberto Treviño Cervantes dd356efb6b CaMa patient card: the SEER model's survival by clinical scenario beside the production model's 2026-11-22 09:22:15 -06:00
Roberto Treviño Cervantes 01271621b7 Merge feature/cama-survival into dev, keeping dev's CaMa patient card 2026-11-22 09:19:17 -06:00
ulises 4c181af291 CaMa patient card: the recurrence figure of the scenarios the patient meets, and a menu of both cohorts' scenarios
Shown only for patients after treatment, in the recurrence slot of "Pronóstico y recomendaciones". Includes the survival
figure this builds on.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 08:46:39 -06:00
Angel Capetillo Zavala b8bf57e235 feat(cacu): presentar KPI provisionales de tiempo a tratamiento
Adapta 245622b a las secciones de oportunidad del PR #20 y reutiliza el contrato C3r. Conserva la ruta y los paneles reservados del Histórico.
2026-11-22 05:53:59 -06:00
edgar 17cef51d90 Screening route: without a requested period, open on the newest one that has published boxes
A semester that has just begun has no events and the chart opened on it, empty, while earlier ones had data.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit a15e37ed77)
2026-11-22 05:40:50 -06:00
edgar 7692952ec9 Risk record: the evaluation instant reads as a day and minute in UTC
The index date is a calendar day and the evaluation time was the raw ISO instant, so the two looked inconsistent. The
instant now shows as 'YYYY-MM-DD HH:MM UTC' (the full value stays in the <time> element's datetime).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit ea2664f324)
2026-11-22 05:40:22 -06:00
edgar feaed5ff0e Indicators: a typed page size is brought into 1 to the maximum, one maximum for both lists
An input's max only flags the field and still lets a larger number be typed. The follow-up table and the tracking
list now clamp the value when it changes and when the query is sent, and both read the single PAGE_SIZE_MAX instead
of a literal 200.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 1342b1712d)
2026-11-22 05:37:25 -06:00
Angel Capetillo Zavala 999bc4ecf5 fix(indicadores): distinguish EEG findings and populations 2026-11-22 04:03:33 -06:00
Angel Capetillo Zavala 6ed87ff3d8 Fix CaMa Histórico order expectation in the f4c spec 2026-11-22 03:28:05 -06:00
Angel Capetillo Zavala ff4ad2c964 Análisis de riesgos: TEA and CaCu headings and the EEG status label 2026-11-22 03:21:09 -06:00
Angel Capetillo Zavala b5f8e5bfc2 Histórico: TEA order and EEG normal/abnormal lines, CaMa titles, order and captions 2026-11-22 03:18:19 -06:00
Angel Capetillo Zavala f04478e600 CaMa Indicadores: five time figures under «Tiempo de tamizaje a diagnóstico», requested clinical titles, order and confirmation rate 2026-11-22 03:11:12 -06:00
Angel Capetillo Zavala 6a0c3c9e92 Histórico CaCu: remove the notice above the panels 2026-11-22 02:49:46 -06:00
Angel Capetillo Zavala e3c9849e29 Port TEA and CaCu section 1 adjustments onto the Histórico integration
TEA: Indicadores tab, opportunity summary with real contract values, ordered
opportunity and clinical figures, «No aceptable» label for the EEG quality.
CaCu: renamed lab-result KPI, six time figures under «Tiempo de tamizaje a
diagnóstico», clinical figures with the pending «Progresión por grupo de riesgo».
CaCu's colposcopy and biopsy times use the measures the screening route
publishes and leave them to the route chart while it is shown.
2026-11-22 02:20:31 -06:00
Angel Capetillo Zavala 10773edcc1 Histórico CaCu: remove the simulation-only gate so the tab and its queries behave the same in every build 2026-11-22 02:11:29 -06:00
Angel Capetillo Zavala 8b80e1d26c Checkpoint: Histórico CaCu integration by Codex, before consolidating the TEA/CaCu section 1 work 2026-11-22 02:09:35 -06:00
edgar 2a48c28245 Merge pull request 'CaCu indicators: screening route chart, proportion intervals and survival notebook chooser' (#19) from integration/cacu-indicadores into dev
Reviewed-on: #19
2026-11-22 01:01:26 -06:00
edgar e1a8127c22 feat(indicadores): add the screening route chart to CaCu
Horizontal bars of the days from the sample to each event of the route (cytology result, colposcopy, biopsy result and
diagnosis), cumulative with the Q1 to Q3 interval or step by step with each step starting where the previous one ends.
It reads the seven duration measures of the route and shows up in CaCu's page once the catalog publishes all of them;
the measures only it draws get no card of their own.
2026-11-22 00:23:36 -06:00
edgar 6de193f44e fix(indicadores): draw CaCu's proportions in the history
The WebApi names the group of a proportion `principal`; the page read it as `total` only for CaMa, so the EU13 and
IND1 trends of CaCu came out empty. The rename now applies to every domain.
2026-11-22 00:23:33 -06:00
edgar 0059427179 fix(indicadores): read a proportion's interval as percentages
The ic-bajo and ic-alto of a proportion's score travel as proportions; the rows hold percentages, like the value,
so the history trend draws its confidence band on the same axis.
2026-11-22 00:23:28 -06:00
edgar 8192f92be9 Governance: choose a notebook kept in the code or upload one
The "Correr un notebook" dialog offers "Del código" (the domain's templates from /governance/notebook-templates, each
with the scenarios it can run for) or "Subir archivo". Choosing a template fills its scenario; a scenario it doesn't
serve keeps "Correr" disabled. The request sends the template's id and no file. A domain without templates opens on
the upload, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-22 00:23:28 -06:00
roberto 1fef7812b4 Merge pull request 'CaMa recurrence figure: the y axis follows the months it draws' (#17) from fix/cama-recurrence-axis into dev
Reviewed-on: #17
2026-11-21 15:37:58 -06:00
angel 6465165e34 CaMa recurrence figure: the y axis follows the months it draws 2026-11-21 15:36:00 -06:00
angel a26df55214 Merge pull request 'CaMa patient record: survival and recurrence figures; governance trains any scenario' (#16) from feature/cama-roundtrip into dev
Reviewed-on: #16
2026-11-21 15:03:15 -06:00
rockdrigo 72e5f9bf93 CaMa record: the recurrence analysis only for patients after treatment 2026-11-21 14:57:30 -06:00
rockdrigo 08f1d812ac CaMa patient record as specified: recurrence and survival analyses with a scenario selector and their risk factors 2026-11-21 14:43:46 -06:00
rockdrigo ce207a72a5 Merge origin/dev 2026-11-21 13:50:16 -06:00
rockdrigo 5094880622 CaMa patient record: the recurrence figures of the scenarios she meets 2026-11-21 13:34:56 -06:00
Angel Capetillo Zavala 093ceffa36 feat(indicadores): rename the Seguimiento tab to Análisis de riesgos in CaCu, TEA and CaMa
The tab has the same name in every domain, and the texts that point to it
(patient lists opened from the analysis, the patient file error) use it.
2026-11-21 13:27:15 -06:00
Angel Capetillo Zavala 6a7c1d0cbd feat(home): drop the topbar section label, shorten the eyebrow and rename the indicators action
The topbar no longer shows «Análisis de información» next to the logo; the
breadcrumb stays on the workspace routes. The home eyebrow reads «ISSSTELEON»
and the «Indicadores» action is «Modelos predictivos de riesgo».
2026-11-21 13:27:14 -06:00
rockdrigo fb5a4ed5cc CaMa patient record: the pipeline's figure of each clinical scenario she belongs to, without a curve of her own 2026-11-21 13:14:06 -06:00
rockdrigo e8ce7a487b CaMa patient record: no subgroup panel, one legend entry for the patient 2026-11-21 13:03:19 -06:00
angel a3a552ad0e Merge pull request 'Integration/tea eeg analysis into dev' (#15) from integration/tea-eeg-analysis-into-dev into dev
Reviewed-on: #15
2026-11-21 12:35:52 -06:00
Angel Capetillo Zavala fb54cfb188 Merge feature/tea-eeg-analysis into dev (TEA age norm and ADOS-2 relation) 2026-11-21 12:23:41 -06:00
rockdrigo 7adceb86bf CaMa patient record: the pipeline's survival figure with her curve, computed live and comparable with her subgroup 2026-11-21 12:07:21 -06:00
alberto 4e9b25bd8f feat(tea): read the age-norm curve, the age at the EEG and the ADOS-2 relation from the WebApi's FHIR answer 2026-11-21 11:17:59 -06:00
rockdrigo a7b5f4c50b CaMa patient survival figure: the legend claims an interval only when one is drawn 2026-11-21 10:53:41 -06:00
rockdrigo 4d159ae0d0 CaMa survival figure in the patient's risk evaluation instead of a tab; no test-data tags on the risk record 2026-11-21 10:13:47 -06:00
rockdrigo 4fba4fa861 CaMa development view reads each table's column order 2026-11-21 05:03:52 -06:00
rockdrigo db4d743413 Governance: spec for the risk batches panel's domains 2026-11-21 04:48:43 -06:00
rockdrigo d6c52c8536 Governance: risk batches of CaMa beside CaCu's 2026-11-21 04:24:19 -06:00
rockdrigo 1969ffdb5f Merge origin/dev 2026-11-21 04:00:07 -06:00
rockdrigo 699d4b13e1 Merge remote-tracking branch 'origin/feature/cohorts-dbt-canonical' into dev-mvp 2026-11-21 03:59:50 -06:00
rockdrigo c5cbaaab13 CaMa development view on the survival tab; governance trains any scenario in the background 2026-11-21 03:28:13 -06:00
rockdrigo cc802cbb57 The CaMa risk spec builds a summary with the clinical scenario 2026-11-21 03:00:10 -06:00
rockdrigo e7a6398168 Merge origin/feature/tea-eeg-analysis 2026-11-21 02:51:31 -06:00
rockdrigo 62027f2216 Merge origin/ulises/tea-seguimiento 2026-11-21 02:51:31 -06:00
rockdrigo 88dc7537c2 Merge origin/feature/163-cama-risk-curves 2026-11-21 02:51:31 -06:00
rockdrigo 0cb9395cd6 Merge feature/cama-roundtrip 2026-11-21 02:51:31 -06:00
rockdrigo e74e3d8fd4 CaMa: a patient's risk in her record and a Supervivencia tab with the model's curves
The risk table takes a domain (CaCu by default); the CaMa record shows the mortality at 6, 12 and 18 months from the
model's index date. The Supervivencia tab draws the cohort's Kaplan-Meier with its band, the adjusted curve, the fractional
Weibull and the model's survival with its bootstrap interval; its wording comes from the model's settings.
2026-11-21 02:07:34 -06:00
edgar 0fc80bd29a Merge remote-tracking branch 'origin/feature/163-cama-risk-curves' into feature/cohorts-dbt-canonical 2026-11-21 02:06:26 -06:00
rockdrigo dae8bc517e CaMa follow-up: the clinical scenario as Post-tratamiento or En observación in the list, the record and its PDF 2026-11-21 01:55:05 -06:00
alberto 68e2930e65 chore(tea): drop the local simulated-server mode; TEA follow-up reads only the WebApi 2026-11-21 01:30:45 -06:00
Angel Capetillo Zavala bb957ec6a4 fix(indicadores): format the hover text of CaCu's donuts per sector 2026-11-21 01:29:18 -06:00
Angel Capetillo Zavala 02e28e624b feat(indicadores): read CaCu category groups and stratified compositions from FHIR 2026-11-21 01:29:18 -06:00
Angel Capetillo Zavala 08161db1c4 feat(indicadores): map CaCu measures to the indicator ids the page reads 2026-11-21 01:27:59 -06:00
ulises fa029d69b8 Seguimiento TEA: gráfica de la norma por edad con el paciente
El panel de la derecha muestra el mapa de zonas o la norma por edad (bandas
5-95 y 25-75 %, mediana y el punto del paciente). Datos de ejemplo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:50:10 -06:00
ulises 67ae7f482f TEA: el panel de relación con el ADOS-2 muestra solo las zonas alteradas del paciente
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:50:10 -06:00
ulises 304c563845 TEA: panel «Relación con el ADOS-2» en la ficha del paciente (prototipo) y modo simulado local
El panel muestra, por cada asociación clara de la cohorte (modelo de OR), la zona del EEG con el z del
paciente, el aspecto del ADOS-2, el OR con su intervalo, la probabilidad para el paciente y lo observado.
El campo relacion_ados2 es opcional. El modo simulado (servidor de prueba en Python y configuración
«simulado» de Angular) es solo para trabajar en local.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:50:10 -06:00
ulises efe4404c4e Seguimiento TEA: gráfica de la norma por edad con el paciente
El panel de la derecha muestra el mapa de zonas o la norma por edad (bandas
5-95 y 25-75 %, mediana y el punto del paciente). Datos de ejemplo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:27:16 -06:00
edgar 7d180417d8 Merge dev into feature/cohorts-dbt-canonical
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:23:11 -06:00
edgar 00f773dd75 CaCu patient record reads the patient's FHIR RiskAssessment
The record asks GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id> and validates the searchset Bundle at the
boundary (simulado tag, the patient asked for, one index date, probabilities and intervals); it shows the model, the
risk's index date, the outcome, the evaluation and one row per horizon from each prediction's whenPeriod. The cohort's
definition and the PIMM variables are no longer shown; an empty Bundle is a patient without a confirmed risk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:11:56 -06:00
edgar 3bb1c8dd84 CaCu patient record shows the risk's index date
The record's index date is riesgo.fecha_indice (the model's decision point the horizons count from), not the cohort
member's; the field is optional in the contract and validated as an ISO date.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:02:48 -06:00
AlbertoPMDM ef4f606648 fix(tea): one card per EEG metric and the electrode map within its column
(cherry picked from commit b53322ed72)
2026-11-20 21:56:05 -06:00
ulises 54b3e50ca5 TEA: el panel de relación con el ADOS-2 muestra solo las zonas alteradas del paciente
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 20:35:24 -06:00
ulises 680cc0adc6 TEA: panel «Relación con el ADOS-2» en la ficha del paciente (prototipo) y modo simulado local
El panel muestra, por cada asociación clara de la cohorte (modelo de OR), la zona del EEG con el z del
paciente, el aspecto del ADOS-2, el OR con su intervalo, la probabilidad para el paciente y lo observado.
El campo relacion_ados2 es opcional. El modo simulado (servidor de prueba en Python y configuración
«simulado» de Angular) es solo para trabajar en local.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 20:06:15 -06:00
AlbertoPMDM b53322ed72 fix(tea): one card per EEG metric and the electrode map within its column 2026-11-20 19:52:10 -06:00
Manuel Aurrecoechea Castillo c32d2b6012 feat(indicadores): show full domain names and share CaMa's summary
CaCu and TEA use the same menu labels and compact summary layout as cáncer de mama.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 19:28:27 -06:00
rockdrigo 7aa3d2c6e6 Stratified bars: a sidebar to show or hide each stratum, and the breakdown in counts or in percent of each stratum 2026-11-20 17:03:41 -06:00
Angel Capetillo Zavala c2c6d9ef47 Merge feature/tea-eeg-analysis into dev (TEA candidate composition) 2026-11-20 14:44:48 -06:00
angel d4d3ea3837 Merge pull request 'Restore published CaMa histopathology and mammography counts' (#14) from fix/cama-reversion-selectiva into dev 2026-11-20 10:03:41 -06:00
Angel Capetillo Zavala 3385df4ba3 Merge current WebApp dev into the CaMa selective rollback 2026-11-20 09:57:32 -06:00
Manuel Aurrecoechea Castillo 96b1cabb5a feat(cama): space the opportunity strip, share its period and unify history lines
The section sat flush against its cards, each card repeated the period, the history selector was taller than the summary, and each CaMa line used a different color.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 09:49:32 -06:00
Angel Capetillo Zavala 366591f247 fix(cama): restore published histopathology and mammography counts 2026-11-20 09:07:38 -06:00
angel 241631b884 Merge pull request 'Finalize CaMa wording, demo mammography counts and histologic classification' (#13) from feature/cama-clasificacion-histologica into dev 2026-11-20 00:52:29 -06:00
Angel Capetillo Zavala 6c063344a3 feat(cama): adjust summary wording, double mastography counts and classify histologic types
Reword the histopathologic confirmation note, the BI-RADS 4, 5 or 6 titles and the
radiologic interpretation time title. Show twice the BI-RADS 4, 5 or 6 mastography
counts in the FHIR and base data services. Add the histologic type classification
and a follow-up table column that appears only when a row carries tipo_histologico.
2026-11-20 00:32:27 -06:00
angel 2f5b1ce1f2 Merge pull request 'Feature/cama audit histopathology demo' (#12) from feature/cama-audit-histopathology-demo into dev
Reviewed-on: #12
2026-11-19 19:45:53 -06:00
Angel Capetillo Zavala 56b3ac6b0c feat(cama): add synthetic histopathology breakdown for demo 2026-11-19 19:36:18 -06:00
Angel Capetillo Zavala f6603ae76e fix(cama): align BI-RADS labels and remove historical detection chart 2026-11-19 19:04:22 -06:00
Manuel Aurrecoechea Castillo 21ae95b5ed 20261119 CaMa: ayuda en cada dona de BI-RADS
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 18:11:20 -06:00
Manuel Aurrecoechea Castillo ce2e86c045 20261119 CaMa: cada dona de BI-RADS lleva su título y la categoría más alta
El resumen ya no repite el porcentaje publicado; pacientes y mastografías se leen en su propia gráfica.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 18:05:40 -06:00
angel 0f8eb0ec94 Merge pull request 'Add unavailable CaMa diagnosis-to-treatment card' (#11) from feature/cama-diagnosis-to-treatment-card into dev 2026-11-19 17:51:43 -06:00
Angel Capetillo Zavala 2f6d419453 Add unavailable CaMa diagnosis-to-treatment card 2026-11-19 17:48:13 -06:00
Manuel Aurrecoechea Castillo f34f9e1607 20261119 favico 2026-11-19 17:17:45 -06:00
Manuel Aurrecoechea Castillo c7dd134fce 20261119 CaMa titulos ayuda filtros
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 17:13:07 -06:00
Manuel Aurrecoechea Castillo 03cc9c9800 20261119 CaMa: donas de BI-RADS y etiquetas del resumen
La oportunidad dice confirmación histopatológica, la tarjeta de mastografías muestra dos donas y Cómo leer puede reintentar los metadatos.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 15:50:01 -06:00
AlbertoPMDM 04795a09cc feat(tea): read the EEG analysis's verdict, quality checks and age baselines 2026-11-19 15:43:27 -06:00
Manuel Aurrecoechea Castillo de3d247d0d 20261119 Favicon colores textos 2026-11-19 15:10:59 -06:00
Angel Capetillo Zavala ee87bcb8d0 test(webapp): seed the visual login session in indicadores specs
The indicadores navigation, sections and cancer-journey specs routed through
the real routes without a session, so authGuard redirected to LoginPage.
Add auth.testing helpers that seed and clear the sessionStorage session, use
them in those specs, and add a spec that /indicadores/<dominio> without a
session presents LoginPage with returnUrl.
2026-11-19 11:33:26 -06:00
Erick ivan aaeea7a7b0 refactor(auth): keep the session in the browser
The WebApi no longer authenticates, so the login validates against the accounts in auth.service.ts and the session lives in sessionStorage. The guard, the domain guard and the filtering of the import workspace and governance stay as they were; the interceptor and the /auth proxy entries go away because nothing answers 401.
2026-11-19 10:32:25 -06:00
Erick ivan 7f17681409 feat(auth): login screen and domain-scoped navigation
Session login against /auth/*, with a guard on every route and an interceptor that returns to the login on 401. The header, the import workspace and both governance panels only offer the account's own domains (auth/dominios.ts), and a batch opens on the account's database.

The sign-in screen follows the app's palette: logo above the title, the action button in the shared tokens, and no register or password-recovery rows.
2026-11-19 09:36:54 -06:00
angel d72c18756f Merge pull request 'test(indicadores): follow the published CAM-03 title and the Análisis tab' (#10) from fix/ci-spec-contracts into dev
Reviewed-on: #10
2026-11-19 00:09:54 -06:00
Angel Capetillo Zavala baf5edca42 test(indicadores): follow the published CAM-03 title and the Análisis tab
The history names CAM-03 «Resultado histopatológico»; the CAM-03 expectation in the F4C spec
now uses that title.

The CaMa page does not offer the Análisis tab while CAMA_ANALYSIS_ENABLED is off. The journey
specs that open it run only while the flag is on and are reported as skipped otherwise. The
domain-change spec selects patients through the page instead of through that tab, so it keeps
checking that the selection is cleared and that CaCu and TEA keep their sections.
2026-11-18 23:41:41 -06:00
Manuel Aurrecoechea Castillo fefa28ae7a 20261118 Pastilla Fix 2026-11-18 16:53:56 -06:00
Manuel Aurrecoechea Castillo a217ddae38 20261118 Color Fix 2026-11-18 16:10:11 -06:00
Manuel Aurrecoechea Castillo 97fcb37761 20261118 Sharts Colors 2026-11-18 15:43:23 -06:00
Manuel Aurrecoechea Castillo 58ff3870be 20261118 colorfix front
Cambio de los colores de las graficas para tener una mejor armonía de colores y evitar el uso de la unión de colores que interpreten ideas falsas
2026-11-18 15:16:13 -06:00
Angel Capetillo Zavala 439a039ff4 fix(cama): recuperar el tamaño responsivo de la dona BI-RADS 2026-11-18 14:58:54 -06:00
Angel Capetillo Zavala 049a9ca43c fix(cama): ocultar temporalmente la pestaña Análisis 2026-11-18 14:15:49 -06:00
Angel Capetillo Zavala f128f2e13a fix(cama): mostrar solo el conteo al pasar sobre la dona 2026-11-18 13:15:54 -06:00
Angel Capetillo Zavala 20b8c80aaf fix(cama): equilibrar centro y anillo de la dona 2026-11-18 12:56:27 -06:00
Angel Capetillo Zavala 8e85c91f15 fix(cama): completar ajustes visuales de indicadores 2026-11-18 12:23:17 -06:00
Angel Capetillo Zavala 1ac8d5c258 fix(cama): ajustar resumen y ocultar análisis 2026-11-18 09:25:38 -06:00
Angel Capetillo Zavala 23cd89e882 Adjust CaMa indicator labels 2026-11-17 12:44:25 -06:00
Angel Capetillo Zavala 47a0ab5f1b Connect CaMa dashboard to follow-up, analysis and L3 FHIR measures
Preserve dev governance and risk-batch UI. Validate cohort navigation, API contracts and shared summary/history measures. Production build passes; 1785 tests pass with the six known Node 26 localStorage failures.
2026-11-17 10:44:08 -06:00
Roberto Treviño Cervantes dc37c54938 wording fixes 2026-11-17 02:17:24 -06:00
roberto 2834fac85c Merge pull request 'Kit exit: TEA over FHIR, dashboard-test presentation merged in' (#9) from feature/kit-exit-integration into dev
Reviewed-on: #9
2026-11-16 21:09:07 -06:00
Roberto Treviño Cervantes be77c50b45 Merge dashboard-test: the CaMa dashboard's presentation over the FHIR measures, with TEA's history and summary kept 2026-11-15 05:37:15 -06:00
Roberto Treviño Cervantes 40d8c8655e Merge remote-tracking branch 'origin/feature/163-tea-redesign' into feature/kit-exit-integration 2026-11-15 00:43:27 -06:00
Angel Capetillo Zavala 7580319fc8 fix(cama): single vertical scroll in Análisis epidemiológico
The visually-hidden labels are absolutely positioned and had no positioned ancestor in the view, so they were laid out against the document and, with the table far down the page, gave the document its own vertical scroll next to the one of the page container. The view is now their containing block.
2026-11-14 07:56:33 -06:00
Angel Capetillo Zavala 7a2f0f42a9 feat(cama): Análisis epidemiológico frame with category cards, cut-off bar and the BI-RADS count 2026-11-14 00:14:53 -06:00
alberto 4ffd3797b6 Indicators: the history chart and the KPI card read the total when a measure publishes more groups 2026-11-13 21:15:47 -06:00
alberto b42428b068 TEA: the EEG result measure draws one bar per alteration 2026-11-13 19:38:36 -06:00
Angel Capetillo Zavala 01d6e71f07 Accept 64-bit patient identifiers 2026-11-13 18:23:45 -06:00
Angel Capetillo Zavala 3b246b4f1f Identify follow-up patients by pac_id
Rows name their patient with pac_id (a decimal string) or the legacy
id_seudonimo. pac_id wins; an invalid pac_id is never replaced by the
legacy field, and a page that repeats a patient or mixes both fields is
not drawn or exported. The table, patient record, PDF and spreadsheet
follow the announced identifier column and label. CaCu requests risk
only with a pac_id.
2026-11-13 18:19:27 -06:00
Angel Capetillo Zavala caf5f954b7 Proxy patient routes without the cohort access token 2026-11-13 18:19:26 -06:00
edgar edb868f372 Patient record reads its risk from GET /cacu/pacientes/<pac_id>/riesgo, by the id the follow-up list shows 2026-11-13 17:29:54 -06:00
rockdrigo d9009a2e1e Indicators read the WebApi's FHIR endpoint; TEA follow-up, period summary and patient views, history and highlight figures; side navigation removed 2026-11-13 17:03:23 -06:00
Angel Capetillo Zavala 2e0938628c Merge commit '0acee49de2098b2f9d06607f7d374091a5f4b764' into dashboard-test
# Conflicts:
#	src/app/features/indicadores/etiquetas-cohorte.ts
#	src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts
2026-11-13 15:45:55 -06:00
Angel Capetillo Zavala 3783505dbd Use the regular window for breast follow-up 2026-11-13 15:44:01 -06:00
Angel Capetillo Zavala 0acee49de2 fix(cama): regular follow-up opens on the 3-month window and adopts the cohort the server returns
The follow-up list asks for the regular window without quoting a revision; when the answer
names a cohort the next pages and the files quote it. A new cut-off or a revision that changed
under the list is asked for again without the old revision (once, then reported). Leaving the
analysis' selection returns to the regular window. A server that does not answer from the cohort
keeps the plain list.

Histopathology codes are written with the catalog labels (Benigno, Carcinoma in situ, Carcinoma
invasor, Desconocido); other values stay as they arrive.
2026-11-13 15:43:02 -06:00
Angel Capetillo Zavala 18e9260705 Keep breast follow-up on the selected cohort 2026-11-13 15:32:39 -06:00
Angel Capetillo Zavala 3f4cf2217f Merge commit '7971a49dcda5f9759f6cf4693c1c725153172edb' into dashboard-test 2026-11-13 15:23:06 -06:00
edgar bb2f49be37 Measures read from /<domain>/indicadores 2026-11-13 15:19:01 -06:00
edgar b68af3a48a KPIs page draws durations as boxes and reads a composition's categories from its first stratifier 2026-11-13 15:19:00 -06:00
edgar 7eb144e8fe KPIs page drawing CaCu's measures from the WebApi's FHIR MeasureReport bundles 2026-11-13 15:19:00 -06:00
Angel Capetillo Zavala 7971a49dcd feat(cama): regular follow-up read from the cohort, with the revision refreshed on a new cut-off
The follow-up tab of breast cancer now reads the cohort the analysis publishes: it asks for the
cohort's revision at today's cut-off and lists the whole cohort quoting it. Where the server does
not publish the cohort (404 or 503 on its aggregate) the plain follow-up list is read.

- Another cut-off in the form asks for that cut-off's revision before the list; a revision that
  changes under the list (409) is asked for again once and the same query repeated, and a conflict
  that persists is reported.
- "Quitar selección" returns to the whole cohort instead of another source.
- An empty whole cohort says "Sin pacientes para el corte seleccionado"; filters and windows keep
  the text of the filters.
- Filters, cut-off, page and rows are kept while a record is opened and closed.
- Page specs that open CaMa follow-up answer the aggregate first.
2026-11-13 15:18:11 -06:00
Angel Capetillo Zavala c06cce20df Pass synthetic cohort access through the server proxy 2026-11-13 15:17:14 -06:00
Angel Capetillo Zavala 2b0f6dfbed feat(cama): readable BI-RADS and age labels, the biopsy report date, and no export of a list that does not match its group
Contract review against WebApi 1d5f1e0 (webapi/cama_analysis.py, cama_cohort.py, docs/cama-cohort-api.md).

- The cohort's list is rewritten once on arrival so the table, the record and the PDF/XLSX show
  "BI-RADS 5" and "50 a 59 años" (also "Menores de 40 años", "70 años o más", "Sin dato"); the codes
  stay in `<clave>_codigo` and in the filter options, which are what the requests send. Only codes
  whose meaning the API's own code confirms are labelled; biopsy grades are left as they arrive.
- The record calls the biopsy date what the list calls it ("Fecha de reporte"): in the cohort it is
  the date of the biopsy report, which can be known while its result is not.
- With the same cohort revision, cut-off and filter the aggregate and the list are counted from the
  same rows, so a different total breaks the contract: the list shows an alert and its PDF/XLSX
  buttons are disabled.
- When no category is published the analysis says so and keeps "No publicado": the answer cannot
  tell an empty cohort from categories under the threshold.
- Tests: the chosen cut-off reaches the aggregate, the list, the record and every page of the file.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 14:29:45 -06:00
Angel Capetillo Zavala c509cb7f87 Connect TEA screening views to FHIR 2026-11-13 14:28:04 -06:00
Angel Capetillo Zavala 5807f218b1 Add TEA status measure view 2026-11-13 14:28:04 -06:00
Angel Capetillo Zavala 1d43ebff3b feat(indicadores): Análisis epidemiológico tab for breast cancer, and the way back from Seguimiento
A CaMa-only tab between Histórico and Seguimiento shows how many patients of the cohort fall in
each BI-RADS category at a cut-off (GET /cama/analisis/indicadores?corte=), as the cohort API
publishes it. It is a descriptive count, not an incidence or a survival estimate.

- Loading, pending (404), unavailable (503), error and out-of-contract states; the answer is
  validated as an aggregate (no patient rows, nothing published under the threshold).
- A suppressed category is drawn grey and says why; only a published category opens its patients
  in Seguimiento ("Ver pacientes" or a click on its bar).
- The page keeps the selection while the user moves between tabs, clears it on a domain change, and
  "Volver al análisis" returns to the analysis as it was, with the scroll and the focus on the
  control that opened the list, and no new request.
- Tables and figure scroll inside their own region at phone width. CaCu and TEA keep their three
  sections. Curves, the heatmap and the cohort diagnostics of the prototype wait for an API.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 14:07:34 -06:00
Angel Capetillo Zavala eb92b99a1d feat(seguimiento): list opened on a group of the cohort, with its window, cut-off, cohort and revision
The follow-up list of breast cancer can now be opened on a selection that the analysis names: the
whole cohort (window 0, offered only while the selection is active), the cut-off the analysis was
computed at, the group's filter, and the cohort with its revision, which the server requires and
repeats.

- A cohort's list quotes `cohorte`, `escenario` and `revision` (not filters) on every page and in the
  export; an answer that loses a filter, changes the window or the cut-off, or is another cohort or
  revision is not drawn and cannot be exported.
- A new selection cancels the previous request; while it loads, and when it fails (403, 409, 503),
  no list of the previous query stays on screen.
- Inside the cohort the form refines the same cohort and says so; "Quitar selección" leaves it.
- "Volver al análisis" and a note when the list holds a different number of patients than the
  analysis counted.
- PDF and XLSX state the selection, the cut-off and "Toda la cohorte"; the file name tells a
  selection apart; an export in progress is cancelled, and a finished one discarded, when the query
  on screen changes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 14:07:31 -06:00
Roberto Treviño Cervantes 4d67b019a6 updating nlp policies; more robust recognition beyond rules 2026-11-13 11:52:42 -06:00
Roberto Treviño Cervantes 934a793da3 fix governance reqs; allow for sandboxed jupyter notebooks for testing 2026-11-13 11:52:42 -06:00
Roberto Treviño Cervantes e6abf44bef improve ingestion system to match isssteleon setup 2026-11-13 11:52:42 -06:00
Angel Capetillo Zavala ee75e7a2a0 Chore: Visual fix. 2026-11-13 00:01:18 -06:00
Angel Capetillo Zavala b84d428814 Add breast cancer follow-up reports and patient record 2026-11-12 22:40:21 -06:00
Angel Capetillo Zavala 17a91d3924 style(indicadores): CaMa header, simplified general filters and collapsible suppressed-data notes
CaMa header reads "Sistema TNM de clasificación tumoral" without the top subtitle.
The general filters block is titled "Filtros generales" and drops the scope
description and the applied-filter summary. In the Histórico the suppressed-data
text becomes a collapsed footnote (details/summary) with the same full text.
CaCu and TEA headers and filters are unchanged.
2026-11-12 13:20:04 -06:00
Angel Capetillo Zavala cda3563184 Verify follow-up against final API responses 2026-11-12 11:57:48 -06:00
Angel Capetillo Zavala 7a6f87d141 Remove demonstration notices from CaMa views 2026-11-12 11:57:47 -06:00
Angel Capetillo Zavala 78313adb4a style(indicadores): CaMa histopathology rates stay readable at phone width
The rates figure lets the category labels size their own margin, shortens the
axis title, keeps few ticks and wraps «BI-RADS 4 sin subtipo» when the window is
600 px wide or less, and is redrawn when the window crosses that width. Values
and states are unchanged. The reading text keeps the capitals of a category
code inside a sentence («lesión de riesgo (B3)»).
2026-11-12 11:35:27 -06:00
Angel Capetillo Zavala 7dc420773f feat(indicadores): CaMa detection and result-to-diagnosis indicators wired with real payloads
CAM-01 and CAM-02 already had their KPI cards and history panels waiting for the
catalog; they are now covered with the answers WebApi gives for the synthetic
base, both visible (lowered suppression threshold) and suppressed (normal
threshold). Once published they draw only their KPI card in the summary, as the
mockup does, instead of an extra generic figure card; their evolution stays in
the history.

The stacked history figure now keeps a category the catalog announces even when
no row carries it, so a missing category is named under the figure instead of
silently disappearing. The integration specs also cover the summary and the
history with CAM-01, CAM-02 and CAM-03 published.
2026-11-12 11:35:27 -06:00
Angel Capetillo Zavala 552e2c194f feat(indicadores): CaMa histopathology by BI-RADS drawn from the published matrix
The card for cama_histopatologia_birads now shows rates with their Wilson
interval per BI-RADS category and a two-ring donut of the biopsy result, with
group and category selection, period navigation and the published values table.
A pure adapter turns the stratified C2 response into rows and figures; the view
only asks for the data and draws what the adapter returns.

BI-RADS 4 is a row of its own. The denominator is benign, B3, in situ and
invasive; no biopsy and no data are reported apart. A published zero is a zero,
a suppressed cell is suppressed, and a cell or stratum the response does not
carry is unavailable, never zero: no rate or donut total is drawn over an
incomplete matrix. The card keeps its place first in the summary and stays
pending while the catalog does not publish the indicator.

The `birads` stratum is added to the accepted dimensions of the data request.
The CaCu cytology confirmation view is not touched.
2026-11-12 11:35:27 -06:00
Angel Capetillo Zavala 8f01f8693d feat(indicadores): CaMa follow-up tab drawn from the announced filters and columns
The tab asks GET /cama/seguimiento when it is first opened and draws the form,
the table, the details and the pagination from what the answer announces, so a
later change of source behind the endpoint needs no change here. It shows the
demonstration notice when the answer is simulated, a clear pending state while
the endpoint is not published (404 on the first page), and error, empty and
retry states. Stale requests are cancelled.

The sections, CaCu and initial-integration specs now expect the CaMa request
when the tab opens.
2026-11-12 11:35:27 -06:00
Angel Capetillo Zavala ad8444a788 feat(indicadores): generic follow-up client with a strict response contract
GET /<dominio>/seguimiento with the window, page, size, cut-off date and the filters the list announces. Filters and columns come with the answer; only demonstration answers (simulado: true) are accepted and anything outside the contract is rejected before it reaches a view. The fixture is the synthetic answer of the reference prototype and is used by tests only.
2026-11-12 11:35:27 -06:00
Angel Capetillo Zavala f78db1ae37 feat(indicadores): CaMa KPI cards show only their own line, as in the reference
The kit's notes are no longer appended to CaMa's opportunity cards (they stay in the figure footers, Histórico and Datos y definiciones). The four cards measure 308 x 220 px at 1366 px, like the reference. TEA keeps its notes and CaCu already hid them.
2026-11-12 11:35:27 -06:00
Angel Capetillo Zavala 0914b8db23 feat(indicadores): CaMa summary keeps the paired card and a pending histopathology card
Confirmation, screening-to-diagnosis and exam-to-result cards leave the summary (they stay in Histórico and Datos y definiciones). The histopathological result by BI-RADS keeps its place and structure as a pending card, with no figure or number, until the catalog publishes its indicator. The patients KPI uses the reference's wording.
2026-11-12 11:35:26 -06:00
Angel Capetillo Zavala 8aa66c6277 style(indicadores): CaMa's filter block as one compact row, as in the reference
Fields and Aplicar at 40 px, tighter padding and a small description. Only the CaMa block changes; CaCu and TEA keep their filters.
2026-11-12 11:35:26 -06:00
Angel Capetillo Zavala 1e1999f264 style(indicadores): Roboto headings, 4 px corners and the reference's title and card sizes, scoped to the indicators pages
Tokens are set on body when the indicators header is present, so menus, selects and dialogs share them; the other routes keep Rajdhani and their shapes.

(cherry picked from commit f5103b483d9d7188b4feffe91beda38d997004d4)
2026-11-12 01:43:27 -06:00
Angel Capetillo Zavala e95c175f9b fix(shell): load the domain menu deferred and let the header wrap on narrow screens
The menu and its overlay were in the initial bundle of every route (+183 kB); they now load in their own chunk, with a same-size placeholder. On phones the title moves to a second row instead of being squeezed beside the selector.

(cherry picked from commit 2ccddf80dbbe41a328281fcdc1c95ebe421f4191)
2026-11-12 01:43:27 -06:00
Angel Capetillo Zavala ff03a88ea0 feat(indicadores): domain navigation moves to the header; searchVisible reads the catalog before the domain
The in-page domain buttons are removed, since the header selector replaces them. Also fixes a computed that, after a visit to CaMa, never became true again, so CaCu and TEA lost their search box when switched to from CaMa.

(cherry picked from commit 3678c3653b33fcb98ba2334ca8f03f838dc86440)
2026-11-12 01:43:27 -06:00
Angel Capetillo Zavala d761a6fb1a feat(shell): indicators header with the platform title and a domain selector
On /indicadores/<dominio> the header shows «Plataforma de Indicadores» and a menu button with the current domain (TEA, CaCu, Cáncer de mama) that links to the other two through the router. Institutional routes keep their breadcrumb header.

(cherry picked from commit 79a18fd7a8ed1a3a58201e7cc24c9692b53dbc47)
2026-11-12 01:43:27 -06:00
Angel Capetillo Zavala 2982d482bf feat(indicadores): CaMa history tab with the charts the published contracts support
A Histórico tab between Resumen and Seguimiento, for CaMa only: monthly or semestral interval, how many periods to show, and a custom period dialog. Counts are stacked, rates draw their confidence band and medians their quartile band; suppressed periods are shaded and listed, and a rate over no denominator or a median over no observations is no value. Five charts use published indicators; the three whose indicator the catalog does not publish are drawn as pending panels.

(cherry picked from commit 268d7443e0a89da8d6bc67ecb2b5db2715236f93)
2026-11-12 01:43:26 -06:00
Roberto Treviño Cervantes 0ee53fd286 Remember SQL connections in the browser, never the password 2026-11-12 01:13:34 -06:00
Angel Capetillo Zavala 5e16f5454b fix(indicadores): reconcile CaMa period selection and contracts 2026-11-12 00:39:57 -06:00
Angel Capetillo Zavala ce3ed34fbf feat(indicadores): CaMa paired card of mammograms and patients by BI-RADS
One card draws the exams by category as a donut and, per BI-RADS family, the patients next to the exams. Patients come from cama_birads_456_paciente (each patient once per period, in the category of the most severe exam), so its exclusive categories are added within that indicator only, for the verified version 0.2.0; other versions, suppressed or missing cells leave the figure unknown. No exams-per-patient ratio is computed and patients are never derived from exams. The patients' indicator has no card of its own while the exams' one is published.

(cherry picked from commit b7bafd178896cb2715049d5c8293185f31391c92)
2026-11-12 00:29:14 -06:00
Angel Capetillo Zavala d159067efd feat(indicadores): CaMa clinical section heading and counter, without search, pins, navigation or representation selector
CaMa's graphic section reads «Indicadores clínicos» and counts the indicators it draws. The search box, pins, floating navigation, representation selector and figure count are not drawn for CaMa; CaCu and TEA keep them.

(cherry picked from commit e54ee5a55aa3722f6895300fa7e8cefb28f12ebb)
2026-11-12 00:29:14 -06:00
Angel Capetillo Zavala 7b8fd9e01d feat(indicadores): CaMa labels, single-period filters and the four-card strip
CaMa reads «cáncer de mama» everywhere on the indicators page and uses the compact filter: interval, one period and Aplicar on one row, without the mode selector, the multiple selection or the editing summaries. The opportunity strip is the four cards only, and the biopsy distribution card is no longer drawn in the summary (it stays in Datos y definiciones). Other domains keep their filter and strip.

(cherry picked from commit 7c9dcf634e5870fec35ab96347b0863b2e3bb86e)
2026-11-12 00:29:08 -06:00
Angel Capetillo Zavala 8a3f68df6b fix(indicadores): guard invalid C1 denominators and preserve status 2026-11-11 23:56:32 -06:00
Angel Capetillo Zavala bc75c058e1 feat(indicadores): CaMa's four opportunity cards, pending where the catalog lacks the indicator
Cards: patients with BI-RADS 4, 5 and 6, histopathological detection rate, screening to result and result to diagnosis times. The detection rate and the result-to-diagnosis time are not published by the catalog yet, so they are drawn as explicit pending cards and are queried once the catalog lists them. cama_eu38a is added to the CaMa KPIs.
2026-11-11 23:56:32 -06:00
edgar 62cdb252ca Measures read from /<domain>/indicadores 2026-11-08 01:37:43 -06:00
edgar 8f2906fe6f KPIs page draws durations as boxes and reads a composition's categories from its first stratifier 2026-11-08 01:16:04 -06:00
edgar e8628508d8 KPIs page drawing CaCu's measures from the WebApi's FHIR MeasureReport bundles 2026-11-08 00:33:01 -06:00
edgar 53edec8692 feat(tea): periodos personalizados en Histórico
«Personalizado…» en «Periodos a mostrar» abre un diálogo con los periodos del
intervalo elegido, por año. Las figuras muestran solo los elegidos, sin volver
a consultar, y cada intervalo recuerda su propia selección.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 15:21:18 -06:00
edgar a1ea31039e feat(tea): abrir las alteraciones del EEG con un mapa visible
Al desplegar un paciente se abre su primera alteración, o la primera métrica
si no tiene alteraciones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 13:46:26 -06:00
edgar ef631e2c0b feat(tea): cambios de la reunión del 5 de noviembre
Resumen
- Estado del caso (completo, en proceso, fuera del protocolo) al cierre del
  periodo, en una figura y en el párrafo, separado de diagnóstico confirmado.
- Tiempos por paso: M-CHAT a ADOS-2, ADOS-2 a diagnóstico y total.
- Un solo formato: barras. M24 son barras apiladas por grupo de edad.
- «Descargar reporte» abre la impresión con el periodo y los indicadores
  seleccionados.

Histórico
- Porcentaje de casos en proceso, tiempos por paso en la misma escala y
  calidad de los EEG (indicador solo de esta pestaña, con `vistas`).
- Ejes con unidades y fechas como «mar 2025».

Seguimiento
- Columna y filtro de estado del caso, con lo que falta.
- Filtro por tipo de alteración y resumen de EEG que sigue los filtros.
- Módulo de ADOS-2 junto al puntaje.
- Tarjetas de alteraciones: al elegir una se apartan y aparece su mapa, sin
  caja, con leyenda de colores. Referencia por grupo de edad.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 13:38:53 -06:00
edgar 27dc7a0166 feat(tea): calidad del EEG con criterios de PREP y calificación general
- La calificación general es una palabra (Bueno, Aceptable o Malo), como en
  Automagic, y es la peor de sus criterios.
- Los criterios son lo que busca PREP, con números: canales afectados de 19 y
  ruido de línea en dB.
- Se quitan impedancia, artefactos, canales rechazados, segmentos útiles y el
  puntaje de 100.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 12:46:01 -06:00
edgar e6353f9f4c test(tea): nuevas alteraciones del EEG en el resumen del paciente
Ritmo posterior, husos de sueño N2 y N3, picos paroxísticos y gradiente
anteroposterior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 11:55:07 -06:00
edgar 3bb9c2121d feat(tea): botones y rótulos en la dona C2 de un solo anillo
Sin grupos de categorías (M23), la dona de TEA se dibuja como la de M21: un
anillo con rótulos, el total al centro y un botón por categoría.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:56:54 -06:00
edgar 737c6f9f14 feat(tea): redactar el resumen según los pacientes de M23
M23 ya no cuenta los diagnósticos descartados: el párrafo dice ahora «evaluados
por psicología [...] diagnóstico confirmado o en proceso».

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:48:19 -06:00
edgar 8e543cbcc6 feat(tea): filtros de edad, M-CHAT y ADOS-2 en Seguimiento
- Filtros por grupo de edad, rango de riesgo M-CHAT-R/F y nivel de CSS ADOS-2.
  Se envían a la API como grupo_edad, mchat_min/max y css_min/max.
- Se quita «Ordenar por prioridad», también de CaCu, donde estaba deshabilitado.
- El grupo de edad menor pasa a 16-23 meses, igual que en los indicadores.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:06:37 -06:00
edgar ea7aad5067 test(tea): husos del sueño por etapa N2 y N3 en el resumen del paciente
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:56:25 -06:00
edgar 09b52e6b0a feat(tea): pestaña Histórico, colores por edad en EEG y acordeón en Seguimiento
- Evolución pasa a llamarse Histórico y añade «Periodos a mostrar»: los
  últimos 5, 10, 15... meses o semestres, según el intervalo elegido.
- M21 y M22 usan un color por grupo de edad, sin verde ni rojo, también en
  sus líneas de Histórico.
- Se quita el selector «Representación gráfica».
- Todas las filas de Seguimiento de TEA se despliegan en su lugar; se quita
  la ventana propia de los pacientes impares.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:41:05 -06:00
edgar 078db53ae4 feat(tea): pestaña Evolución y paleta con el verde de ISSSTELEON
- Pestaña Evolución (solo TEA), entre Resumen y Seguimiento: una figura por
  indicador con todos los periodos publicados, mensual o semestral. Barras
  apiladas para C2, línea con intervalo de confianza para C1 y mediana con
  cuartiles para C3r. Los periodos suprimidos se sombrean, no se dibujan
  como cero.
- Paleta: verde #A8C243 y rojo ladrillo #B8433A, comprobados para
  daltonismo. Las líneas usan un verde más oscuro sobre fondo claro.
- «Sin EEG» conserva su color en M21 y M22.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:09:02 -06:00
edgar 957f4cd024 feat(tea): botones para resaltar grupos y categorías en las figuras
- Leyenda con botones, como la distribución de resultados citológicos de
  cáncer cervicouterino: el grupo o la categoría elegida conserva su color,
  el resto se atenúa, «Volver» retrocede y un clic en la figura equivale al
  botón (indicadores-highlight.ts).
- M21, M22 y M24 con botones por grupo de edad; el centro de las donas
  muestra la selección.
- En TEA, la dona C2 de un periodo (M23) se dibuja con ambos anillos y
  botones, y sus barras también los tienen.
2026-11-03 21:22:51 +00:00
edgar 1ce8d98663 feat(tea): ficha de paciente en tres columnas y dona de M21 solo con EEG
- La ficha propia del paciente reparte los paneles en tres columnas
  (dos o una en pantallas más estrechas), con los puntajes por reactivo
  abiertos y un mapa más grande.
- La dona de M21 muestra solo a los pacientes con EEG por grupo de edad;
  el centro conserva el porcentaje total con EEG.
2026-11-03 20:28:14 +00:00
edgar 1771cb7ec6 feat(tea): ficha propia para la mitad de los pacientes de Seguimiento
Los pacientes con número impar abren su propia ventana, como la ficha de
cáncer cervicouterino (con «Regresar» y un resumen arriba); los pares
conservan el resumen desplegable en la fila. El encabezado de la ficha ya
nombra el dominio en lugar de decir siempre cáncer cervicouterino.
2026-11-03 19:58:30 +00:00
edgar b74f188b15 feat(tea): dona por grupo de edad para M21 y barras por grupo de edad para M22
- M21 (fig_c1_dona_edad): solo el anillo por grupo de edad, con el porcentaje
  total con EEG al centro.
- M22 (fig_c1_barras_edad): una barra por grupo de edad con el porcentaje de
  pacientes sin EEG.
- M24 conserva la dona de dos anillos.
2026-11-03 19:45:32 +00:00
edgar 5196f20e47 feat(tea): dona de dos anillos por grupo de edad para M21, M22 y M24
Figura fig_c1_donas para indicadores C1 de un semestre: el anillo interior
divide la población entre con y sin el evento, y el exterior cada parte por
grupo de edad, con el mismo dibujo que la distribución de resultados
citológicos de cáncer cervicouterino. Se construye con los datos
estratificados por grupo de edad.
2026-11-03 19:22:54 +00:00
edgar 5d4cd6f654 feat(indicadores): enlace «Ir» en el selector y seguimiento de TEA más compacto
- Se quita el botón flotante de navegación por indicadores.
- Cada opción de «Buscar indicadores» tiene un enlace «Ir» que lleva a su
  tarjeta (y la muestra si estaba oculta por la selección).
- Resumen del paciente en Seguimiento más compacto; «Puntajes por reactivo»
  plegado por defecto, con un triángulo para desplegarlo.
2026-11-03 19:22:54 +00:00
edgar a05717f92d feat(tea): intervalo de análisis, resumen más preciso y alteraciones del EEG
- Filtro general: «Intervalo de análisis» (Semestral/Mensual) en lugar de
  «Modalidad»; al cambiar de intervalo se elige el periodo más reciente.
- Resumen de TEA: evaluaciones con o sin diagnóstico y diagnóstico positivo
  de TEA explícito.
- Seguimiento: panel «Alteraciones del EEG» (exponente aperiódico, husos del
  sueño, entropía multiescala) con posibles efectos asociados. Datos de
  ejemplo, pendientes de validación médica.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 00:07:22 +00:00
edgar 123232592f feat(indicadores): un solo periodo y selector de indicadores gráficos
- El filtro general admite un único periodo (Elegir periodo); agregar otro lo reemplaza.
- Buscar indicadores pasa a ser una lista desplegable con casillas; solo los
  indicadores marcados se muestran en Indicadores gráficos, con Mostrar todos.
2026-10-30 23:24:38 +00:00
edgar 2cbb994667 feat(tea): seguimiento con resumen por paciente y resumen por periodo
- Pestaña Seguimiento de TEA: tabla de pacientes con filtro de alteraciones EEG
  y fila desplegable con ADOS-2 por reactivo, calidad del EEG y mapa topográfico
  (GET /tea/seguimiento/<id>).
- Indicadores destacados: M21 y M22 (pacientes con TEA con y sin EEG).
- Con un solo periodo elegido, TEA muestra un párrafo de resumen en lugar de
  las tarjetas.
2026-10-30 23:24:38 +00:00
Roberto Treviño Cervantes f4d2a3e85f add bitacora page, self-hosted fonts/icons, review fixes for the install package 2026-10-30 11:19:34 -06:00
Roberto Treviño Cervantes 8c63ed83ac preliminary release 2026-10-29 12:14:56 -06:00
Roberto Treviño Cervantes e6e6fb7210 preliminary release 2026-10-29 12:12:15 -06:00
angel 82efba35cb Merge pull request 'Feature/eu7 transiciones animadas' (#8) from feature/eu7-transiciones-animadas into dev
Reviewed-on: #8
2026-10-28 17:18:12 +00:00
Angel Capetillo Zavala 26fe1ccbb3 feat(cacu): preparar interfaz de riesgo individual de paciente 2026-10-28 10:36:58 -06:00
Angel Capetillo Zavala 94c63c460c feat(eu7): incorporar transiciones animadas en dona y barras 2026-10-28 09:45:00 -06:00
angel 05a9967906 Merge pull request 'feat(indicadores): integrar ajustes CaCu, ficha de paciente y mejoras de navegación' (#7) from feature/detalle-paciente-cacu into dev
Reviewed-on: #7
2026-10-27 21:26:28 +00:00
Angel Capetillo Zavala 1c0bdf6184 feat(indicadores): completar ficha CaCu y navegación clínica 2026-10-27 14:46:51 -06:00
Roberto Treviño Cervantes 51517ddf61 integrating latest dashboard changes 2026-10-26 01:42:32 -06:00
edgar 70aa739f97 Bitácora: IND1 ya no cita kpi_catalog.yaml en la ficha
CSO5.5
2026-10-25 21:25:26 +00:00
edgar 394f2c626b fix(indicadores): «Valores publicados» y la tabla de contingencia plegada
Las tablas desplegables decían «Valores publicados y celdas suprimidas» o «… y cajas no disponibles», que confundía: ahora dicen «Valores publicados». La tabla de contingencia de citología y biopsia estaba siempre a la vista; ahora va plegada bajo «Valores publicados», como las demás. Registrado en docs/bitacora-textos.md.

CSO5.5
2026-10-25 19:43:19 +00:00
edgar 644803cf21 docs: pendiente de IND1 (fecha de corte y calidad del espécimen)
CSO5.5
2026-10-25 19:33:54 +00:00
edgar 8e9a40dec4 docs: pendientes de los textos de Tiempo de tamizaje a diagnóstico
CSO5.5
2026-10-25 18:58:40 +00:00
edgar 1bdec1b838 docs: pendientes de la ficha técnica y de la consulta de calidad satisfactoria
El método estadístico y los campos nuevos de la ficha se posponen; los textos dirán «calidad de espécimen satisfactoria» y la consulta se alineará después.

CSO5.5
2026-10-25 18:36:30 +00:00
edgar 220d5b9d26 fix(indicadores): decir qué junta «Sin dato» bajo la dona de resultados citológicos
«Sin resultado válido en el periodo» no decía qué es un resultado válido. La nota ahora dice «con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte», que es lo que cuenta la consulta. Registrado en docs/bitacora-textos.md.

CSO5.5
2026-10-25 18:08:00 +00:00
edgar fbfd97ec31 fix(indicadores): decir cáncer cervicouterino en lugar de CaCu en pantalla
CaCu es el nombre que le dimos nosotros, no el que busca un médico. Las etiquetas de la página dicen «cáncer cervicouterino», con mayúscula donde abre el texto (la línea «Cáncer cervicouterino, investigación», que ya no dice «Dominio»). El botón del encabezado para cambiar de proyecto sigue diciendo «CaCu», provisional; las direcciones no cambian (/indicadores/cacu). El encabezado dice «Indicadores» en lugar de «Dashboard de indicadores» y el subtítulo «Explora los indicadores de …» sin mencionar el servicio de reportes. «Datos y definiciones» ya no repite «Dominio: …» bajo su título. TEA y CaMa conservan su nombre. Registrado en docs/bitacora-textos.md.

CSO5.5
2026-10-25 17:47:14 +00:00
edgar 18692acc88 fix(indicadores): tarjetas de CaCu sin el pie de las figuras y con cuartiles escritos
Las tarjetas de indicadores de oportunidad de CaCu mostraban, después de su línea, las notas del kit (el pie de las figuras): repetían la definición y, en los tiempos, hablaban de la caja. Ahora dicen solo su línea: «Pacientes con citología tomada en el periodo.» y «n citologías; primer cuartil: x días; tercer cuartil: y días.», sin Q1 ni Q3. El número de Pacientes evaluadas no cambia; «Datos y definiciones» de CaCu aclara que incluye las citologías con espécimen insatisfactorio. TEA y CaMa no cambian. Registrado en docs/bitacora-textos.md.

CSO5.5
2026-10-25 17:18:24 +00:00
edgar 6c84dab730 refactor(indicadores): quitar interpretación y metodología de datos y definiciones
La sección general de advertencias al final de Datos y definiciones repetía avisos genéricos (nulos, periodos, intervalos, uso para investigación) que no son de ningún indicador y solo agregaban ruido; la interpretación de cada gráfica está en su botón Cómo leer. Se quita solo la sección de la plantilla y la aserción de la prueba que buscaba su texto.

CSO5.5
2026-10-25 01:46:37 +00:00
edgar 12ce93f58c fix(indicadores): conservar el pie del kit y la lectura de la fecha de corte
El kit no cambia el formato del pie de las figuras: sigue publicando «<fuente> · Fecha de corte: AAAA-MM-DD» y la misma fuente de TEA. Se revierten la expresión regular que valida el pie de TEA, la extracción de la fecha de corte bajo la gráfica, los fixtures sintéticos y sus specs a como estaban. El cambio de textos de pantalla queda solo en los literales que se muestran o se leen en aria-label, sin tocar la lógica que compara o valida.

CSO5.5
2026-10-25 01:40:17 +00:00
edgar dcaf1a8832 fix(indicadores): quitar flechas, rayas y puntos medios de los textos de pantalla
Los textos que ve una persona, visibles o en aria-label, ya no usan flechas ni rayas o puntos medios como separador: se separan con comas o se reescribe la frase (por ejemplo «Días de toma a resultado (laboratorio)», «Último dato visible, 2025-S1», «Dominio CaCu, investigación», «2025-S2, 1 de 3» o «Datos y definiciones de CaCu»). El pie que publica el kit cambia al mismo estilo, así que la validación del pie de TEA y la lectura de la fecha de corte reconocen el formato nuevo con comas y siguen aceptando el anterior para no romper con un kit previo. Se ajustan los fixtures sintéticos y las specs a los textos nuevos.

CSO5.5
2026-10-25 01:37:53 +00:00
edgar 04d529392e refactor(indicadores): quitar el resumen de indicadores del final de la página
La tabla de resumen repetía en formato largo los valores de todas las figuras; cada figura ya trae su propia tabla de valores. Se quitan el componente indicadores-numeric-summary y sus filas (indicadores-numeric-rows), y las pruebas que dependían de ellos.

CSO5.5
2026-10-25 01:19:07 +00:00
edgar 6f3e7e22f9 fix(indicadores): decir intervalo de tiempo en lugar de granularidad
El filtro general y sus mensajes de compatibilidad nombran «Intervalo de tiempo» (semestre o mes) en lugar de «Granularidad», que no es un término clínico. Cambian la etiqueta del selector y los cinco mensajes que la mencionan; las pruebas que citaban esos textos se ajustan.

CSO5.5
2026-10-25 01:04:14 +00:00
edgar 12a0398903 refactor(indicadores): quitar la tabla de reglas de datos y definiciones
Las reglas de cálculo que publica el kit en `parametros` (clave, valor, estado y fuente) irán en un apéndice o manual técnico aparte, no en la pestaña «Datos y definiciones». Se quita la tabla «Reglas» y su formato de valores, y la pestaña conserva la ficha técnica, las referencias y las poblaciones. También se retiran el tipo y la validación estricta de `parametros` en el servicio: ya nadie los usa y una lista mal formada bloqueaba los metadatos completos. Si el servidor envía `parametros`, se ignoran.

CSO5.5
2026-10-24 22:11:33 +00:00
edgar 03e51c07cc feat(indicadores): panel de tasa de confirmación histopatológica, tiempos pareados y ficha técnica
Agrega el panel de tasa de confirmación histopatológica (cacu_confirmacion_citologia): tasas por resultado citológico de alto grado con su intervalo de Wilson a la izquierda, dona del grado de biopsia a la derecha y tabla de contingencia; la vista base es «LIEAG o más» y las pacientes sin biopsia aún no entran al denominador. Une en una sola figura los tiempos de toma a resultado (pedido por id, oculto en el catálogo) y de toma a diagnóstico. La pestaña Datos y definiciones muestra la ficha técnica y las reglas del kit en tablas; las notas de cada figura pasan a su Cómo leer, las tarjetas dejan solo valor, n y periodo, y el Cómo leer de EU7 muestra solo lo que publica el kit. Las transiciones animadas quedan fuera, como entrega aparte para el diseñador.

CSO5.5
2026-10-24 21:04:57 +00:00
edgar e6be341ad9 Redondeo único de porcentajes y etiqueta de la última citología sin resultado
- indicadores-format.ts: una regla para todo porcentaje mostrado. Una décima,
  medio hacia arriba; entre 0 y 0.1, la primera cifra significativa (0.04 %).
  De un conteo se calcula con enteros; de un valor publicado, sin sorpresas de
  coma flotante. La usan el resumen numérico (que mostraba el valor crudo,
  «0.6600660066 %»), los KPI, la dona, las barras y la tabla de EU7.
- Seguimiento: la última citología sin Bethesda dice «Insatisfactoria» si su
  calidad lo es y «Sin resultado al corte» si no; antes las dos decían
  «No disponible», que queda para cuando no hay citología.

CSO5.5
2026-10-24 18:17:54 +00:00
angel 85ec11ab0f Merge pull request 'feat(indicadores): ajustar indicadores CaCu y presentacion EU7' (#6) from feature/dona-barras-generales into dev
Reviewed-on: #6
2026-10-24 03:23:00 +00:00
Angel Capetillo Zavala db9ab0d1a7 feat(indicadores): ajustar indicadores CaCu y presentacion EU7
Actualiza los indicadores de oportunidad y clínicos de CaCu, incorpora el KPI no disponible, prioriza EU7, independiza dos figuras mediante Todos con reporte y añade el selector de prioridad no disponible en Seguimiento. Integra además los totales por escenario en las barras de EU7 y elimina el listado inferior redundante.
2026-10-23 21:18:43 -06:00
angel af70d6f378 Merge pull request 'feat(indicadores): interacción dona-barras, homologación visual y escenario clínico EU7' (#5) from feature/dona-barras-generales into dev
Reviewed-on: #5
2026-10-23 19:26:56 +00:00
Angel Capetillo Zavala 1940f4fa47 feat(isssteleon): add EU7 clinical scenario charts 2026-10-23 13:18:57 -06:00
alberto ec406d5d2d Merge pull request 'Reword "¿Cómo leer?" text for proportion and box charts' (#4) from fix/como-leer-textos into dev
Reviewed-on: #4
2026-10-23 18:27:14 +00:00
edgar 7b82427713 Reword "¿Cómo leer?" text for proportion and box charts
Replace "denominadores pequeños" with "tamaño de muestra pequeño" and drop the mention of Plotly from the box chart and fallback texts.
2026-10-23 18:26:26 +00:00
Angel Capetillo Zavala ec642df834 style(indicadores): homologar tarjetas y navegación de dominios
Homologa la presentación de figuras y tarjetas en TEA, CaCu y CaMa; recupera las leyendas superiores, permite la expansión independiente de Cómo leer y mueve la navegación de dominios a un selector compacto con resaltado institucional en la topbar. Preserva el comportamiento de Plotly y la interacción dona-barras.
2026-10-23 12:14:17 -06:00
Angel Capetillo Zavala 540506bde0 feat(indicadores): conectar donas jerárquicas con barras generales
Habilita el filtrado visual local de barras generales mediante selecciones jerárquicas C2, preservando datos originales, periodos, porcentajes y restauración de la distribución completa.
2026-10-23 10:32:40 -06:00
Roberto Treviño Cervantes d9245fe9b7 integration layer; merge work on indicators from forks with existing ingestion pipeline 2026-10-23 08:07:02 -06:00
angel 14fd765122 Merge pull request 'Integra las mejoras del dashboard de indicadores para TEA, CaCu y CaMa.' (#3) from feature/dashboard-tabs-colores-donas into dev
Reviewed-on: #3
2026-10-23 07:30:35 +00:00
Angel Capetillo Zavala 9639423a32 feat(indicadores): completa metadatos y navegación multiperiodo 2026-10-23 01:18:24 -06:00
Angel Capetillo Zavala 1fe88dfb45 feat(indicadores): dashboard interactivo multidominio y seguimiento CaCu 2026-10-22 17:10:35 -06:00
edgar a30dbbb102 Merge pull request 'Feature/cama birads45' (#2) from feature/cama-birads45 into dev
Reviewed-on: #2
2026-10-20 07:04:58 +00:00
Roberto Treviño Cervantes b0608fdc70 Merge remote-tracking branch 'origin/feature/frontend-flujo_inicial-20260923' into wip/mapping 2026-09-24 11:30:40 -06:00
Angel Capetillo Zavala 473a269bed Feature: Flujo inicial 2026-09-23 16:39:33 -06:00
548 changed files with 74415 additions and 1368 deletions
-6
View File
@@ -42,9 +42,3 @@ __screenshots__/
# System files
.DS_Store
Thumbs.db
# Temporary UX reports and one-off static checks
/UX-*-informe.md
/scripts/ux06b-resources.test.mjs
/scripts/ux06c-presentation.test.mjs
/scripts/ux06d-presentation.test.mjs
+9 -7
View File
@@ -1,10 +1,12 @@
FROM node:22-slim
# Production image: the Angular build served by nginx, which proxies the API paths to `webapi`.
FROM node:22-slim AS build
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm install
COPY package.json package-lock.json ./
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
+10 -53
View File
@@ -1,59 +1,16 @@
# WebApp
This project was generated using [Angular CLI](https://github.com/angular/angular-cli) version 22.1.8.
## Development server
To start a local development server, run:
Interfaz de ISSSTELEON en Angular y Angular Material: conexión e importación de
datos (`/conectar`), bitácora de cargas (`/bitacora`), gobernanza y tablero de
indicadores (`/indicadores`).
```bash
ng serve
npm ci
npx ng serve # http://localhost:4200
npx ng test --watch=false # pruebas unitarias (Vitest)
npx ng build # compilación de producción en dist/WebApp
```
Once the server is running, open your browser and navigate to `http://localhost:4200/`. The application will automatically reload whenever you modify any of the source files.
## Code scaffolding
Angular CLI includes powerful code scaffolding tools. To generate a new component, run:
```bash
ng generate component component-name
```
For a complete list of available schematics (such as `components`, `directives`, or `pipes`), run:
```bash
ng generate --help
```
## Building
To build the project run:
```bash
ng build
```
This will compile your project and store the build artifacts in the `dist/` directory. By default, the production build optimizes your application for performance and speed.
## Running unit tests
To execute unit tests with the [Vitest](https://vitest.dev/) test runner, use the following command:
```bash
ng test
```
## Running end-to-end tests
For end-to-end (e2e) testing, run:
```bash
ng e2e
```
Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs.
## Additional Resources
For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.
`ng serve` envía las rutas de la API a WebApi en `localhost:5050`
(`proxy.conf.json`). La imagen de Docker (`Dockerfile`) sirve la compilación con
nginx (`nginx.conf`), que reenvía esas mismas rutas al servicio `webapi`.
+32 -4
View File
@@ -31,6 +31,14 @@
}
],
"styles": [
"node_modules/@fontsource/roboto/300.css",
"node_modules/@fontsource/roboto/400.css",
"node_modules/@fontsource/roboto/500.css",
"node_modules/@fontsource/rajdhani/600.css",
"node_modules/@fontsource/rajdhani/700.css",
"node_modules/@fontsource/roboto-mono/400.css",
"node_modules/@fontsource/roboto-mono/600.css",
"node_modules/material-icons/iconfont/filled.css",
"src/styles.scss"
]
},
@@ -44,8 +52,8 @@
},
{
"type": "anyComponentStyle",
"maximumWarning": "4kB",
"maximumError": "8kB"
"maximumWarning": "6kB",
"maximumError": "10kB"
}
],
"outputHashing": "all"
@@ -54,25 +62,45 @@
"optimization": false,
"extractLicenses": false,
"sourceMap": true
},
"simulado": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true,
"fileReplacements": [
{
"replace": "src/app/app.config.ts",
"with": "src/app/app.config.simulado.ts"
}
]
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular/build:dev-server",
"options": { "proxyConfig": "proxy.conf.json" },
"options": {
"proxyConfig": "proxy.conf.json"
},
"configurations": {
"production": {
"buildTarget": "WebApp:build:production"
},
"development": {
"buildTarget": "WebApp:build:development"
},
"simulado": {
"buildTarget": "WebApp:build:simulado",
"proxyConfig": "simulado/proxy.simulado.json"
}
},
"defaultConfiguration": "development"
},
"test": {
"builder": "@angular/build:unit-test"
"builder": "@angular/build:unit-test",
"options": {
"isolate": true
}
}
}
}
+35
View File
@@ -0,0 +1,35 @@
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;
gzip on;
gzip_types text/css application/javascript application/json image/svg+xml;
gzip_min_length 1024;
location ~ ^/(api|imports|data|cacu|cama|tea|governance|reportes|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;
}
# Bundles carry a content hash in their name; index.html doesn't, so it
# must be revalidated or browsers keep running the previous release.
location ~* \.(js|css)$ {
add_header Cache-Control "public, max-age=31536000, immutable";
try_files $uri =404;
}
location / {
add_header Cache-Control "no-cache";
try_files $uri $uri/ /index.html;
}
}
+283 -2
View File
@@ -16,9 +16,15 @@
"@angular/material": "^22.1.7",
"@angular/platform-browser": "^22.1.0",
"@angular/router": "^22.1.0",
"@fontsource/rajdhani": "^5.3.0",
"@fontsource/roboto": "^5.3.0",
"@fontsource/roboto-mono": "^5.3.0",
"material-icons": "^1.13.14",
"pdfmake": "0.3.14",
"plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
"tslib": "^2.3.0",
"write-excel-file": "4.1.1"
},
"devDependencies": {
"@angular/build": "^22.1.8",
@@ -1417,6 +1423,33 @@
}
}
},
"node_modules/@fontsource/rajdhani": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/rajdhani/-/rajdhani-5.3.0.tgz",
"integrity": "sha512-oBJgSIibWJvVBKseme1JczqPLoDHN97LHti4uh0LjfcJqQoVmnQQlRKIpEjTJV559rmVQ6qbVZZwKwk2wkBTtw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/roboto": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/roboto/-/roboto-5.3.0.tgz",
"integrity": "sha512-BapRJOWYP+LZ21zp+wBQjfpPYKRoxc4LspJ/RLuI+HSMBD5u/X4O+ESDrSvEqDSy0rAl7GwBJ+09mdc16cVQ1Q==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/roboto-mono": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/roboto-mono/-/roboto-mono-5.3.0.tgz",
"integrity": "sha512-yhwplHMHW9dCk+1pZuERfcJe+K3rosGVZEoK0XktkxRSqQ9qsipSwwiuW2/8Qmtp9lzu3Ixa/ie4BMH3i8CkZQ==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@harperfast/extended-iterable": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@harperfast/extended-iterable/-/extended-iterable-1.0.3.tgz",
@@ -2670,6 +2703,30 @@
"@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4"
}
},
"node_modules/@noble/ciphers": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz",
"integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/hashes": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
"integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@oxc-parser/binding-android-arm-eabi": {
"version": "0.142.0",
"resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.142.0.tgz",
@@ -3666,6 +3723,12 @@
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
"license": "MIT"
},
"node_modules/@swc/helpers": {
"version": "0.5.24",
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.24.tgz",
"integrity": "sha512-6tcXo4kA8HgGO7AVmawB57RYi/piBPYVHVcO6dXjX+SZw8GoHmi262sp4v2Ha2kNP9Cx84qei27yT+fjS1lxgg==",
"license": "Apache-2.0"
},
"node_modules/@tybys/wasm-util": {
"version": "0.10.4",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz",
@@ -3980,6 +4043,15 @@
"node": ">=12"
}
},
"node_modules/base64-js": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.8.tgz",
"integrity": "sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/baseline-browser-mapping": {
"version": "2.11.25",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.25.tgz",
@@ -4070,6 +4142,35 @@
"dev": true,
"license": "ISC"
},
"node_modules/brotli": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/brotli/-/brotli-1.3.3.tgz",
"integrity": "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.1.2"
}
},
"node_modules/brotli/node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/browserslist": {
"version": "4.29.0",
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.0.tgz",
@@ -4326,6 +4427,15 @@
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/clone": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz",
"integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==",
"license": "MIT",
"engines": {
"node": ">=0.8"
}
},
"node_modules/content-disposition": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",
@@ -4529,6 +4639,12 @@
"node": ">=8"
}
},
"node_modules/dfa": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz",
"integrity": "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==",
"license": "MIT"
},
"node_modules/dom-serializer": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
@@ -4890,7 +5006,6 @@
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"dev": true,
"license": "MIT"
},
"node_modules/fast-string-truncated-width": {
@@ -4955,6 +5070,12 @@
}
}
},
"node_modules/fflate": {
"version": "0.8.3",
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
"license": "MIT"
},
"node_modules/finalhandler": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",
@@ -4987,6 +5108,23 @@
"node": ">=6"
}
},
"node_modules/fontkit": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/fontkit/-/fontkit-2.0.4.tgz",
"integrity": "sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==",
"license": "MIT",
"dependencies": {
"@swc/helpers": "^0.5.12",
"brotli": "^1.3.2",
"clone": "^2.1.2",
"dfa": "^1.2.0",
"fast-deep-equal": "^3.1.3",
"restructure": "^3.0.0",
"tiny-inflate": "^1.0.3",
"unicode-properties": "^1.4.0",
"unicode-trie": "^2.0.0"
}
},
"node_modules/forwarded": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
@@ -5831,6 +5969,16 @@
"url": "https://opencollective.com/parcel"
}
},
"node_modules/linebreak": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz",
"integrity": "sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==",
"license": "MIT",
"dependencies": {
"base64-js": "0.0.8",
"unicode-trie": "^2.0.0"
}
},
"node_modules/listr2": {
"version": "11.0.0",
"resolved": "https://registry.npmjs.org/listr2/-/listr2-11.0.0.tgz",
@@ -5933,6 +6081,12 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/material-icons": {
"version": "1.13.14",
"resolved": "https://registry.npmjs.org/material-icons/-/material-icons-1.13.14.tgz",
"integrity": "sha512-kZOfc7xCC0rAT8Q3DQixYAeT+tBqZnxkseQtp2bxBxz7q5pMAC+wmit7vJn1g/l7wRU+HEPq23gER4iPjGs5Cg==",
"license": "Apache-2.0"
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
@@ -6336,6 +6490,12 @@
"@oxc-parser/binding-win32-x64-msvc": "0.142.0"
}
},
"node_modules/pako": {
"version": "0.2.9",
"resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz",
"integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==",
"license": "MIT"
},
"node_modules/parse5": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz",
@@ -6439,6 +6599,34 @@
"dev": true,
"license": "MIT"
},
"node_modules/pdfkit": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.20.2.tgz",
"integrity": "sha512-Q/w03ICAQyXfHNfTsg1udp0ADerdBN0s7a6XSPL7J7Ro6ABnafoBOCDBstIO9U02mvzHEV8HrvFIw5iV5ejIRA==",
"license": "MIT",
"dependencies": {
"@noble/ciphers": "^1.3.0",
"@noble/hashes": "^1.8.0",
"fflate": "^0.8.3",
"fontkit": "^2.0.4",
"linebreak": "^1.1.0",
"png-js": "^2.0.0"
}
},
"node_modules/pdfmake": {
"version": "0.3.14",
"resolved": "https://registry.npmjs.org/pdfmake/-/pdfmake-0.3.14.tgz",
"integrity": "sha512-EDyOlwiDnE8e0eITSpHwZCVAP/veWq0TxA2RyhoDO0cSLat7HEGNtKUN6UiW9+YovO2GhcWlK99Q7tj9sof9gg==",
"license": "MIT",
"dependencies": {
"linebreak": "^1.1.0",
"pdfkit": "^0.20.2",
"xmldoc": "^2.0.3"
},
"engines": {
"node": ">=20"
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -6488,6 +6676,14 @@
"integrity": "sha512-3UkyAT7/U8f3sOLavLnUjA6mqFmnqEe246GZhxT0J3TT9oZ0mh6SgwsL1yo/3/4xfmRSDFdGOxe+EsvT2XiE0g==",
"license": "MIT"
},
"node_modules/png-js": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/png-js/-/png-js-2.0.0.tgz",
"integrity": "sha512-GdzJuUMc6ZSpxFJWVxtOH1bzYHym+TOnveqUjb+VJIbZWbZzyiRGFiKhbiielfpYbgMlhHVhsJ0FTazfuRFkMA==",
"dependencies": {
"fflate": "^0.8.2"
}
},
"node_modules/postcss": {
"version": "8.5.28",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
@@ -6718,6 +6914,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/restructure": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/restructure/-/restructure-3.0.2.tgz",
"integrity": "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==",
"license": "MIT"
},
"node_modules/rolldown": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.0.tgz",
@@ -6816,6 +7018,15 @@
"@parcel/watcher": "^2.4.1"
}
},
"node_modules/sax": {
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",
"integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=11.0.0"
}
},
"node_modules/saxes": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
@@ -7150,6 +7361,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/tiny-inflate": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz",
"integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==",
"license": "MIT"
},
"node_modules/tinybench": {
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
@@ -7313,6 +7530,46 @@
"node": ">=20.18.1"
}
},
"node_modules/unicode-properties": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz",
"integrity": "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.3.0",
"unicode-trie": "^2.0.0"
}
},
"node_modules/unicode-properties/node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/unicode-trie": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz",
"integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==",
"license": "MIT",
"dependencies": {
"pako": "^0.2.5",
"tiny-inflate": "^1.0.0"
}
},
"node_modules/unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
@@ -8033,6 +8290,18 @@
"dev": true,
"license": "ISC"
},
"node_modules/write-excel-file": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/write-excel-file/-/write-excel-file-4.1.1.tgz",
"integrity": "sha512-MUnCnNtQrcZek832ZcU24uU0rSphFmKPD1DvIjXOlygVb93CV7Tme6H3jUTkxsMmjB2W7HIzERzjqTi5kui71A==",
"license": "MIT",
"dependencies": {
"fflate": "^0.8.2"
},
"engines": {
"node": ">=18"
}
},
"node_modules/xml-name-validator": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
@@ -8050,6 +8319,18 @@
"dev": true,
"license": "MIT"
},
"node_modules/xmldoc": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/xmldoc/-/xmldoc-2.0.3.tgz",
"integrity": "sha512-6gRk4NY/Jvg67xn7OzJuxLRsGgiXBaPUQplVJ/9l99uIugxh4FTOewYz5ic8WScj7Xx/2WvhENiQKwkK9RpE4w==",
"license": "MIT",
"dependencies": {
"sax": "^1.4.3"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/y18n": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
+7 -1
View File
@@ -19,9 +19,15 @@
"@angular/material": "^22.1.7",
"@angular/platform-browser": "^22.1.0",
"@angular/router": "^22.1.0",
"@fontsource/rajdhani": "^5.3.0",
"@fontsource/roboto": "^5.3.0",
"@fontsource/roboto-mono": "^5.3.0",
"material-icons": "^1.13.14",
"pdfmake": "0.3.14",
"plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
"tslib": "^2.3.0",
"write-excel-file": "4.1.1"
},
"devDependencies": {
"@angular/build": "^22.1.8",
+9 -4
View File
@@ -1,6 +1,11 @@
{
"/tea/**": { "target": "http://127.0.0.1:5000", "secure": false },
"/cacu/**": { "target": "http://127.0.0.1:5000", "secure": false },
"/cama/**": { "target": "http://127.0.0.1:5000", "secure": false },
"/health": { "target": "http://127.0.0.1:5000", "secure": false }
"/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 },
"/reportes": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true }
}

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 717 B

+38
View File
@@ -0,0 +1,38 @@
# Modo simulado (solo nuestra copia local, rama `ulises/tea-seguimiento`)
Para ver y modificar la página de seguimiento de TEA sin la plataforma completa ni su preproceso.
Todo es **inventado**. No forma parte de la WebApp que se entrega.
| Archivo | Qué es |
|---|---|
| `datos_tea.json` | 120 niños inventados: lista, ficha y la relación con el ADOS-2 (modelo de OR de E27). Se genera; no se versiona |
| `servidor.py` | Servidor de prueba (Python, sin instalar nada) en `localhost:5051` |
| `proxy.simulado.json` | Las rutas de la API, al servidor de prueba |
| `../src/app/app.config.simulado.ts` | Igual que `app.config.ts`, pero el seguimiento de TEA lee el contrato JSON (`/tea/seguimiento`) |
## Cómo se usa
1. Generar los datos (una vez, o cuando cambie el modelo), desde `biomarcadores-tea/`:
```
python experimentos/E27_modelo_or/simulado_plataforma.py
```
2. Levantar el servidor de prueba, desde `webapp-tea/`:
```
python simulado/servidor.py
```
3. En otra terminal, la página, desde `webapp-tea/`:
```
npx ng serve --configuration simulado --port 4300
```
4. Abrir `http://localhost:4300/indicadores/tea`, entrar a **Seguimiento** y abrir un paciente.
## El panel nuevo: «Relación con el ADOS-2»
En la ficha del paciente (`tea-paciente-resumen.*`) muestra, por cada asociación clara de la cohorte (q < 0.05):
- la zona del EEG y el z del paciente, marcada si está alterada (|z| ≥ 2);
- el aspecto del ADOS-2 (reactivo o dominio);
- el OR de la cohorte con su intervalo y su q;
- la probabilidad que el modelo da a este paciente (con su edad y módulo) frente a la de un niño con z = 0;
- lo que muestra su ADOS-2.
El campo `relacion_ados2` es opcional: sin él (la plataforma real hoy), el panel no aparece.
+47
View File
@@ -0,0 +1,47 @@
{
"/api": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/imports": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/data": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/health": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/cacu": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/cama": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/tea": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/governance": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/reportes": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
}
}
+110
View File
@@ -0,0 +1,110 @@
"""
servidor.py — Servidor de prueba con datos SIMULADOS para ver la página de TEA sin la plataforma completa.
Solo para nuestra copia local (rama ulises/tea-seguimiento): no forma parte de la WebApp que se entrega.
Responde lo que pide la sección de seguimiento de TEA en su contrato JSON:
- `/tea/seguimiento`: la lista, con filtros y páginas;
- `/tea/seguimiento/<id>`: la ficha, incluido el campo nuevo `relacion_ados2`.
A lo demás de `/tea/...` contesta vacío, para que la página cargue.
Los datos los escribe `biomarcadores-tea/experimentos/E27_modelo_or/simulado_plataforma.py` en `datos_tea.json`.
python simulado/servidor.py # http://localhost:5051
npx ng serve --configuration simulado --port 4300
"""
from __future__ import annotations
import json
import math
import sys
from datetime import date, timedelta
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, unquote, urlparse
PUERTO = 5051
DATOS = json.loads((Path(__file__).with_name("datos_tea.json")).read_text(encoding="utf-8"))
VACIO_FHIR = {"resourceType": "Bundle", "type": "searchset", "total": 0, "entry": []}
def _num(q, k):
v = q.get(k, [None])[0]
try:
return float(v) if v is not None else None
except ValueError:
return None
def lista(q: dict) -> dict:
meses = int(q.get("meses", ["12"])[0]) if q.get("meses", ["12"])[0] in ("1", "3", "6", "12") else 12
corte = q.get("corte", [date.today().isoformat()])[0]
page = max(1, int(q.get("page", ["1"])[0]))
size = min(200, max(1, int(q.get("page_size", ["25"])[0])))
filtro = q.get("alteraciones_eeg", [None])[0]
ps = DATOS["pacientes"]
if filtro in ("normal", "anormal"):
ps = [p for p in ps if p["alteraciones_eeg"] == filtro]
elif filtro == "sin_eeg_valido":
ps = [p for p in ps if p["ultimo_eeg"] is None]
if q.get("grupo_edad"):
ps = [p for p in ps if p["grupo_edad"].startswith(q["grupo_edad"][0].replace("_", "-"))]
for campo, lo, hi in (("mchat", "mchat_min", "mchat_max"), ("css_ados2", "css_min", "css_max")):
a, b = _num(q, lo), _num(q, hi)
if a is not None:
ps = [p for p in ps if p[campo] is not None and a <= p[campo] <= (b if b is not None else 99)]
if q.get("estado_caso"):
ps = [p for p in ps if p["estado_caso"] == q["estado_caso"][0]]
if q.get("alteracion"):
ps = [p for p in ps if q["alteracion"][0] in p["alteraciones"]]
total = len(ps)
por_alt = [{"codigo": t["codigo"], "etiqueta": t["etiqueta"], "n": sum(t["codigo"] in p["alteraciones"] for p in ps)}
for t in DATOS["tipos_alteracion"]]
hasta = date.fromisoformat(corte)
return {
"simulado": True, "corte": corte,
"ventana": {"meses": meses, "desde": (hasta - timedelta(days=30 * meses)).isoformat(), "hasta": corte},
"filtros": {"alteraciones_eeg": filtro},
"paginacion": {"page": page, "page_size": size, "total_items": total, "total_pages": max(1, math.ceil(total / size))},
"items": ps[(page - 1) * size: page * size],
"tipos_alteracion": DATOS["tipos_alteracion"],
"resumen_eeg": {"validadas": True, "con_eeg_valido": total,
"normales": sum(p["alteraciones_eeg"] == "normal" for p in ps),
"anormales": sum(p["alteraciones_eeg"] == "anormal" for p in ps), "sin_eeg": 0,
"por_alteracion": por_alt},
}
class Manejador(BaseHTTPRequestHandler):
def _json(self, cuerpo, codigo=200):
datos = json.dumps(cuerpo, ensure_ascii=False).encode("utf-8")
self.send_response(codigo)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(datos)))
self.end_headers()
self.wfile.write(datos)
def do_GET(self): # noqa: N802
u = urlparse(self.path)
ruta, q = u.path.rstrip("/"), parse_qs(u.query)
if ruta == "/tea/seguimiento":
return self._json(lista(q))
if ruta.startswith("/tea/seguimiento/"):
d = DATOS["detalles"].get(unquote(ruta.rsplit("/", 1)[1]))
return self._json(d) if d else self._json({"error": "no encontrado"}, 404)
if "/fhir/" in ruta:
return self._json(VACIO_FHIR)
if ruta.endswith("/indicadores"):
return self._json([])
if ruta == "/health":
return self._json({"status": "ok", "simulado": True})
return self._json({"error": "sin datos simulados para esta ruta"}, 404)
def log_message(self, fmt, *args):
sys.stderr.write(" " + fmt % args + "\n")
if __name__ == "__main__":
print(f"Servidor simulado en http://localhost:{PUERTO} ({len(DATOS['pacientes'])} niños inventados)")
ThreadingHTTPServer(("127.0.0.1", PUERTO), Manejador).serve_forever()
+137
View File
@@ -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);
+92
View File
@@ -0,0 +1,92 @@
// Covers the shell's header: on an indicators page it carries the platform title and the domain selector; on
// the institutional routes it keeps the breadcrumb. The pages are stubs: only the header and the router matter.
import { Component } from '@angular/core';
import { Location } from '@angular/common';
import { TestBed } from '@angular/core/testing';
import { provideRouter, Router } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { App } from './app';
import { routes } from './app.routes';
import { DOMINIOS } from './features/indicadores/indicadores.models';
@Component({ template: 'página', selector: 'app-stub' })
class Stub {}
describe('Encabezado del marco', () => {
const rutas = [
{ path: '', component: Stub },
{ path: 'conectar', component: Stub, data: { workspace: true, breadcrumb: 'Conectar datos' } },
{ path: 'gobernanza', component: Stub, data: { workspace: true, breadcrumb: 'Gobernanza de modelos' } },
...DOMINIOS.map(dominio => ({ path: `indicadores/${dominio}`, component: Stub, data: { workspace: true, breadcrumb: 'Indicadores', dominio } })),
];
let fixture: ReturnType<typeof TestBed.createComponent<App>>, router: Router;
beforeEach(async () => {
await TestBed.configureTestingModule({ imports: [App], providers: [provideRouter(rutas), provideHttpClient(), provideHttpClientTesting()] }).compileComponents();
fixture = TestBed.createComponent(App); router = TestBed.inject(Router);
fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); document.querySelectorAll('.cdk-overlay-container').forEach(e => e.replaceChildren()); });
const root = () => fixture.nativeElement as HTMLElement;
async function ir(url: string) { await router.navigateByUrl(url); await fixture.whenStable(); fixture.detectChanges(); }
const selector = () => root().querySelector('.domain-selector') as HTMLButtonElement | null;
async function abrirMenu() {
selector()!.click(); fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
return [...document.querySelectorAll('.mat-mdc-menu-panel a[mat-menu-item]')] as HTMLAnchorElement[];
}
it('las rutas de los tres dominios existen en el enrutador de la aplicación', () => {
// Fails if the selector would point at a route the application does not have.
// The application's routes live under the guarded parent ('login' is its sibling).
const paths = routes.flatMap((ruta) => [ruta.path, ...(ruta.children ?? []).map((hijo) => hijo.path)]);
for (const dominio of DOMINIOS) expect(paths).toContain(`indicadores/${dominio}`);
});
it.each([['tea', 'Trastorno del espectro autista'], ['cacu', 'Cáncer cervicouterino'], ['cama', 'Cáncer de mama']] as const)('en /indicadores/%s muestra el título de la plataforma y el selector con «%s»', async (dominio, etiqueta) => {
await ir('/indicadores/' + dominio);
expect(root().querySelector('.platform-title')?.textContent).toBe('Plataforma de Indicadores');
expect(selector()?.textContent?.replace(/\s+/g, ' ').trim()).toBe(etiqueta + ' ▾');
expect(root().querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON');
// The breadcrumb is replaced, not duplicated beside the selector.
expect(root().querySelector('.site-header__nav')).toBeNull();
expect(root().querySelector('.app-shell--indicadores')).not.toBeNull();
});
it('el selector tiene nombre accesible con el dominio actual y anuncia un menú', async () => {
await ir('/indicadores/cama');
expect(selector()!.getAttribute('aria-label')).toBe('Dominio actual: Cáncer de mama. Cambiar dominio');
expect(selector()!.getAttribute('aria-haspopup')).toBe('menu');
expect(selector()!.tagName).toBe('BUTTON');
expect(selector()!.tabIndex).toBeGreaterThanOrEqual(0);
});
it('el menú ofrece los otros dos dominios con sus rutas institucionales', async () => {
await ir('/indicadores/cama');
const items = await abrirMenu();
expect(items.map(a => a.textContent?.trim())).toEqual(['Trastorno del espectro autista', 'Cáncer cervicouterino']);
expect(items.map(a => a.getAttribute('href'))).toEqual(['/indicadores/tea', '/indicadores/cacu']);
expect(selector()!.getAttribute('aria-expanded')).toBe('true');
});
it('elegir otro dominio navega por el enrutador, actualiza el selector y deja una entrada en el historial', async () => {
await ir('/indicadores/cama');
const items = await abrirMenu();
items[1].click(); await fixture.whenStable(); fixture.detectChanges();
expect(router.url).toBe('/indicadores/cacu');
expect(selector()!.textContent).toContain('Cáncer cervicouterino');
// The choice is a router navigation (a history entry), not a page reload: going back lands on the previous domain.
const ubicacion = TestBed.inject(Location);
ubicacion.back(); await new Promise(r => setTimeout(r, 100));
expect(ubicacion.path()).toBe('/indicadores/cama');
});
it.each(['/', '/conectar', '/gobernanza'])('en %s conserva el encabezado institucional sin selector', async url => {
// Fails if the indicators header leaks into the institutional routes.
await ir(url);
expect(selector()).toBeNull();
expect(root().querySelector('.platform-title')).toBeNull();
expect(root().querySelector('.site-header__section')).toBeNull();
expect(root().querySelector('.site-header__nav')?.textContent).not.toContain('Análisis de información');
expect(root().querySelector('.app-shell--indicadores')).toBeNull();
if (url !== '/') expect(root().querySelector('.site-header__crumb')?.textContent).toContain(url === '/conectar' ? 'Conectar datos' : 'Gobernanza de modelos');
});
it('una ruta parecida que no es de indicadores no activa el selector', async () => {
await router.navigateByUrl('/'); fixture.detectChanges();
expect(selector()).toBeNull();
});
});
+21
View File
@@ -0,0 +1,21 @@
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { IndicadoresService } from './features/indicadores/indicadores.service';
import { IndicadoresPeriodos } from './features/indicadores/indicadores-periodos';
import { FhirIndicadoresPeriodos, FhirIndicadoresService } from './features/indicadores/indicadores-fhir';
// SOLO para el modo «simulado» (ng serve --configuration simulado): igual que app.config.ts, pero el seguimiento
// de TEA lee el contrato JSON (`/tea/seguimiento`) del servidor de prueba (`simulado/servidor.py`).
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
provideHttpClient(),
// The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract
// (`/<domain>/indicadores/<id>/datos`, `/tea/seguimiento`).
{ provide: IndicadoresService, useClass: FhirIndicadoresService },
{ provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos },
]
};
+14 -2
View File
@@ -1,12 +1,24 @@
import { provideHttpClient } from '@angular/common/http';
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { IndicadoresService } from './features/indicadores/indicadores.service';
import { IndicadoresPeriodos } from './features/indicadores/indicadores-periodos';
import { TeaSeguimientoService } from './features/indicadores/tea-seguimiento.service';
import { FhirIndicadoresPeriodos, FhirIndicadoresService } from './features/indicadores/indicadores-fhir';
import { FhirTeaSeguimientoService } from './features/indicadores/tea-seguimiento-fhir';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
provideHttpClient()
// La sesión es del navegador (`auth/auth.service.ts`): no hay interceptor
// porque la WebApi no responde 401.
provideHttpClient(),
// The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract
// (`/<domain>/indicadores/<id>/datos`, `/tea/seguimiento`).
{ provide: IndicadoresService, useClass: FhirIndicadoresService },
{ provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos },
{ provide: TeaSeguimientoService, useClass: FhirTeaSeguimientoService },
]
};
+53 -18
View File
@@ -1,20 +1,55 @@
<a class="skip-link" href="#contenido-principal">Saltar al contenido principal</a>
<header class="institutional-header">
<div class="header-content">
<img class="institutional-logo" src="images/LogoISSSTELEON.png" alt="ISSSTELEON"
width="1125" height="358" />
<span class="platform-title">{{ title }}</span>
</div>
</header>
<div class="app-shell" [class.app-shell--workspace]="workspace()" [class.app-shell--indicadores]="!!activeDomain()">
@if (!sinCromo()) {
<header class="site-header">
<div class="site-header__content">
<a class="brand" routerLink="/" aria-label="ISSSTELEON, inicio">
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
</a>
@if (activeDomain(); as domain) {
<span class="platform-title">{{ title }}</span>
@if (otherDomains().length) {
@defer (on immediate) {
<app-domain-selector [actual]="domain" [otros]="otherDomains()" [labels]="domainLabels" />
} @placeholder {
<!-- Same size as the selector until its code arrives, so the header does not jump. -->
<span class="domain-selector domain-selector--espera" aria-hidden="true">{{ domainLabels[domain] }}</span>
}
} @else {
<!-- An account with a single domain has nothing to switch to: the domain is a label. -->
<span class="domain-selector domain-selector--espera">{{ domainLabels[domain] }}</span>
}
} @else {
<nav class="site-header__nav" aria-label="Secciones">
@if (breadcrumb(); as crumb) {
<span class="site-header__crumb" aria-current="page">{{ crumb }}</span>
}
</nav>
}
@if (usuario(); as sesion) {
<button
class="site-header__salir"
type="button"
(click)="salir()"
[attr.title]="'Cerrar sesión de ' + sesion.nombre"
[attr.aria-label]="'Cerrar sesión de ' + sesion.nombre"
>
<mat-icon aria-hidden="true">logout</mat-icon>
<span class="site-header__salir-nombre">{{ sesion.nombre }}</span>
</button>
}
</div>
</header>
}
<main #mainContent id="contenido-principal" tabindex="-1">
<router-outlet />
</main>
<main class="app-main">
<router-outlet />
</main>
@if (showBackToTop()) {
<button class="back-to-top" type="button" aria-label="Volver al inicio" (click)="backToTop()">
<svg aria-hidden="true" focusable="false" viewBox="0 0 24 24" width="24" height="24">
<path d="M12 19V5m-7 7 7-7 7 7" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
</svg>
</button>
}
@if (!workspace() && !sinCromo()) {
<footer class="site-footer">
<div class="site-footer__content">
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
</div>
</footer>
}
</div>
-47
View File
@@ -1,47 +0,0 @@
import { routes } from './app.routes';
import { TestBed } from '@angular/core/testing';
import { Router, provideRouter } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { IndicadoresPage } from './features/indicadores/indicadores-page';
it('permite acceso directo a /indicadores sin guard ni autenticación', async () => {
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] });
const harness = await RouterTestingHarness.create();
await harness.navigateByUrl('/indicadores', IndicadoresPage);
expect(TestBed.inject(Router).url).toBe('/indicadores/tea');
expect(harness.routeNativeElement?.textContent).toContain('Dashboard de indicadores');
const http = TestBed.inject(HttpTestingController);
http.expectOne('/tea/indicadores').flush([]);
http.verify();
});
for (const dominio of ['tea', 'cacu', 'cama']) {
it(`navega directamente al dominio ${dominio} y conserva la ruta compartida diferida`, async () => {
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] });
const harness = await RouterTestingHarness.create();
const page = await harness.navigateByUrl(`/indicadores/${dominio}`, IndicadoresPage);
expect(page.dominio).toBe(dominio);
const http = TestBed.inject(HttpTestingController);
http.expectOne(`/${dominio}/indicadores`).flush([]);
expect(harness.routeNativeElement?.querySelectorAll('nav a').length).toBe(3);
http.verify();
});
}
it('cancela catálogos pendientes durante navegación rápida entre dominios', async () => {
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] });
const harness = await RouterTestingHarness.create();
const http = TestBed.inject(HttpTestingController);
await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
const tea = http.expectOne('/tea/indicadores');
await harness.navigateByUrl('/indicadores/cacu', IndicadoresPage);
const cacu = http.expectOne('/cacu/indicadores');
const page = await harness.navigateByUrl('/indicadores/cama', IndicadoresPage);
expect(tea.cancelled).toBe(true);
expect(cacu.cancelled).toBe(true);
expect(() => tea.flush([])).toThrow();
http.expectOne('/cama/indicadores').flush([]);
expect(page.dominio).toBe('cama');
expect(page.catalog()).toEqual([]);
http.verify();
});
+63 -2
View File
@@ -1,8 +1,69 @@
import { Routes } from '@angular/router';
import { Home } from './home';
import { authGuard } from './auth/auth.guard';
import { dominioGuard } from './auth/dominio.guard';
import { DOMINIOS } from './features/indicadores/indicadores.models';
const loadIndicadores = () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage);
export const routes: Routes = [
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
...DOMINIOS.map(dominio => ({ path: `indicadores/${dominio}`, data: { dominio }, loadComponent: loadIndicadores })),
{
path: 'login',
title: 'Inicio de sesión | ISSSTELEON',
loadComponent: () => import('./auth/login-page').then((m) => m.LoginPage),
// Sin encabezado ni pie: la pantalla ocupa la ventana completa.
data: { sinCromo: true },
},
{
// Todo lo demás vive detrás de la sesión; el guard corre en cada ruta hija.
path: '',
canActivateChild: [authGuard],
children: [
{ path: '', component: Home, title: 'Análisis de información | ISSSTELEON' },
{
path: 'indicadores/tea-estatus',
title: 'Casos por estatus | ISSSTELEON',
loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage),
canActivate: [dominioGuard],
data: { workspace: true, breadcrumb: 'Casos por estatus', dominio: 'tea' },
},
{
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: 'bitacora',
title: 'Bitácora de cargas | ISSSTELEON',
loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage),
data: { workspace: true, breadcrumb: 'Bitácora de cargas' },
},
{
path: 'kpis',
title: 'Indicadores | ISSSTELEON',
loadComponent: () => import('./features/indicadores/kpis-page').then(m => m.KpisPage),
// The page reads CaCu's measures: an account of another domain goes to its own.
canActivate: [dominioGuard],
data: { workspace: true, breadcrumb: 'Indicadores', dominio: 'cacu' },
},
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
...DOMINIOS.map(dominio => ({
path: `indicadores/${dominio}`,
title: 'Indicadores | ISSSTELEON',
data: { workspace: true, breadcrumb: 'Indicadores', dominio },
canActivate: [dominioGuard],
loadComponent: loadIndicadores,
})),
{ path: '**', redirectTo: '' },
],
},
];
+160 -91
View File
@@ -1,109 +1,178 @@
:host {
display: block;
min-height: 100%;
}
.institutional-header {
position: sticky;
top: 0;
z-index: 100;
background: var(--issste-surface);
border-bottom: 3px solid var(--issste-logo-lime);
}
.header-content {
.app-shell {
display: flex;
align-items: center;
gap: var(--issste-space-4);
box-sizing: border-box;
min-height: 69px;
max-width: 1488px;
margin-inline: auto;
padding-inline: var(--issste-page-gutter);
flex-direction: column;
min-height: 100vh;
min-height: 100dvh;
}
.institutional-logo {
.site-header {
background: var(--color-surface);
border-bottom: 1px solid var(--color-border);
}
.site-header__content {
align-items: center;
display: flex;
justify-content: space-between;
min-height: var(--site-header-height);
padding: 0 clamp(32px, 3.2vw, 48px);
}
.brand {
align-items: center;
display: inline-flex;
}
.brand img {
display: block;
flex: 0 0 auto;
width: 200px;
height: auto;
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;
}
.app-main {
display: flex;
flex: 1;
min-height: 0;
}
.app-shell--workspace {
height: 100dvh;
overflow: hidden;
}
.site-footer {
background: var(--color-text-secondary);
}
.site-footer__content {
align-items: center;
display: flex;
justify-content: center;
min-height: 86px;
padding: 0 clamp(32px, 3.2vw, 48px);
}
.site-footer img {
display: block;
filter: brightness(0) invert(1);
height: auto;
width: clamp(160px, 15vw, 185px);
}
@media (max-width: 600px) {
.site-header__content {
min-height: var(--site-header-height);
padding: 0 20px;
}
.brand img {
width: clamp(132px, 42vw, 170px);
}
.site-footer__content {
min-height: 76px;
padding: 0 20px;
}
.site-footer img {
width: 155px;
}
}
.platform-title {
color: var(--issste-text);
color: var(--color-text);
font-family: var(--issste-font-heading);
font-size: 1.5rem;
font-weight: 600;
font-size: 1.25rem;
font-weight: 500;
line-height: 1.15;
margin-inline-start: var(--issste-space-4);
margin-inline-end: auto;
overflow-wrap: anywhere;
}
main {
padding: var(--issste-space-4) var(--issste-page-gutter) 5.5rem;
scroll-margin-top: var(--issste-header-clearance);
.domain-selector--espera {
align-items: center; border-radius: var(--issste-radius); box-sizing: border-box; display: inline-flex; flex: 0 0 auto;
max-width: 100%; background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; line-height: 1.2;
min-height: 40px; padding: 0 16px; white-space: nowrap;
}
.skip-link {
position: fixed;
top: var(--issste-space-2);
left: var(--issste-page-gutter);
z-index: 101;
transform: translateY(-200%);
padding: var(--issste-space-2) var(--issste-space-3);
color: var(--issste-surface);
background: var(--issste-text);
border-radius: var(--issste-radius);
}
.skip-link:focus {
transform: translateY(0);
}
@media (max-width: 550px) {
.header-content {
gap: var(--issste-space-2);
min-height: 64px;
}
.institutional-logo {
width: 145px;
}
.platform-title {
font-size: 1.125rem;
}
}
@media (max-width: 359px) {
.header-content {
flex-wrap: wrap;
justify-content: center;
padding-block: var(--issste-space-2);
gap: var(--issste-space-1);
}
.platform-title {
flex-basis: 100%;
text-align: center;
}
}
.back-to-top {
position: fixed;
right: max(var(--issste-page-gutter), env(safe-area-inset-right));
bottom: max(var(--issste-space-4), env(safe-area-inset-bottom));
z-index: 90;
display: grid;
place-items: center;
width: 48px;
height: 48px;
padding: 0;
border: 1px solid var(--issste-text);
border-radius: 50%;
background: var(--issste-text);
color: var(--issste-surface);
/* Session exit: the same action look as the home buttons, in header size. */
.site-header__salir {
align-items: center;
background: transparent;
border: 1px solid var(--color-action);
border-radius: 8px;
color: var(--color-text);
cursor: pointer;
display: inline-flex;
flex: none;
font: inherit;
font-size: 13px;
font-weight: 600;
gap: 6px;
margin-inline-start: var(--space-4);
min-height: 34px;
padding: 0 var(--space-3);
transition:
background-color 0.2s ease,
border-color 0.2s ease,
color 0.2s ease;
}
.back-to-top:hover { background: var(--issste-text-secondary); }
.back-to-top:focus-visible { outline: 3px solid var(--issste-text); outline-offset: 4px; }
.site-header__salir:hover {
background: var(--color-action-hover);
border-color: var(--color-action);
}
.site-header__salir:focus-visible {
outline: 2px solid var(--color-action);
outline-offset: 2px;
}
.site-header__salir mat-icon {
color: var(--color-action);
font-size: 18px;
height: 18px;
width: 18px;
}
// Full domain names need their own track. On a wide header they sit beside the title;
// below 900px the name takes a row of its own so the logo and the exit stay together.
.app-shell--indicadores .site-header__content {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto auto;
grid-template-areas: "brand title domain salir";
align-items: center;
column-gap: 16px;
row-gap: 8px;
padding-block: 8px;
}
.app-shell--indicadores .brand { grid-area: brand; }
.app-shell--indicadores .platform-title { grid-area: title; margin: 0; overflow-wrap: normal; }
.app-shell--indicadores .domain-selector,
.app-shell--indicadores .domain-selector--espera { grid-area: domain; justify-self: end; }
.app-shell--indicadores .site-header__salir { grid-area: salir; margin-inline-start: 0; }
@media (max-width: 900px) {
.app-shell--indicadores .site-header__content {
grid-template-columns: auto minmax(0, 1fr);
grid-template-areas:
"brand salir"
"domain domain"
"title title";
}
.app-shell--indicadores .domain-selector,
.app-shell--indicadores .domain-selector--espera { justify-self: start; white-space: normal; }
.app-shell--indicadores .platform-title { font-size: 1.125rem; }
}
+109 -104
View File
@@ -1,121 +1,126 @@
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { provideRouter, Router } from '@angular/router';
import { of } from 'rxjs';
import { App } from './app';
import { routes } from './app.routes';
import { AuthService, Usuario } from './auth/auth.service';
describe('App — UX-06B', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [App],
providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()],
}).compileComponents();
});
const TODOS: Usuario = { usuario: 'admin', nombre: 'Administrador', dominios: ['cacu', 'cama', 'tea'] };
function render() {
/**
* Doble de la sesión: `App` lee la señal y los guards preguntan si hay sesión y
* qué dominios alcanza. Las pruebas de este archivo cubren el marco, no el
* inicio de sesión en sí (`auth/auth.service.spec.ts`).
*/
function authFalso(sesion: Usuario | null) {
return {
usuario: signal(sesion),
autenticado: signal(sesion !== null),
sesion: () => of(sesion),
puedeVer: (dominio: string) => sesion?.dominios.includes(dominio) ?? false,
logout: () => of(undefined),
limpiar: () => undefined,
};
}
async function montar(sesion: Usuario | null): Promise<Router> {
await TestBed.configureTestingModule({
imports: [App],
providers: [
provideRouter(routes),
provideHttpClient(),
provideHttpClientTesting(),
{ provide: AuthService, useValue: authFalso(sesion) },
],
}).compileComponents();
return TestBed.inject(Router);
}
describe('App', () => {
async function render(url: string) {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
return fixture;
await TestBed.inject(Router).navigateByUrl(url).catch(() => false);
await fixture.whenStable();
fixture.detectChanges();
return fixture.nativeElement as HTMLElement;
}
it('should create the app', () => {
expect(render().componentInstance).toBeTruthy();
describe('con sesión de administrador', () => {
beforeEach(() => montar(TODOS));
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('home shows only the brand name as eyebrow and names the risk models action', async () => {
// Fails if the eyebrow regains the section text or the action goes back to «Indicadores».
const page = await render('/');
expect(page.querySelector('.home__eyebrow')?.textContent?.trim()).toBe('ISSSTELEON');
const acciones = Array.from(page.querySelectorAll('.home__action')).map(a => a.textContent?.replace(/\s+/g, ' ').trim());
expect(acciones.some(t => t?.endsWith('Modelos predictivos de riesgo'))).toBe(true);
expect(acciones.some(t => t?.endsWith('Indicadores'))).toBe(false);
});
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();
}, 15000);
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();
});
it('el encabezado nombra al usuario de la sesión y ofrece cerrarla', async () => {
// Fails if the shell forgets the session: the user would have no way out.
const page = await render('/');
expect(page.querySelector('.site-header__salir')?.textContent).toContain('Administrador');
});
});
it('renders one institutional header and the platform identification', () => {
const element = render().nativeElement as HTMLElement;
expect(element.querySelectorAll('header')).toHaveLength(1);
expect(element.querySelector('header')?.textContent).toContain('Plataforma de Indicadores');
describe('con una cuenta de un solo dominio', () => {
beforeEach(() => montar({ usuario: 'cacu', nombre: 'Equipo CaCu', dominios: ['cacu'] }));
it('no deja abrir el dominio ajeno: la manda al suyo', async () => {
// Fails if the domain scope exists only on the server: the interface would show an empty page.
await render('/indicadores/cama');
expect(TestBed.inject(Router).url).toBe('/indicadores/cacu');
}, 15000);
it('el encabezado no ofrece los otros dominios', async () => {
const page = await render('/indicadores/cacu');
expect(page.querySelector('app-domain-selector')).toBeNull();
expect(page.querySelector('.domain-selector--espera')?.textContent).toContain('Cáncer cervicouterino');
});
});
it('uses the authorized static logo with alternative text and intrinsic proportions', () => {
const logo = (render().nativeElement as HTMLElement).querySelector('header img');
expect(logo?.getAttribute('src')).toBe('images/LogoISSSTELEON.png');
expect(logo?.getAttribute('alt')).toBe('ISSSTELEON');
expect(logo?.getAttribute('width')).toBe('1125');
expect(logo?.getAttribute('height')).toBe('358');
});
describe('sin sesión', () => {
beforeEach(() => montar(null));
it('keeps the routed content inside a main landmark and a keyboard skip target', () => {
const element = render().nativeElement as HTMLElement;
const main = element.querySelector('main#contenido-principal');
expect(main?.querySelector('router-outlet')).toBeTruthy();
expect(main?.getAttribute('tabindex')).toBe('-1');
expect(element.querySelector('a.skip-link')?.getAttribute('href')).toBe('#contenido-principal');
});
it('cualquier ruta manda al inicio de sesión y no muestra el marco', async () => {
const page = await render('/conectar');
expect(TestBed.inject(Router).url).toContain('/login');
expect(page.querySelector('.login')).not.toBeNull();
expect(page.querySelector('.site-header')).toBeNull();
expect(page.querySelector('.site-footer')).toBeNull();
expect(page.querySelector('app-connect-page')).toBeNull();
});
it('does not duplicate domain navigation or introduce shell HTTP requests', () => {
const fixture = render();
fixture.detectChanges();
const element = fixture.nativeElement as HTMLElement;
expect(element.querySelector('nav')).toBeNull();
expect(element.querySelectorAll('[routerLink]')).toHaveLength(0);
TestBed.inject(HttpTestingController).expectNone(() => true);
TestBed.inject(HttpTestingController).verify();
});
});
describe('App — UX-06D volver al inicio', () => {
let scrollY: number;
beforeEach(() => {
scrollY = 0;
vi.spyOn(window, 'scrollY', 'get').mockImplementation(() => scrollY);
TestBed.configureTestingModule({ imports: [App], providers: [provideRouter([])] });
});
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); });
function render() {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
return fixture;
}
function scroll(fixture: ReturnType<typeof render>, position: number) {
scrollY = position;
window.dispatchEvent(new Event('scroll'));
fixture.detectChanges();
}
it('oculta al inicio y en el umbral, muestra después y vuelve a ocultar al subir', () => {
const fixture = render();
expect(fixture.nativeElement.querySelector('.back-to-top')).toBeNull();
scroll(fixture, 400);
expect(fixture.nativeElement.querySelector('.back-to-top')).toBeNull();
scroll(fixture, 401);
expect(fixture.nativeElement.querySelector('.back-to-top')).not.toBeNull();
scroll(fixture, 0);
expect(fixture.nativeElement.querySelector('.back-to-top')).toBeNull();
});
it('reconoce una posición restaurada al montar el shell', () => {
scrollY = 900;
expect(render().nativeElement.querySelector('.back-to-top')).not.toBeNull();
});
it.each([false, true])('activa un botón nativo y respeta movimiento reducido=%s', reduced => {
const matchMedia = vi.fn().mockReturnValue({ matches: reduced } as MediaQueryList);
vi.stubGlobal('matchMedia', matchMedia);
const scrollTo = vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
const fixture = render();
scroll(fixture, 900);
const button = fixture.nativeElement.querySelector('.back-to-top') as HTMLButtonElement;
const main = fixture.nativeElement.querySelector('main') as HTMLElement;
const focus = vi.spyOn(main, 'focus');
expect(button.type).toBe('button');
expect(button.tabIndex).toBe(0);
expect(button.getAttribute('aria-label')).toBe('Volver al inicio');
expect(button.querySelector('svg')?.getAttribute('aria-hidden')).toBe('true');
button.click();
expect(matchMedia).toHaveBeenCalledWith('(prefers-reduced-motion: reduce)');
expect(scrollTo).toHaveBeenCalledWith({ top: 0, behavior: reduced ? 'instant' : 'smooth' });
expect(focus).toHaveBeenCalledWith({ preventScroll: true });
// Native Enter/Space activation is checked in Chrome, not emulated by jsdom.
});
it('registra un listener pasivo y elimina exactamente el mismo al destruir', () => {
const add = vi.spyOn(window, 'addEventListener');
const remove = vi.spyOn(window, 'removeEventListener');
const fixture = render();
const registration = add.mock.calls.find(call => call[0] === 'scroll')!;
expect(registration[2]).toEqual({ passive: true });
fixture.destroy();
expect(remove).toHaveBeenCalledWith('scroll', registration[1]);
scrollY = 900;
window.dispatchEvent(new Event('scroll'));
expect(fixture.componentInstance.showBackToTop()).toBe(false);
it('el destino pedido viaja en returnUrl para volver después de entrar', async () => {
await render('/gobernanza');
expect(TestBed.inject(Router).url).toContain('returnUrl=%2Fgobernanza');
});
});
});
+54 -23
View File
@@ -1,33 +1,64 @@
import { DOCUMENT } from '@angular/common';
import { Component, ElementRef, inject, OnDestroy, OnInit, signal, ViewChild } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { Component, computed, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { MatIconModule } from '@angular/material/icon';
import { ActivatedRoute, NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router';
import { filter, map } from 'rxjs';
import { AuthService } from './auth/auth.service';
import { DomainSelector } from './domain-selector';
import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models';
@Component({
imports: [RouterOutlet],
imports: [MatIconModule, RouterLink, RouterOutlet, DomainSelector],
selector: 'app-root',
styleUrl: './app.scss',
templateUrl: './app.html',
})
export class App implements OnInit, OnDestroy {
export class App {
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
private readonly auth = inject(AuthService);
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<string, unknown> },
);
/** 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);
/** The login screen (`data.sinCromo`) owns the whole window: no header, no footer. */
readonly sinCromo = computed(() => !!this.leafRouteData()['sinCromo']);
protected readonly usuario = this.auth.usuario;
protected readonly title = 'Plataforma de Indicadores';
readonly showBackToTop = signal(false);
@ViewChild('mainContent') private mainContent?: ElementRef<HTMLElement>;
private readonly browserWindow = inject(DOCUMENT).defaultView;
private readonly updateScroll = () => this.showBackToTop.set((this.browserWindow?.scrollY ?? 0) > 400);
protected readonly domainLabels: Record<Dominio, string> = {
tea: 'Trastorno del espectro autista', cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama',
};
private readonly url = toSignal(this.router.events.pipe(
filter((event) => event instanceof NavigationEnd), map(event => event.urlAfterRedirects)), { initialValue: this.router.url });
/** On an indicators page the header names its domain and switches to the others. */
protected readonly activeDomain = computed(() =>
DOMINIOS.find(domain => new RegExp(`^/indicadores/${domain}(?:[/?#]|$)`).test(this.url())));
/** Only the domains the account may see: the header never offers a forbidden one. */
private readonly permitidos = computed<readonly Dominio[]>(() => {
const sesion = this.auth.usuario();
return sesion ? DOMINIOS.filter(dominio => sesion.dominios.includes(dominio)) : DOMINIOS;
});
protected readonly otherDomains = computed(() =>
this.permitidos().filter(domain => domain !== this.activeDomain()));
ngOnInit() {
this.updateScroll();
this.browserWindow?.addEventListener('scroll', this.updateScroll, { passive: true });
}
backToTop() {
const reducedMotion = this.browserWindow?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
// Keep keyboard focus near the destination when the floating button disappears.
this.mainContent?.nativeElement.focus({ preventScroll: true });
this.browserWindow?.scrollTo({ top: 0, behavior: reducedMotion ? 'instant' : 'smooth' });
}
ngOnDestroy() {
this.browserWindow?.removeEventListener('scroll', this.updateScroll);
protected salir(): void {
// Whether the server session was already gone, the browser ends up at the login screen.
this.auth.logout().subscribe({
next: () => void this.router.navigate(['/login']),
error: () => void this.router.navigate(['/login']),
});
}
}
+22
View File
@@ -0,0 +1,22 @@
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { map } from 'rxjs';
import { AuthService } from './auth.service';
/**
* Sin sesión no hay ruta protegida: se manda al inicio de sesión y se recuerda
* `returnUrl` para volver a donde iba el usuario.
*/
export const authGuard: CanActivateFn = (_ruta, estado) => {
const auth = inject(AuthService);
const router = inject(Router);
return auth
.sesion()
.pipe(
map(
(usuario) =>
usuario !== null ||
router.createUrlTree(['/login'], { queryParams: { returnUrl: estado.url } }),
),
);
};
+60
View File
@@ -0,0 +1,60 @@
// La sesión vive en el navegador (la WebApi no autentica): estas pruebas fijan
// el contrato del servicio —quién entra, qué dominios ve y qué queda guardado—
// porque de él dependen el guard de rutas y el recorte de los selectores.
import { TestBed } from '@angular/core/testing';
import { AuthService } from './auth.service';
describe('AuthService', () => {
let auth: AuthService;
beforeEach(() => {
sessionStorage.clear();
TestBed.configureTestingModule({});
auth = TestBed.inject(AuthService);
});
it('entra con la contraseña correcta y deja al usuario en la señal', () => {
auth.login('cama', 'cama2026').subscribe();
expect(auth.usuario()).toEqual({ usuario: 'cama', nombre: 'Equipo CaMa', dominios: ['cama'] });
expect(auth.autenticado()).toBe(true);
});
it('rechaza una contraseña incorrecta sin abrir sesión', () => {
let error: Error | undefined;
auth.login('cama', 'otra').subscribe({ error: (e: Error) => (error = e) });
expect(error?.message).toContain('incorrectos');
expect(auth.autenticado()).toBe(false);
});
it('dice qué dominios puede ver la cuenta', () => {
auth.login('cama', 'cama2026').subscribe();
expect(auth.puedeVer('cama')).toBe(true);
expect(auth.puedeVer('cacu')).toBe(false);
expect(auth.puedeVer('tea')).toBe(false);
});
it('el administrador ve los tres dominios', () => {
auth.login('admin', 'admin2026').subscribe();
expect(['cacu', 'cama', 'tea'].every((dominio) => auth.puedeVer(dominio))).toBe(true);
});
it('cerrar sesión borra al usuario y lo guardado', () => {
auth.login('tea', 'tea2026').subscribe();
auth.logout().subscribe();
expect(auth.autenticado()).toBe(false);
expect(sessionStorage.getItem('isssteleon.sesion')).toBeNull();
});
it('la sesión sobrevive a una recarga de la pestaña', () => {
// Fails if the login is kept only in memory: a refresh would log the team out mid-task.
auth.login('cacu', 'cacu2026').subscribe();
TestBed.resetTestingModule();
TestBed.configureTestingModule({});
expect(TestBed.inject(AuthService).usuario()?.usuario).toBe('cacu');
});
});
+91
View File
@@ -0,0 +1,91 @@
import { Injectable, computed, signal } from '@angular/core';
import { Observable, of, throwError } from 'rxjs';
/** El usuario de la sesión, con los dominios que la interfaz le deja ver. */
export interface Usuario {
readonly usuario: string;
readonly nombre: string;
readonly dominios: readonly string[];
}
/**
* Cuentas de la interfaz. La WebApi no tiene autenticación: el inicio de sesión
* y el recorte por dominio viven aquí, en el navegador, para ordenar el trabajo
* de cada equipo. No son seguridad: cualquiera puede leer esta lista en el
* paquete de la aplicación y la API responde a quien la llame.
*/
const CUENTAS: readonly (Usuario & { contrasena: string })[] = [
{ usuario: 'admin', contrasena: 'admin2026', nombre: 'Administrador', dominios: ['cacu', 'cama', 'tea'] },
{ usuario: 'cacu', contrasena: 'cacu2026', nombre: 'Equipo CaCu', dominios: ['cacu'] },
{ usuario: 'cama', contrasena: 'cama2026', nombre: 'Equipo CaMa', dominios: ['cama'] },
{ usuario: 'tea', contrasena: 'tea2026', nombre: 'Equipo TEA', dominios: ['tea'] },
];
/** La sesión se guarda por pestaña: cerrar el navegador pide entrar de nuevo. */
const CLAVE = 'isssteleon.sesion';
/**
* Sesión local de la aplicación. Es la única fuente de verdad del usuario: el
* guard pregunta aquí, los paneles filtran dominios con `puedeVer` y salir solo
* borra el registro del navegador.
*/
@Injectable({ providedIn: 'root' })
export class AuthService {
private readonly usuarioActual = signal<Usuario | null>(this.leer());
readonly usuario = this.usuarioActual.asReadonly();
readonly autenticado = computed(() => this.usuarioActual() !== null);
/** Si la cuenta puede ver ese dominio. Sin sesión no se opina (los guards deciden). */
puedeVer(dominio: string): boolean {
const sesion = this.usuarioActual();
return sesion ? sesion.dominios.includes(dominio) : true;
}
/** La sesión guardada en esta pestaña; se resuelve al instante, sin servidor. */
sesion(): Observable<Usuario | null> {
return of(this.usuarioActual());
}
/** Valida contra la lista local; un error marca las credenciales como incorrectas. */
login(usuario: string, contrasena: string): Observable<Usuario> {
const cuenta = CUENTAS.find((c) => c.usuario === usuario.trim() && c.contrasena === contrasena);
if (!cuenta) return throwError(() => new Error('usuario o contraseña incorrectos'));
const sesion: Usuario = { usuario: cuenta.usuario, nombre: cuenta.nombre, dominios: [...cuenta.dominios] };
this.establecer(sesion);
return of(sesion);
}
logout(): Observable<void> {
this.limpiar();
return of(undefined);
}
limpiar(): void {
this.usuarioActual.set(null);
try {
sessionStorage.removeItem(CLAVE);
} catch {
// Almacenamiento deshabilitado: la sesión dura lo que la pestaña en memoria.
}
}
private establecer(sesion: Usuario): void {
this.usuarioActual.set(sesion);
try {
sessionStorage.setItem(CLAVE, JSON.stringify(sesion));
} catch {
// Idem: sin almacenamiento, la sesión no sobrevive a una recarga.
}
}
private leer(): Usuario | null {
try {
const crudo = sessionStorage.getItem(CLAVE);
if (!crudo) return null;
const sesion = JSON.parse(crudo) as Usuario;
return typeof sesion?.usuario === 'string' && Array.isArray(sesion.dominios) ? sesion : null;
} catch {
return null;
}
}
}
+17
View File
@@ -0,0 +1,17 @@
import { Usuario } from './auth.service';
/** Same key AuthService persists the visual session under. */
const CLAVE_SESION = 'isssteleon.sesion';
/**
* Seeds the browser-only visual session before the router and AuthService are created,
* so routes behind authGuard render instead of redirecting to /login. Pair every call
* with `limpiarSesionVisual()` in afterEach so the session never leaks between tests.
*/
export function iniciarSesionVisual(sesion: Usuario = { usuario: 'admin', nombre: 'Administrador', dominios: ['cacu', 'cama', 'tea'] }): void {
sessionStorage.setItem(CLAVE_SESION, JSON.stringify(sesion));
}
export function limpiarSesionVisual(): void {
sessionStorage.removeItem(CLAVE_SESION);
}
+22
View File
@@ -0,0 +1,22 @@
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { map } from 'rxjs';
import { AuthService } from './auth.service';
/**
* Cada cuenta ve solo sus dominios: una ruta con `data.dominio` ajeno manda a la
* cuenta a su primer dominio. Sin sesión no decide nada (`authGuard` ya la
* mandó al inicio de sesión).
*/
export const dominioGuard: CanActivateFn = (ruta) => {
const auth = inject(AuthService);
const router = inject(Router);
const pedido = ruta.data?.['dominio'] as string | undefined;
return auth.sesion().pipe(
map((usuario) => {
if (!usuario || !pedido || usuario.dominios.includes(pedido)) return true;
const propio = usuario.dominios[0];
return propio ? router.createUrlTree(['/indicadores', propio]) : router.createUrlTree(['/']);
}),
);
};
+27
View File
@@ -0,0 +1,27 @@
import { AuthService } from './auth.service';
/**
* Helpers for the screens that list domains (cargar información, gobernanza):
* an account only ever sees its own, and «Todos» only belongs to one that
* reaches every domain — the administrator.
*/
/** De la lista dada, las entradas cuyo dominio alcanza la cuenta. */
export function dominiosPermitidos<T extends { id: string }>(auth: AuthService, dominios: readonly T[]): T[] {
return dominios.filter((dominio) => auth.puedeVer(dominio.id));
}
/** Si la cuenta alcanza todos: solo entonces tiene sentido ofrecer «Todos». */
export function alcanzaTodos(auth: AuthService, dominios: readonly { id: string }[]): boolean {
return dominios.every((dominio) => auth.puedeVer(dominio.id));
}
/**
* El dominio con el que abre una pantalla: el único que alcanza la cuenta, o
* `null` («Todos») cuando alcanza varios. Sin sesión resuelta devuelve `null`,
* que es el comportamiento de siempre.
*/
export function dominioInicial<T extends string>(auth: AuthService, dominios: readonly { id: T }[]): T | null {
const propios = dominiosPermitidos(auth, dominios);
return propios.length === 1 ? propios[0].id : null;
}
+59
View File
@@ -0,0 +1,59 @@
<section class="login" aria-labelledby="login-titulo">
<div class="login__caja">
<img class="login__logo" src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
<h1 class="login__titulo" id="login-titulo">Inicio de sesión</h1>
<form class="login__formulario" (ngSubmit)="ingresar()" novalidate>
<mat-form-field appearance="outline" class="login__campo" subscriptSizing="dynamic">
<input
matInput
name="usuario"
[(ngModel)]="usuario"
placeholder="Usuario"
aria-label="Usuario"
autocomplete="username"
autocapitalize="none"
spellcheck="false"
/>
</mat-form-field>
<mat-form-field appearance="outline" class="login__campo" subscriptSizing="dynamic">
<input
matInput
name="contrasena"
[(ngModel)]="contrasena"
[type]="verContrasena() ? 'text' : 'password'"
placeholder="Contraseña"
aria-label="Contraseña"
autocomplete="current-password"
/>
<button
mat-icon-button
matSuffix
type="button"
class="login__ojo"
(click)="mostrarContrasena()"
[attr.aria-label]="verContrasena() ? 'Ocultar contraseña' : 'Mostrar contraseña'"
[attr.aria-pressed]="verContrasena()"
>
<mat-icon>{{ verContrasena() ? 'visibility_off' : 'visibility' }}</mat-icon>
</button>
</mat-form-field>
@if (error(); as mensaje) {
<p class="login__error" role="alert">{{ mensaje }}</p>
}
<button
type="submit"
class="login__ingresar"
[disabled]="!usuario.trim() || !contrasena || enviando()"
>
{{ enviando() ? 'Ingresando…' : 'Ingresar' }}
</button>
</form>
<p class="login__legal">©{{ anio }} Todos los derechos reservados.</p>
</div>
</section>
+170
View File
@@ -0,0 +1,170 @@
:host {
display: flex;
flex: 1;
min-width: 0;
/* The button borrows the home actions' palette: white with a thin gray border
until the form is complete, then `--color-action` (see styles.scss). */
--login-fondo: #f8f9fa;
--login-borde: #e9ecef;
}
.login {
align-items: center;
display: flex;
flex: 1;
justify-content: center;
/* The whole block sits a little below the middle: the logo above it gives the screen its weight. */
padding: var(--space-9) var(--space-5) var(--space-8);
}
.login__caja {
display: flex;
flex-direction: column;
gap: var(--space-4);
max-width: 340px;
width: 100%;
}
/* The brand opens the screen and is the biggest thing on it: it is what fills the empty space. */
.login__logo {
align-self: center;
display: block;
margin-bottom: 0;
width: 260px;
animation: login-logo-entrada 600ms ease-out both;
}
@keyframes login-logo-entrada {
from {
opacity: 0;
transform: translateY(-8px);
}
to {
opacity: 1;
transform: none;
}
}
@media (prefers-reduced-motion: reduce) {
.login__logo {
animation: none;
}
}
.login__titulo {
align-items: center;
color: var(--color-text);
display: flex;
font-family: var(--font-heading);
font-size: 1.375rem;
font-weight: 600;
gap: var(--space-4);
margin: 0 0 var(--space-2);
white-space: nowrap;
}
/* The two rules that flank the title, as in the reference screen. */
.login__titulo::before,
.login__titulo::after {
background: var(--color-border);
content: '';
flex: 1;
height: 1px;
}
.login__formulario {
display: flex;
flex-direction: column;
gap: var(--space-3);
}
.login__campo {
width: 100%;
--mat-form-field-container-height: 44px;
--mat-form-field-container-vertical-padding: 12px;
}
.login__ojo {
color: var(--color-text-secondary);
}
/* Edge paints its own reveal control over the password field; the eye in the field is ours. */
.login__campo input::-ms-reveal,
.login__campo input::-ms-clear {
display: none;
}
.login__error {
color: var(--mat-sys-error);
font-size: 0.875rem;
margin: calc(-1 * var(--space-1)) 0 0;
}
/* The button shares the fields' width: one column, one border, no icon and no underline.
Its border turns teal when the form is complete, and it fades in instead of switching. */
.login__ingresar {
align-items: center;
background: var(--login-fondo);
border: 1px solid var(--login-borde);
border-radius: 10px;
color: var(--color-text-secondary);
cursor: default;
display: flex;
font: inherit;
font-size: 0.9375rem;
font-weight: 500;
justify-content: center;
margin-top: var(--space-2);
min-height: 46px;
padding: 0 var(--space-5);
text-decoration: none;
transition:
background-color 260ms ease,
border-color 260ms ease,
color 260ms ease;
width: 100%;
}
.login__ingresar:not(:disabled) {
border-color: var(--color-action);
color: var(--color-text);
cursor: pointer;
}
.login__ingresar:hover:not(:disabled) {
background: var(--color-action-hover);
border-color: var(--color-action);
}
.login__ingresar:focus-visible {
outline: 2px solid var(--color-action);
outline-offset: 2px;
}
.login__ingresar:disabled {
background: var(--login-fondo);
border-color: var(--login-borde);
}
.login__legal {
color: var(--color-text-secondary);
font-size: 0.8125rem;
margin: var(--space-4) 0 0;
text-align: center;
}
@media (max-width: 600px) {
.login {
padding: var(--space-7) var(--space-4);
}
.login__caja {
max-width: 100%;
}
.login__logo {
width: 208px;
}
}
+61
View File
@@ -0,0 +1,61 @@
import { Component, OnInit, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthService } from './auth.service';
/**
* Inicio de sesión: valida contra las cuentas locales de `AuthService` y, si el
* usuario ya tiene sesión, salta al destino. `returnUrl` lo pone el guard cuando
* una ruta protegida lo trajo aquí.
*/
@Component({
selector: 'app-login-page',
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
styleUrl: './login-page.scss',
templateUrl: './login-page.html',
})
export class LoginPage implements OnInit {
private readonly auth = inject(AuthService);
private readonly router = inject(Router);
private readonly ruta = inject(ActivatedRoute);
protected usuario = '';
protected contrasena = '';
protected readonly verContrasena = signal(false);
protected readonly enviando = signal(false);
protected readonly error = signal<string | null>(null);
protected readonly anio = new Date().getFullYear();
ngOnInit(): void {
// Quien ya inició sesión y abre /login vuelve derecho a la aplicación.
this.auth.sesion().subscribe((usuario) => {
if (usuario) void this.router.navigateByUrl(this.destino());
});
}
protected ingresar(): void {
if (!this.usuario.trim() || !this.contrasena || this.enviando()) return;
this.enviando.set(true);
this.error.set(null);
this.auth.login(this.usuario.trim(), this.contrasena).subscribe({
next: () => void this.router.navigateByUrl(this.destino()),
error: () => {
this.enviando.set(false);
this.error.set('Usuario o contraseña incorrectos.');
},
});
}
protected mostrarContrasena(): void {
this.verContrasena.update((visible) => !visible);
}
private destino(): string {
const pedido = this.ruta.snapshot.queryParamMap.get('returnUrl');
return pedido?.startsWith('/') && !pedido.startsWith('/login') ? pedido : '/';
}
}
+314
View File
@@ -0,0 +1,314 @@
/** 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<string, unknown>;
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<string, unknown>; kind: string }[];
source_metadata?: Record<string, unknown>;
/** Columns whose sampled cells hold files (PDF, images) that can be read as documents. */
document_columns?: string[];
}
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<string, unknown>;
}
/** One entry of `/imports/validate`'s `source` / `/imports/commit`'s `sources`. */
export interface ImportSourcePayload extends SourceLocator {
target: string;
label?: string;
column_mapping: Record<string, string>;
defaults?: Record<string, unknown>;
derived?: Record<string, DerivationRule>;
documents?: DocumentColumnsConfig;
/** Also store, on the patient, captions the documents print that the project's catalog already knows. */
catalog_fallback?: boolean;
}
// Derived fields and document columns
export type DerivationParamKind = 'column' | 'columns' | 'text' | 'integer' | 'mapping' | 'boolean';
export interface DerivationParam {
name: string;
kind: DerivationParamKind;
label: string;
required: boolean;
default: unknown;
}
/** One operation a derived field may use, as `/imports/derivations` lists it. */
export interface DerivationSpec {
op: string;
label: string;
description: string;
params: DerivationParam[];
}
export interface DerivationCatalog {
derivations: DerivationSpec[];
cases: string[];
}
/** `{op, ...params, case?}`: how one target field is computed from source columns. */
export type DerivationRule = { op: string; case?: string } & Record<string, unknown>;
/** A grouping or naming given as a column, a list of columns or a rule. */
export type ColumnRule = string | string[] | DerivationRule;
/** Which columns of a source hold documents, and how their records are formed. */
export interface DocumentColumnsConfig {
columns: string[];
group_by?: ColumnRule;
name_by?: ColumnRule;
file_field?: string;
segmentation?: string;
pages_per_record?: number;
ocr_mode?: OcrMode;
key_pattern?: string;
include_pattern?: string;
exclude_pattern?: string;
overrides?: Record<string, Record<string, unknown>>;
}
// Clinical documents
export type OcrMode = 'auto' | 'always' | 'never';
export interface DocumentSettings {
segmentation: string;
pages_per_record: number;
ocr_mode: OcrMode;
key_pattern: string;
/** Only documents whose text matches (regular expression, case and accents ignored). */
include_pattern?: string;
/** Documents whose text matches are left out. */
exclude_pattern?: string;
}
export interface ExtractedField {
value: unknown;
confidence: number;
/** etiqueta | patron | texto_libre | medicion | columna_fuente | manual */
method: string;
/** What the report says about the mention: afirmado, negado, incierto, hipotetico, historico, presuntivo. */
assertion?: string | null;
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<string, ExtractedField>;
missing: string[];
conflicts: { field: string; kept: ExtractedField; discarded: ExtractedField }[];
sources: { document: string; page_numbers: number[] }[];
images: DocumentImage[];
/** `false` when the pages only name another kind of study than the target's; `null` when they name none. */
on_topic?: boolean | null;
/** Per field, the other values the extractors proposed, best first. */
alternatives?: Record<string, ExtractedField[]>;
}
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[];
/** The extraction code's version and its ranker's, as stored with each row. */
nlp_version?: string;
}
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<string, number>;
/** Rows combined into a row of another source (`merge_duplicates`). */
merged?: number;
warnings?: RowError[];
}
export interface BatchResult {
ok: boolean;
results: CommitSourceResult[];
/** Id of this attempt in the aggregate import log (`/reportes/importaciones`). */
audit_id?: string;
indicadores_en_recalculo?: boolean;
}
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;
}
+18
View File
@@ -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<ConnectorInfo[]> {
return this.connectors$;
}
}
+15
View File
@@ -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/<target>: 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<DataPage> {
const params = new HttpParams().set('limit', limit).set('offset', offset);
return this.http.get<DataPage>(`/data/${encodeURIComponent(target)}`, { params });
}
}
@@ -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<string, unknown>, target: string): Observable<DocumentExtraction> {
return this.http.post<DocumentExtraction>('/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<Blob> {
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' });
}
}
+12
View File
@@ -0,0 +1,12 @@
/** Base64 of a File's bytes, for JSON endpoints that carry a file. */
export function fileToBase64(file: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const dataUrl = reader.result as string;
resolve(dataUrl.slice(dataUrl.indexOf(',') + 1));
};
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
}
+24
View File
@@ -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<PreviewResponse> {
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<PreviewResponse>('/imports/sources/file/preview', form);
}
/** Same payload an import source carries, e.g. several EDF files at once. */
previewPayload(kind: SourceType, payload: Record<string, unknown>, target: string | null): Observable<PreviewResponse> {
return this.http.post<PreviewResponse>(`/imports/sources/${kind}/preview`, { payload, ...(target ? { target } : {}) });
}
}
+48
View File
@@ -0,0 +1,48 @@
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, shareReplay } from 'rxjs';
import {
BatchResult,
ConflictStrategy,
DerivationCatalog,
ImportSourcePayload,
PreviewResponse,
Row,
ValidationResult,
} from './api.types';
/**
* POST /imports/validate (one source, writes nothing), POST /imports/commit
* (a batch, one transaction), the rows a source would write
* (POST /imports/mapped-preview), the columns documents add to a source
* (POST /imports/sources/document/columns) and the operations derived
* fields may use (GET /imports/derivations, fetched once).
*/
@Injectable({ providedIn: 'root' })
export class ImportsApi {
private readonly http = inject(HttpClient);
private catalog?: Observable<DerivationCatalog>;
derivations(): Observable<DerivationCatalog> {
this.catalog ??= this.http.get<DerivationCatalog>('/imports/derivations').pipe(shareReplay(1));
return this.catalog;
}
/** A source with document columns: its own columns plus every field and caption its documents print. */
documentColumns(source: ImportSourcePayload): Observable<PreviewResponse> {
return this.http.post<PreviewResponse>('/imports/sources/document/columns', { source });
}
mappedPreview(source: ImportSourcePayload, limit = 20): Observable<{ rows: Row[] }> {
return this.http.post<{ rows: Row[] }>('/imports/mapped-preview', { source, limit });
}
validate(source: ImportSourcePayload): Observable<ValidationResult> {
return this.http.post<ValidationResult>('/imports/validate', { source });
}
/** `mergeDuplicates`: rows of different sources with the same natural key become one record. */
commit(sources: ImportSourcePayload[], onConflict: ConflictStrategy, mergeDuplicates = false): Observable<BatchResult> {
return this.http.post<BatchResult>('/imports/commit', { sources, on_conflict: onConflict, merge_duplicates: mergeDuplicates });
}
}
+48
View File
@@ -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<PdfDetectResponse> {
const form = new FormData();
form.append('file', file);
return this.http.post<PdfDetectResponse>('/imports/sources/pdf/detect', form);
}
/** Raw PNG bytes; the caller turns them into an object URL. */
pageImage(file: File, pageNumber: number, dpi?: number): Observable<Blob> {
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<PreviewResponse> {
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<PreviewResponse>('/imports/sources/pdf/table/preview', form);
}
extractRegions(file: File, regions: RegionSpec[], target: string | null, dpi = 150): Observable<RegionExtractResponse> {
return from(fileToBase64(file)).pipe(
switchMap((file_base64) =>
this.http.post<RegionExtractResponse>('/imports/sources/pdf/regions/extract', {
file_base64,
regions,
dpi,
...(target ? { target } : {}),
}),
),
);
}
}
+18
View File
@@ -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);
}
+42
View File
@@ -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<string[]> {
return this.http.post<{ schemas: string[] }>('/imports/sources/sql/schemas', connection).pipe(map((response) => response.schemas));
}
tables(connection: SqlConnectionRef, schema?: string): Observable<string[]> {
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<SourceColumn[]> {
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<PreviewResponse> {
return this.http.post<PreviewResponse>('/imports/sources/sql/preview', {
...connection,
...(source.query ? { query: source.query } : { table: source.table, ...(source.schema ? { schema: source.schema } : {}) }),
...(target ? { target } : {}),
});
}
}
+20
View File
@@ -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<TargetMeta[]> {
return this.targets$;
}
}
@@ -0,0 +1,191 @@
@let f = flow();
@let s = summary();
<div class="mapper" cdkDropListGroup>
<section class="mapper__columns" aria-labelledby="source-columns-title">
<header class="mapper__header">
<h3 id="source-columns-title">Columnas de origen</h3>
<mat-button-toggle-group
hideSingleSelectionIndicator
[value]="onlyUnusedColumns()"
(change)="onlyUnusedColumns.set($event.value)"
aria-label="Filtrar columnas de origen"
>
<mat-button-toggle [value]="false">Todas ({{ f.sourceColumns().length }})</mat-button-toggle>
<mat-button-toggle [value]="true">Sin usar ({{ s.unused }})</mat-button-toggle>
</mat-button-toggle-group>
</header>
<div class="tray" cdkDropList [cdkDropListData]="'tray'" [cdkDropListEnterPredicate]="acceptsColumns" (cdkDropListDropped)="onDropOnTray($event)">
@for (column of columns(); track column.name) {
<div class="column-chip" [class.column-chip--used]="!!mappedTo(column.name)" cdkDrag [cdkDragData]="column.name">
<mat-icon class="column-chip__type" [matTooltip]="column.inferred_type | typeLabel" aria-hidden="true">{{
column.inferred_type | typeIcon
}}</mat-icon>
<span class="column-chip__text">
<span class="column-chip__name">{{ column.name }}</span>
<span class="column-chip__sample" [title]="samples().get(column.name) ?? ''">{{ samples().get(column.name) || '(vacío)' }}</span>
</span>
@if (mappedTo(column.name); as field) {
<span class="column-chip__target" [title]="'Asignada a ' + field">→ {{ field }}</span>
}
<mat-icon class="column-chip__grip" aria-hidden="true">drag_indicator</mat-icon>
<div *cdkDragPreview class="drag-preview">
<mat-icon aria-hidden="true">{{ column.inferred_type | typeIcon }}</mat-icon>{{ column.name }}
</div>
</div>
} @empty {
<p class="tray__empty">{{ onlyUnusedColumns() ? 'Todas las columnas están asignadas.' : 'La fuente no tiene columnas.' }}</p>
}
</div>
</section>
<section class="mapper__fields" aria-labelledby="target-fields-title">
<header class="mapper__header">
<h3 id="target-fields-title">Campos de {{ f.target.table }}</h3>
<span class="mapper__summary" aria-live="polite">
{{ s.covered }}/{{ s.total }} asignados
@if (s.missing > 0) {
· <strong class="mapper__missing">{{ s.missing }} obligatorio(s) sin asignar</strong>
}
</span>
</header>
<div class="mapper__toolbar">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="mapper__search">
<mat-icon matPrefix aria-hidden="true">search</mat-icon>
<mat-label>Buscar campo</mat-label>
<input matInput (input)="onSearch($event)" />
</mat-form-field>
<mat-button-toggle-group
hideSingleSelectionIndicator
[value]="fieldFilter()"
(change)="fieldFilter.set($event.value)"
aria-label="Filtrar campos de destino"
>
<mat-button-toggle value="all">Todos</mat-button-toggle>
<mat-button-toggle value="required">Obligatorios</mat-button-toggle>
<mat-button-toggle value="unassigned">Sin asignar</mat-button-toggle>
</mat-button-toggle-group>
<span class="mapper__spacer"></span>
@if (s.suggestions > 0) {
<button mat-stroked-button type="button" (click)="confirmAll()" matTooltip="Aceptar las asignaciones automáticas marcadas con %">
<mat-icon aria-hidden="true">done_all</mat-icon>Confirmar {{ s.suggestions }}
</button>
}
<button mat-stroked-button type="button" (click)="autoMap()" matTooltip="Asignar por nombre lo que siga libre">
<mat-icon aria-hidden="true">auto_fix_high</mat-icon>Auto-mapear
</button>
<button mat-button type="button" (click)="f.clearMapping()">
<mat-icon aria-hidden="true">layers_clear</mat-icon>Limpiar
</button>
</div>
@if (lastAutoMap() !== null) {
<p class="mapper__note" role="status">
{{ lastAutoMap() === 0 ? 'No se encontraron más coincidencias por nombre.' : 'Se asignaron ' + lastAutoMap() + ' campo(s).' }}
</p>
}
<div class="fields" role="list">
@for (field of fields(); track field.name) {
@let mapping = f.mapping.byField().get(field.name);
@let defaultValue = f.defaults()[field.name];
<div
class="field"
role="listitem"
[class.field--missing]="field.required && !mapping && !defaultValue"
[class.field--mapped]="!!mapping || !!defaultValue"
>
<div class="field__meta">
<mat-icon class="field__type" [matTooltip]="field.type | typeLabel" aria-hidden="true">{{ field.type | typeIcon }}</mat-icon>
<span class="field__name">{{ field.name }}</span>
@if (field.required) {
<span class="field__required" matTooltip="Obligatorio">*</span>
}
@if (errorsFor(field.name); as errors) {
<span class="field__errors" [matTooltip]="errors + ' fila(s) no pasan la validación en este campo'">
<mat-icon aria-hidden="true">report</mat-icon>{{ errors }}
</span>
}
</div>
<div
class="slot"
cdkDropList
[cdkDropListData]="field.name"
[cdkDropListEnterPredicate]="acceptsColumns"
(cdkDropListDropped)="onDropOnField($event)"
>
@if (mapping) {
<div class="slot__chip" [class.slot__chip--suggested]="mapping.confidence !== undefined" cdkDrag [cdkDragData]="mapping.source">
<mat-icon aria-hidden="true">drag_indicator</mat-icon>
<span class="slot__source" [title]="mapping.source">{{ mapping.source }}</span>
@if (mapping.confidence !== undefined) {
<span class="slot__confidence" [matTooltip]="'Sugerencia automática (' + mapping.reason + ')'">{{
confidenceLabel(mapping.confidence)
}}</span>
<button mat-icon-button type="button" class="slot__button" matTooltip="Confirmar" [attr.aria-label]="'Confirmar ' + field.name" (click)="f.confirmSuggestion(field.name)">
<mat-icon aria-hidden="true">check</mat-icon>
</button>
}
<button mat-icon-button type="button" class="slot__button" matTooltip="Quitar" [attr.aria-label]="'Quitar asignación de ' + field.name" (click)="f.unmapField(field.name)">
<mat-icon aria-hidden="true">close</mat-icon>
</button>
<div *cdkDragPreview class="drag-preview"><mat-icon aria-hidden="true">view_column</mat-icon>{{ mapping.source }}</div>
</div>
} @else {
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="slot__select">
<mat-select placeholder="Arrastra o elige una columna" [value]="null" (selectionChange)="pick(field.name, $event.value)" [attr.aria-label]="'Columna para ' + field.name">
@for (column of f.sourceColumns(); track column.name) {
<mat-option [value]="column.name">
{{ column.name }}
@if (mappedTo(column.name); as other) {
<span class="slot__option-note">(ahora en {{ other }})</span>
}
</mat-option>
}
</mat-select>
</mat-form-field>
}
</div>
<div class="field__default">
@if (editingDefault() === field.name) {
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="field__default-input">
<mat-label>Valor por defecto</mat-label>
<input
matInput
appAutofocus
#defaultInput
[value]="defaultValue ?? ''"
(keydown.enter)="saveDefault(field.name, defaultInput.value)"
(keydown.escape)="editingDefault.set(null)"
(blur)="saveDefault(field.name, defaultInput.value)"
/>
</mat-form-field>
} @else if (defaultValue) {
<mat-chip-set>
<mat-chip (removed)="f.setDefault(field.name, null)" (click)="editingDefault.set(field.name)" matTooltip="Se usa cuando la celda está vacía o no hay columna asignada">
= {{ defaultValue }}
<button matChipRemove [attr.aria-label]="'Quitar valor por defecto de ' + field.name"><mat-icon>cancel</mat-icon></button>
</mat-chip>
</mat-chip-set>
} @else {
<button
mat-icon-button
type="button"
class="field__default-button"
matTooltip="Valor por defecto"
[attr.aria-label]="'Valor por defecto para ' + field.name"
(click)="editingDefault.set(field.name)"
>
<mat-icon aria-hidden="true">edit_note</mat-icon>
</button>
}
</div>
</div>
} @empty {
<p class="fields__empty">Ningún campo coincide con el filtro.</p>
}
</div>
</section>
</div>
@@ -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;
}
}
@@ -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<string>;
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<string>);
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');
});
});
@@ -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<ImportFlow>();
readonly fieldFilter = signal<FieldFilter>('all');
readonly fieldSearch = signal('');
readonly onlyUnusedColumns = signal(false);
readonly editingDefault = signal<string | null>(null);
readonly lastAutoMap = signal<number | null>(null);
readonly acceptsColumns = (drag: CdkDrag) => typeof drag.data === 'string';
readonly fields = computed<TargetField[]>(() => {
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<SourceColumn[]>(() => {
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<string, string>();
for (const column of this.flow().sourceColumns()) {
const values = new Set<string>();
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<string>): void {
this.flow().map(event.item.data as string, event.container.data);
}
onDropOnTray(event: CdkDragDrop<string>): 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)}%`;
}
}
@@ -0,0 +1,87 @@
<div class="workspace">
<mat-toolbar class="workspace__toolbar">
<button mat-icon-button type="button" (click)="paneOpen.set(!paneOpen())" [attr.aria-label]="paneOpen() ? 'Ocultar conexiones' : 'Mostrar conexiones'">
<mat-icon aria-hidden="true">{{ paneOpen() ? 'menu_open' : 'menu' }}</mat-icon>
</button>
<div class="workspace__title">
<span class="workspace__eyebrow">Análisis de información</span>
<h1>Conectar datos</h1>
</div>
<mat-button-toggle-group
class="workspace__domains"
hideSingleSelectionIndicator
[value]="store.domain()"
[disabled]="store.domainLocked()"
(change)="setDomain($event.value)"
aria-label="Base de datos destino"
[matTooltip]="store.domainLocked() ? 'Una carga va a una sola base; quita los flujos para cambiarla' : 'Base de datos destino'"
>
@for (domain of domains(); track domain.id) {
<mat-button-toggle [value]="domain.id" [attr.aria-label]="domain.description">{{ domain.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
<span class="workspace__spacer"></span>
<button mat-stroked-button type="button" (click)="openGallery()">
<mat-icon aria-hidden="true">add</mat-icon>Obtener datos
</button>
<button mat-stroked-button type="button" (click)="openExplorer()" [disabled]="store.targets().length === 0">
<mat-icon aria-hidden="true">travel_explore</mat-icon>Explorar la base
</button>
<button mat-stroked-button type="button" (click)="validateAll()" [disabled]="store.submittableFlows().length === 0 || validatingAll()">
<mat-icon aria-hidden="true">fact_check</mat-icon>Validar todo
</button>
<button
mat-flat-button
type="button"
class="workspace__load"
(click)="openLoad()"
[disabled]="store.submittableFlows().length === 0"
[matBadge]="store.submittableFlows().length || null"
>
<mat-icon aria-hidden="true">cloud_upload</mat-icon>Cargar a la base
</button>
</mat-toolbar>
@if (store.catalogError(); as error) {
<p class="workspace__alert" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ error }}</p>
}
<!-- One drop-list group for the whole workspace: tables dragged out of the
connections pane can land on the canvas or on a destination entity.
The column mapper has its own inner group, so column drags stay in it. -->
<mat-sidenav-container class="workspace__body" autosize cdkDropListGroup>
<mat-sidenav mode="side" [opened]="paneOpen()" class="workspace__pane" disableClose>
<app-connections-panel
(addConnection)="openGallery()"
(useTable)="useTable($event)"
(addQuery)="addQuery($event)"
(drawRegions)="drawRegions($event)"
></app-connections-panel>
</mat-sidenav>
<mat-sidenav-content class="workspace__main">
<app-flow-canvas (tableDropped)="onTableDropped($event)" (addConnection)="openGallery()"></app-flow-canvas>
@if (store.selectedFlow(); as flow) {
<app-flow-editor [flow]="flow" class="workspace__editor"></app-flow-editor>
}
</mat-sidenav-content>
</mat-sidenav-container>
<footer class="workspace__status" aria-live="polite">
@let s = store.summary();
<span><mat-icon aria-hidden="true">cable</mat-icon>{{ s.connections }} conexión(es)</span>
<span><mat-icon aria-hidden="true">account_tree</mat-icon>{{ s.flows }} flujo(s) · {{ s.ready }} listo(s)</span>
@if (s.incomplete) {
<span class="workspace__status-warn"><mat-icon aria-hidden="true">rule</mat-icon>{{ s.incomplete }} sin mapear</span>
}
<span><mat-icon aria-hidden="true">table_rows</mat-icon>{{ s.rows | number }} filas de origen</span>
@if (s.errors) {
<span class="workspace__status-warn"><mat-icon aria-hidden="true">report</mat-icon>{{ s.errors | number }} con errores</span>
}
<span class="workspace__spacer"></span>
<span>Destino: {{ store.domain().toUpperCase() }}</span>
</footer>
</div>
@@ -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;
}
}
@@ -0,0 +1,161 @@
import { DragDropModule } from '@angular/cdk/drag-drop';
import { DecimalPipe } from '@angular/common';
import { Component, Injector, computed, 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 { AuthService } from '../../../auth/auth.service';
import { dominiosPermitidos } from '../../../auth/dominios';
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 auth = inject(AuthService);
private readonly dialog = inject(MatDialog);
private readonly snackBar = inject(MatSnackBar);
private readonly injector = inject(Injector);
/** Only the account's own databases: the picker never offers a domain the server will reject. */
readonly domains = computed(() => dominiosPermitidos(this.auth, DOMAINS));
readonly paneOpen = signal(true);
readonly validatingAll = signal(false);
setDomain(domain: Domain): void {
this.store.setDomain(domain);
}
openGallery(): void {
this.dialog
.open<ConnectorGalleryDialog, void, DataConnection[]>(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, NewFlowDialogData, TargetMeta>(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, SqlConnection, SqlQueryResult>(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, PdfRegionsDialogData, PdfRegionsResult>(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<void> {
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, void, LoadDialogResult>(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, DatabaseExplorerData>(DatabaseExplorerDialog, {
injector: this.injector,
width: '1280px',
maxWidth: '98vw',
data: { targets: this.store.targets(), initial: initial ?? flow?.target.key },
});
}
}
@@ -0,0 +1,154 @@
<section class="pane" aria-labelledby="connections-title">
<header class="pane__header">
<h2 id="connections-title">Conexiones</h2>
<button mat-icon-button type="button" matTooltip="Obtener datos" aria-label="Obtener datos" (click)="addConnection.emit()">
<mat-icon aria-hidden="true">add_circle</mat-icon>
</button>
</header>
@if (store.connections().length === 0) {
<div class="pane__empty">
<app-file-dropzone [accept]="store.acceptedExtensions()" [keepSelection]="false" (filesChange)="onFilesDropped($event)"></app-file-dropzone>
<button mat-stroked-button type="button" class="pane__db-button" (click)="addConnection.emit()">
<mat-icon aria-hidden="true">storage</mat-icon>Conectar una base de datos
</button>
</div>
} @else {
<mat-accordion multi displayMode="flat" class="connections">
@for (connection of store.connections(); track connection.id) {
<mat-expansion-panel [expanded]="true" class="connection">
<mat-expansion-panel-header class="connection__header">
<mat-icon class="connection__icon" aria-hidden="true">{{ connection.icon }}</mat-icon>
<span class="connection__text">
<span class="connection__label" [title]="connection.label">{{ connection.label }}</span>
<span class="connection__type">{{ connection.typeLabel }} · {{ connection.tables().length }} tabla(s)</span>
</span>
@switch (connection.state()) {
@case ('loading') {
<mat-spinner diameter="18" aria-label="Abriendo conexión"></mat-spinner>
}
@case ('error') {
<mat-icon class="connection__error-icon" [matTooltip]="connection.error() ?? ''" aria-label="Error">error</mat-icon>
}
}
<button
mat-icon-button
type="button"
class="connection__menu"
[matMenuTriggerFor]="menu"
(click)="$event.stopPropagation()"
[attr.aria-label]="'Acciones de ' + connection.label"
>
<mat-icon aria-hidden="true">more_vert</mat-icon>
</button>
<mat-menu #menu="matMenu">
@if (isSql(connection)) {
<button mat-menu-item type="button" (click)="addQuery.emit(connection)">
<mat-icon aria-hidden="true">manage_search</mat-icon>Nueva consulta SQL
</button>
}
@if (isPdf(connection)) {
<button mat-menu-item type="button" (click)="drawRegions.emit(connection)" [disabled]="!connection.detection()">
<mat-icon aria-hidden="true">crop_free</mat-icon>Dibujar regiones
</button>
}
<button mat-menu-item type="button" (click)="store.reloadConnection(connection)">
<mat-icon aria-hidden="true">refresh</mat-icon>Volver a leer
</button>
<button mat-menu-item type="button" (click)="store.removeConnection(connection)">
<mat-icon aria-hidden="true">delete</mat-icon>Quitar conexión
</button>
</mat-menu>
</mat-expansion-panel-header>
@if (connection.error(); as error) {
<p class="connection__error" role="alert">{{ error }}</p>
}
<div
class="tables"
cdkDropList
cdkDropListSortingDisabled
[cdkDropListData]="connection.tables()"
[cdkDropListEnterPredicate]="nothingEnters"
>
@for (table of connection.tables(); track table.id) {
<div class="table-item" cdkDrag [cdkDragData]="table" (dblclick)="useTable.emit({ table })">
<mat-icon class="table-item__icon" aria-hidden="true">{{ table.icon }}</mat-icon>
<span class="table-item__text">
<span class="table-item__name" [title]="table.name">{{ table.name }}</span>
<span class="table-item__kind">{{ table.kindLabel }}</span>
</span>
@if (flowCount(table); as count) {
<span class="table-item__flows" [matTooltip]="count + ' flujo(s) usan esta tabla'">{{ count }}</span>
}
<button
mat-icon-button
type="button"
class="table-item__action"
matTooltip="Mapear a la base"
[attr.aria-label]="'Mapear ' + table.name"
(click)="useTable.emit({ table })"
>
<mat-icon aria-hidden="true">arrow_forward</mat-icon>
</button>
@if (table.removable) {
<button
mat-icon-button
type="button"
class="table-item__action"
matTooltip="Quitar"
[attr.aria-label]="'Quitar ' + table.name"
(click)="store.removeTable(table)"
>
<mat-icon aria-hidden="true">close</mat-icon>
</button>
}
<div *cdkDragPreview class="drag-preview">
<mat-icon aria-hidden="true">{{ table.icon }}</mat-icon>{{ table.label }}
</div>
<div *cdkDragPlaceholder class="table-item table-item--placeholder"></div>
</div>
} @empty {
@if (connection.state() === 'ready') {
<p class="tables__empty">
Sin tablas.
</p>
}
}
</div>
</mat-expansion-panel>
}
</mat-accordion>
}
<mat-divider></mat-divider>
<header class="pane__header">
<h2>Destino</h2>
<span class="pane__caption">{{ store.targets().length }} tablas</span>
</header>
<p class="pane__hint">Arrastra una tabla de origen sobre una entidad para mapearla directamente.</p>
<mat-list class="targets" dense>
@for (target of store.targets(); track target.key) {
<mat-list-item
class="target-item"
cdkDropList
[cdkDropListData]="target"
[cdkDropListEnterPredicate]="onlyTables"
(cdkDropListDropped)="onDropOnTarget($event)"
>
<mat-icon matListItemIcon aria-hidden="true">table_chart</mat-icon>
<span matListItemTitle class="target-item__title">
{{ target.table }}
@if (store.flowsByTarget().get(target.key); as count) {
<span class="target-item__flows" [matTooltip]="count + ' flujo(s) cargan esta tabla'">{{ count }}</span>
}
</span>
<span matListItemLine>
{{ target.fields.length }} campos@if (target.conflict_fields) { · clave {{ target.conflict_fields.join(', ') }} }
</span>
</mat-list-item>
}
</mat-list>
</section>
@@ -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;
}
@@ -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<void>();
readonly useTable = output<TableUse>();
readonly addQuery = output<SqlConnection>();
readonly drawRegions = output<PdfConnection>();
/** 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<TargetMeta>): void {
const table = event.item.data;
if (table instanceof SourceTable) this.useTable.emit({ table, target: event.container.data });
}
}
@@ -0,0 +1,166 @@
<h2 mat-dialog-title class="gallery__title">
@if (view() !== 'catalog') {
<button mat-icon-button type="button" (click)="back()" aria-label="Volver a los conectores">
<mat-icon aria-hidden="true">arrow_back</mat-icon>
</button>
}
<span>{{ view() === 'catalog' ? 'Obtener datos' : entry()?.name }}</span>
</h2>
<mat-dialog-content class="gallery__content">
@switch (view()) {
@case ('catalog') {
<div class="gallery">
<mat-nav-list class="gallery__categories" aria-label="Categorías de conectores">
@for (item of visibleCategories(); track item.id) {
<a mat-list-item [activated]="category() === item.id" (click)="category.set(item.id)" role="button">
<mat-icon matListItemIcon aria-hidden="true">{{ item.icon }}</mat-icon>
<span matListItemTitle>{{ item.label }}</span>
</a>
}
</mat-nav-list>
<section class="gallery__main">
<mat-form-field appearance="outline" class="gallery__search" subscriptSizing="dynamic">
<mat-icon matPrefix aria-hidden="true">search</mat-icon>
<mat-label>Buscar conector</mat-label>
<input matInput (input)="onSearch($event)" />
</mat-form-field>
@if (catalogError(); as error) {
<p class="db-test db-test--error" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ error }}</p>
}
<div class="gallery__grid" role="list">
@for (item of visibleEntries(); track item.id) {
<button
type="button"
class="connector-card"
matRipple
role="listitem"
[disabled]="!item.available"
[matTooltip]="item.available ? '' : 'No disponible en este servidor'"
(click)="pick(item)"
>
<mat-icon class="connector-card__icon" aria-hidden="true">{{ item.icon }}</mat-icon>
<span class="connector-card__name">{{ item.name }}</span>
<span class="connector-card__description">{{ item.description }}</span>
</button>
} @empty {
<p class="gallery__empty">Ningún conector coincide con la búsqueda.</p>
}
</div>
</section>
</div>
}
@case ('files') {
<p class="gallery__hint">
@switch (entry()?.connector?.kind) {
@case ('document') {
Agrega todos los documentos juntos: reportes, formatos o notas en PDF o imagen. Se separan por paciente aunque
uno ocupe varias páginas o varios archivos, y los campos se extraen del texto, incluido el texto libre.
}
@case ('edf') {
Agrega todos los registros juntos; cada archivo será una fila con los datos del estudio y el archivo original.
}
@default {
Puedes agregar varios archivos a la vez; cada uno se convierte en una conexión y sus tablas (las hojas de un
libro de Excel, las tablas de un PDF) quedan disponibles para mapear.
}
}
</p>
<app-file-dropzone [accept]="entry()?.connector?.extensions ?? []" (filesChange)="files.set($event)"></app-file-dropzone>
}
@case ('database') {
<p class="gallery__hint">
Solo lectura: la conexión se abre en modo de solo lectura y únicamente se permiten consultas SELECT.
</p>
@if (engine() === 'url') {
<form [formGroup]="urlForm" class="db-form" (ngSubmit)="connectDatabase()">
<mat-form-field appearance="outline" class="db-form__wide">
<mat-label>Cadena de conexión</mat-label>
<input matInput formControlName="url" placeholder="postgresql+psycopg2://usuario:contraseña@host:5432/base" autocomplete="off" />
<mat-hint>Formato SQLAlchemy: dialecto+driver://usuario:contraseña&#64;host:puerto/base</mat-hint>
</mat-form-field>
</form>
} @else {
@if (savedConnections().length) {
<div class="saved-connections">
<span class="saved-connections__label">Conexiones guardadas</span>
<div class="saved-connections__list">
@for (saved of savedConnections(); track saved.id) {
<div class="saved-connection">
<button type="button" class="saved-connection__pick" matRipple (click)="applySaved(saved)">
<mat-icon aria-hidden="true">storage</mat-icon>
<span>{{ saved.label }}</span>
</button>
<button
mat-icon-button
type="button"
class="saved-connection__forget"
(click)="forgetSaved(saved, $event)"
aria-label="Eliminar esta conexión guardada"
matTooltip="Eliminar"
>
<mat-icon aria-hidden="true">close</mat-icon>
</button>
</div>
}
</div>
</div>
}
<form [formGroup]="serverForm" class="db-form" (ngSubmit)="connectDatabase()">
<mat-form-field appearance="outline" class="db-form__host">
<mat-label>Servidor</mat-label>
<input matInput formControlName="host" placeholder="10.0.10.41" autocomplete="off" />
</mat-form-field>
<mat-form-field appearance="outline" class="db-form__port">
<mat-label>Puerto</mat-label>
<input matInput type="number" formControlName="port" />
<mat-hint>Predeterminado: {{ serverEngine()?.default_port }}</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" class="db-form__wide">
<mat-label>Base de datos</mat-label>
<input matInput formControlName="database" autocomplete="off" />
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Usuario</mat-label>
<input matInput formControlName="user" autocomplete="off" />
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Contraseña</mat-label>
<input matInput type="password" formControlName="password" autocomplete="new-password" />
</mat-form-field>
</form>
<mat-checkbox [checked]="remember()" (change)="remember.set($event.checked)">
Guardar servidor, usuario y base de datos para conexiones futuras (la contraseña no se guarda)
</mat-checkbox>
}
@if (testing()) {
<mat-progress-bar mode="indeterminate" aria-label="Probando conexión"></mat-progress-bar>
}
@if (testResult(); as result) {
<p class="db-test" [class.db-test--error]="!result.ok" role="status">
<mat-icon aria-hidden="true">{{ result.ok ? 'check_circle' : 'error' }}</mat-icon>{{ result.message }}
</p>
}
}
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button mat-dialog-close type="button">Cancelar</button>
@if (view() === 'files') {
<button mat-flat-button type="button" [disabled]="files().length === 0" (click)="connectFiles()">
Conectar {{ files().length > 1 ? files().length + ' archivos' : '' }}
</button>
}
@if (view() === 'database') {
<button mat-stroked-button type="button" [disabled]="testing()" (click)="testConnection()">
<mat-icon aria-hidden="true">network_check</mat-icon>Probar conexión
</button>
<button mat-flat-button type="button" [disabled]="databaseFormInvalid" (click)="connectDatabase()">Conectar</button>
}
</mat-dialog-actions>
@@ -0,0 +1,176 @@
.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);
}
.saved-connections {
margin-bottom: var(--space-4);
}
.saved-connections__label {
color: var(--mat-sys-on-surface-variant);
display: block;
font: var(--mat-sys-label-small);
margin-bottom: var(--space-1);
}
.saved-connections__list {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
.saved-connection {
align-items: center;
background: var(--mat-sys-surface-variant);
border-radius: var(--mat-sys-corner-full);
display: flex;
gap: var(--space-1);
padding-right: var(--space-1);
}
.saved-connection__pick {
align-items: center;
background: none;
border: 0;
color: var(--mat-sys-on-surface-variant);
cursor: pointer;
display: flex;
font: var(--mat-sys-body-small);
gap: var(--space-1);
padding: var(--space-1) 0 var(--space-1) var(--space-3);
mat-icon {
font-size: 18px;
height: 18px;
width: 18px;
}
}
.saved-connection__forget {
--mdc-icon-button-state-layer-size: 28px;
height: 28px;
width: 28px;
mat-icon {
font-size: 16px;
height: 16px;
width: 16px;
}
}
.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;
}
@@ -0,0 +1,197 @@
import { Component, computed, inject, signal } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
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 { SavedSqlConnection, listSavedSqlConnections, removeSqlConnection, saveSqlConnection } from '../../domain/saved-sql-connections';
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,
MatCheckboxModule,
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<ConnectorGalleryDialog, DataConnection[]>>(MatDialogRef);
private readonly gateway = inject(SourceGateway);
private readonly formBuilder = inject(FormBuilder);
readonly categories = GALLERY_CATEGORIES;
readonly category = signal<GalleryCategory>('all');
readonly search = signal('');
readonly view = signal<View>('catalog');
readonly entry = signal<GalleryEntry | null>(null);
readonly catalogError = signal<string | null>(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)),
);
readonly files = signal<File[]>([]);
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 remember = signal(false);
readonly engine = computed(() => this.entry()?.engine ?? null);
readonly serverEngine = computed(() => {
const engine = this.engine();
return engine && engine !== 'url' ? engine : null;
});
private readonly savedConnectionsAll = signal(listSavedSqlConnections());
/** Only the ones for the engine currently picked, so a saved SQL Server entry never fills a MySQL form. */
readonly savedConnections = computed(() => {
const engineId = this.serverEngine()?.id;
return engineId ? this.savedConnectionsAll().filter((saved) => saved.engine === engineId) : [];
});
applySaved(saved: SavedSqlConnection): void {
this.serverForm.patchValue({ host: saved.host, port: saved.port, database: saved.database, user: saved.user });
this.testResult.set(null);
}
forgetSaved(saved: SavedSqlConnection, event: Event): void {
event.stopPropagation();
removeSqlConnection(saved.id);
this.savedConnectionsAll.set(listSavedSqlConnections());
}
pick(entry: GalleryEntry): void {
if (!entry.available) return;
this.entry.set(entry);
this.testResult.set(null);
this.remember.set(false);
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;
if (this.remember() && 'server' in ref) {
const { password: _password, ...shape } = ref.server;
saveSqlConnection({ label: this.connectionLabel(), ...shape });
}
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() });
}
}
@@ -0,0 +1,82 @@
@let f = flow();
<div class="grid-toolbar">
<mat-button-toggle-group hideSingleSelectionIndicator [value]="view()" (change)="view.set($event.value)" aria-label="Vista de datos">
<mat-button-toggle value="target"><mat-icon aria-hidden="true">table_chart</mat-icon> Destino</mat-button-toggle>
<mat-button-toggle value="source"><mat-icon aria-hidden="true">input</mat-icon> Origen</mat-button-toggle>
</mat-button-toggle-group>
@if (view() === 'target') {
<mat-slide-toggle [checked]="onlyErrors()" (change)="onlyErrors.set($event.checked)" [disabled]="!f.validation()">
Solo filas con errores
</mat-slide-toggle>
}
<span class="grid-toolbar__caption">
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
}
</span>
</div>
@if (columns().length === 0) {
<p class="grid-empty">
@if (view() === 'target') {
Aún no hay campos asignados — mapea columnas en la pestaña «Mapeo».
} @else {
La fuente no tiene columnas.
}
</p>
} @else {
<div class="grid-scroll">
<table mat-table [dataSource]="rows()" class="grid">
<ng-container matColumnDef="__row" sticky>
<th mat-header-cell *matHeaderCellDef class="grid__index">#</th>
<td mat-cell *matCellDef="let row" class="grid__index" [class.grid__index--error]="row.hasErrors">
{{ row.index + 1 }}
</td>
</ng-container>
@for (column of columns(); track column.id) {
<ng-container [matColumnDef]="column.id">
<th mat-header-cell *matHeaderCellDef class="grid__header">
<span class="grid__title"><mat-icon aria-hidden="true">{{ column.type | typeIcon }}</mat-icon>{{ column.title }}</span>
@if (column.subtitle) {
<span class="grid__subtitle">{{ column.subtitle }}</span>
}
@if (column.errorRate !== null) {
<span
class="quality"
[matTooltip]="qualityPercent(column.errorRate) + '% de las filas válidas en este campo'"
[attr.aria-label]="qualityPercent(column.errorRate) + '% válido'"
>
<span class="quality__ok" [style.width.%]="qualityPercent(column.errorRate)"></span>
<span class="quality__bad" [style.width.%]="100 - qualityPercent(column.errorRate)"></span>
</span>
}
</th>
<td mat-cell *matCellDef="let row">
@let value = cell(row, column);
@let cellErrors = errors(row, column);
<span
class="grid__cell"
[class.grid__cell--error]="cellErrors.length > 0"
[class.grid__cell--default]="value.isDefault"
[class.grid__cell--empty]="value.isEmpty"
[matTooltip]="cellErrors.length ? errorText(cellErrors) : ''"
>
@if (cellErrors.length) {
<mat-icon aria-hidden="true">error_outline</mat-icon>
}
{{ value.text }}
</span>
</td>
</ng-container>
}
<tr mat-header-row *matHeaderRowDef="displayedColumns(); sticky: true"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns()"></tr>
<tr class="mat-row" *matNoDataRow>
<td class="grid-empty" [attr.colspan]="displayedColumns().length">Ninguna fila de la muestra tiene errores.</td>
</tr>
</table>
</div>
}
@@ -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;
}
@@ -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<ImportFlow>();
readonly view = signal<GridView>('target');
readonly onlyErrors = signal(false);
readonly columns = computed<GridColumn[]>(() => {
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<GridRow[]>(() => {
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;
}
@@ -0,0 +1,61 @@
<h2 mat-dialog-title class="explorer__title">
<mat-icon aria-hidden="true">travel_explore</mat-icon>Explorar la base de datos
<button mat-icon-button type="button" (click)="refresh()" aria-label="Actualizar"><mat-icon aria-hidden="true">refresh</mat-icon></button>
</h2>
<mat-dialog-content class="explorer">
<mat-nav-list class="explorer__tables" aria-label="Tablas">
@for (target of data.targets; track target.key) {
<a mat-list-item [activated]="selected() === target" (click)="open(target)" role="button">
<mat-icon matListItemIcon aria-hidden="true">table_chart</mat-icon>
<span matListItemTitle>{{ target.table }}</span>
<span matListItemLine>
@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 {
…
}
</span>
</a>
}
</mat-nav-list>
<section class="explorer__rows">
@if (loading()) {
<mat-progress-bar mode="indeterminate" aria-label="Cargando filas"></mat-progress-bar>
}
@if (error(); as message) {
<p class="explorer__error" role="alert">{{ message }}</p>
}
@if (page(); as p) {
@if (p.rows.length === 0) {
<p class="explorer__empty">La tabla está vacía.</p>
} @else {
<div class="explorer__scroll">
<table mat-table [dataSource]="p.rows" class="explorer__table">
@for (column of allColumns(); track column) {
<ng-container [matColumnDef]="column">
<th mat-header-cell *matHeaderCellDef>{{ column }}</th>
<td mat-cell *matCellDef="let row" [class.explorer__null]="row[column] === null">{{ display(row[column]) }}</td>
</ng-container>
}
<tr mat-header-row *matHeaderRowDef="allColumns(); sticky: true"></tr>
<tr mat-row *matRowDef="let row; columns: allColumns()"></tr>
</table>
</div>
<mat-paginator
[length]="p.total"
[pageIndex]="pageIndex()"
[pageSize]="pageSize()"
[pageSizeOptions]="[25, 50, 100]"
(page)="onPage($event)"
aria-label="Paginación de filas"
></mat-paginator>
}
}
</section>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button mat-dialog-close type="button">Cerrar</button>
</mat-dialog-actions>
@@ -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;
}
}
@@ -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<DatabaseExplorerData>(MAT_DIALOG_DATA);
private readonly api = inject(DataApi);
readonly totals = signal<Map<string, number | null>>(new Map());
readonly selected = signal<TargetMeta | null>(null);
readonly page = signal<DataPage | null>(null);
readonly pageIndex = signal(0);
readonly pageSize = signal(25);
readonly loading = signal(false);
readonly error = signal<string | null>(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.'));
},
});
}
}
@@ -0,0 +1,217 @@
<h2 mat-dialog-title>Revisar extracción · {{ target.domain.toUpperCase() }} {{ target.table }}</h2>
<mat-dialog-content class="review">
<aside class="review__side">
<section class="settings" aria-label="Cómo se leen los documentos">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Separar registros</mat-label>
<mat-select [value]="settings().segmentation" (valueChange)="updateSettings({ segmentation: $event })">
@for (option of segmentations; track option.id) {
<mat-option [value]="option.id">{{ option.label }}</mat-option>
}
</mat-select>
</mat-form-field>
@if (settings().segmentation === 'pages') {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Páginas por registro</mat-label>
<input
matInput
type="number"
min="1"
[ngModel]="settings().pages_per_record"
(ngModelChange)="updateSettings({ pages_per_record: $event || 1 })"
/>
</mat-form-field>
}
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Formato del identificador (opcional)</mat-label>
<input
matInput
placeholder="EXP-\d{4}"
[ngModel]="settings().key_pattern"
(ngModelChange)="updateSettings({ key_pattern: $event })"
/>
<mat-hint>Expresión regular; ayuda a encontrar el expediente sin etiqueta.</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Solo documentos que digan</mat-label>
<input matInput [ngModel]="settings().include_pattern ?? ''" (ngModelChange)="updateSettings({ include_pattern: $event })" />
<mat-hint>Expresión regular; sin distinguir mayúsculas ni acentos.</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Omitir documentos que digan</mat-label>
<input matInput [ngModel]="settings().exclude_pattern ?? ''" (ngModelChange)="updateSettings({ exclude_pattern: $event })" />
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>OCR</mat-label>
<mat-select [value]="settings().ocr_mode" (valueChange)="updateSettings({ ocr_mode: $event })">
<mat-option value="auto">Solo páginas escaneadas</mat-option>
<mat-option value="always">Todas las páginas</mat-option>
<mat-option value="never">Nunca (solo texto del PDF)</mat-option>
</mat-select>
</mat-form-field>
<button mat-stroked-button type="button" [disabled]="extracting()" (click)="extract()">
<mat-icon aria-hidden="true">refresh</mat-icon>Volver a extraer
</button>
</section>
<header class="records__header">
<span>{{ records().length }} registro(s)</span>
@if (needsReview()) {
<span class="records__review">{{ needsReview() }} por revisar</span>
}
</header>
<mat-nav-list class="records" aria-label="Registros extraídos">
@for (record of records(); track record.index; let i = $index) {
<a mat-list-item [activated]="i === selectedIndex()" (click)="select(i)" role="button">
<mat-icon matListItemIcon [class.records__warn]="recordNeedsReview(record)" aria-hidden="true">
{{ recordNeedsReview(record) ? 'error_outline' : 'check_circle' }}
</mat-icon>
<span matListItemTitle>{{ record.key ?? 'Registro ' + (i + 1) }}</span>
<span matListItemLine>
@for (source of record.sources; track $index) {
{{ source.document }} p. {{ source.page_numbers.join(', ') }}@if (!$last) { · }
}
</span>
</a>
} @empty {
@if (!extracting()) {
<p class="records__empty">No se encontró ningún registro.</p>
}
}
</mat-nav-list>
</aside>
<section class="review__main">
@if (extracting()) {
<mat-progress-bar mode="indeterminate" aria-label="Leyendo documentos"></mat-progress-bar>
<p class="review__hint">Leyendo documentos; las páginas escaneadas pasan por OCR y pueden tardar.</p>
}
@if (error(); as message) {
<p class="review__error" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ message }}</p>
}
@if (selected(); as record) {
<header class="record__header">
<h3>{{ record.key ?? 'Registro ' + (selectedIndex() + 1) }}</h3>
<span class="record__confidence" [class.record__confidence--low]="record.confidence < reviewBelow">
Confianza mínima {{ record.confidence | percent }}
</span>
</header>
@if (record.on_topic === false) {
<p class="record__off-topic" role="status">
<mat-icon aria-hidden="true">report</mat-icon>
Sus páginas mencionan otro tipo de estudio y no el de este destino; sus valores quedan vacíos para que los revise.
</p>
}
<table class="fields" aria-label="Campos extraídos">
<thead>
<tr>
<th scope="col">Campo</th>
<th scope="col">Valor</th>
<th scope="col">Confianza</th>
<th scope="col">De dónde se leyó</th>
</tr>
</thead>
<tbody>
@for (field of fields(); track field.name) {
@let found = extracted(record, field.name);
@let conflict = conflictFor(record, field.name);
<tr [class.fields__row--missing]="field.required && !value(record, field.name)">
<th scope="row" class="fields__name" [matTooltip]="field.labels.join(' · ')">
{{ field.name }}@if (field.required) {<span class="fields__required" aria-label="obligatorio">*</span>}
</th>
<td class="fields__value">
<input
class="fields__input"
[class.fields__input--edited]="isOverridden(record, field.name)"
[value]="value(record, field.name)"
(change)="setValue(record, field.name, $any($event.target).value)"
[attr.aria-label]="'Valor de ' + field.name"
/>
@if (alternatives(record, field.name).length && !isOverridden(record, field.name)) {
<span class="fields__alternatives">
También:
@for (alternative of alternatives(record, field.name); track $index) {
<button
type="button"
class="fields__alternative"
(click)="pick(record, field.name, alternative)"
[matTooltip]="(methodLabels[alternative.method] ?? alternative.method) + ' · ' + (alternative.confidence | percent) + (alternative.line ? ' · “' + alternative.line + '”' : '')"
>
{{ alternative.value }}
</button>
}
</span>
}
@if (conflict) {
<span class="fields__conflict" [matTooltip]="'Otro documento dice: ' + conflict.discarded.value + ' (' + conflict.discarded.document + ' p. ' + conflict.discarded.page_number + ')'">
<mat-icon aria-hidden="true">compare_arrows</mat-icon>difiere
</span>
}
</td>
<td class="fields__confidence">
@if (isOverridden(record, field.name)) {
<span class="method method--manual">Manual</span>
} @else if (found) {
<mat-progress-bar
mode="determinate"
[value]="found.confidence * 100"
[class.low]="found.confidence < reviewBelow"
[attr.aria-label]="'Confianza ' + (found.confidence | percent)"
></mat-progress-bar>
<span class="method">{{ methodLabels[found.method] ?? found.method }} · {{ found.confidence | percent }}</span>
@if (found.assertion && assertionLabels[found.assertion]) {
<span class="method method--assertion">{{ assertionLabels[found.assertion] }}</span>
}
}
</td>
<td class="fields__evidence">
@if (found?.line && !isOverridden(record, field.name)) {
<button mat-button type="button" class="evidence" (click)="showPage(found?.document, found?.page_number)">
<span class="evidence__line">“{{ found?.line }}”</span>
<span class="evidence__where">{{ found?.document }} p. {{ found?.page_number }}</span>
</button>
}
</td>
</tr>
}
</tbody>
</table>
@if (record.images.length) {
<h4 class="record__subtitle">Imágenes en sus páginas</h4>
<div class="images">
@for (image of record.images; track $index) {
<button type="button" class="image" (click)="showPage(image.document, image.page_number)">
@if (thumbnails()[thumbnailKey(image)]; as url) {
<img [src]="url" [alt]="(image.kind === 'scan' ? 'Página escaneada' : 'Imagen') + ' de ' + image.document + ', página ' + image.page_number" />
} @else {
<mat-icon aria-hidden="true">image</mat-icon>
}
<span>{{ image.kind === 'scan' ? 'Escaneo' : 'Imagen' }} · p. {{ image.page_number }}</span>
</button>
}
</div>
}
@if (page(); as shown) {
<h4 class="record__subtitle">{{ shown.document }} · página {{ shown.page }}</h4>
@if (shown.url) {
<img class="page" [src]="shown.url" [alt]="shown.document + ', página ' + shown.page" />
} @else {
<mat-progress-bar mode="indeterminate" aria-label="Cargando página"></mat-progress-bar>
}
}
}
</section>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button mat-dialog-close type="button">Cancelar</button>
<button mat-flat-button type="button" [disabled]="extracting() || settingsChanged" (click)="apply()"
[matTooltip]="settingsChanged ? 'Vuelve a extraer para aplicar la nueva configuración' : ''">
Aplicar
</button>
</mat-dialog-actions>
@@ -0,0 +1,269 @@
.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__alternatives {
align-items: center;
color: var(--mat-sys-on-surface-variant);
display: flex;
flex-wrap: wrap;
font: var(--mat-sys-label-small);
gap: 4px;
margin-top: 2px;
}
.fields__alternative {
background: var(--mat-sys-surface-container-high);
border: 0;
border-radius: 999px;
color: var(--mat-sys-on-surface);
cursor: pointer;
font: var(--mat-sys-label-small);
padding: 1px 8px;
&:hover,
&:focus-visible {
background: var(--mat-sys-secondary-container);
}
}
.method--assertion {
color: var(--mat-sys-tertiary);
display: block;
}
.record__off-topic {
align-items: center;
background: var(--mat-sys-error-container);
color: var(--mat-sys-on-error-container);
display: flex;
font: var(--mat-sys-body-small);
gap: var(--space-2);
margin: 0 0 var(--space-2);
padding: var(--space-2) var(--space-3);
}
.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;
}
}
@@ -0,0 +1,67 @@
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { SourceGateway } from '../../api/source-gateway';
import { DocumentExtraction, ExtractedRecord } from '../../api/api.types';
import { DocumentReviewDialog } from './document-review-dialog';
/**
* The review of extracted documents: the other readings the extractors proposed can be picked as a correction, a
* record whose pages name another kind of study asks for review, and a qualified mention shows how it was qualified.
* The table is a stub holding one extraction already made, so no request is sent; the gateway is never called.
*/
describe('DocumentReviewDialog', () => {
const record: ExtractedRecord = {
index: 0,
key: 'K-1',
confidence: 0.9,
fields: { bx_cin_grado: { value: 'LIEAG', confidence: 0.9, method: 'texto_libre', assertion: 'presuntivo' } },
missing: [],
conflicts: [],
sources: [{ document: 'a.pdf', page_numbers: [1] }],
images: [],
on_topic: true,
alternatives: { bx_cin_grado: [{ value: 'LIEBG', confidence: 0.7, method: 'etiqueta', line: 'Diagnóstico: NIC I' }] },
};
function open(records: ExtractedRecord[]) {
const extraction = { key_field: 'pac_id_hospital', fields: [{ name: 'bx_cin_grado', kind: 'choice', required: false, labels: [] }], records } as unknown as DocumentExtraction;
const table = {
settings: () => ({}),
overrides: () => ({}),
extractions: signal({ biopsia: extraction }),
configure: vi.fn(),
};
TestBed.configureTestingModule({
imports: [DocumentReviewDialog],
providers: [
{ provide: MAT_DIALOG_DATA, useValue: { table, target: { key: 'biopsia', domain: 'cacu', table: 'biopsia_cervical' }, segmentations: [] } },
{ provide: MatDialogRef, useValue: { close: vi.fn() } },
{ provide: SourceGateway, useValue: {} },
],
});
const fixture = TestBed.createComponent(DocumentReviewDialog);
fixture.detectChanges();
return fixture;
}
it('picks another reading as the correction', () => {
// Fails if the alternatives stop being offered or picking one stops recording it as an override.
const fixture = open([record]);
const dialog = fixture.componentInstance;
const [alternative] = dialog.alternatives(record, 'bx_cin_grado');
dialog.pick(record, 'bx_cin_grado', alternative);
expect(dialog.value(record, 'bx_cin_grado')).toBe('LIEBG');
expect(dialog.isOverridden(record, 'bx_cin_grado')).toBe(true);
});
it('shows how a mention was qualified and asks to review off-topic records', () => {
// Fails if the assertion label or the off-topic warning disappear from the page.
const fixture = open([record, { ...record, index: 1, on_topic: false }]);
expect(fixture.nativeElement.textContent).toContain('Presuntivo');
expect(fixture.componentInstance.needsReview()).toBe(1);
fixture.componentInstance.select(1);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('otro tipo de estudio');
});
});
@@ -0,0 +1,222 @@
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<string, string> = {
etiqueta: 'Etiqueta',
patron: 'Patrón',
texto_libre: 'Texto libre',
medicion: 'Medición',
columna_fuente: 'Columna',
manual: 'Manual',
};
/** How a value's mention is qualified, for the ones a reviewer should notice. */
const ASSERTION_LABELS: Record<string, string> = {
incierto: 'Incierto',
hipotetico: 'Hipotético',
historico: 'Antecedente',
presuntivo: 'Presuntivo',
};
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<DocumentReviewData>(MAT_DIALOG_DATA);
private readonly dialogRef = inject<MatDialogRef<DocumentReviewDialog, boolean>>(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 assertionLabels = ASSERTION_LABELS;
readonly reviewBelow = REVIEW_BELOW;
readonly settings = signal<DocumentSettings>({ ...this.table.settings() });
readonly overrides = signal<FieldOverrides>(structuredClone(this.table.overrides(this.target.key)));
readonly extracting = signal(false);
readonly error = signal<string | null>(null);
readonly selectedIndex = signal(0);
readonly extraction = computed(() => this.table.extractions()[this.target.key] ?? null);
readonly records = computed(() => this.extraction()?.records ?? []);
readonly fields = computed<DocumentFieldSpec[]>(() => this.extraction()?.fields ?? []);
readonly selected = computed<ExtractedRecord | null>(() => 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<Record<string, string>>({});
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);
});
}
updateSettings(patch: Partial<DocumentSettings>): 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.'));
},
});
}
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 || record.on_topic === false
);
}
alternatives(record: ExtractedRecord, field: string): ExtractedField[] {
return record.alternatives?.[field] ?? [];
}
/** Takes another reading the extractors proposed; the correction teaches the ranker once imported. */
pick(record: ExtractedRecord, field: string, alternative: ExtractedField): void {
this.setValue(record, field, alternative.value === null || alternative.value === undefined ? '' : String(alternative.value));
}
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;
}
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) }));
});
}
apply(): void {
this.table.configure(this.settings(), { [this.target.key]: this.overrides() });
this.dialogRef.close(true);
}
}
@@ -0,0 +1,37 @@
<div class="dropzone" [class.dropzone--active]="isDragOver()" (dragenter)="onDragEnter($event)" (dragover)="onDragOver($event)" (dragleave)="onDragLeave($event)" (drop)="onDrop($event)">
<mat-icon class="dropzone__icon" aria-hidden="true">cloud_upload</mat-icon>
<p class="dropzone__title">Arrastra tus archivos aquí</p>
<p class="dropzone__formats">{{ formatsLabel }}</p>
<input #fileInput class="visually-hidden" type="file" [multiple]="multiple()" [attr.accept]="acceptAttribute" aria-label="Seleccionar archivos" (change)="onFileSelection($event)" />
<button class="upload-action upload-action--outlined select-files-button" mat-stroked-button type="button" (click)="fileInput.click()">
<mat-icon aria-hidden="true">upload_file</mat-icon>
<span>Seleccionar archivos</span>
</button>
</div>
@if (fileMessages().length > 0) {
<ul class="file-messages" aria-live="polite" aria-label="Mensajes sobre archivos">
@for (message of fileMessages(); track $index) { <li>{{ message }}</li> }
</ul>
}
@if (files().length > 0) {
<section class="selected-files" aria-labelledby="selected-files-title">
<header class="selected-files__header">
<h3 id="selected-files-title">Archivos seleccionados</h3>
<span class="selected-files__count" aria-label="Cantidad de archivos">{{ files().length }}</span>
</header>
<ul class="selected-files__list">
@for (file of files(); track file.name + ':' + file.size) {
<li class="file-row">
<mat-icon class="file-row__icon" aria-hidden="true">{{ fileIcon(file) }}</mat-icon>
<span class="file-row__name" [title]="file.name">{{ file.name }}</span>
<span class="file-row__size">{{ formatFileSize(file.size) }}</span>
<button class="file-row__remove" mat-icon-button type="button" [attr.aria-label]="'Eliminar ' + file.name" (click)="removeFile(file)">
<mat-icon aria-hidden="true">close</mat-icon>
</button>
</li>
}
</ul>
</section>
}
@@ -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;
}
@@ -0,0 +1,126 @@
import { TestBed } from '@angular/core/testing';
import { FileDropzone } from './file-dropzone';
describe('FileDropzone', () => {
function createFixture(keepSelection = true) {
const fixture = TestBed.createComponent(FileDropzone);
fixture.componentRef.setInput('accept', ['xlsx', 'csv', 'json', 'pdf']);
fixture.componentRef.setInput('keepSelection', keepSelection);
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<HTMLInputElement>('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<HTMLInputElement>('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<HTMLButtonElement>('.file-row__remove')!.click();
fixture.detectChanges();
expect(compiled.querySelectorAll('.file-row')).toHaveLength(0);
expect(emitted.at(-1)).toEqual([]);
});
it('without keepSelection emits only each new batch and lists nothing', () => {
const fixture = createFixture(false);
const compiled = fixture.nativeElement as HTMLElement;
const component = fixture.componentInstance;
const emitted: File[][] = [];
component.filesChange.subscribe((files) => emitted.push(files));
const drop = (files: File[]) =>
component.onDrop({ preventDefault: () => undefined, dataTransfer: { files } } as unknown as DragEvent);
const first = new File(['a'], 'uno.csv');
const second = new File(['b'], 'dos.csv');
drop([first]);
drop([second]);
drop([new File(['x'], 'malo.docx')]);
fixture.detectChanges();
expect(emitted).toEqual([[first], [second]]);
expect(compiled.querySelectorAll('.file-row')).toHaveLength(0);
});
it('honors a custom accept input', () => {
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);
});
});
@@ -0,0 +1,133 @@
import { Component, input, output, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
/**
* Drag-and-drop and file-picker area that validates files by extension and size.
* With `keepSelection` it keeps and emits the whole selected list; without it,
* it emits only each batch of newly accepted files and keeps nothing.
*/
@Component({
imports: [MatButtonModule, MatIconModule],
selector: 'app-file-dropzone',
styleUrl: './file-dropzone.scss',
templateUrl: './file-dropzone.html',
})
export class FileDropzone {
readonly accept = input.required<string[]>();
readonly multiple = input(true);
readonly keepSelection = input(true);
readonly filesChange = output<File[]>();
readonly files = signal<File[]>([]);
readonly fileMessages = signal<string[]>([]);
readonly isDragOver = signal(false);
private dragDepth = 0;
get allowedExtensions(): Set<string> {
return new Set(this.accept().map((extension) => extension.toLowerCase()));
}
get acceptAttribute(): string {
return this.accept().map((extension) => `.${extension}`).join(',');
}
get formatsLabel(): string {
return this.accept().map((extension) => extension.toUpperCase()).join(' · ');
}
onFileSelection(event: Event): void {
const input = event.target as HTMLInputElement;
this.addFiles(input.files ? Array.from(input.files) : []);
input.value = '';
}
onDragEnter(event: DragEvent): void {
event.preventDefault();
this.dragDepth++;
this.isDragOver.set(true);
}
onDragOver(event: DragEvent): void {
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';
}
onDragLeave(event: DragEvent): void {
event.preventDefault();
this.dragDepth = Math.max(0, this.dragDepth - 1);
if (this.dragDepth === 0) this.isDragOver.set(false);
}
onDrop(event: DragEvent): void {
event.preventDefault();
this.dragDepth = 0;
this.isDragOver.set(false);
this.addFiles(event.dataTransfer?.files ? Array.from(event.dataTransfer.files) : []);
}
removeFile(fileToRemove: File): void {
this.files.update((files) => files.filter((file) => file !== fileToRemove));
this.filesChange.emit(this.files());
}
formatFileSize(size: number): string {
if (size < 1024) return `${size} bytes`;
const units = ['KB', 'MB', 'GB'];
let value = size / 1024;
let unit = 0;
while (value >= 1024 && unit < units.length - 1) {
value /= 1024;
unit++;
}
return `${new Intl.NumberFormat('es-MX', { maximumFractionDigits: 1 }).format(value)} ${units[unit]}`;
}
fileIcon(file: File): string {
const extension = this.extensionOf(file.name);
if (extension === 'pdf') return 'picture_as_pdf';
if (extension === 'csv' || extension === 'xlsx') return 'table_chart';
return 'data_object';
}
private addFiles(incomingFiles: File[]): void {
const messages: string[] = [];
const kept = this.keepSelection() && this.multiple() ? [...this.files()] : [];
const accepted = [...kept];
for (const file of incomingFiles) {
const extension = this.extensionOf(file.name);
if (!this.allowedExtensions.has(extension)) {
messages.push(`${file.name} no fue agregado. Formato no compatible.`);
continue;
}
if (file.size === 0) {
messages.push(`${file.name} no fue agregado. El archivo está vacío.`);
continue;
}
if (accepted.some((existing) => existing.name === file.name && existing.size === file.size)) {
messages.push(`${file.name} ya se encuentra seleccionado.`);
continue;
}
if (!this.multiple()) {
accepted.length = 0;
}
accepted.push(file);
if (!this.multiple()) break;
}
this.fileMessages.set(messages);
if (this.keepSelection()) {
this.files.set(accepted);
this.filesChange.emit(accepted);
} else if (accepted.length > kept.length) {
this.filesChange.emit(accepted.slice(kept.length));
}
}
private extensionOf(fileName: string): string {
const finalDot = fileName.lastIndexOf('.');
return finalDot >= 0 ? fileName.slice(finalDot + 1).toLowerCase() : '';
}
}
@@ -0,0 +1,102 @@
<section
class="canvas"
cdkDropList
cdkDropListSortingDisabled
[cdkDropListEnterPredicate]="onlyTables"
(cdkDropListDropped)="onDrop($event)"
aria-labelledby="canvas-title"
>
<header class="canvas__header">
<h2 id="canvas-title">Flujos de carga</h2>
<span class="canvas__caption">
{{ store.flows().length }} flujo(s) · cada uno lleva una tabla de origen a una tabla de la base
</span>
</header>
<div class="canvas__grid">
@for (flow of store.flows(); track flow.id) {
<mat-card
appearance="outlined"
class="flow-card"
[class.flow-card--selected]="store.selectedFlow() === flow"
(click)="store.select(flow)"
tabindex="0"
(keydown.enter)="store.select(flow)"
role="button"
[attr.aria-pressed]="store.selectedFlow() === flow"
>
<div class="flow-card__route">
<span class="flow-card__end">
<mat-icon aria-hidden="true">{{ flow.table.icon }}</mat-icon>
<span class="flow-card__name" [title]="flow.label">{{ flow.table.name }}</span>
</span>
<mat-icon class="flow-card__arrow" aria-hidden="true">arrow_right_alt</mat-icon>
<span class="flow-card__end flow-card__end--target">
<mat-icon aria-hidden="true">table_chart</mat-icon>
<span class="flow-card__name">{{ flow.target.table }}</span>
</span>
<button
mat-icon-button
type="button"
class="flow-card__menu"
[matMenuTriggerFor]="menu"
(click)="$event.stopPropagation()"
[attr.aria-label]="'Acciones del flujo ' + flow.label"
>
<mat-icon aria-hidden="true">more_vert</mat-icon>
</button>
<mat-menu #menu="matMenu">
<button mat-menu-item type="button" (click)="store.reloadFlow(flow)">
<mat-icon aria-hidden="true">refresh</mat-icon>Volver a leer la fuente
</button>
<button mat-menu-item type="button" (click)="store.removeFlow(flow)">
<mat-icon aria-hidden="true">delete</mat-icon>Quitar flujo
</button>
</mat-menu>
</div>
<p class="flow-card__source" [title]="flow.label">{{ flow.table.connection.label }}</p>
<mat-progress-bar
mode="determinate"
[value]="coverage(flow)"
[attr.aria-label]="'Campos asignados: ' + coverage(flow) + '%'"
></mat-progress-bar>
<div class="flow-card__facts">
<app-flow-status [status]="flow.status()"></app-flow-status>
<span matTooltip="Campos de destino con columna o valor por defecto">
{{ mappedFields(flow) }}/{{ flow.target.fields.length }} campos
</span>
@if (flow.totalRows() !== null) {
<span>{{ flow.totalRows() | number }} filas</span>
}
@if (flow.validation(); as validation) {
@if (validation.error_count > 0) {
<span class="flow-card__errors">{{ validation.error_count | number }} con errores</span>
}
}
@if (flow.result(); as result) {
<span class="flow-card__loaded">+{{ result.created }} / ↻{{ result.updated }}</span>
}
</div>
</mat-card>
}
<div class="canvas__drop" [class.canvas__drop--alone]="store.flows().length === 0">
<mat-icon aria-hidden="true">move_to_inbox</mat-icon>
<p>
@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 <mat-icon inline aria-hidden="true">arrow_forward</mat-icon>.
}
</p>
@if (store.connections().length === 0) {
<button mat-flat-button type="button" (click)="addConnection.emit()">
<mat-icon aria-hidden="true">add</mat-icon>Obtener datos
</button>
}
</div>
</div>
</section>
@@ -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;
}
@@ -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<SourceTable>();
readonly addConnection = output<void>();
readonly onlyTables = (drag: CdkDrag) => drag.data instanceof SourceTable;
onDrop(event: CdkDragDrop<unknown>): 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;
}
}
@@ -0,0 +1,82 @@
@let f = flow();
<section class="editor" [attr.aria-label]="'Flujo ' + f.label">
<header class="editor__header">
<div class="editor__route">
<mat-icon aria-hidden="true">{{ f.table.icon }}</mat-icon>
<span class="editor__source" [title]="f.label">{{ f.label }}</span>
<mat-icon class="editor__arrow" aria-hidden="true">arrow_right_alt</mat-icon>
<mat-icon class="editor__target-icon" aria-hidden="true">table_chart</mat-icon>
<span class="editor__target">{{ f.target.domain.toUpperCase() }} · {{ f.target.table }}</span>
<app-flow-status [status]="f.status()"></app-flow-status>
</div>
<div class="editor__actions">
@if (f.totalRows() !== null) {
<span class="editor__rows">{{ f.totalRows() | number }} filas en la fuente</span>
}
@if (documentTable()) {
<button mat-stroked-button type="button" [disabled]="f.loading()" (click)="reviewExtraction()">
<mat-icon aria-hidden="true">rule</mat-icon>Revisar extracción
</button>
}
<button mat-stroked-button type="button" (click)="store.reloadFlow(f)" matTooltip="Volver a leer la fuente">
<mat-icon aria-hidden="true">refresh</mat-icon>Actualizar
</button>
<button mat-flat-button type="button" [disabled]="!f.canSubmit || f.validating()" (click)="validate()">
<mat-icon aria-hidden="true">fact_check</mat-icon>Validar
</button>
</div>
</header>
@if (f.loading()) {
<mat-progress-bar mode="indeterminate" aria-label="Leyendo la fuente"></mat-progress-bar>
}
@if (f.error(); as error) {
<p class="editor__error" role="alert">
<mat-icon aria-hidden="true">error</mat-icon>{{ error }}
<button mat-button type="button" (click)="store.reloadFlow(f)">Reintentar</button>
</p>
}
@if (f.preview()) {
<mat-tab-group
[selectedIndex]="tab()"
(selectedIndexChange)="tab.set($event)"
animationDuration="0ms"
mat-stretch-tabs="false"
mat-align-tabs="start"
class="editor__tabs"
>
<mat-tab>
<ng-template mat-tab-label>
<mat-icon aria-hidden="true">account_tree</mat-icon>Mapeo
@if (f.missingRequired().length) {
<span class="tab-count tab-count--warn">{{ f.missingRequired().length }}</span>
}
</ng-template>
<div class="editor__panel"><app-column-mapper [flow]="f"></app-column-mapper></div>
</mat-tab>
<mat-tab>
<ng-template mat-tab-label>
<mat-icon aria-hidden="true">functions</mat-icon>Reglas
@if (f.documents() || (f.derived() | keyvalue).length) {
<span class="tab-count">{{ (f.derived() | keyvalue).length + (f.documents() ? 1 : 0) }}</span>
}
</ng-template>
<div class="editor__panel"><app-mapping-rules [flow]="f"></app-mapping-rules></div>
</mat-tab>
<mat-tab>
<ng-template mat-tab-label><mat-icon aria-hidden="true">table_view</mat-icon>Datos</ng-template>
<div class="editor__panel"><app-data-grid [flow]="f"></app-data-grid></div>
</mat-tab>
<mat-tab>
<ng-template mat-tab-label>
<mat-icon aria-hidden="true">fact_check</mat-icon>Validación
@if (f.validation(); as validation) {
<span class="tab-count" [class.tab-count--warn]="validation.error_count > 0">{{ validation.error_count | number }}</span>
}
</ng-template>
<div class="editor__panel"><app-validation-report [flow]="f" (validate)="validate()"></app-validation-report></div>
</mat-tab>
</mat-tab-group>
}
</section>
@@ -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;
}
@@ -0,0 +1,75 @@
import { DecimalPipe, KeyValuePipe } 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 { MappingRules } from '../mapping-rules/mapping-rules';
import { FlowStatusChip } from '../shared/flow-status';
import { ValidationReport } from '../validation-report/validation-report';
const VALIDATION_TAB = 3;
/** Everything about the selected flow: its mapping, its rules, its data, its validation. */
@Component({
selector: 'app-flow-editor',
imports: [
ColumnMapper,
DataGrid,
DecimalPipe,
FlowStatusChip,
KeyValuePipe,
MappingRules,
MatBadgeModule,
MatButtonModule,
MatIconModule,
MatProgressBarModule,
MatTabsModule,
MatTooltipModule,
ValidationReport,
],
templateUrl: './flow-editor.html',
styleUrl: './flow-editor.scss',
})
export class FlowEditor {
readonly flow = input.required<ImportFlow>();
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, DocumentReviewData, boolean>(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<void> {
await this.store.validate(this.flow());
this.tab.set(VALIDATION_TAB);
}
}
@@ -0,0 +1,118 @@
<h2 mat-dialog-title>Cargar a la base de datos · {{ store.domain().toUpperCase() }}</h2>
<mat-dialog-content>
@if (validating()) {
<p class="lead">Validando todas las filas de {{ flows().length }} flujo(s)…</p>
<mat-progress-bar mode="indeterminate" aria-label="Validando"></mat-progress-bar>
} @else {
@if (!batch()) {
<p class="lead">
Se escribirán <strong>{{ totals().valid | number }}</strong> 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) {
<strong class="warn">{{ totals().errors | number }} fila(s) con errores se omitirán.</strong>
}
</p>
} @else if (outcome(); as o) {
<p class="lead lead--done">
<mat-icon aria-hidden="true">cloud_done</mat-icon>
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}.
}
</p>
@if (o.created + o.updated > 0) {
<p class="lead">Los indicadores se recalcularán automáticamente. El avance y el resumen de esta carga pueden consultarse en la Bitácora de cargas.</p>
}
}
<table mat-table [dataSource]="flows()" class="flows">
<ng-container matColumnDef="flow">
<th mat-header-cell *matHeaderCellDef>Flujo</th>
<td mat-cell *matCellDef="let flow">
<span class="flows__name">{{ flow.table.name }}</span>
<span class="flows__target">→ {{ flow.target.table }}</span>
</td>
</ng-container>
<ng-container matColumnDef="status">
<th mat-header-cell *matHeaderCellDef>Estado</th>
<td mat-cell *matCellDef="let flow"><app-flow-status [status]="flow.status()"></app-flow-status></td>
</ng-container>
<ng-container matColumnDef="rows">
<th mat-header-cell *matHeaderCellDef>Filas</th>
<td mat-cell *matCellDef="let flow">{{ flow.validation()?.total_rows | number }}</td>
</ng-container>
<ng-container matColumnDef="valid">
<th mat-header-cell *matHeaderCellDef>Válidas</th>
<td mat-cell *matCellDef="let flow">{{ flow.validation()?.valid_count | number }}</td>
</ng-container>
<ng-container matColumnDef="errors">
<th mat-header-cell *matHeaderCellDef>Con error</th>
<td mat-cell *matCellDef="let flow" [class.warn]="flow.validation()?.error_count">{{ flow.validation()?.error_count | number }}</td>
</ng-container>
<ng-container matColumnDef="outcome">
<th mat-header-cell *matHeaderCellDef>Resultado</th>
<td mat-cell *matCellDef="let flow">
@if (flow.result(); as result) {
+{{ result.created }} · ↻{{ result.updated }} · ✕{{ result.rejected }}@if (result.merged) { · ⧉{{ result.merged }} }
} @else {
—
}
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="columns"></tr>
<tr mat-row *matRowDef="let row; columns: columns"></tr>
</table>
@if (skipped().length > 0) {
<p class="note">
<mat-icon aria-hidden="true">info</mat-icon>
{{ skipped().length }} flujo(s) no se cargarán porque no están listos (faltan obligatorios o la fuente falló).
</p>
}
@if (!batch()) {
<section class="policy" aria-labelledby="policy-title">
<h3 id="policy-title">Si un registro ya existe en la base</h3>
<mat-radio-group [value]="store.upsertAvailable() ? store.onConflict() : 'reject'" (change)="setStrategy($event.value)">
<mat-radio-button value="reject">Omitirlo (se reporta como conflicto)</mat-radio-button>
<mat-radio-button value="upsert" [disabled]="!store.upsertAvailable()">
Actualizarlo con los campos mapeados (los demás campos no se tocan)
</mat-radio-button>
</mat-radio-group>
@if (!store.upsertAvailable()) {
<p class="note">Actualizar solo es posible cuando todas las tablas destino tienen clave natural (p. ej. Paciente).</p>
}
</section>
@if (mergeAvailable()) {
<section class="policy" aria-labelledby="merge-title">
<h3 id="merge-title">Datos de un mismo paciente en varias fuentes</h3>
<mat-checkbox [checked]="store.mergeDuplicates()" (change)="toggleMerge($event.checked)">
Combinar las filas con la misma clave en un solo registro antes de validar
</mat-checkbox>
<p class="note">
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.
</p>
</section>
}
}
@if (store.committing()) {
<mat-progress-bar mode="indeterminate" aria-label="Cargando"></mat-progress-bar>
}
@if (store.commitError(); as error) {
<p class="error" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ error }}</p>
}
}
</mat-dialog-content>
<mat-dialog-actions align="end">
@if (batch()) {
<button mat-button mat-dialog-close type="button">Cerrar</button>
<button mat-flat-button type="button" (click)="explore()"><mat-icon aria-hidden="true">travel_explore</mat-icon>Explorar la base</button>
} @else {
<button mat-button mat-dialog-close type="button">Cancelar</button>
<button mat-flat-button type="button" [disabled]="validating() || store.committing() || !canLoad()" (click)="load()">
<mat-icon aria-hidden="true">cloud_upload</mat-icon>Cargar {{ totals().valid | number }} filas
</button>
}
</mat-dialog-actions>
@@ -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;
}
}
@@ -0,0 +1,97 @@
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<LoadDialog, LoadDialogResult>>(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 writes; frozen once it starts so the results match what was sent. */
private readonly _frozenFlows = signal<ImportFlow[] | null>(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<void> {
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);
}
/** Merging can add flows to the batch; validate them so their rows show up in the preview. */
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');
}
}
@@ -0,0 +1,238 @@
@let f = flow();
@let docs = documentForm();
<div class="rules">
<section class="rules__section" aria-labelledby="documents-title">
<header class="rules__header">
<h3 id="documents-title"><mat-icon aria-hidden="true">document_scanner</mat-icon>Documentos dentro de columnas</h3>
@if (f.documents()) {
<span class="rules__badge">Leyendo {{ f.documents()!.columns.length }} columna(s)</span>
}
</header>
<p class="rules__hint">
Si alguna columna guarda archivos (PDF o imágenes, como binario, hexadecimal o base64), se leen y todo lo que
imprimen (campos conocidos y cualquier otra etiqueta) aparece como columnas nuevas que puede asignar o usar en reglas.
Los valores que vienen de columnas de la fuente se respetan por encima de lo que diga el documento.
@if (f.documentColumns().length) {
Columnas con archivos detectadas: <strong>{{ f.documentColumns().join(', ') }}</strong>.
}
</p>
<div class="rules__grid">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Columnas con documentos</mat-label>
<mat-select multiple [ngModel]="docs.columns" (ngModelChange)="patchDocuments({ columns: $event })">
@for (name of columnNames(); track name) {
<mat-option [value]="name">{{ name }}@if (f.documentColumns().includes(name)) { (archivo) }</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Agrupar registros por</mat-label>
<mat-select [ngModel]="docs.group_by" (ngModelChange)="patchDocuments({ group_by: $event })">
<mat-option value="">Por el identificador del paciente</mat-option>
@for (name of columnNames(); track name) {
<mat-option [value]="name">{{ name }}</mat-option>
}
</mat-select>
<mat-hint>Las filas con el mismo valor forman un solo registro (p. ej. un número de estudio).</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Guardar el documento en</mat-label>
<mat-select [ngModel]="docs.file_field" (ngModelChange)="patchDocuments({ file_field: $event })">
<mat-option value="">No guardar</mat-option>
@for (field of fileFields(); track field.name) {
<mat-option [value]="field.name">{{ field.name }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>OCR</mat-label>
<mat-select [ngModel]="docs.ocr_mode" (ngModelChange)="patchDocuments({ ocr_mode: $event })">
<mat-option value="auto">Solo páginas escaneadas</mat-option>
<mat-option value="always">Todas las páginas</mat-option>
<mat-option value="never">Nunca (solo texto del PDF)</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Solo documentos que digan</mat-label>
<input matInput [ngModel]="docs.include_pattern" (ngModelChange)="patchDocuments({ include_pattern: $event })" />
<mat-hint>Expresión regular; sin distinguir mayúsculas ni acentos.</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Omitir documentos que digan</mat-label>
<input matInput [ngModel]="docs.exclude_pattern" (ngModelChange)="patchDocuments({ exclude_pattern: $event })" />
</mat-form-field>
</div>
<mat-checkbox [checked]="f.catalogFallback()" (change)="f.setCatalogFallback($event.checked)">
Guardar también, en el expediente de cada paciente, las etiquetas de los documentos que el catálogo del proyecto ya
conoce
</mat-checkbox>
<p class="rules__hint">
Las etiquetas que nadie usa no se guardan: aparecen, solo con su nombre y cuántos registros las traen, en la
Bitácora de cargas.
</p>
<div class="rules__actions">
<button mat-flat-button type="button" [disabled]="documentsBusy()" (click)="applyDocuments()">
<mat-icon aria-hidden="true">play_arrow</mat-icon>Leer documentos
</button>
@if (f.documents()) {
<button mat-button type="button" (click)="clearDocuments()">Dejar de leerlos</button>
}
</div>
@if (documentsBusy()) {
<mat-progress-bar mode="indeterminate" />
}
@if (documentsError(); as error) {
<p class="rules__error" role="alert">{{ error }}</p>
}
</section>
<section class="rules__section" aria-labelledby="derived-title">
<header class="rules__header">
<h3 id="derived-title"><mat-icon aria-hidden="true">functions</mat-icon>Campos calculados</h3>
</header>
<p class="rules__hint">
Para cuando las columnas no coinciden una a una con los campos: unir nombre y apellidos, separar un nombre completo,
tomar la primera columna con valor, extraer un dato de un texto o traducir códigos. Funciona igual con columnas de la
fuente y con lo leído de los documentos.
</p>
@for (item of rules(); track item.field) {
<div class="rule">
<mat-icon aria-hidden="true">arrow_forward</mat-icon>
<strong>{{ item.field }}</strong>
<span class="rule__summary">{{ item.summary }}</span>
<button mat-icon-button type="button" [attr.aria-label]="'Quitar regla de ' + item.field" (click)="removeRule(item.field)">
<mat-icon>delete</mat-icon>
</button>
</div>
}
<div class="rules__grid">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Campo</mat-label>
<mat-select [ngModel]="ruleField()" (ngModelChange)="ruleField.set($event)">
@for (field of f.target.fields; track field.name) {
<mat-option [value]="field.name">{{ field.name }}@if (field.required) { * }</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Cómo calcularlo</mat-label>
<mat-select [ngModel]="ruleOp()" (ngModelChange)="chooseOp($event)">
@for (spec of catalog()?.derivations ?? []; track spec.op) {
<mat-option [value]="spec.op" [matTooltip]="spec.description">{{ spec.label }}</mat-option>
}
</mat-select>
@if (selectedSpec(); as spec) {
<mat-hint>{{ spec.description }}</mat-hint>
}
</mat-form-field>
@for (param of selectedSpec()?.params ?? []; track param.name) {
@switch (param.kind) {
@case ('column') {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{ param.label }}</mat-label>
<mat-select [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)">
@for (name of columnNames(); track name) {
<mat-option [value]="name">{{ name }}</mat-option>
}
</mat-select>
</mat-form-field>
}
@case ('columns') {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{ param.label }} (en orden)</mat-label>
<mat-select multiple [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)">
@for (name of columnNames(); track name) {
<mat-option [value]="name">{{ name }}</mat-option>
}
</mat-select>
</mat-form-field>
}
@case ('integer') {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{ param.label }}</mat-label>
<input matInput type="number" [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)" />
</mat-form-field>
}
@case ('boolean') {
<mat-checkbox [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)">{{ param.label }}</mat-checkbox>
}
@case ('mapping') {
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="rules__wide">
<mat-label>{{ param.label }}</mat-label>
<textarea matInput rows="3" placeholder="M = Masculino" [ngModel]="mappingText(param.name)" (ngModelChange)="setMappingText(param.name, $event)"></textarea>
<mat-hint>Una equivalencia por línea: valor = nuevo valor.</mat-hint>
</mat-form-field>
}
@default {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{ param.label }}</mat-label>
<input matInput [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)" />
</mat-form-field>
}
}
}
@if (selectedSpec()) {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Mayúsculas</mat-label>
<mat-select [ngModel]="ruleCase()" (ngModelChange)="ruleCase.set($event)">
<mat-option value="">Sin cambio</mat-option>
<mat-option value="upper">MAYÚSCULAS</mat-option>
<mat-option value="lower">minúsculas</mat-option>
<mat-option value="title">Tipo Título</mat-option>
</mat-select>
</mat-form-field>
}
</div>
<div class="rules__actions">
<button mat-stroked-button type="button" [disabled]="!ruleField() || !selectedSpec()" (click)="addRule()">
<mat-icon aria-hidden="true">add</mat-icon>Agregar regla
</button>
</div>
@if (ruleError(); as error) {
<p class="rules__error" role="alert">{{ error }}</p>
}
</section>
<section class="rules__section" aria-labelledby="result-title">
<header class="rules__header">
<h3 id="result-title"><mat-icon aria-hidden="true">preview</mat-icon>Resultado</h3>
<button mat-stroked-button type="button" [disabled]="previewBusy()" (click)="preview()">
<mat-icon aria-hidden="true">visibility</mat-icon>Ver cómo quedarían las filas
</button>
</header>
@if (previewBusy()) {
<mat-progress-bar mode="indeterminate" />
}
@if (previewError(); as error) {
<p class="rules__error" role="alert">{{ error }}</p>
}
@if (previewRows(); as rows) {
<div class="rules__table-wrap">
<table class="rules__table">
<thead>
<tr>
@for (column of previewColumns(); track column) {
<th scope="col">{{ column }}</th>
}
</tr>
</thead>
<tbody>
@for (row of rows; track $index) {
<tr>
@for (column of previewColumns(); track column) {
<td>{{ cell(row[column]) }}</td>
}
</tr>
} @empty {
<tr><td>La fuente no dio filas.</td></tr>
}
</tbody>
</table>
</div>
}
</section>
</div>
@@ -0,0 +1,113 @@
:host {
display: block;
}
.rules {
display: flex;
flex-direction: column;
gap: 24px;
padding: 16px;
}
.rules__section {
display: flex;
flex-direction: column;
gap: 12px;
}
.rules__header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
h3 {
display: flex;
align-items: center;
gap: 8px;
margin: 0;
font: var(--mat-sys-title-medium);
}
}
.rules__badge {
font: var(--mat-sys-label-medium);
color: var(--mat-sys-primary);
}
.rules__hint {
margin: 0;
font: var(--mat-sys-body-small);
color: var(--mat-sys-on-surface-variant);
}
.rules__grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 12px 16px;
align-items: start;
}
.rules__wide {
grid-column: 1 / -1;
}
.rules__actions {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.rules__error {
margin: 0;
color: var(--mat-sys-error);
font: var(--mat-sys-body-medium);
}
.rule {
display: flex;
align-items: center;
gap: 8px;
padding: 4px 8px;
border-radius: 8px;
background: var(--mat-sys-surface-container);
}
.rule__summary {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--mat-sys-on-surface-variant);
}
.rules__table-wrap {
overflow-x: auto;
max-height: 360px;
border: 1px solid var(--mat-sys-outline-variant);
border-radius: 8px;
}
.rules__table {
border-collapse: collapse;
font: var(--mat-sys-body-small);
th,
td {
padding: 4px 8px;
border-bottom: 1px solid var(--mat-sys-outline-variant);
text-align: left;
white-space: nowrap;
max-width: 240px;
overflow: hidden;
text-overflow: ellipsis;
}
th {
position: sticky;
top: 0;
background: var(--mat-sys-surface-container-high);
}
}
@@ -0,0 +1,255 @@
import { Component, computed, effect, inject, input, signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
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 { firstValueFrom } from 'rxjs';
import {
DerivationParam,
DerivationRule,
DerivationSpec,
DocumentColumnsConfig,
OcrMode,
Row,
apiErrorMessage,
} from '../../api/api.types';
import { ImportsApi } from '../../api/imports.api';
import { ImportFlow } from '../../domain/import-flow';
interface DocumentForm {
columns: string[];
group_by: string;
file_field: string;
ocr_mode: OcrMode;
include_pattern: string;
exclude_pattern: string;
}
/**
* What a plain column-to-field mapping can't express, for any kind of
* source: columns whose cells hold documents (read for every field and
* caption they print, which then become columns of their own), target
* fields computed from several columns, and a look at the rows as they
* would be written.
*
* The operations and their parameters come from the server
* (`/imports/derivations`), so a new operation needs no change here.
*/
@Component({
selector: 'app-mapping-rules',
imports: [
FormsModule,
MatButtonModule,
MatCheckboxModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatProgressBarModule,
MatSelectModule,
MatTooltipModule,
],
templateUrl: './mapping-rules.html',
styleUrl: './mapping-rules.scss',
})
export class MappingRules {
readonly flow = input.required<ImportFlow>();
private readonly api = inject(ImportsApi);
readonly catalog = toSignal(this.api.derivations());
readonly columnNames = computed(() => this.flow().sourceColumns().map((column) => column.name));
readonly fileFields = computed(() => this.flow().target.fields.filter((field) => field.type === 'binary' || field.name.endsWith('_blob')));
readonly documentForm = signal<DocumentForm>(this.emptyDocumentForm());
readonly documentsBusy = signal(false);
readonly documentsError = signal<string | null>(null);
readonly ruleField = signal<string>('');
readonly ruleOp = signal<string>('');
readonly ruleParams = signal<Record<string, unknown>>({});
readonly ruleCase = signal<string>('');
readonly ruleError = signal<string | null>(null);
readonly previewRows = signal<Row[] | null>(null);
readonly previewBusy = signal(false);
readonly previewError = signal<string | null>(null);
readonly selectedSpec = computed<DerivationSpec | undefined>(() =>
this.catalog()?.derivations.find((spec) => spec.op === this.ruleOp()),
);
readonly rules = computed(() =>
Object.entries(this.flow().derived()).map(([field, rule]) => ({ field, rule, summary: this.describe(rule) })),
);
readonly previewColumns = computed(() => {
const rows = this.previewRows() ?? [];
return [...new Set(rows.flatMap((row) => Object.keys(row)))];
});
constructor() {
// The form follows the flow: what it has configured, or the columns the server flagged.
effect(() => {
const flow = this.flow();
const current = flow.documents();
this.documentForm.set(current ? this.formFrom(current) : { ...this.emptyDocumentForm(), columns: flow.documentColumns() });
});
}
// -- documents -----------------------------------------------------------
patchDocuments(patch: Partial<DocumentForm>): void {
this.documentForm.update((form) => ({ ...form, ...patch }));
}
async applyDocuments(): Promise<void> {
const form = this.documentForm();
const flow = this.flow();
if (!form.columns.length) {
this.clearDocuments();
return;
}
flow.setDocuments({
columns: form.columns,
group_by: form.group_by || undefined,
file_field: form.file_field || undefined,
ocr_mode: form.ocr_mode,
include_pattern: form.include_pattern.trim() || undefined,
exclude_pattern: form.exclude_pattern.trim() || undefined,
});
this.documentsBusy.set(true);
this.documentsError.set(null);
try {
flow.useDocumentPreview(await firstValueFrom(this.api.documentColumns(await flow.toPayload())));
} catch (error) {
this.documentsError.set(apiErrorMessage(error, 'No se pudieron leer los documentos.'));
} finally {
this.documentsBusy.set(false);
}
}
clearDocuments(): void {
this.flow().setDocuments(null);
this.documentsError.set(null);
}
// -- derived fields ------------------------------------------------------
chooseOp(op: string): void {
this.ruleOp.set(op);
const spec = this.catalog()?.derivations.find((candidate) => candidate.op === op);
this.ruleParams.set(Object.fromEntries((spec?.params ?? []).map((param) => [param.name, this.initial(param)])));
this.ruleError.set(null);
}
setParam(name: string, value: unknown): void {
this.ruleParams.update((params) => ({ ...params, [name]: value }));
}
/** `clave = valor` lines, the text form of a `mapping` parameter. */
mappingText(name: string): string {
const value = this.ruleParams()[name];
return value && typeof value === 'object' ? Object.entries(value).map(([k, v]) => `${k} = ${v}`).join('\n') : '';
}
setMappingText(name: string, text: string): void {
const entries = text
.split('\n')
.map((line) => line.split('='))
.filter((parts) => parts.length >= 2 && parts[0].trim())
.map(([key, ...rest]) => [key.trim(), rest.join('=').trim()]);
this.setParam(name, Object.fromEntries(entries));
}
addRule(): void {
const spec = this.selectedSpec();
const field = this.ruleField();
if (!spec || !field) return;
const params = this.ruleParams();
const missing = spec.params.filter((param) => param.required && this.blank(params[param.name]));
if (missing.length) {
this.ruleError.set(`Falta: ${missing.map((param) => param.label).join(', ')}`);
return;
}
const rule: DerivationRule = { op: spec.op };
for (const param of spec.params) {
const value = params[param.name];
if (!this.blank(value)) rule[param.name] = param.kind === 'integer' ? Number(value) : value;
}
if (this.ruleCase()) rule.case = this.ruleCase();
this.flow().setDerived(field, rule);
this.ruleField.set('');
this.ruleOp.set('');
this.ruleParams.set({});
this.ruleCase.set('');
this.ruleError.set(null);
}
removeRule(field: string): void {
this.flow().setDerived(field, null);
}
// -- preview ---------------------------------------------------------------
async preview(): Promise<void> {
this.previewBusy.set(true);
this.previewError.set(null);
try {
const { rows } = await firstValueFrom(this.api.mappedPreview(await this.flow().toPayload(), 10));
this.previewRows.set(rows);
} catch (error) {
this.previewError.set(apiErrorMessage(error, 'No se pudo armar la vista previa.'));
} finally {
this.previewBusy.set(false);
}
}
cell(value: unknown): string {
if (value === null || value === undefined) return '';
return typeof value === 'object' ? JSON.stringify(value) : String(value);
}
private describe(rule: DerivationRule): string {
const spec = this.catalog()?.derivations.find((candidate) => candidate.op === rule.op);
const parts = (spec?.params ?? [])
.filter((param) => !this.blank(rule[param.name]))
.map((param) => `${param.label}: ${this.cell(rule[param.name])}`);
return [spec?.label ?? rule.op, ...parts, ...(rule.case ? [`(${rule.case})`] : [])].join(' · ');
}
private initial(param: DerivationParam): unknown {
if (param.kind === 'columns') return [];
if (param.kind === 'mapping') return {};
return param.default ?? (param.kind === 'boolean' ? false : '');
}
private blank(value: unknown): boolean {
return (
value === null ||
value === undefined ||
(typeof value === 'string' && !value.trim()) ||
(Array.isArray(value) && !value.length) ||
(typeof value === 'object' && !Array.isArray(value) && !Object.keys(value as object).length)
);
}
private emptyDocumentForm(): DocumentForm {
return { columns: [], group_by: '', file_field: '', ocr_mode: 'auto', include_pattern: '', exclude_pattern: '' };
}
private formFrom(config: DocumentColumnsConfig): DocumentForm {
return {
columns: config.columns,
group_by: typeof config.group_by === 'string' ? config.group_by : '',
file_field: config.file_field ?? '',
ocr_mode: config.ocr_mode ?? 'auto',
include_pattern: config.include_pattern ?? '',
exclude_pattern: config.exclude_pattern ?? '',
};
}
}
@@ -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<string, number>;
}
/** "¿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: `
<h2 mat-dialog-title>Nueva carga desde «{{ data.table.name }}»</h2>
<mat-dialog-content>
<p class="hint">Elige la tabla de destino. Puedes cargar varias fuentes en la misma tabla y una misma fuente en varias tablas.</p>
<mat-selection-list
[multiple]="false"
(selectionChange)="selected.set($event.options[0].value)"
aria-label="Tabla de destino"
>
@for (target of data.targets; track target.key) {
<mat-list-option [value]="target" [selected]="target === selected()">
<mat-icon matListItemIcon aria-hidden="true">table_chart</mat-icon>
<span matListItemTitle>
{{ target.table }}
@if (target === suggested) {
<span class="tag">Sugerida</span>
}
</span>
<span matListItemLine>
{{ target.fields.length }} campos · {{ requiredCount(target) }} obligatorios
@if (data.existingTargets.get(target.key); as count) {
· ya la cargan {{ count }} flujo(s)
}
</span>
</mat-list-option>
}
</mat-selection-list>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button mat-dialog-close type="button">Cancelar</button>
<button mat-flat-button type="button" [disabled]="!selected()" (click)="dialogRef.close(selected() ?? undefined)">Crear flujo</button>
</mat-dialog-actions>
`,
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<NewFlowDialogData>(MAT_DIALOG_DATA);
readonly dialogRef = inject<MatDialogRef<NewFlowDialog, TargetMeta>>(MatDialogRef);
readonly suggested = suggestTarget(this.data.table.name, this.data.targets, this.data.table.connection.label);
readonly selected = signal<TargetMeta | null>(this.suggested);
requiredCount(target: TargetMeta): number {
return target.fields.filter((field) => field.required).length;
}
}
@@ -0,0 +1,56 @@
<div class="viewer">
<div class="viewer__toolbar">
<button mat-icon-button type="button" [disabled]="pageNumber() <= 1" (click)="previous()" aria-label="Página anterior">
<mat-icon aria-hidden="true">chevron_left</mat-icon>
</button>
<span class="viewer__page-label">Página {{ pageNumber() }} de {{ pageCount() }}</span>
<button mat-icon-button type="button" [disabled]="pageNumber() >= pageCount()" (click)="next()" aria-label="Página siguiente">
<mat-icon aria-hidden="true">chevron_right</mat-icon>
</button>
</div>
@if (loading()) {
<mat-progress-bar mode="indeterminate" aria-label="Cargando página"></mat-progress-bar>
}
@if (error()) {
<p class="viewer__error" role="alert">{{ error() }}</p>
}
<div class="viewer__stage">
@if (imageUrl(); as url) {
<img [src]="url" [attr.alt]="'Página ' + pageNumber() + ' del PDF'" class="viewer__image" />
<div class="region-overlay" appRegionDrawOverlay #overlay="appRegionDrawOverlay" (regionDrawn)="regionDrawn.emit($event)">
@for (region of regionsOnCurrentPage(); track region.target_field) {
<div
class="region-overlay__box"
[style.left.%]="region.bbox[0] * 100"
[style.top.%]="region.bbox[1] * 100"
[style.width.%]="(region.bbox[2] - region.bbox[0]) * 100"
[style.height.%]="(region.bbox[3] - region.bbox[1]) * 100"
>
<span class="region-overlay__label">
{{ region.target_field }}
<button
type="button"
class="region-overlay__remove"
(pointerdown)="$event.stopPropagation()"
(click)="onRemoveClick($event, region)"
[attr.aria-label]="'Quitar región ' + region.target_field"
>×</button>
</span>
</div>
}
@if (overlay.liveBox(); as box) {
<div
class="region-overlay__live"
[style.left.px]="box.x"
[style.top.px]="box.y"
[style.width.px]="box.width"
[style.height.px]="box.height"
></div>
}
</div>
}
</div>
</div>
@@ -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);
}
@@ -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<Blob> {
this.calls.push(pageNumber);
return of(new Blob([`page-${pageNumber}`], { type: 'image/png' }));
}
}
describe('PdfPageViewer', () => {
let fakeApi: FakePdfSourceApi;
let createObjectURL: ReturnType<typeof vi.spyOn>;
let revokeObjectURL: ReturnType<typeof vi.spyOn>;
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']);
});
});
@@ -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<File>();
readonly pageNumber = input.required<number>();
readonly pageCount = input.required<number>();
/** Drawn regions on all pages; only the current page's are rendered. */
readonly regions = input<RegionSpec[]>([]);
readonly pageNumberChange = output<number>();
readonly regionDrawn = output<DrawnRegionBox>();
readonly regionRemove = output<RegionSpec>();
private readonly pdfApi = inject(PdfSourceApi);
readonly imageUrl = signal<string | null>(null);
readonly loading = signal(false);
readonly error = signal<string | null>(null);
private readonly blobCache = new Map<number, Blob>();
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);
}
}
@@ -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: `<div class="overlay" appRegionDrawOverlay (regionDrawn)="onRegionDrawn($event)"></div>`,
})
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<x1, y0<y1)', () => {
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();
});
});
@@ -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<x1 and y0<y1. */
export interface DrawnRegionBox {
x0: number;
y0: number;
x1: number;
y1: number;
}
/** A live-drag box in CSS pixels, relative to the overlay element's own origin. */
export interface LiveDrawBox {
x: number;
y: number;
width: number;
height: number;
}
/** Drags below this size (in either dimension) are treated as accidental clicks. */
const MIN_DRAG_PX = 5;
/**
* Draws boxes with plain pointer events on an overlay sized to the rendered
* page, and emits each one normalized via `regionDrawn`. CDK drag-drop is
* not used because it moves existing elements; here a box is defined by a
* single drag.
*
* Pointer capture keeps move/up events on this element when the pointer
* leaves it mid-drag. The in-progress box is exposed as `liveBox`
* (`#overlay="appRegionDrawOverlay"`) for the host template to render.
*/
@Directive({
selector: '[appRegionDrawOverlay]',
exportAs: 'appRegionDrawOverlay',
})
export class RegionDrawOverlay {
readonly regionDrawn = output<DrawnRegionBox>();
readonly liveBox = signal<LiveDrawBox | null>(null);
private readonly element = inject(ElementRef<HTMLElement>);
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 };
}
}
@@ -0,0 +1,74 @@
<h2 mat-dialog-title>Dibujar regiones · {{ connection.label }}</h2>
<mat-dialog-content class="regions">
<div class="regions__viewer">
<app-pdf-page-viewer
[file]="connection.file"
[pageNumber]="page()"
[pageCount]="pageCount"
[regions]="regions()"
(pageNumberChange)="page.set($event)"
(regionDrawn)="onRegionDrawn($event)"
(regionRemove)="remove($event)"
></app-pdf-page-viewer>
</div>
<aside class="regions__side">
<mat-form-field appearance="outline" class="regions__name">
<mat-label>Nombre de la tabla</mat-label>
<input matInput [value]="name()" (input)="name.set($any($event.target).value)" />
</mat-form-field>
<p class="regions__hint">
Arrastra sobre la página para marcar cada columna. Cada región se vuelve una columna de origen: nómbrala (se
sugieren los campos de la base) y luego mapéala como cualquier otra tabla.
@if (connection.detection()?.has_text_layer === false) {
<br /><strong>Documento escaneado:</strong> el texto se leerá por OCR.
}
</p>
@for (region of regions(); track $index) {
<div class="region" [class.region--invalid]="duplicateNames().has(region.target_field)">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="region__name">
<mat-label>Columna</mat-label>
<input
matInput
#nameInput
[value]="region.target_field"
[matAutocomplete]="auto"
(change)="rename(region, nameInput.value)"
(keydown.enter)="rename(region, nameInput.value)"
/>
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="rename(region, $event.option.value)">
@for (option of suggestionsFor(nameInput.value); track option) {
<mat-option [value]="option">{{ option }}</mat-option>
}
</mat-autocomplete>
</mat-form-field>
<div class="region__meta">
<mat-checkbox
[checked]="region.page_numbers.length === pageCount && pageCount > 1"
[disabled]="pageCount === 1"
(change)="setAllPages(region, $event.checked)"
>
Todas las páginas
</mat-checkbox>
<span class="region__pages">{{ pagesLabel(region) }}</span>
<button mat-icon-button type="button" (click)="remove(region)" [attr.aria-label]="'Quitar ' + region.target_field">
<mat-icon aria-hidden="true">delete</mat-icon>
</button>
</div>
</div>
} @empty {
<p class="regions__empty"><mat-icon aria-hidden="true">crop_free</mat-icon>Aún no hay regiones.</p>
}
@if (duplicateNames().size > 0) {
<p class="regions__error" role="alert">Cada columna necesita un nombre único.</p>
}
</aside>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button mat-dialog-close type="button">Cancelar</button>
<button mat-flat-button type="button" [disabled]="!canAccept()" (click)="accept()">
Agregar tabla ({{ regions().length }} columnas)
</button>
</mat-dialog-actions>
@@ -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;
}
}
@@ -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<PdfRegionsDialogData>(MAT_DIALOG_DATA);
private readonly dialogRef = inject<MatDialogRef<PdfRegionsDialog, PdfRegionsResult>>(MatDialogRef);
readonly connection = this.data.connection;
readonly pageCount = this.connection.detection()?.page_count ?? 1;
readonly page = signal(1);
readonly regions = signal<RegionSpec[]>([]);
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() })),
});
}
}
@@ -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<HTMLInputElement>>(ElementRef).nativeElement;
afterNextRender(() => {
element.focus();
element.select();
});
}
}
@@ -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<FlowStatus, { label: string; icon: string; tone: string; hint: string }> = {
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: `
<span class="flow-status" [attr.data-tone]="view().tone" [matTooltip]="view().hint">
<mat-icon aria-hidden="true">{{ view().icon }}</mat-icon>{{ view().label }}
</span>
`,
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<FlowStatus>();
readonly view = computed(() => PRESENTATION[this.status()]);
}
@@ -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}`;
};
}
@@ -0,0 +1,41 @@
import { Pipe, PipeTransform } from '@angular/core';
const ICONS: Record<string, string> = {
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, string> = {
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');
}
}
@@ -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: `
<h2 mat-dialog-title>Consulta SQL · {{ connection.label }}</h2>
<mat-dialog-content>
<form [formGroup]="form" class="query-form">
<mat-form-field appearance="outline">
<mat-label>Nombre</mat-label>
<input matInput formControlName="name" />
</mat-form-field>
<mat-form-field appearance="outline" class="query-form__sql">
<mat-label>SELECT</mat-label>
<textarea matInput formControlName="query" rows="8" spellcheck="false"></textarea>
<mat-hint>Una sola sentencia SELECT (o WITH … SELECT). La conexión es de solo lectura.</mat-hint>
</mat-form-field>
</form>
@if (running()) {
<mat-progress-bar mode="indeterminate" aria-label="Ejecutando consulta"></mat-progress-bar>
}
@if (error(); as message) {
<p class="query-error" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ message }}</p>
}
@if (preview(); as result) {
<p class="query-summary">{{ result.total_rows }} filas · {{ result.columns.length }} columnas</p>
<div class="query-preview">
<table mat-table [dataSource]="result.sample_rows.slice(0, 5)">
@for (column of result.columns; track column.name) {
<ng-container [matColumnDef]="column.name">
<th mat-header-cell *matHeaderCellDef>{{ column.name }}</th>
<td mat-cell *matCellDef="let row">{{ row[column.name] }}</td>
</ng-container>
}
<tr mat-header-row *matHeaderRowDef="columnNames()"></tr>
<tr mat-row *matRowDef="let row; columns: columnNames()"></tr>
</table>
</div>
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button mat-dialog-close type="button">Cancelar</button>
<button mat-stroked-button type="button" [disabled]="form.invalid || running()" (click)="run()">
<mat-icon aria-hidden="true">play_arrow</mat-icon>Probar
</button>
<button mat-flat-button type="button" [disabled]="form.invalid || !preview()" (click)="accept()">Agregar</button>
</mat-dialog-actions>
`,
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<SqlConnection>(MAT_DIALOG_DATA);
private readonly dialogRef = inject<MatDialogRef<SqlQueryDialog, SqlQueryResult>>(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<string | null>(null);
readonly preview = signal<PreviewResponse | null>(null);
readonly columnNames = signal<string[]>([]);
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());
}
}
@@ -0,0 +1,99 @@
@let f = flow();
@if (f.validating()) {
<mat-progress-bar mode="indeterminate" aria-label="Validando"></mat-progress-bar>
}
@if (f.validation(); as validation) {
<div class="tiles">
<div class="tile">
<span class="tile__value">{{ validation.total_rows | number }}</span>
<span class="tile__label">filas leídas</span>
</div>
<div class="tile tile--ok">
<span class="tile__value">{{ validation.valid_count | number }}</span>
<span class="tile__label">válidas · {{ validPercent() }}%</span>
</div>
<div class="tile" [class.tile--warn]="validation.error_count > 0">
<span class="tile__value">{{ validation.error_count | number }}</span>
<span class="tile__label">con errores (se omiten)</span>
</div>
@if (f.result(); as result) {
<div class="tile tile--ok">
<span class="tile__value">{{ result.created | number }} / {{ result.updated | number }}</span>
<span class="tile__label">insertadas / actualizadas</span>
</div>
}
</div>
@if (errors().length > 0) {
<div class="filters">
<mat-chip-listbox multiple [value]="categories()" (change)="onCategories($event.value)" aria-label="Filtrar por tipo de error">
@for (item of countsByCategory(); track item.category) {
<mat-chip-option [value]="item.category">{{ categoryLabels[item.category] }} · {{ item.count }}</mat-chip-option>
}
</mat-chip-listbox>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="filters__field">
<mat-label>Campo</mat-label>
<mat-select [value]="field()" (selectionChange)="onField($event.value)">
<mat-option [value]="null">Todos</mat-option>
@for (name of fieldsWithErrors(); track name) {
<mat-option [value]="name">{{ name }}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<div class="table-scroll">
<table mat-table [dataSource]="pageRows()" class="errors">
<ng-container matColumnDef="row">
<th mat-header-cell *matHeaderCellDef>Fila</th>
<td mat-cell *matCellDef="let error">{{ error.row_index + 1 }}</td>
</ng-container>
<ng-container matColumnDef="field">
<th mat-header-cell *matHeaderCellDef>Campo</th>
<td mat-cell *matCellDef="let error" class="errors__field">{{ error.field }}</td>
</ng-container>
<ng-container matColumnDef="category">
<th mat-header-cell *matHeaderCellDef>Tipo</th>
<td mat-cell *matCellDef="let error">
<span class="category" [attr.data-category]="error.category">{{ categoryLabel(error.category) }}</span>
</td>
</ng-container>
<ng-container matColumnDef="value">
<th mat-header-cell *matHeaderCellDef>Valor</th>
<td mat-cell *matCellDef="let error" class="errors__value">{{ display(error.raw_value) }}</td>
</ng-container>
<ng-container matColumnDef="message">
<th mat-header-cell *matHeaderCellDef>Detalle</th>
<td mat-cell *matCellDef="let error">{{ error.message }}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="columns; sticky: true"></tr>
<tr mat-row *matRowDef="let row; columns: columns"></tr>
</table>
</div>
<mat-paginator
[length]="filtered().length"
[pageIndex]="page().index"
[pageSize]="page().size"
[pageSizeOptions]="[25, 50, 100]"
(page)="onPage($event)"
aria-label="Paginación de errores"
></mat-paginator>
} @else {
<p class="all-good"><mat-icon aria-hidden="true">verified</mat-icon>Todas las filas pasan la validación.</p>
}
} @else if (!f.validating()) {
<div class="empty">
<mat-icon aria-hidden="true">fact_check</mat-icon>
<p>
La validación revisa <strong>todas</strong> las filas de la fuente contra las reglas de la tabla destino
(obligatorios, catálogos, formatos) sin escribir nada en la base.
</p>
<button mat-flat-button type="button" [disabled]="!f.canSubmit" (click)="validate.emit()">
<mat-icon aria-hidden="true">play_arrow</mat-icon>Validar ahora
</button>
@if (!f.canSubmit) {
<p class="empty__hint">Completa primero los campos obligatorios en «Mapeo».</p>
}
</div>
}
@@ -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);
}
@@ -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<ErrorCategory, string> = {
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<ImportFlow>();
readonly validate = output<void>();
readonly categoryLabels = CATEGORY_LABELS;
readonly columns = ['row', 'field', 'category', 'value', 'message'];
readonly categories = signal<ErrorCategory[]>([]);
readonly field = signal<string | null>(null);
readonly page = signal({ index: 0, size: 25 });
readonly errors = computed<RowError[]>(() => this.flow().validation()?.errors ?? []);
readonly countsByCategory = computed(() => {
const counts = new Map<ErrorCategory, number>();
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);
}
}

Some files were not shown because too many files have changed in this diff Show More