feat(cama): the four BI-RADS charts as two, mammograms and patients on one card
How: PARES_CONTEOS pairs two C2 counts of the same finding, one per exam and one per patient, with the map from exam category to patient category (BI-RADS 4A, 4B and 4C are a patient's BI-RADS 4). The exams' card (cama_birads_456_mastografia) draws IndicadorConteosPareados: a donut of the mammograms by category with their total in the centre, and grouped bars with each patient BI-RADS next to its mammograms and "≈ n por paciente" at the end of each pair. Both counts come from the same period request; a suppressed cell leaves its sum, ratio and the donut undrawn instead of using zero. The patients' indicator has no card of its own in Resumen (esSocioConteos); it still feeds its opportunity card and Histórico. Implications: the view depends on the exams' and patients' category ids (B4A..B6, BIRADS_4..BIRADS_6) matching grupoDe; a renamed category makes the view reject the answer as incompatible. The real API already publishes both indicators with these ids.
This commit is contained in:
@@ -20,11 +20,13 @@ import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
|
||||
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
||||
import { vistaConfirmacion } from './indicadores-confirmacion-citologia';
|
||||
import { parTiempos } from './indicadores-tiempos-pareados';
|
||||
import { parConteos } from './indicadores-conteos-pareados';
|
||||
import { IndicadorConteosPareados } from './indicador-conteos-pareados';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-catalog-card',
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || !!tiempos' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia],
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || !!tiempos || !!conteos' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorConteosPareados],
|
||||
template: `
|
||||
<mat-card>
|
||||
<header>
|
||||
@@ -47,6 +49,10 @@ import { parTiempos } from './indicadores-tiempos-pareados';
|
||||
<div #visibilityRegion class="confirmacion-region">
|
||||
<app-indicador-confirmacion-citologia [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (conteos; as par) {
|
||||
<div #visibilityRegion class="conteos-region">
|
||||
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (tiempos; as par) {
|
||||
<div #visibilityRegion class="tiempos-region">
|
||||
<app-indicador-tiempos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
@@ -125,6 +131,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
get isConfirmacion() { return !!vistaConfirmacion(this.dominio, this.indicador); }
|
||||
// Connected time pairs replace the diagnosis card with one coordinated box plot.
|
||||
get tiempos() { return parTiempos(this.dominio, this.indicador.id); }
|
||||
// Exams and patients of the same finding, drawn together on the exams' card.
|
||||
get conteos() { return parConteos(this.dominio, this.indicador.id); }
|
||||
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
|
||||
get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; }
|
||||
private updateNumeric() {
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
<section class="conteos" [attr.aria-label]="indicador.titulo + ', por ' + par.unidades.pacientes.slice(0, -1) + ' y por ' + par.unidades.examenes.slice(0, -1)">
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||
@if (helpOpen) {
|
||||
<div class="methodology">
|
||||
@if (metadata) {
|
||||
@for (guide of readingGuide; track guide.figura) {
|
||||
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
||||
<h3>{{ guide.nombre }}</h3>
|
||||
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
|
||||
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
||||
</section>
|
||||
} @empty { <p>El servicio no publica instrucciones de lectura para estas figuras.</p> }
|
||||
} @else { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
||||
</div>
|
||||
}
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando {{ par.unidades.examenes }} y {{ par.unidades.pacientes }} del mismo periodo…</p> }
|
||||
@case ('empty') { <p role="status">No hay periodos publicados por los dos conteos.</p> }
|
||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (status() === 'ready' && model; as m) {
|
||||
@if (pages.length > 1) {
|
||||
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
|
||||
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||
<span role="status">{{ m.periodo }}, {{ periodIndex + 1 }} de {{ pages.length }}</span>
|
||||
<button type="button" aria-label="Periodo siguiente" [disabled]="periodIndex === pages.length - 1" (click)="changePeriod(1)">›</button>
|
||||
</nav>
|
||||
}
|
||||
<div class="figures">
|
||||
<section class="figure"><h3>{{ par.unidades.examenes | titlecase }} por categoría, {{ m.periodo }}</h3>
|
||||
@if (total) {
|
||||
<app-plotly-chart [figure]="donutFigure!" [showNotes]="false" [label]="indicador.titulo + ', dona, ' + m.periodo" />
|
||||
} @else { <p role="status">{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}</p> }
|
||||
@if (m.sinDato) { <p class="note">Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.</p> }
|
||||
</section>
|
||||
<section class="figure"><h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}</h3>
|
||||
<app-plotly-chart [figure]="barsFigure!" [showNotes]="false" [label]="indicador.titulo + ', barras por ' + par.unidades.pacientes.slice(0, -1) + ', ' + m.periodo" />
|
||||
</section>
|
||||
</div>
|
||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
|
||||
<table><caption>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}</caption>
|
||||
<thead><tr><th scope="col">Categoría</th><th scope="col">{{ par.unidades.pacientes | titlecase }}</th><th scope="col">{{ par.unidades.examenes | titlecase }}</th></tr></thead>
|
||||
<tbody>@for (f of m.filas; track f.id) { <tr><th scope="row">{{ f.etiqueta }}</th><td>{{ texto(f.pacientes) }}</td><td>{{ texto(f.examenes) }}</td></tr> }</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,22 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
.conteos { min-width: 0; padding-top: var(--issste-space-3); }
|
||||
p, h3, summary { overflow-wrap: anywhere; }
|
||||
.applied-summary, .note { color: var(--issste-text-secondary); }
|
||||
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.reading-guide h3 { margin: 0 0 .25rem; }
|
||||
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
|
||||
h3 { font-size: 1rem; font-weight: 500; line-height: 1.5; }
|
||||
.periods { display: flex; align-items: center; gap: var(--issste-space-3); }
|
||||
.periods button { min-width: 44px; min-height: 44px; font-size: 1.25rem; color: var(--issste-text); background: var(--issste-surface);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); cursor: pointer; }
|
||||
.periods button:disabled { opacity: .5; cursor: default; }
|
||||
// The two figures share the card in equal halves; one above the other on a narrow card.
|
||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||
@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
app-plotly-chart { --plot-height: 400px; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.table-scroll { overflow: auto; }
|
||||
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||
caption { text-align: start; font-weight: 600; }
|
||||
@@ -0,0 +1,117 @@
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { TitleCasePipe } from '@angular/common';
|
||||
import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { barrasConteos, ConteosIncompatibles, donaConteos, ModeloConteos, modelosConteos, ParConteos, totalExamenes } from './indicadores-conteos-pareados';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-conteos-pareados',
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart, TitleCasePipe],
|
||||
templateUrl: './indicador-conteos-pareados.html',
|
||||
styleUrl: './indicador-conteos-pareados.scss',
|
||||
})
|
||||
export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) par!: ParConteos;
|
||||
// The card's indicator (the exams); its partner (the patients) has no card and is requested by id.
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() visible = true;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
readonly metadataRequested = output<void>();
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
message = '';
|
||||
periodIndex = 0;
|
||||
pages: ModeloConteos[] = [];
|
||||
donutFigure?: PlotlyFigure;
|
||||
barsFigure?: PlotlyFigure;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
|
||||
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||
get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; }
|
||||
get total() { return this.model ? totalExamenes(this.model) : null; }
|
||||
texto(n: number | null) { return n === null ? 'Sin dato' : n.toLocaleString('es-MX'); }
|
||||
helpOpen = false;
|
||||
// "Cómo leer": what the kit publishes for the exams' two figures.
|
||||
get readingGuide() {
|
||||
const figuras = [['fig_c2_donas', 'Dona por categoría'], ['fig_c2_barras', 'Pacientes y ' + this.par.unidades.examenes]] as const;
|
||||
return figuras.flatMap(([figura, nombre]) => {
|
||||
const detail = this.metadata?.figuras_detalle?.find(item => item.figura === figura);
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
|
||||
});
|
||||
}
|
||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.par.examenes, this.par.pacientes, this.indicador.tipos_periodo]);
|
||||
if (key !== this.key) {
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.clear();
|
||||
if (!this.visible) { this.status.set('deferred'); return; }
|
||||
this.load();
|
||||
} else if (this.visible && !this.loaded) this.load();
|
||||
else if (this.model && changes['tema']) this.draw();
|
||||
}
|
||||
retry() { if (this.visible) this.load(); }
|
||||
private clear() { this.pages = []; this.periodIndex = 0; this.donutFigure = undefined; this.barsFigure = undefined; }
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.clear();
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
if (this.indicador.id !== this.par.examenes || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
|
||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica el conteo necesario para esta vista.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
const key = this.key;
|
||||
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
|
||||
this.status.set('loading');
|
||||
this.subscription = combineLatest([
|
||||
this.snapshots.datos(this.dominio, this.par.examenes, this.applied.tipo, periods, this.indicador.version),
|
||||
this.snapshots.datos(this.dominio, this.par.pacientes, this.applied.tipo, periods),
|
||||
]).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: ([examenes, pacientes]) => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.pages = modelosConteos(this.par, examenes, pacientes, this.applied.tipo);
|
||||
// The most recent period first; navigation goes back.
|
||||
this.periodIndex = Math.max(0, this.pages.length - 1);
|
||||
this.draw(); this.status.set(this.model ? 'ready' : 'empty');
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
error: error => { if (key === this.key) this.failure(error); },
|
||||
});
|
||||
}
|
||||
private failure(error: unknown) {
|
||||
this.clear();
|
||||
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||
: error instanceof ConteosIncompatibles ? error.message : httpMessage(error);
|
||||
this.status.set(error instanceof ConteosIncompatibles || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
|
||||
? 'incompatible' : 'error');
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
changePeriod(step: number) {
|
||||
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
|
||||
this.periodIndex += step; this.draw();
|
||||
}
|
||||
private draw() {
|
||||
const m = this.model;
|
||||
if (!m) return;
|
||||
this.donutFigure = donaConteos(m, this.par, this.tema);
|
||||
this.barsFigure = barrasConteos(m, this.par, this.tema);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import { barrasConteos, ConteosIncompatibles, donaConteos, esSocioConteos, modelosConteos, PARES_CONTEOS, parConteos, razon, totalExamenes } from './indicadores-conteos-pareados';
|
||||
|
||||
// Covers the paired counts of cáncer de mama: mammograms by BI-RADS (donut) and each patient BI-RADS next to its
|
||||
// mammograms (bars). Fixtures: two one-period answers built below, with the categories the API publishes.
|
||||
const par = PARES_CONTEOS[0];
|
||||
const filas = (n: Record<string, number | null>) => Object.entries(n).map(([categoria, v]) =>
|
||||
({ periodo: '2025-S2', grupo: 'TOTAL', estrato: null, categoria, n: v, suprimido: v === null ? 1 : 0 }));
|
||||
const examenes = (n: Record<string, number | null> = { B4A: 30, B4B: 18, B4C: 12, B5: 1016, B6: 972, SIN_DATO: 20 }) => ({
|
||||
id: 'cama_birads_456_mastografia', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S2'],
|
||||
categorias: Object.fromEntries(Object.keys(n).map(k => [k, { etiqueta: k === 'SIN_DATO' ? 'Sin dato' : 'BI-RADS ' + k.slice(1), color: '#C26A2B' }])),
|
||||
filas: filas(n) }) as unknown as IndicadorDatos;
|
||||
const pacientes = () => ({ id: 'cama_birads_456_paciente', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S2'],
|
||||
categorias: { BIRADS_4: { etiqueta: 'BI-RADS 4' }, BIRADS_5: { etiqueta: 'BI-RADS 5' }, BIRADS_6: { etiqueta: 'BI-RADS 6' } },
|
||||
filas: filas({ BIRADS_4: 15, BIRADS_5: 254, BIRADS_6: 243 }) }) as unknown as IndicadorDatos;
|
||||
|
||||
describe('Conteos por mastografía y por paciente', () => {
|
||||
it('la tarjeta de mastografías los dibuja y la de pacientes no tiene tarjeta propia', () => {
|
||||
// Fails if the pair is found on the wrong card, or the patients still get a card of their own.
|
||||
expect(parConteos('cama', 'cama_birads_456_mastografia')).toBe(par);
|
||||
expect(parConteos('cama', 'cama_birads_456_paciente')).toBeUndefined();
|
||||
expect(esSocioConteos('cama', 'cama_birads_456_paciente', ['cama_birads_456_mastografia', 'cama_birads_456_paciente'])).toBe(true);
|
||||
expect(esSocioConteos('cama', 'cama_birads_456_paciente', ['cama_birads_456_paciente'])).toBe(false);
|
||||
});
|
||||
it('suma 4A, 4B y 4C en el BI-RADS 4 de la paciente y deja «Sin dato» fuera de la dona', () => {
|
||||
// Fails if subcategories don't add up to their patient category, or uncategorised exams enter the donut.
|
||||
const [m] = modelosConteos(par, examenes(), pacientes(), 'semestre');
|
||||
expect(m.filas.map(f => [f.id, f.pacientes, f.examenes])).toEqual([['BIRADS_4', 15, 60], ['BIRADS_5', 254, 1016], ['BIRADS_6', 243, 972]]);
|
||||
expect(razon(m.filas[0])).toBe(4);
|
||||
expect(totalExamenes(m)).toBe(2048); expect(m.sinDato).toBe(20);
|
||||
expect(donaConteos(m, par, 'claro').data[0]['values']).toEqual([30, 18, 12, 1016, 972]);
|
||||
expect(barrasConteos(m, par, 'claro').data.map(t => t['x'])).toEqual([[15, 254, 243], [60, 1016, 972]]);
|
||||
});
|
||||
it('una celda suprimida no se vuelve cero', () => {
|
||||
// Fails if a suppressed exam count is drawn as zero or its category's sum and ratio are still computed.
|
||||
const [m] = modelosConteos(par, examenes({ B4A: null, B4B: 18, B4C: 12, B5: 1016, B6: 972 }), pacientes(), 'semestre');
|
||||
expect(totalExamenes(m)).toBeNull(); expect(m.filas[0].examenes).toBeNull(); expect(razon(m.filas[0])).toBeNull();
|
||||
expect(donaConteos(m, par, 'claro').data).toEqual([]);
|
||||
});
|
||||
it('rechaza respuestas de otro indicador o intervalo', () => {
|
||||
// Fails if the view accepts data that isn't the pair it draws.
|
||||
expect(() => modelosConteos(par, pacientes(), pacientes(), 'semestre')).toThrow(ConteosIncompatibles);
|
||||
expect(() => modelosConteos(par, examenes(), pacientes(), 'mes')).toThrow(ConteosIncompatibles);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { Dominio, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { percentNumber } from './indicadores-format';
|
||||
|
||||
// Two C2 counts of the same finding, one per exam and one per patient: the exams' composition as a donut, and
|
||||
// each patient category next to its exams, so the bars say how many exams each patient has.
|
||||
export interface ParConteos {
|
||||
dominio: Dominio;
|
||||
examenes: string;
|
||||
pacientes: string;
|
||||
// Exam category -> patient category it adds to (BI-RADS 4A, 4B and 4C are a patient's BI-RADS 4).
|
||||
grupoDe: Readonly<Record<string, string>>;
|
||||
unidades: { examenes: string; pacientes: string; porPaciente: string };
|
||||
}
|
||||
export const PARES_CONTEOS: readonly ParConteos[] = [
|
||||
{ dominio: 'cama', examenes: 'cama_birads_456_mastografia', pacientes: 'cama_birads_456_paciente',
|
||||
grupoDe: { B4A: 'BIRADS_4', B4B: 'BIRADS_4', B4C: 'BIRADS_4', B5: 'BIRADS_5', B6: 'BIRADS_6' },
|
||||
unidades: { examenes: 'mastografías', pacientes: 'pacientes', porPaciente: 'por paciente' } },
|
||||
];
|
||||
// The card of the exams draws the pair; the patients' indicator is its partner and has no card of its own.
|
||||
export const parConteos = (dominio: Dominio, id: string) => PARES_CONTEOS.find(p => p.dominio === dominio && p.examenes === id);
|
||||
export const esSocioConteos = (dominio: Dominio, id: string, ids: readonly string[]) =>
|
||||
PARES_CONTEOS.some(p => p.dominio === dominio && p.pacientes === id && ids.includes(p.examenes));
|
||||
|
||||
export interface CategoriaConteo { id: string; etiqueta: string; color: string; n: number | null; }
|
||||
export interface FilaConteo { id: string; etiqueta: string; pacientes: number | null; examenes: number | null; }
|
||||
export interface ModeloConteos { periodo: string; examenes: CategoriaConteo[]; sinDato: number | null; filas: FilaConteo[]; notas: string[]; }
|
||||
export class ConteosIncompatibles extends Error {}
|
||||
|
||||
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const fail = (message: string): never => { throw new ConteosIncompatibles(message); };
|
||||
const escapar = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
const miles = (v: number) => v.toLocaleString('es-MX');
|
||||
// A suppressed or unpublished cell is unknown, never zero.
|
||||
function cuenta(filas: Record<string, unknown>[], periodo: string, categoria: string): number | null {
|
||||
const fila = filas.find(f => f['periodo'] === periodo && f['categoria'] === categoria);
|
||||
return fila && fila['suprimido'] === 0 && typeof fila['n'] === 'number' && Number.isSafeInteger(fila['n']) && fila['n'] >= 0 ? fila['n'] : null;
|
||||
}
|
||||
const sumar = (valores: (number | null)[]) => valores.some(v => v === null) ? null : valores.reduce<number>((s, v) => s + v!, 0);
|
||||
|
||||
/** One model per period both responses publish, in chronological order. */
|
||||
export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacientes: IndicadorDatos, tipo: string): ModeloConteos[] {
|
||||
for (const [d, id] of [[examenes, par.examenes], [pacientes, par.pacientes]] as const) {
|
||||
if (d.id !== id || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos) || !Array.isArray(d.filas) || !registro(d['categorias'])) {
|
||||
fail('Los datos no corresponden a los conteos por mastografía y por paciente.');
|
||||
}
|
||||
}
|
||||
const catExamenes = examenes['categorias'] as Record<string, unknown>, catPacientes = pacientes['categorias'] as Record<string, unknown>;
|
||||
const etiqueta = (cat: Record<string, unknown>, id: string) => registro(cat[id]) && typeof cat[id]['etiqueta'] === 'string' ? cat[id]['etiqueta'] as string : id;
|
||||
const color = (id: string) => registro(catExamenes[id]) && typeof catExamenes[id]['color'] === 'string' ? catExamenes[id]['color'] as string : '#8A9199';
|
||||
const ids = Object.keys(par.grupoDe).filter(id => Object.hasOwn(catExamenes, id));
|
||||
const filasIds = [...new Set(Object.values(par.grupoDe))];
|
||||
if (!ids.length || filasIds.some(id => !Object.hasOwn(catPacientes, id))) fail('Las categorías de mastografías y pacientes no coinciden.');
|
||||
const periodos = [...examenes.periodos].filter(p => pacientes.periodos.includes(p)).sort();
|
||||
const filasE = examenes.filas as Record<string, unknown>[], filasP = pacientes.filas as Record<string, unknown>[];
|
||||
return periodos.map(periodo => {
|
||||
const cats = ids.map(id => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id), n: cuenta(filasE, periodo, id) }));
|
||||
return {
|
||||
periodo, examenes: cats, sinDato: Object.hasOwn(catExamenes, 'SIN_DATO') ? cuenta(filasE, periodo, 'SIN_DATO') : 0,
|
||||
filas: filasIds.map(id => ({ id, etiqueta: etiqueta(catPacientes, id), pacientes: cuenta(filasP, periodo, id),
|
||||
examenes: sumar(cats.filter(c => par.grupoDe[c.id] === id).map(c => c.n)) })),
|
||||
notas: [...new Set([...(examenes.notas ?? []), ...(pacientes.notas ?? [])])],
|
||||
};
|
||||
});
|
||||
}
|
||||
export const totalExamenes = (m: ModeloConteos) => sumar(m.examenes.map(c => c.n));
|
||||
export const razon = (f: FilaConteo) => f.pacientes && f.examenes !== null ? f.examenes / f.pacientes : null;
|
||||
|
||||
/** Exams by category around their total; nothing is drawn when a cell is unknown. */
|
||||
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure {
|
||||
const total = totalExamenes(m);
|
||||
if (!total) return { data: [], layout: {} };
|
||||
const p = c2Theme(tema), n = m.examenes.map(c => c.n!);
|
||||
return { data: [{ type: 'pie', hole: .6, sort: false, direction: 'clockwise', values: n, labels: m.examenes.map(c => escapar(c.etiqueta)),
|
||||
marker: { colors: m.examenes.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'text', textposition: 'inside',
|
||||
text: n.map((v, i) => v / total < .05 ? '' : escapar(m.examenes[i].etiqueta) + '<br>' + percentNumber(100 * v / total) + ' %'),
|
||||
customdata: n.map(v => [miles(v), percentNumber(100 * v / total)]),
|
||||
hovertemplate: `%{label}<br>%{customdata[0]} ${par.unidades.examenes}, %{customdata[1]} %<extra></extra>` }],
|
||||
layout: { autosize: true, height: 400, showlegend: false, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text },
|
||||
annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false, font: { size: 18, color: p.text },
|
||||
text: `<b>${miles(total)}</b><br>${par.unidades.examenes}` }] }, config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
/** Per patient category: patients next to their exams, and how many exams each patient has. */
|
||||
export function barrasConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema), y = m.filas.map(f => escapar(f.etiqueta));
|
||||
const traza = (clave: 'pacientes' | 'examenes', nombre: string, color: string) => ({
|
||||
type: 'bar', orientation: 'h', name: nombre, y, x: m.filas.map(f => f[clave]), marker: { color },
|
||||
text: m.filas.map(f => f[clave] === null ? 'Sin dato' : miles(f[clave]!)), textposition: 'outside', cliponaxis: false,
|
||||
hovertemplate: `%{y}: %{x} ${nombre}<extra></extra>` });
|
||||
const maximo = Math.max(1, ...m.filas.map(f => f.examenes ?? 0), ...m.filas.map(f => f.pacientes ?? 0));
|
||||
return { data: [traza('pacientes', par.unidades.pacientes, '#7A8794'), traza('examenes', par.unidades.examenes, '#C26A2B')],
|
||||
layout: { autosize: true, height: 400, barmode: 'group', bargap: .3, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { t: 16, l: 96, r: 150, b: 56 }, legend: { orientation: 'h', y: -0.14, itemclick: false, itemdoubleclick: false },
|
||||
yaxis: { type: 'category', autorange: 'reversed', automargin: true, fixedrange: true },
|
||||
xaxis: { range: [0, maximo * 1.18], gridcolor: p.grid, zeroline: false, fixedrange: true },
|
||||
annotations: m.filas.map((f, i) => {
|
||||
const r = razon(f);
|
||||
return { x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: y[i], yref: 'y', showarrow: false, align: 'left', font: { size: 12, color: p.text },
|
||||
text: r === null ? 'Sin razón' : `<b>≈ ${r.toLocaleString('es-MX', { maximumFractionDigits: 1 })}</b> ${par.unidades.porPaciente}` };
|
||||
}) }, config: { displayModeBar: false } };
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { catchError, first, map, of, startWith, Subject, switchMap, takeUntil } from 'rxjs';
|
||||
import { Dominio, isDominio, Indicador, Tema } from './indicadores.models';
|
||||
import { vistaEscenario } from './indicadores-eu7-escenario';
|
||||
import { esSocioConteos } from './indicadores-conteos-pareados';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
@@ -314,7 +315,9 @@ export class IndicadoresPage {
|
||||
readonly catalogOrder = computed(() => {
|
||||
const catalog = this.catalog();
|
||||
// The interactive views go first.
|
||||
const resumen = catalog.filter(item => !item.vistas || item.vistas.includes('resumen'));
|
||||
// A paired partner is drawn on its pair's card, not on one of its own.
|
||||
const ids = catalog.map(item => item.id);
|
||||
const resumen = catalog.filter(item => (!item.vistas || item.vistas.includes('resumen')) && !esSocioConteos(this.dominio, item.id, ids));
|
||||
const primero = (item: Indicador) => !!vistaEscenario(this.dominio, item);
|
||||
return [...resumen.filter(primero), ...resumen.filter(item => !primero(item))];
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user