T17: sweep of the WebApp after the feature-parity work

Removed the legacy indicator layout, unused chart helpers, styles and
exports, the card-actions component, fetch-all and explanatory comments;
one pager shared by the four worklists, shared filter-row styles, one
FHIR name and CURP reader, downloads through export/, the concept-map
editor on Material controls.
This commit is contained in:
2026-12-01 06:48:57 -06:00
parent 8237e9f483
commit 7c98566579
61 changed files with 338 additions and 1166 deletions
+4 -4
View File
@@ -1,7 +1,7 @@
import type { Observation, ObservationComponent } from 'fhir/r4';
import { code, ext } from './fhir';
export const ADOS2_ITEMS = [
const ADOS2_ITEMS = [
'vocalization_directed',
'pointing',
'gestures',
@@ -26,18 +26,18 @@ export const ADOS2_ITEMS = [
'repetitive_interests',
];
export interface Ados2Item {
interface Ados2Item {
code: string;
title: string;
score?: number;
}
export interface Ados2Subdomain {
interface Ados2Subdomain {
subdomain: string;
items: Ados2Item[];
}
export interface Ados2Domain {
interface Ados2Domain {
domain: string;
subdomains: Ados2Subdomain[];
}
-1
View File
@@ -16,7 +16,6 @@ export const appConfig: ApplicationConfig = {
provideRouter(routes, withComponentInputBinding()),
provideHttpClient(),
provideApiConfiguration('/api'),
// Icons are the Material Symbols font served with the app.
provideAppInitializer(() => {
inject(MatIconRegistry).setDefaultFontSetClass('material-symbols-outlined');
}),
+1 -3
View File
@@ -21,7 +21,7 @@
.title {
flex: 1;
min-width: 0; // gives way to the switcher and the sections, on one line
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
@@ -29,7 +29,6 @@
font-weight: 500;
}
// Nothing in the header wraps or shrinks: the title gives way first, then hides.
.domain,
.sections a,
.user {
@@ -90,7 +89,6 @@
.sections {
gap: var(--space-3);
}
// the account by its icon alone; the switcher's name cut short if it must be
.user .who-name {
display: none;
}
-5
View File
@@ -16,7 +16,6 @@ export const DOMAINS: Record<Domain, string> = {
tea: 'Trastorno del espectro autista',
};
/** The shell: header (logo, the domain's title and switcher, or the section), page, footer. */
@Component({
selector: 'app-root',
imports: [
@@ -43,17 +42,13 @@ export class App {
),
{ initialValue: '' },
);
/** The section and domain of a page that has one (indicators, governance): the switcher
* moves between that section's domains. */
private readonly place = computed(() => /^\/(indicadores|gobernanza)\/(\w+)/.exec(this.url()));
protected readonly section = computed(() => this.place()?.[1] ?? 'indicadores');
protected readonly domain = computed(() => this.place()?.[2] as Domain | undefined);
protected readonly others = computed(() =>
(this.domains.value() ?? []).filter((d) => d !== this.domain() && this.auth.canSee(d)),
);
/** The sign-in page shows only the brand. */
protected readonly onLogin = computed(() => this.url().startsWith('/login'));
/** Where "Indicadores" goes: the first domain this user may see. */
protected readonly home = computed(
() => `/indicadores/${this.auth.user()?.domains[0] ?? 'cacu'}`,
);
+1 -9
View File
@@ -5,7 +5,6 @@ import { firstValueFrom } from 'rxjs';
import { ApiConfiguration } from '../api/api-configuration';
import type { Domain } from '../api/models/domain';
/** Who is signed in, and the domains the app shows them. */
export interface User {
id: string;
email: string;
@@ -14,18 +13,14 @@ export interface User {
domains: Domain[];
}
/** The web app's sign-in (the API's fastapi-users, a session cookie). It decides only what
* the app shows: the API answers without a session. */
@Injectable({ providedIn: 'root' })
export class Auth {
private readonly http = inject(HttpClient);
private readonly root = inject(ApiConfiguration).rootUrl;
/** undefined: not asked yet; null: nobody signed in. */
private readonly current = signal<User | null | undefined>(undefined);
readonly user = this.current.asReadonly();
readonly signedIn = computed(() => !!this.current());
/** Whether the signed-in user may see the domain (an administrator sees every one). */
canSee(domain: string): boolean {
const u = this.current();
return !!u && (u.is_superuser || u.domains.includes(domain as Domain));
@@ -40,7 +35,6 @@ export class Auth {
return this.current() ?? null;
}
/** Signs in; a wrong user or password comes back as words for the form. */
async login(email: string, password: string): Promise<string | null> {
const body = new HttpParams().set('username', email.trim()).set('password', password);
try {
@@ -64,15 +58,13 @@ export class Auth {
}
}
/** Pages show only to someone signed in; the others go to the sign-in page and come back. */
export const signedIn: CanActivateFn = async (_route, state) => {
const auth = inject(Auth);
const router = inject(Router); // before any await: inject works only in the guard's first turn
const router = inject(Router);
const user = auth.user() === undefined ? await auth.load() : auth.user();
return user ? true : router.createUrlTree(['/login'], { queryParams: { next: state.url } });
};
/** A domain's pages show only to whom may see it. */
export const domainAllowed: CanActivateFn = (route) => {
const auth = inject(Auth);
const domain = route.paramMap.get('domain') ?? route.data['domain'];
-3
View File
@@ -22,7 +22,6 @@
width: 100%;
}
/* The brand opens the screen and is the biggest thing on it. */
.logo {
align-self: center;
animation: logo-in 600ms ease-out both;
@@ -43,7 +42,6 @@
}
}
/* The title between two rules. */
.title {
align-items: center;
color: var(--color-text);
@@ -86,7 +84,6 @@
margin: -4px 0 0;
}
/* One column with the fields; its border turns to the action color once the form is complete. */
.enter {
align-items: center;
background: var(--login-background);
-2
View File
@@ -7,7 +7,6 @@ import { MatInputModule } from '@angular/material/input';
import { Router } from '@angular/router';
import { Auth } from './auth';
/** "Inicio de sesión": the brand, two fields and one button. */
@Component({
selector: 'app-login',
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
@@ -17,7 +16,6 @@ import { Auth } from './auth';
export class Login {
private readonly auth = inject(Auth);
private readonly router = inject(Router);
/** Where to go once signed in (the page that asked for it). */
readonly next = input<string>('');
protected email = '';
protected password = '';
-53
View File
@@ -1,53 +0,0 @@
import { TestBed } from '@angular/core/testing';
import { MatDialog } from '@angular/material/dialog';
import { describe, expect, it, vi } from 'vitest';
import { CardActions } from './card-actions';
describe('CardActions', () => {
it('opens the published definition and emits back only through the filtered action', async () => {
const fixture = TestBed.createComponent(CardActions);
fixture.componentRef.setInput('measures', [
{
resourceType: 'Measure',
status: 'active',
title: 'Oportunidad',
description: 'Definición publicada',
group: [
{
population: [
{
code: { text: 'Numerador' },
criteria: { language: 'text/plain', description: 'Casos oportunos' },
},
{ criteria: { language: 'text/plain' } },
],
},
],
},
]);
const back = vi.fn();
fixture.componentInstance.back.subscribe(back);
fixture.detectChanges();
const host: HTMLElement = fixture.nativeElement;
expect(host.textContent).not.toContain('Volver');
host.querySelector<HTMLButtonElement>('[aria-label="Ver definición"]')!.click();
fixture.detectChanges();
await fixture.whenStable();
const dialog = document.querySelector('[role="dialog"]')!;
expect(dialog.textContent).toContain('Oportunidad');
expect(dialog.textContent).toContain('Definición publicada');
expect(dialog.textContent).toContain('Numerador');
expect(dialog.textContent).toContain('Casos oportunos');
expect(dialog.textContent).toContain('Sin definición publicada');
TestBed.inject(MatDialog).closeAll();
fixture.componentRef.setInput('filtered', true);
fixture.detectChanges();
[...host.querySelectorAll('button')]
.find((button) => button.textContent?.trim() === 'Volver')!
.click();
expect(back).toHaveBeenCalledOnce();
});
});
-72
View File
@@ -1,72 +0,0 @@
import { Component, inject, input, output, TemplateRef } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
import { MatButtonModule } from '@angular/material/button';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatMenuModule } from '@angular/material/menu';
import type { Measure } from 'fhir/r4';
@Component({
selector: 'app-card-actions',
imports: [NgTemplateOutlet, MatButtonModule, MatDialogModule, MatMenuModule],
template: `
<button mat-icon-button type="button" aria-label="Ver definición" (click)="open(definition)">
?
</button>
@if (settings(); as content) {
<button mat-button type="button" [matMenuTriggerFor]="menu">Configuración</button>
<mat-menu #menu="matMenu">
<ng-template matMenuContent>
<ng-container [ngTemplateOutlet]="content" />
</ng-template>
</mat-menu>
}
@if (filtered()) {
<button mat-button type="button" (click)="back.emit()">Volver</button>
}
<ng-template #definition>
<h2 mat-dialog-title>Definición</h2>
<mat-dialog-content>
@for (measure of measures(); track $index) {
<h3>{{ measure.title }}</h3>
@if (measure.description) {
<p>{{ measure.description }}</p>
}
@for (group of measure.group ?? []; track $index) {
@for (population of group.population ?? []; track $index) {
<p>
@if (population.code?.text; as text) {
<strong>{{ text }}</strong>
}
@if (population.criteria.description; as description) {
{{ description }}
} @else if (!population.code?.text) {
Sin definición publicada
}
</p>
} @empty {
<p>Sin definición publicada</p>
}
} @empty {
<p>Sin definición publicada</p>
}
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button type="button" mat-dialog-close>Cerrar</button>
</mat-dialog-actions>
</ng-template>
`,
styles: ':host { display: inline-flex; align-items: center; gap: var(--space-1); }',
})
export class CardActions {
private readonly dialog = inject(MatDialog);
readonly measures = input.required<Measure[]>();
readonly settings = input<TemplateRef<unknown>>();
readonly filtered = input(false);
readonly back = output<void>();
protected open(template: TemplateRef<unknown>): void {
this.dialog.open(template);
}
}
+33 -20
View File
@@ -2,23 +2,30 @@ import { HttpErrorResponse } from '@angular/common/http';
import { Component, inject, input, output, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
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 { Api } from '../api/api';
import { getConceptMap } from '../api/fn/ingest/get-concept-map';
import { saveConceptMap } from '../api/fn/ingest/save-concept-map';
/** One translation: a site's code onto a platform code of one target system. */
interface Row {
target: string;
code: string;
platform: string;
}
/** A site's codes in platform terms (a FHIR ConceptMap), edited as a table: a new
* laboratory spelling is one more row. The API refuses a code no platform field allows. */
@Component({
selector: 'app-concept-map-editor',
imports: [FormsModule, MatButtonModule, MatIconModule],
imports: [
FormsModule,
MatButtonModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatSelectModule,
],
template: `
<h3>
Códigos del sitio · <span class="muted">{{ id() }}</span>
@@ -36,20 +43,31 @@ interface Row {
@for (row of rows(); track $index) {
<tr>
<td>
<select [(ngModel)]="row.target" [attr.aria-label]="'Sistema destino ' + $index">
@for (t of targets(); track t) {
<option [value]="t">{{ short(t) }}</option>
}
</select>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-select [(ngModel)]="row.target" [aria-label]="'Sistema destino ' + $index">
@for (t of targets(); track t) {
<mat-option [value]="t">{{ short(t) }}</mat-option>
}
</mat-select>
</mat-form-field>
</td>
<td>
<input [(ngModel)]="row.code" [attr.aria-label]="'Código del sitio ' + $index" />
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<input
matInput
[(ngModel)]="row.code"
[attr.aria-label]="'Código del sitio ' + $index"
/>
</mat-form-field>
</td>
<td>
<input
[(ngModel)]="row.platform"
[attr.aria-label]="'Código de la plataforma ' + $index"
/>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<input
matInput
[(ngModel)]="row.platform"
[attr.aria-label]="'Código de la plataforma ' + $index"
/>
</mat-form-field>
</td>
<td>
<button mat-icon-button (click)="remove($index)" aria-label="Quitar fila">
@@ -72,12 +90,8 @@ interface Row {
font-weight: 500;
margin: 16px 0 8px;
}
input,
select {
mat-form-field {
width: 100%;
box-sizing: border-box;
font: inherit;
padding: 4px;
}
.actions {
display: flex;
@@ -134,7 +148,6 @@ export class ConceptMapEditor {
this.rows.update((r) => r.filter((_, j) => j !== i));
}
/** The rows as a ConceptMap: one group per target system. */
protected async save(): Promise<void> {
const groups = new Map<string, Row[]>();
for (const r of this.rows().filter((r) => r.target && r.code && r.platform)) {
-2
View File
@@ -141,7 +141,6 @@ h2 {
}
}
// The canvas's nodes: the kind small on top, the name below in two lines at most.
:host ::ng-deep default-node {
box-sizing: border-box;
overflow: hidden;
@@ -188,7 +187,6 @@ h2 {
font-size: 13px;
}
// Fields in the panel keep their hints clear of the next field's label.
:host ::ng-deep .panel mat-form-field {
margin-bottom: var(--space-3);
}
+16 -35
View File
@@ -71,7 +71,7 @@ export const KINDS: Record<Kind, string> = {
link: 'Identificar a la persona',
target: 'Guardar en la plataforma',
};
export const HELP: Record<Kind, string> = {
const HELP: Record<Kind, string> = {
source: 'De dónde vienen los datos: una base de datos, una carpeta, la nube o una API.',
read: 'Extrae el texto de cada documento (PDF, Word, escaneos con OCR).',
route:
@@ -86,8 +86,6 @@ export const HELP: Record<Kind, string> = {
};
const ID = /^[a-z][a-z0-9_]*$/;
/** /conectar: an operator draws a site's pipeline on a canvas (nodes and the edges between
* them), fills each node's form, previews what it gives, saves a version and runs it. */
@Component({
selector: 'app-conectar',
imports: [
@@ -105,7 +103,6 @@ const ID = /^[a-z][a-z0-9_]*$/;
Vflow,
ConceptMapEditor,
],
// Forms are this page's only: Formly loads with it, not with the app.
providers: [provideFormlyCore([...withFormlyMaterial(), FORMLY_TYPES])],
templateUrl: './conectar.html',
styleUrl: './conectar.scss',
@@ -116,7 +113,6 @@ export class Conectar {
private readonly dialog = inject(MatDialog);
protected readonly kinds = Object.entries(KINDS) as [Kind, string][];
protected readonly help = HELP;
/** "Avanzado": the selected node as JSON, as edited and not applied yet. */
protected readonly rawDraft = signal<string | undefined>(undefined);
protected readonly rawError = signal('');
@@ -125,7 +121,6 @@ export class Conectar {
protected readonly pipelineId = signal<string | undefined>(undefined);
protected readonly version = signal<number | undefined>(undefined);
/** The drawn pipeline: node configs (positions live on the canvas nodes). */
protected readonly docs = signal<Doc[]>([]);
protected readonly nodes = signal<CanvasNode[]>([]);
protected readonly edges = computed(() =>
@@ -142,23 +137,9 @@ export class Conectar {
return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status);
});
/** What the node forms share: each entity's fields by their titles (the catalog's). */
protected readonly formOptions = { formState: { fields: {} as Record<string, unknown> } };
private readonly titles = effect(() => {
const entities = (this.schema.value()?.['entities'] ?? {}) as Record<
string,
{ properties?: Record<string, { title?: string }> }
>;
this.formOptions.formState.fields = Object.fromEntries(
Object.entries(entities).map(([e, s]) => [
e,
Object.fromEntries(Object.entries(s.properties ?? {}).map(([f, p]) => [f, p.title ?? f])),
]),
);
});
protected form = new UntypedFormGroup({});
protected model: Record<string, unknown> = {};
/** The selected node's form, generated from its kind's JSON Schema. */
protected readonly fields = computed<FormlyFieldConfig[]>(() => {
const kind = this.doc()?.kind;
const pipeline = this.schema.value()?.['pipeline'];
@@ -166,6 +147,21 @@ export class Conectar {
return [this.jsonschema.toFieldConfig(nodeSchema(pipeline as never, kind))];
});
constructor() {
effect(() => {
const entities = (this.schema.value()?.['entities'] ?? {}) as Record<
string,
{ properties?: Record<string, { title?: string }> }
>;
this.formOptions.formState.fields = Object.fromEntries(
Object.entries(entities).map(([e, s]) => [
e,
Object.fromEntries(Object.entries(s.properties ?? {}).map(([f, p]) => [f, p.title ?? f])),
]),
);
});
}
protected readonly preview = signal<Record<string, unknown>[] | undefined>(undefined);
protected readonly columns = computed(() => Object.keys(this.preview()?.[0] ?? {}));
@@ -212,7 +208,6 @@ export class Conectar {
this.place(kind, {});
}
/** "Fuente de datos": the dialog walks the operator through it; editing reopens it. */
protected async connectSource(id?: string): Promise<void> {
const doc = id ? (this.docs().find((d) => d.id === id) as Source | undefined) : undefined;
const data: SourceDialogData = {
@@ -292,12 +287,10 @@ export class Conectar {
this.rawError.set('');
}
/** A source the dialog drew (its answers make its dlt fields). */
protected guided(d: Doc): Source['guided'] {
return d.kind === 'source' ? ((d as Source).guided ?? undefined) : undefined;
}
/** The form's values into the selected node. */
protected edited(model: Record<string, unknown>): void {
const id = this.selected();
if (!id) return;
@@ -310,15 +303,11 @@ export class Conectar {
);
}
/** The node as the platform keeps it (its place on the canvas aside). */
protected raw(d: Doc): string {
const { position, ...rest } = d as Doc & { position?: unknown };
return JSON.stringify(rest, null, 2);
}
/** "Aplicar": the edited JSON becomes the node. Its kind stays; its id changes with the
* Id field (so the arrows follow). A source whose dlt fields change is drawn by hand from
* then on (unless a catalog type makes it exactly: the platform reads it back). */
protected applyRaw(): void {
const d = this.doc();
const text = this.rawDraft();
@@ -367,7 +356,6 @@ export class Conectar {
?.text.set(text(doc));
}
/** The drawn pipeline, each node where it sits on the canvas. */
private drawn(): Pipeline {
const at = new Map(this.nodes().map((n) => [n.id, n.point()]));
return { nodes: this.docs().map((d) => ({ ...d, position: at.get(d.id) })) } as Pipeline;
@@ -391,7 +379,6 @@ export class Conectar {
}
}
/** Saves, starts the `ingest` job and follows it to its end. */
protected async start(): Promise<void> {
const id = this.pipelineId();
if (!id || !(await this.save())) return;
@@ -410,7 +397,6 @@ export class Conectar {
}
}
/** What the node gives: a source's first rows, or what any other node gave in the last run. */
protected async show(): Promise<void> {
const doc = this.doc();
const id = this.pipelineId();
@@ -427,12 +413,10 @@ export class Conectar {
}
}
/** The run in Dagster's own UI (its port beside this app's). */
protected readonly dagster = computed(() => {
const run = this.run();
return run ? `${location.protocol}//${location.hostname}:5712/runs/${run.id}` : '';
});
/** The ConceptMap a node names, if its kind takes one. */
protected conceptMap(d: Doc): string | undefined {
return 'concept_map' in d ? (d.concept_map ?? undefined) : undefined;
}
@@ -447,8 +431,6 @@ export class Conectar {
}
function text(d: Doc): string {
// ngx-vflow draws a node's text as HTML: the kind above, the name below (two lines at
// most; the whole of it on hover). The name is the operator's text, so it is escaped.
const kind = KINDS[d.kind ?? 'source'];
const name = escape(d.label || d.id);
return (
@@ -457,7 +439,6 @@ function text(d: Doc): string {
);
}
/** Each node's distance from the sources: its column when it has no saved position. */
function depths(docs: Doc[]): Map<string, number> {
const by = new Map(docs.map((d) => [d.id, d]));
const found = new Map<string, number>();
+5 -19
View File
@@ -16,11 +16,8 @@ import type { JSONSchema7 } from 'json-schema';
type Schema = JSONSchema7 & { $defs?: Record<string, Schema>; prefixItems?: unknown };
/** The canvas edits these itself; the form leaves them out. */
const CANVAS_FIELDS = ['id', 'kind', 'inputs', 'position'];
/** A node kind's form schema from the pipeline's JSON Schema (pydantic's): `$ref`s inlined,
* optional values as their type, and maps or tuples (which forms don't draw) as JSON. */
export function nodeSchema(pipeline: Schema, kind: string): Schema {
const defs = pipeline.$defs ?? {};
const name = Object.keys(defs).find(
@@ -28,10 +25,8 @@ export function nodeSchema(pipeline: Schema, kind: string): Schema {
)!;
const node = structuredClone(defs[name]);
for (const field of CANVAS_FIELDS) delete node.properties?.[field];
// The panel says what the kind does (in Spanish); the class's own docstring is for code.
delete node.title;
delete node.description;
// What a guided dialog fills, or what only JSON can say, is for the "Avanzado" tab.
for (const [field, value] of Object.entries(node.properties ?? {})) {
const simple = simplify(value as Schema, defs) as Schema & { widget?: unknown };
if ((value as { advanced?: boolean }).advanced || isJson(simple))
@@ -115,7 +110,6 @@ function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
return out;
}
/** An object's fields, one after another. */
@Component({
selector: 'app-formly-object',
imports: [FormlyField],
@@ -133,9 +127,8 @@ function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
styles:
'.legend { font-weight: 500; margin: 8px 0 4px; } .hint { color: var(--color-text-secondary); font-size: 12px; margin: 0 0 8px; }',
})
export class ObjectType extends FieldType {}
class ObjectType extends FieldType {}
/** A list: each item with a remove button, and an add button. */
@Component({
selector: 'app-formly-array',
imports: [FormlyField, MatButtonModule, MatIconModule],
@@ -156,9 +149,8 @@ export class ObjectType extends FieldType {}
styles:
'.legend { font-weight: 500; margin: 8px 0 4px; } .item { display: flex; align-items: flex-start; gap: 4px; } .item formly-field { flex: 1; }',
})
export class ArrayType extends FieldArrayType {}
class ArrayType extends FieldArrayType {}
/** A value forms don't draw (a map, a pair, anything), edited as JSON. */
@Component({
selector: 'app-formly-json',
imports: [MatFormFieldModule, MatInputModule, ReactiveFormsModule],
@@ -181,7 +173,7 @@ export class ArrayType extends FieldArrayType {}
`,
styles: '.json { width: 100%; } textarea { font-family: monospace; font-size: 12px; }',
})
export class JsonType extends FieldType<FormlyFieldConfig> {
class JsonType extends FieldType<FormlyFieldConfig> {
protected error = '';
protected text(): string {
return this.formControl.value === undefined
@@ -199,8 +191,6 @@ export class JsonType extends FieldType<FormlyFieldConfig> {
}
}
/** A map of names to texts (fields to columns, fields to patterns, date formats): a row
* per entry, its name and its text, to add or remove. */
@Component({
selector: 'app-formly-map',
imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule, MatSelectModule],
@@ -270,9 +260,7 @@ export class JsonType extends FieldType<FormlyFieldConfig> {
}
`,
})
export class MapType extends FieldType<FormlyFieldConfig> {
/** The platform fields a key can be, by title: the node's study's, or every study's when
* it names none (formState.fields: entity -> field -> title). */
class MapType extends FieldType<FormlyFieldConfig> {
protected keyOptions(current: string): [string, string][] {
const all = (this.options?.formState?.fields ?? {}) as Record<string, Record<string, string>>;
const entity = (this.model as Record<string, unknown> | undefined)?.['entity'] as
@@ -297,7 +285,6 @@ export class MapType extends FieldType<FormlyFieldConfig> {
this.save(rows);
}
protected add(): void {
// a new row needs a key before it is kept: the first field not used yet, or a new name
const rows = this.rows();
const used = new Set(rows.map(([k]) => k));
const free = this.props['fieldKeys']
@@ -312,7 +299,6 @@ export class MapType extends FieldType<FormlyFieldConfig> {
}
}
/** Pairs of names (a join's columns, the first input's = the second's): a row per pair. */
@Component({
selector: 'app-formly-pairs',
imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
@@ -363,7 +349,7 @@ export class MapType extends FieldType<FormlyFieldConfig> {
}
`,
})
export class PairsType extends FieldType<FormlyFieldConfig> {
class PairsType extends FieldType<FormlyFieldConfig> {
protected rows(): [string, string][] {
return ((this.formControl.value ?? []) as [string, string][]).map((r) => [r[0], r[1]]);
}
+2 -19
View File
@@ -26,7 +26,6 @@ import type { SourceType } from '../api/models/source-type';
import type { Tested } from '../api/models/tested';
import type { Uploaded } from '../api/models/uploaded';
/** What the dialog is opened with: the source being edited, if any. */
export interface SourceDialogData {
pipeline?: string;
node?: string;
@@ -35,13 +34,11 @@ export interface SourceDialogData {
}
const NONE: string[] = [];
/** What it gives back: the dialog's answers (the node's dlt fields are made from them). */
export interface SourceDialogResult {
guided: Guided;
label: string;
}
/** The catalog's generic icon words, as Material Symbols. */
const ICONS: Record<string, string> = {
database: 'database',
upload: 'upload_file',
@@ -58,9 +55,6 @@ const ICONS: Record<string, string> = {
};
const MASK = '********';
/** "Nueva fuente": the operator picks what kind of source the data is in, answers only what
* that kind needs (in plain words, with pickers and sign-in buttons), tests the connection,
* picks a table if there are several, sees the first rows, and saves. No dlt, no JSON. */
@Component({
selector: 'app-source-dialog',
imports: [
@@ -115,7 +109,6 @@ export class SourceDialog {
protected readonly showPassword = signal<Record<string, boolean>>({});
protected readonly testing = signal(false);
/** The tables the last listing found: kept while one is picked and its rows shown. */
protected readonly tableList = signal<string[]>([]);
protected readonly tested = signal<Tested | undefined>(undefined);
protected readonly columns = computed(() => Object.keys(this.tested()?.rows?.[0] ?? {}));
@@ -160,7 +153,7 @@ export class SourceDialog {
protected set(name: string, value: unknown): void {
this.answers.update((a) => ({ ...a, [name]: value }));
if (this.type()?.fields[name]?.type === 'table') return;
this.tested.set(undefined); // another connection: test again
this.tested.set(undefined);
this.tableList.set([]);
}
protected setNumber(name: string, value: string): void {
@@ -180,7 +173,6 @@ export class SourceDialog {
return a ? (a.user ?? 'cuenta conectada') : undefined;
}
/** "Probar conexión": what the source holds, in plain words. */
protected async test(): Promise<void> {
const type = this.typeId();
if (!type) return;
@@ -205,22 +197,18 @@ export class SourceDialog {
}
}
/** A list answer (the columns picked), as a list. */
protected listed(name: string): string[] {
const v = this.value(name);
return Array.isArray(v) ? (v as string[]) : NONE; // a new list each time renders forever
return Array.isArray(v) ? (v as string[]) : NONE;
}
/** The columns to pick from: the first rows', and those already picked. */
protected columnOptions(name: string): string[] {
return [...new Set([...this.columns(), ...this.listed(name)])];
}
/** The tables a database listed, for its table field. */
protected tables(): string[] {
return this.tableList();
}
/** Server folders, under the roots the operator mounted. */
protected async openFolder(field: string, path?: string | null): Promise<void> {
try {
const at = await this.api.invoke(browse, path ? { path } : {});
@@ -239,14 +227,11 @@ export class SourceDialog {
if (b) this.set(b.field, path);
this.browsing.set(undefined);
}
/** Whether the field being browsed takes a file (else a folder). */
protected readonly browsingFiles = computed(() => {
const b = this.browsing();
return !!b && this.type()?.fields[b.field]?.type === 'server_file';
});
/** Files or a whole folder from this computer, sent with progress; a folder keeps its
* subfolders. More files can be added to the same set. */
protected upload(field: string, list: FileList | null): void {
if (!list?.length) return;
const body = new FormData();
@@ -286,7 +271,6 @@ export class SourceDialog {
this.upload(field, event.dataTransfer?.files ?? null);
}
/** "Iniciar sesión con …": the provider's page in a window; it hands the account back. */
protected async signIn(field: string, provider: string): Promise<void> {
this.problem.set('');
let started;
@@ -313,7 +297,6 @@ export class SourceDialog {
return typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v ?? '');
}
/** Answers without empty ones (a default takes their place on the server). */
private cleaned(): Record<string, unknown> {
return Object.fromEntries(
Object.entries(this.answers()).filter(([, v]) => v !== '' && v !== null && v !== undefined),
-3
View File
@@ -1,4 +1,3 @@
/** The zones the metrics are summed over (models.tea.eeg.spindles.ZONES). */
export const ZONE_NAMES: Record<string, string> = {
frontal_left: 'Frontal izquierda',
frontal_right: 'Frontal derecha',
@@ -12,7 +11,6 @@ export const ZONE_NAMES: Record<string, string> = {
global: 'Global',
};
/** The association's biomarkers (core.tea.association.BIOMARKERS). */
export const BIOMARKER_NAMES: Record<string, string> = {
spikes: 'Picos paroxísticos',
spindles: 'Husos de sueño N2',
@@ -20,7 +18,6 @@ export const BIOMARKER_NAMES: Record<string, string> = {
gradient: 'Gradiente anteroposterior',
};
/** ADOS-2 items by their number (core.tea.association.ITEMS), and the CSS. */
export const OUTCOME_NAMES: Record<string, string> = {
ados2_item_01: 'Vocalización espontánea dirigida a otros',
ados2_item_02: 'Señalar',
+8
View File
@@ -0,0 +1,8 @@
export function download(blob: Blob, filename: string): void {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
setTimeout(() => URL.revokeObjectURL(url), 0);
}
+1 -22
View File
@@ -1,6 +1,5 @@
import type { Bundle, Patient } from 'fhir/r4';
import { describe, expect, it, vi } from 'vitest';
import { allRows, downloadPdf, downloadXlsx, MAX_ROWS, safeName } from './index';
import { downloadPdf, downloadXlsx, MAX_ROWS, safeName } from './index';
const mocks = vi.hoisted(() => {
const toFile = vi.fn();
@@ -61,26 +60,6 @@ describe('export', () => {
await expect(downloadPdf('tea-patient-4821-2026-11-30', [])).rejects.toThrow();
});
it('follows next links, skipping empty entries and stopping inside the last page', async () => {
const patient = (id: string): Patient => ({ resourceType: 'Patient', id });
const bundle = (patients: Patient[], next: string): Bundle => ({
resourceType: 'Bundle',
type: 'searchset',
entry: [{}, ...patients.map((resource) => ({ resource }))],
link: [{ relation: 'next', url: next }],
});
const getPage = vi
.fn<(url: string) => Promise<Bundle>>()
.mockResolvedValueOnce(bundle([patient('1')], '/page/2'))
.mockResolvedValueOnce(bundle([patient('2'), patient('3')], '/page/3'));
await expect(allRows<Patient>('/page/1', getPage, 2)).resolves.toEqual([
patient('1'),
patient('2'),
]);
expect(getPage.mock.calls).toEqual([['/page/1'], ['/page/2']]);
});
it('passes the institutional header and generated timestamp footer to pdfmake', async () => {
const content = [{ text: 'Indicadores' }];
await downloadPdf(name, content);
-20
View File
@@ -1,20 +0,0 @@
import type { Bundle } from 'fhir/r4';
import { MAX_ROWS } from './xlsx';
export async function allRows<T>(
first: string,
getPage: (url: string) => Promise<Bundle>,
max = MAX_ROWS,
): Promise<T[]> {
const rows: T[] = [];
let next: string | undefined = first;
while (next && rows.length < max) {
const page = await getPage(next);
for (const { resource } of page.entry ?? []) {
if (resource) rows.push(resource as T);
if (rows.length >= max) return rows;
}
next = page.link?.find(({ relation }) => relation === 'next')?.url;
}
return rows;
}
+1 -1
View File
@@ -1,4 +1,4 @@
export { allRows } from './fetch-all';
export { downloadPdf, type PdfContent } from './pdf';
export { safeName } from './safe-name';
export { downloadXlsx, MAX_ROWS, type Sheet } from './xlsx';
export { download } from './blob';
+14 -7
View File
@@ -1,15 +1,14 @@
import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import type { Bundle, CodeableConcept, Extension, FhirResource } from 'fhir/r4';
import type { Bundle, CodeableConcept, Extension, FhirResource, Patient } from 'fhir/r4';
import { firstValueFrom } from 'rxjs';
import { ApiConfiguration } from './api/api-configuration';
/** Our extensions and code systems (core.fhir). */
export const CURP = 'https://isssteleon.org/fhir/sid/curp';
export const EXT = 'https://isssteleon.org/fhir/StructureDefinition/';
export type Params = Record<string, string | number | readonly (string | number)[] | undefined>;
/** The domain's FHIR base (`/{domain}/fhir`): reads and searches, typed as R4. */
@Injectable({ providedIn: 'root' })
export class Fhir {
private readonly http = inject(HttpClient);
@@ -19,7 +18,6 @@ export class Fhir {
return firstValueFrom(this.http.get<T>(`${this.root}/${domain}/fhir/${type}/${id}`));
}
/** One page of a search. */
search(domain: string, type: string, params: Params = {}): Promise<Bundle> {
const query = Object.fromEntries(
Object.entries(params).filter(([, v]) => v !== undefined),
@@ -29,7 +27,6 @@ export class Fhir {
);
}
/** The page a bundle's `next` (or `previous`) link points to, through our own base. */
follow(domain: string, bundle: Bundle, relation: 'next' | 'previous'): Promise<Bundle> | null {
const link = bundle.link?.find((l) => l.relation === relation)?.url;
if (!link) return null;
@@ -40,7 +37,6 @@ export class Fhir {
);
}
/** Every page of a search. */
async all(domain: string, type: string, params: Params = {}): Promise<Bundle[]> {
const pages = [await this.search(domain, type, params)];
for (let next = this.follow(domain, pages[0], 'next'); next;) {
@@ -52,7 +48,6 @@ export class Fhir {
}
}
/** The resources of a bundle (or of several pages), by search mode. */
export function resources<T extends FhirResource>(
bundles: Bundle | Bundle[],
type: T['resourceType'],
@@ -79,3 +74,15 @@ export function code(concept: CodeableConcept | undefined): string | undefined {
export function label(concept: CodeableConcept | undefined): string {
return concept?.text ?? concept?.coding?.[0]?.display ?? concept?.coding?.[0]?.code ?? '';
}
export function patientName(patient: Patient | undefined): string | undefined {
return patient?.name?.[0]?.text;
}
export function patientCurp(patient: Patient | undefined): string | undefined {
return patient?.identifier?.find((i) => i.system === CURP)?.value;
}
export function extensions(element: { extension?: Extension[] }, name: string): Extension[] {
return (element.extension ?? []).filter((e) => e.url === EXT + name);
}
+1 -9
View File
@@ -1,3 +1,4 @@
import { download } from '../export';
import { HttpErrorResponse } from '@angular/common/http';
import { Component, inject, input, model, output, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
@@ -37,15 +38,6 @@ export async function exportErrorText(error: unknown): Promise<string> {
}
}
export function download(blob: Blob, filename: string): void {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
setTimeout(() => URL.revokeObjectURL(url), 0);
}
@Component({
selector: 'app-governance-bundles',
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule],
+6 -3
View File
@@ -10,7 +10,12 @@ interface Band {
high?: (number | null)[];
}
export function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] {
export function banded(
name: string,
b: Band,
colour: string,
dash?: 'dot',
): Partial<Plotly.Data>[] {
const lines: Partial<Plotly.Data>[] = [];
if (b.low && b.high) {
lines.push({
@@ -302,7 +307,6 @@ export function interpretabilityFigures(
];
}
case 'associations': {
// Each estimated pair's odds ratio with its 95 % interval, clearest first.
const rows = (report['rows'] as any[])
.filter((r) => r.odds_ratio !== null)
.sort((a, b) => (a.q ?? 1) - (b.q ?? 1));
@@ -396,7 +400,6 @@ export function scenarioFigure(
points('LR + HBN combinado (IC 95 % bootstrap)', horizons, e.points.COMB),
],
layout: {
// One label per month with every curve's survival there, as percentages.
hovermode: 'x unified',
xaxis: { title: { text: 'Meses desde el diagnóstico' }, hoverformat: '.0f' },
yaxis: { title: { text: yTitle }, tickformat: '.1~%', hoverformat: '.1%' },
+1 -1
View File
@@ -33,7 +33,7 @@ import type { Domain } from '../api/models/domain';
import type { Execution as Choice } from '../api/models/execution';
import type { Run } from '../api/models/run';
import { Plot } from '../plot';
import { download } from './bundles';
import { download } from '../export';
import { interpretabilityFigures, studyPoints, type Centile } from './figures';
import { errorText, RunMonitor } from './run-monitor';
+1 -2
View File
@@ -1,5 +1,4 @@
import { downloadPdf, type PdfContent } from '../../export/pdf';
import { safeName } from '../../export/safe-name';
import { downloadPdf, safeName, type PdfContent } from '../../export';
import type { PreviewResult } from '../../api/models/preview-result';
import type { Score } from '../../api/models/score';
+2 -22
View File
@@ -12,7 +12,6 @@ function rgba(hex: string, alpha: number): string {
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`;
}
/** The screening route: each step's median days from the sample, with Q1–Q3. */
export function routeFigure(steps: { label: string; r: Reading | undefined }[]): Figure {
const shown = steps.filter((s) => s.r?.score !== undefined);
return {
@@ -44,12 +43,10 @@ export function routeFigure(steps: { label: string; r: Reading | undefined }[]):
};
}
/** A category's count in the report (the composition's `category` stratum). */
function counted(r: Reading, code: string): number {
return r.strata['category']?.[code]?.['initial-population'] ?? 0;
}
/** Groups inside, their categories outside, the total in the centre. */
export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figure {
const values = catalog.categories.map((c) => counted(r, c.code));
const total = values.reduce((a, b) => a + b, 0);
@@ -108,7 +105,6 @@ export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figur
labels: catalog.categories.map((c) => c.label),
hole: 0.74,
domain: { x: [0, 1], y: [0, 1] },
// along the thin ring, so a label fits its slice
insidetextorientation: 'tangential',
text: values.map((n, i) => (total && n / total >= 0.05 ? catalog.categories[i].label : '')),
marker: {
@@ -122,7 +118,6 @@ export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figur
};
}
/** Each clinical scenario's results as shares of its patients, one stacked bar each. */
export function scenarioBars(
r: Reading,
catalog: Catalog,
@@ -166,8 +161,7 @@ export function scenarioBars(
};
}
/** Wilson score interval at 95 %, in percent. */
export function wilson(k: number, n: number): [number, number] {
function wilson(k: number, n: number): [number, number] {
const z = 1.959963984540054;
const p = k / n;
const d = 1 + (z * z) / n;
@@ -176,8 +170,6 @@ export function wilson(k: number, n: number): [number, number] {
return [100 * (c - h), 100 * (c + h)];
}
/** Per cytology result: of the women with a biopsy, the share whose biopsy is a positive,
* with its 95 % interval; a result nobody had a biopsy for is named, not drawn. */
export function rateDots(
r: Reading,
spec: { stratum: string; rows: Category[]; positive: string[]; axis: string; colored?: boolean },
@@ -248,8 +240,6 @@ export function rateDots(
const decimal = (n: number) => n.toLocaleString('es-MX', { maximumFractionDigits: 2 });
/** A card's template filled from its measure's reading in the period: {n} counted, {obs}
* measured, {median} {q1} {q3} days, {num} {den} {pct}. */
export function fill(template: string, r: Reading): string {
const p = r.populations;
const values: Record<string, string> = {
@@ -265,7 +255,6 @@ export function fill(template: string, r: Reading): string {
return template.replace(/\{(\w+)\}/g, (_, k) => values[k] ?? '');
}
/** A duration's quartile box in the period. */
export function boxFigure(r: Reading, period: string): Figure {
const q1 = r.low ?? r.score!;
const q3 = r.high ?? r.score!;
@@ -289,7 +278,6 @@ export function boxFigure(r: Reading, period: string): Figure {
};
}
/** One ring: the categories' shares, the total in the centre. */
export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure {
const values = catalog.categories.map((c) => counted(r, c.code));
const total = values.reduce((a, b) => a + b, 0);
@@ -306,7 +294,6 @@ export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure
colors: catalog.categories.map((c) => c.color),
line: { color: '#FFFFFF', width: 2 },
},
// an empty slice says nothing (its label would sit on its neighbours')
texttemplate: values.map((v) => (v ? '%{label}<br>%{percent}' : '')),
textposition: 'outside',
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
@@ -329,7 +316,6 @@ export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure
};
}
/** A category's count per bar, one bar each, in the period. */
export function countBars(r: Reading, catalog: Catalog, axis: string, period: string): Figure {
const y = catalog.categories.map((c) => c.label);
return {
@@ -355,8 +341,7 @@ export function countBars(r: Reading, catalog: Catalog, axis: string, period: st
}
const AGE_COLORS = ['#A8C243', '#42C29C', '#9C42C2', '#4269C2'];
/** "16-23" as the screens say it: "16 a 23 meses". */
export const ageLabel = (band: string) => band.replace(/^(\d+)-(\d+)$/, '$1 a $2 meses');
const ageLabel = (band: string) => band.replace(/^(\d+)-(\d+)$/, '$1 a $2 meses');
function ages(r: Reading): [string, Record<string, number>][] {
return Object.entries(r.strata['age_group'] ?? {}).sort(
@@ -364,7 +349,6 @@ function ages(r: Reading): [string, Record<string, number>][] {
);
}
/** By age group: the numerator and the rest of the denominator, stacked. */
export function ageStack(r: Reading, names: [string, string]): Figure {
const rows = ages(r);
const x = rows.map(([a]) => ageLabel(a));
@@ -393,7 +377,6 @@ export function ageStack(r: Reading, names: [string, string]): Figure {
};
}
/** By age group: the numerator's share of the denominator, one bar each. */
export function ageShare(r: Reading, axis: string): Figure {
const rows = ages(r);
return {
@@ -418,9 +401,6 @@ export function ageShare(r: Reading, axis: string): Figure {
};
}
/** A Trazabilidad panel's figure (pages.HISTORY), as the old tab drew it: stacked bars by
* category, or a line with its band (95 % interval, or first to third quartile) drawn as one
* closed shape. */
export function historyFigure(
panel: HistoryPanel,
series: { label: string; r: Reading | undefined }[],
+1 -1
View File
@@ -5,7 +5,7 @@ import { periods } from './measures';
describe('follow-up list', () => {
it('starts the window the day after the same day months before (core.follow_up)', () => {
expect(windowStart('2026-11-22', 3)).toBe('2026-08-23');
expect(windowStart('2026-05-31', 3)).toBe('2026-03-01'); // 2026-02-28, plus one
expect(windowStart('2026-05-31', 3)).toBe('2026-03-01');
expect(windowStart('2026-01-15', 1)).toBe('2025-12-16');
});
+6 -17
View File
@@ -1,7 +1,6 @@
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { code, ext, resources } from '../fhir';
import { code, ext, patientCurp, patientName, resources } from '../fhir';
/** One row of the follow-up list: what the list shows of a patient at the cut-off. */
export interface Row {
patient: Patient;
name?: string;
@@ -15,8 +14,6 @@ export interface Row {
risk: Record<'cin2' | 'cancer', number | undefined>;
}
export const CURP = 'https://isssteleon.org/fhir/sid/curp';
const AGE_GROUPS: [number, number][] = [
[25, 34],
[35, 44],
@@ -38,8 +35,6 @@ export function ageGroup(
return age < groups[0][0] ? `<${groups[0][0]}` : `${groups.at(-1)![1] + 1}+`;
}
/** Her current risk of an outcome at a horizon: from the latest index date any of the
* outcome's models scored her at, the highest when several did (as the list is sorted). */
export function currentRisk(
risks: RiskAssessment[],
outcome: 'cin2' | 'cancer',
@@ -64,8 +59,6 @@ export function currentRisk(
);
}
/** The list's rows from one page: per patient, her latest cytology and HPV sampled in the
* window, her days to diagnosis, and her latest reported biopsy. */
export function rows(page: Bundle, start: string, cutoff: string, horizon: number): Row[] {
const reports = resources<DiagnosticReport>(page, 'DiagnosticReport');
const observations = new Map(resources<Observation>(page, 'Observation').map((o) => [o.id, o]));
@@ -99,8 +92,8 @@ export function rows(page: Bundle, start: string, cutoff: string, horizon: numbe
const theirs = risks.filter((r) => r.subject?.reference === `Patient/${patient.id}`);
return {
patient,
name: patient.name?.[0]?.text,
curp: patient.identifier?.find((i) => i.system === CURP)?.value,
name: patientName(patient),
curp: patientCurp(patient),
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
ageGroup: ageGroup(patient.birthDate, cutoff),
cytology: last && {
@@ -126,7 +119,6 @@ export function rows(page: Bundle, start: string, cutoff: string, horizon: numbe
});
}
/** The window's first day: `months` before the cut-off (the month's last day when shorter), plus one. */
export function windowStart(cutoff: string, months: number): string {
const [y, m, d] = cutoff.split('-').map(Number);
const total = y * 12 + (m - 1) - months;
@@ -137,16 +129,13 @@ export function windowStart(cutoff: string, months: number): string {
return day.toISOString().slice(0, 10);
}
/** One row of CaMa's follow-up list: her latest mammogram reported by the cut-off, where the
* biopsy it led to stands, and how soon she should be seen. */
export interface CamaRow {
interface CamaRow {
patient: Patient;
name?: string;
curp?: string;
status: string;
priority: string;
ageGroup: string;
/** `days`: from the mammogram to its diagnosis, when known by the cut-off. */
mammogram: { date: string; birads?: string; days?: number };
biopsy?: { date: string; histology?: string };
}
@@ -187,8 +176,8 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] {
.at(-1);
return {
patient,
name: patient.name?.[0]?.text,
curp: patient.identifier?.find((i) => i.system === CURP)?.value,
name: patientName(patient),
curp: patientCurp(patient),
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
priority: ext(patient, 'follow-up-priority')?.valueCoding?.code ?? '',
ageGroup: ageGroup(patient.birthDate, cutoff, CAMA_AGE_GROUPS),
-1
View File
@@ -13,7 +13,6 @@ import { TabSeguimiento } from './tab-seguimiento';
import { TabTrazabilidad } from './tab-trazabilidad';
import { Loading } from '../loading';
/** A domain's indicator page: four tabs over its FHIR measures and patients. */
@Component({
selector: 'app-indicadores',
imports: [
-85
View File
@@ -1,85 +0,0 @@
/** Where each measure goes on a domain's indicator page (today's layout); measures not
* named here are clinical cards. Measures are named by their code (`Measure.name`). */
export interface Layout {
kpis: string[];
route: { label: string; fromSample: string; fromStep: string; step: string }[];
/** The measure whose data decides the default period. */
anchor: string;
}
export const LAYOUTS: Record<string, Layout> = {
cacu: {
kpis: [
'CACU_EU7',
'CACU_EU_TIEMPO_REPORTE',
'CACU_DIAS_TOMA_DIAGNOSTICO',
'CACU_DIAS_TOMA_TRATAMIENTO',
'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
],
route: [
{
label: 'Resultado de citología',
step: 'Toma a resultado de citología',
fromSample: 'CACU_EU_TIEMPO_REPORTE',
fromStep: 'CACU_EU_TIEMPO_REPORTE',
},
{
label: 'Colposcopía',
step: 'Del resultado de citología a la colposcopía',
fromSample: 'CACU_DIAS_TOMA_COLPOSCOPIA',
fromStep: 'CACU_DIAS_RESULTADO_COLPOSCOPIA',
},
{
label: 'Resultado de biopsia',
step: 'De la colposcopía al resultado de biopsia',
fromSample: 'CACU_DIAS_TOMA_BIOPSIA',
fromStep: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA',
},
{
label: 'Diagnóstico',
step: 'Del resultado de biopsia al diagnóstico',
fromSample: 'CACU_DIAS_TOMA_DIAGNOSTICO',
fromStep: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO',
},
],
anchor: 'IND1',
},
cama: {
kpis: [
'CAMA_BIRADS',
'CAMA_EU38A',
'CAMA_DIAS_TOMA_DIAGNOSTICO',
'CAMA_CONFIRMACION_BIRADS45',
'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
],
route: [
{
label: 'Resultado de mastografía',
step: 'Toma a resultado de mastografía',
fromSample: 'CAMA_EU38A',
fromStep: 'CAMA_EU38A',
},
{
label: 'Diagnóstico',
step: 'Del resultado de mastografía al diagnóstico',
fromSample: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
fromStep: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
},
],
anchor: 'CAMA_BIRADS',
},
tea: {
kpis: [
'M26_DIAS_MCHAT_ADOS2',
'M27_DIAS_ADOS2_DIAGNOSTICO',
'M25_DIAS_MCHAT_DIAGNOSTICO',
'M23_PACIENTES_EVALUADOS',
'M24_CONFIRMACION_DIAGNOSTICO',
'M21_DIAGNOSTICADOS_CON_EEG',
'M22_DIAGNOSTICADOS_SIN_EEG',
'M29_CALIDAD_EEG',
],
route: [],
anchor: 'M23_PACIENTES_EVALUADOS',
},
};
-213
View File
@@ -1,11 +1,8 @@
import type { Measure, MeasureReport, MeasureReportGroup } from 'fhir/r4';
import { code, ext } from '../fhir';
import { Figure, PALETTE } from '../plot';
export type PeriodType = 'semester' | 'month';
export type Scoring = 'proportion' | 'continuous-variable' | 'cohort';
/** The periods back from today, most recent first: semesters (`2025-S1`) or months. */
export function periods(type: PeriodType, years = 6, today = new Date()): string[] {
const found: string[] = [];
const year = today.getFullYear();
@@ -32,17 +29,12 @@ export function periodLabel(period: string): string {
return `${month} ${year}`;
}
export function scoring(measure: Measure): Scoring {
return code(measure.scoring) as Scoring;
}
export function periodTypes(measure: Measure): PeriodType[] {
return (measure.extension ?? [])
.filter((e) => e.url.endsWith('/period-type'))
.map((e) => e.valueCode as PeriodType);
}
/** What one report says: its counts, its score and interval, and its strata. */
export interface Reading {
populations: Record<string, number>;
score?: number;
@@ -66,7 +58,6 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
const score = group.measureScore;
const strata: Reading['strata'] = {};
for (const s of group.stratifier ?? []) {
// A crossed stratifier (several codes) is keyed `a-b`, its strata `valueA|valueB`.
const name = (s.code ?? []).map((c) => code(c) ?? c.text ?? '').join('-');
strata[name] = Object.fromEntries(
(s.stratum ?? []).map((x) => [
@@ -87,7 +78,6 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
};
}
/** Codes as the screens name them. */
export const LABELS: Record<string, string> = {
NILM: 'Normal (NILM)',
LSIL: 'LIEBG',
@@ -136,7 +126,6 @@ export const LABELS: Record<string, string> = {
['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
),
};
/** A follow-up priority's label. */
export const PRIORITY: Record<string, string> = { high: 'Alta', medium: 'Media', low: 'Baja' };
export const STRATA: Record<string, string> = {
category: 'Categoría',
@@ -146,205 +135,3 @@ export const STRATA: Record<string, string> = {
birads: 'BI-RADS de la mastografía',
};
export const name = (value: string) => LABELS[value] ?? value;
export function formatScore(measure: Measure, r: Reading | undefined): string {
if (!r || r.score === undefined) return 'Sin dato';
switch (scoring(measure)) {
case 'proportion':
return `${(r.score * 100).toFixed(1)} %`;
case 'continuous-variable':
return `${Math.round(r.score * 10) / 10} días`;
default:
return `${r.score}`;
}
}
export function detail(measure: Measure, r: Reading | undefined): string {
if (!r) return '';
const p = r.populations;
switch (scoring(measure)) {
case 'proportion':
return r.score === undefined
? 'Sin pacientes en el periodo.'
: `${p['numerator']} de ${p['denominator']} pacientes. IC 95 %: ${pct(r.low)}–${pct(r.high)}.`;
case 'continuous-variable':
return r.score === undefined
? `${p['initial-population'] ?? 0} sin medición en el periodo.`
: `Mediana de ${p['measure-observation']} mediciones; cuartiles ${r.low}–${r.high} días.`;
default:
return `${p['initial-population'] ?? 0} pacientes.`;
}
}
const pct = (v?: number) => (v === undefined ? '—' : `${(v * 100).toFixed(1)} %`);
/** A donut of one stratifier's counts (initial population), or of numerator vs the rest. */
export type Ring = { labels: string[]; values: number[] };
export function donut(
measure: Measure,
r: Reading,
stratifier = 'category',
inner?: Ring,
outer?: Ring,
): Figure {
let labels: string[], values: number[];
if (scoring(measure) === 'proportion') {
const { numerator = 0, denominator = 0 } = r.populations;
labels = ['Numerador', 'Resto'];
values = [numerator, denominator - numerator];
} else {
const cells = Object.entries(r.strata[stratifier] ?? {});
labels = cells.map(([v]) => name(v));
values = cells.map(([, c]) => c['initial-population'] ?? 0);
}
return {
data: [
{
type: 'pie',
hole: inner ? 0.68 : 0.62,
...(outer ?? { labels, values }),
sort: false,
textinfo: 'value+percent',
marker: { colors: PALETTE },
},
...(inner
? [
{
type: 'pie' as const,
hole: 0.45,
...inner,
sort: false,
textinfo: 'percent' as const,
domain: { x: [0.17, 0.83] as [number, number], y: [0.17, 0.83] as [number, number] },
marker: { colors: PALETTE },
},
]
: []),
],
layout: { showlegend: true, margin: { t: 32, r: 8, b: 32, l: 8 } },
};
}
/** Bars per stratum: the rate (proportion) or the count (others). */
export function strataBars(
measure: Measure,
r: Reading,
stratifier: string,
showCounts = false,
): Figure {
const cells = Object.entries(r.strata[stratifier] ?? {});
const proportion = scoring(measure) === 'proportion';
const values = cells.map(([, c]) =>
proportion
? c['denominator']
? (100 * (c['numerator'] ?? 0)) / c['denominator']
: 0
: (c['initial-population'] ?? 0),
);
return {
data: [
{
type: 'bar',
orientation: 'h',
y: cells.map(([v]) => name(v)),
x: values,
...(showCounts
? {
text: cells.map(([, c], i) => `${c['numerator'] ?? 0} (${values[i].toFixed(1)} %)`),
hovertemplate: '%{y}: %{text}<extra></extra>',
}
: {}),
marker: { color: PALETTE[0] },
},
],
layout: {
xaxis: { title: { text: proportion ? '%' : 'Pacientes' } },
yaxis: { automargin: true },
margin: { t: 8, r: 16, b: 48, l: 8 },
},
};
}
/** Horizontal median bars with their interquartile range, one per measure. */
export function medians(rows: { label: string; r: Reading | undefined }[]): Figure {
const shown = rows.filter((x) => x.r?.score !== undefined);
return {
data: [
{
type: 'bar',
orientation: 'h',
y: shown.map((x) => x.label),
x: shown.map((x) => x.r!.score!),
error_x: {
type: 'data',
symmetric: false,
array: shown.map((x) => (x.r!.high ?? x.r!.score!) - x.r!.score!),
arrayminus: shown.map((x) => x.r!.score! - (x.r!.low ?? x.r!.score!)),
color: '#17324d',
},
marker: { color: PALETTE[0] },
hovertemplate: '%{y}: %{x} días<extra></extra>',
},
],
layout: {
xaxis: { title: { text: 'Días (mediana, Q1–Q3)' } },
yaxis: { automargin: true, autorange: 'reversed' },
},
};
}
/** A measure over time: % with its interval, median with its quartiles, or counts by category. */
export function history(
measure: Measure,
series: { period: string; r: Reading | undefined }[],
): Figure {
const x = series.map((s) => periodLabel(s.period));
const kind = scoring(measure);
if (kind === 'cohort') {
const categories = [
...new Set(series.flatMap((s) => Object.keys(s.r?.strata['category'] ?? {}))),
];
return {
data: categories.map((c, i) => ({
type: 'bar',
name: name(c),
x,
y: series.map((s) => s.r?.strata['category']?.[c]?.['initial-population'] ?? 0),
marker: { color: PALETTE[i % PALETTE.length] },
})),
layout: { barmode: 'stack', yaxis: { title: { text: 'Pacientes' } } },
};
}
const k = kind === 'proportion' ? 100 : 1;
const value = (v?: number) => (v === undefined ? null : v * k);
return {
data: [
{
x,
y: series.map((s) => value(s.r?.high)),
mode: 'lines',
line: { width: 0 },
showlegend: false,
hoverinfo: 'skip',
},
{
x,
y: series.map((s) => value(s.r?.low)),
mode: 'lines',
line: { width: 0 },
fill: 'tonexty',
fillcolor: 'rgba(168,194,67,0.25)',
name: kind === 'proportion' ? 'IC 95 %' : 'Q1–Q3',
},
{
x,
y: series.map((s) => value(s.r?.score)),
mode: 'lines+markers',
name: kind === 'proportion' ? '%' : 'Mediana',
line: { color: PALETTE[0] },
},
],
layout: { yaxis: { title: { text: kind === 'proportion' ? '%' : 'Días' } } },
};
}
+53
View File
@@ -0,0 +1,53 @@
import { Component, input, output } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
@Component({
selector: 'app-pager',
imports: [MatButtonModule],
template: `
<nav class="pager" aria-label="Páginas de pacientes">
<span class="muted"><ng-content /></span>
<button
mat-stroked-button
type="button"
(click)="previous.emit()"
[disabled]="previousDisabled()"
>
Anterior
</button>
<button mat-stroked-button type="button" (click)="next.emit()" [disabled]="nextDisabled()">
Siguiente
</button>
</nav>
`,
styles: `
.pager {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
justify-content: flex-end;
margin-top: var(--space-3);
}
:host(.print-pagination) .pager {
flex-wrap: nowrap;
}
@media print {
:host(.print-pagination) .pager {
display: flex !important;
}
}
.muted {
margin-right: auto;
}
`,
})
export class Pager {
readonly previousDisabled = input.required<boolean>();
readonly nextDisabled = input.required<boolean>();
readonly previous = output<void>();
readonly next = output<void>();
}
+2 -22
View File
@@ -1,13 +1,9 @@
export interface Page {
interface Page {
kpis: Kpi[];
/** Under the cards, before the clinical indicators (CaMa's timeliness boxes). */
opportunity?: Section[];
clinical: Section[];
/** The measure whose data decides the default period. */
anchor: string;
}
/** A card: its measure (none: not published yet), its title, and its value and note as
* templates (figures.fill). */
export interface Kpi {
measure?: string;
title: string;
@@ -19,18 +15,13 @@ export type Section =
| { kind: 'figures'; title?: string; figures: FigureSpec[] }
| {
kind: 'boxes';
/** none: the boxes stand alone (TEA) */
title?: string;
cards: { measure?: string; title: string }[];
/** the measure's own title under each card's (CaMa) */
subtitles?: boolean;
}
/** Each figure in its own card, titled, two to a row (TEA). */
| { kind: 'grid'; figures: FigureSpec[] }
/** TEA's period summary in words, its numbers from the measures. */
| { kind: 'tea-summary' }
| ({ kind: 'card' } & Kpi);
/** Figure titles may carry `{p}`, the applied period. */
export type FigureSpec =
| {
kind: 'donut' | 'share-donut';
@@ -45,7 +36,6 @@ export type FigureSpec =
kind: 'age-stack' | 'age-share';
title: string;
measure: string;
/** the numerator's and the rest's names (stack), or the axis (share) */
names: [string, string];
}
| {
@@ -54,9 +44,7 @@ export type FigureSpec =
measure: string;
stratum: string;
rows: Category[];
/** each row in its category's colour (else all rose) */
colored?: boolean;
/** the categories (of the measure) that count as a positive */
positive: string[];
axis: string;
};
@@ -70,14 +58,12 @@ export interface Category {
export interface Catalog {
groups: { id: string; label: string; color: string }[];
categories: Category[];
/** categories drawn faded (not the ones the figure is about) */
faded?: string[];
}
const OLIVE = '#A8C243';
const ROSE = '#C24269';
/** Bethesda results as the old app grouped and coloured them. */
const CYTOLOGY: Catalog = {
groups: [
{ id: 'normal', label: 'Sin anomalía', color: OLIVE },
@@ -93,7 +79,6 @@ const CYTOLOGY: Catalog = {
],
};
/** Biopsy grades: below high grade, and high grade or worse (what confirmation counts). */
const BIOPSY: Catalog = {
groups: [
{ id: 'low', label: 'Menor que LIEAG', color: OLIVE },
@@ -119,7 +104,6 @@ const CAMA_DAYS = {
};
const PENDING = 'Indicador no publicado en el catálogo institucional.';
/** BI-RADS 4 to 6 as the old app named and coloured them. */
const BIRADS: Catalog = {
groups: [],
categories: [
@@ -430,17 +414,13 @@ export interface HistoryPanel {
title: string;
measure: string;
kind: 'stack' | 'percent' | 'median';
/** stack: the categories, in the old order, with their names and colours */
series?: { code: string; label: string; color: string }[];
/** stack: the y axis */
axis?: string;
group?: string;
}
export interface History {
interface History {
panels: HistoryPanel[];
/** the line's colour (percent and median) */
line: string;
/** how many of the latest months the tab opens with (none: from the first with data) */
months?: number;
}
-6
View File
@@ -5,8 +5,6 @@ import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
/** A search box's text as FHIR Patient search parameters: one word with a digit is an
* identifier (a CURP or a record number); anything else is her name. */
export function patientSearch(text: string): { name?: string; identifier?: string } {
const t = text.trim();
if (!t) return {};
@@ -15,8 +13,6 @@ export function patientSearch(text: string): { name?: string; identifier?: strin
const fold = (s: string) => s.normalize('NFKD').replace(/\p{M}/gu, '').toLowerCase();
/** Whether a row matches the search in the browser (lists loaded whole): each word starts a
* word of one of its texts (a name, an identifier, the pseudonymous id). */
export function matchesSearch(text: string, texts: (string | undefined)[]): boolean {
const words = fold(text).split(/\s+/).filter(Boolean);
if (!words.length) return true;
@@ -24,7 +20,6 @@ export function matchesSearch(text: string, texts: (string | undefined)[]): bool
return known.some((parts) => words.every((w) => parts.some((p) => p.startsWith(w))));
}
/** "Buscar paciente": applied on Enter or the search button, cleared with the cross. */
@Component({
selector: 'app-patient-search',
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
@@ -65,7 +60,6 @@ export function matchesSearch(text: string, texts: (string | undefined)[]): bool
`,
})
export class PatientSearch {
/** The search as applied. */
readonly value = model('');
readonly searched = output<string>();
protected readonly draft = signal('');
-4
View File
@@ -16,9 +16,6 @@ const IMPROVEMENT: Record<string, string> = {
};
const PERIODS: Record<string, string> = { semester: 'Semestral', month: 'Mensual' };
/** "Datos y definiciones" as the old tab: the domain's information, then its catalog, each
* indicator opening to what it is (how it scores, which way is better, its periods and
* strata). */
@Component({
selector: 'app-tab-definiciones',
template: `
@@ -124,7 +121,6 @@ export class TabDefiniciones {
protected readonly domainName = computed(
() => DOMAINS[this.domain() as Domain]?.toLocaleLowerCase('es-MX') ?? this.domain(),
);
/** The periodicities any of its indicators admits. */
protected readonly available = computed(() =>
[...new Set(this.measures().flatMap((m) => periodTypes(m)))].map((p) => PERIODS[p] ?? p),
);
+1 -55
View File
@@ -1,4 +1,4 @@
<div class="filters card">
<div class="filters indicator-filters card">
<h2 class="filters-title">Filtros</h2>
<div class="field">
<span class="label">Intervalo de análisis</span>
@@ -219,58 +219,4 @@
}
}
</ng-template>
} @else {
@if (kpis().length) {
<h2>Indicadores de oportunidad</h2>
<div class="kpis">
@for (m of kpis(); track m.id) {
<mat-card appearance="outlined" class="kpi" [attr.data-measure]="m.name">
<mat-card-content>
<div class="kpi-title">{{ m.title }}</div>
<div class="kpi-value">{{ score(m) }}</div>
<div class="kpi-detail muted">{{ detail(m) }}</div>
</mat-card-content>
</mat-card>
}
</div>
}
@if (layout().route.length) {
<mat-card appearance="outlined" class="route">
<mat-card-header>
<mat-card-title>Ruta del tamizaje</mat-card-title>
<mat-button-toggle-group
[value]="routeView()"
(change)="routeView.set($event.value)"
class="route-toggle"
>
<mat-button-toggle value="sample">Acumulado desde la toma</mat-button-toggle>
<mat-button-toggle value="step">Por pasos</mat-button-toggle>
</mat-button-toggle-group>
</mat-card-header>
<mat-card-content>
<app-plot [figure]="route()" [height]="260" />
</mat-card-content>
</mat-card>
}
<h2>Indicadores clínicos</h2>
<div class="clinical">
@for (m of clinical(); track m.id) {
<mat-card appearance="outlined" class="clinical-card" [attr.data-measure]="m.name">
<mat-card-header>
<mat-card-title>{{ m.title }}</mat-card-title>
<mat-card-subtitle>{{ score(m) }} · {{ detail(m) }}</mat-card-subtitle>
</mat-card-header>
<mat-card-content>
@for (f of figureSets().get(m.name!) ?? []; track f.title) {
<h3 class="figure-title">{{ f.title }}</h3>
<app-plot [figure]="f.figure" [height]="260" />
} @empty {
<p class="muted">Sin datos en el periodo.</p>
}
</mat-card-content>
</mat-card>
}
</div>
}
-50
View File
@@ -3,14 +3,6 @@
padding-top: var(--space-4);
}
.filters {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: var(--space-4);
margin-bottom: var(--space-4);
}
.field {
display: flex;
flex-direction: column;
@@ -73,40 +65,9 @@ h2 {
.kpi-detail {
font-size: 13px;
}
.route {
margin-top: var(--space-4);
}
.route mat-card-header {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
justify-content: space-between;
}
.clinical {
display: grid;
gap: var(--space-4);
grid-template-columns: 1fr;
}
@media (min-width: 1304px) {
.clinical {
grid-template-columns: repeat(2, 1fr);
}
}
.figure-title {
color: var(--color-text-secondary);
font-size: 14px;
font-weight: 500;
margin: var(--space-3) 0 0;
}
/* The old app's page: white sections with a title, cards inside. */
.card.opportunity,
.card.clinical-page {
background: var(--color-surface);
@@ -140,10 +101,6 @@ h3.kpi-title {
min-height: 2.6em;
}
.kpi-detail {
color: var(--color-text-secondary);
}
h3.route-title {
font-size: 16px;
font-weight: 700;
@@ -183,13 +140,6 @@ h2.figure-card-title {
font-size: 14px;
}
.filters {
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: 8px;
padding: 16px;
}
h2.filters-title {
flex-basis: 100%;
font-size: 16px;
+3 -100
View File
@@ -1,6 +1,5 @@
import { Component, computed, effect, inject, input, resource, signal } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
@@ -8,7 +7,6 @@ import { MatSelectModule } from '@angular/material/select';
import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot';
import { LAYOUTS } from './layout';
import {
ageShare,
ageStack,
@@ -22,30 +20,13 @@ import {
shareDonut,
} from './figures';
import { FigureSpec, Kpi, PAGES, Section } from './pages';
import {
detail,
donut,
formatScore,
medians,
name,
periodLabel,
periods,
PeriodType,
reading,
Reading,
scoring,
STRATA,
strataBars,
} from './measures';
import { name, periods, PeriodType, reading, Reading } from './measures';
import { Loading } from '../loading';
/** The period's indicators: the timeliness KPIs, the screening route, and a card per
* clinical measure with its figures. */
@Component({
selector: 'app-tab-indicadores',
imports: [
Loading,
FormsModule,
NgTemplateOutlet,
MatButtonModule,
MatButtonToggleModule,
@@ -64,35 +45,15 @@ export class TabIndicadores {
protected readonly type = signal<PeriodType>('semester');
protected readonly options = computed(() => periods(this.type()));
protected readonly chosen = signal<string | undefined>(undefined);
/** The period the figures show (set by Aplicar). */
protected readonly applied = signal<string | undefined>(undefined);
protected readonly routeView = signal<'sample' | 'step'>('sample');
protected readonly layout = computed(
() => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' },
);
protected readonly pending = 'Indicador no publicado en el catálogo institucional.';
/** The old app's page for this domain, when it is rebuilt as it was (else today's). */
protected readonly page = computed(() => PAGES[this.domain()]);
private readonly byName = computed(() => new Map(this.measures().map((m) => [m.name!, m])));
protected readonly kpis = computed(() =>
this.layout()
.kpis.map((n) => this.byName().get(n))
.filter((m) => !!m),
);
protected readonly clinical = computed(() => {
const placed = new Set([
...this.layout().kpis,
...this.layout().route.flatMap((s) => [s.fromSample, s.fromStep]),
]);
return this.measures().filter((m) => !placed.has(m.name!));
});
/** The latest period with data, the default. */
private readonly latest = resource({
params: () => ({
domain: this.domain(),
anchor: this.byName().get(this.page()?.anchor ?? this.layout().anchor) ?? this.measures()[0],
anchor: this.byName().get(this.page()?.anchor ?? '') ?? this.measures()[0],
all: this.options(),
}),
loader: async ({ params }) => {
@@ -125,8 +86,6 @@ export class TabIndicadores {
},
});
/** The period's readings; none while they load or when reading them failed (an errored
* resource throws on `value()`). */
protected loaded(): Map<string, Reading | undefined> | undefined {
return this.reports.hasValue() ? this.reports.value() : undefined;
}
@@ -141,67 +100,15 @@ export class TabIndicadores {
});
}
protected readonly label = periodLabel;
protected readonly strataNames = STRATA;
protected r(m: Measure): Reading | undefined {
return this.loaded()?.get(m.name!);
}
protected score(m: Measure): string {
return formatScore(m, this.r(m));
}
protected detail(m: Measure): string {
return detail(m, this.r(m));
}
protected readonly pending = 'Indicador no publicado en el catálogo institucional.';
protected setType(type: PeriodType): void {
this.type.set(type);
this.chosen.set(this.options()[0]);
}
protected readonly route = computed<Figure>(() => {
const view = this.routeView();
return medians(
this.layout().route.map((s) => {
const m = this.byName().get(view === 'sample' ? s.fromSample : s.fromStep);
return { label: view === 'sample' ? s.label : s.step, r: m && this.r(m) };
}),
);
});
/** Each clinical card's figures, built once per loaded period. */
protected readonly figureSets = computed(
() =>
new Map(this.clinical().map((m) => [m.name!, this.build(m, this.loaded()?.get(m.name!))])),
);
/** A clinical card's figures: the overall split, then one per stratum. */
private build(m: Measure, r: Reading | undefined): { title: string; figure: Figure }[] {
if (!r || !(r.populations['initial-population'] ?? 0)) return [];
const strata = Object.keys(r.strata).filter(
(s) => s !== 'category' && !s.includes('-') && Object.keys(r.strata[s]).length,
);
const kind = scoring(m);
if (kind === 'continuous-variable')
return [{ title: 'Mediana y cuartiles', figure: medians([{ label: m.title!, r }]) }];
return [
{ title: kind === 'proportion' ? 'Numerador y resto' : 'Por categoría', figure: donut(m, r) },
...strata.map((s) => ({
title: `Por ${STRATA[s]?.toLowerCase() ?? s}`,
figure: strataBars(m, r, s),
})),
];
}
protected readonly name = name;
/** A measure's reading in the applied period, by code. */
protected rd(code: string): Reading | undefined {
return this.loaded()?.get(code);
}
protected kpi(code: string): Measure | undefined {
return this.byName().get(code);
}
/** A card's value and note, from its templates (a card with no measure: its words). */
/** "27 días (mediana)" as the value and its qualifier, shown smaller beneath it. */
protected kpiParts(text: string): [string, string] {
const found = /^(.*?)\s*(\([^)]*\))$/.exec(text);
return found ? [found[1], found[2]] : [text, ''];
@@ -218,16 +125,13 @@ export class TabIndicadores {
if (!r || r.score === undefined) return 'Sin valor disponible';
return k.note ? fill(k.note, r) : '';
}
/** A figure's title, with the applied period in it. */
protected titled(title: string): string {
return title.replace('{p}', this.applied() ?? '');
}
/** A duration's box, or nothing to draw. */
protected boxOf(measure: string | undefined): Figure | undefined {
const r = measure ? this.rd(measure) : undefined;
return r && r.score !== undefined ? boxFigure(r, this.applied() ?? '') : undefined;
}
/** TEA's summary of the period: its numbers from the measures (none: no summary). */
protected readonly teaSummary = computed(() => {
const rd = (c: string) => this.loaded()?.get(c);
const status = rd('M28_CASOS_POR_ESTADO');
@@ -264,7 +168,6 @@ export class TabIndicadores {
protected measureTitle(code: string | undefined): string {
return (code && this.byName().get(code)?.title) || '';
}
/** A clinical section's route or figures, drawn from the applied period's reports. */
protected routeOf(section: Section): Figure | undefined {
if (section.kind !== 'route') return undefined;
const steps = section.steps.map((s) => ({ label: s.label, r: this.rd(s.measure) }));
+22 -29
View File
@@ -1,4 +1,4 @@
<div class="filters card">
<div class="filters worklist-filters card">
<app-patient-search [(value)]="search" (searched)="index.set(0)" />
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label>
@@ -91,14 +91,22 @@
<section class="card eeg-summary" aria-labelledby="tea-eeg-summary">
<h3 id="tea-eeg-summary">EEG de los pacientes del periodo</h3>
<div class="counts">
<span><strong>{{ eeg.normal }}</strong> Normales</span>
<span><strong>{{ eeg.abnormal }}</strong> Anormales</span>
<span><strong>{{ eeg.notValid }}</strong> Sin EEG válido</span>
<span
><strong>{{ eeg.normal }}</strong> Normales</span
>
<span
><strong>{{ eeg.abnormal }}</strong> Anormales</span
>
<span
><strong>{{ eeg.notValid }}</strong> Sin EEG válido</span
>
</div>
@if (eeg.alterations.length) {
<ul class="by-alteration">
@for (alteration of eeg.alterations; track alteration.code) {
<li>{{ name(alteration.code) }}: <strong>{{ alteration.patients }}</strong></li>
<li>
{{ name(alteration.code) }}: <strong>{{ alteration.patients }}</strong>
</li>
}
</ul>
}
@@ -195,9 +203,7 @@
<td>{{ (pair.probability | number: '1.0-4') ?? '—' }}</td>
<td>{{ (pair.reference | number: '1.0-4') ?? '—' }}</td>
<td>
{{
pair.sameDirection == null ? '—' : pair.sameDirection ? 'Sí' : 'No'
}}
{{ pair.sameDirection == null ? '—' : pair.sameDirection ? 'Sí' : 'No' }}
</td>
</tr>
}
@@ -215,25 +221,12 @@
</table>
</div>
<nav class="pager" aria-label="Páginas de pacientes">
<span class="muted">
Página {{ index() + 1 }} de {{ pageCount() }} · {{ filtered().length }} registros
</span>
<button
mat-stroked-button
type="button"
(click)="index.set(index() - 1)"
[disabled]="index() === 0"
>
Anterior
</button>
<button
mat-stroked-button
type="button"
(click)="index.set(index() + 1)"
[disabled]="index() + 1 >= pageCount()"
>
Siguiente
</button>
</nav>
<app-pager
[previousDisabled]="index() === 0"
[nextDisabled]="index() + 1 >= pageCount()"
(previous)="index.set(index() - 1)"
(next)="index.set(index() + 1)"
>
Página {{ index() + 1 }} de {{ pageCount() }} · {{ filtered().length }} registros
</app-pager>
}
+6 -2
View File
@@ -14,6 +14,7 @@ import { Fhir } from '../fhir';
import { Loading } from '../loading';
import { windowStart } from './follow-up';
import { name } from './measures';
import { Pager } from './pager';
import { PatientSearch } from './patient-search';
import {
ASSOCIATION_LABELS,
@@ -41,6 +42,7 @@ import {
MatInputModule,
MatSelectModule,
PatientSearch,
Pager,
RouterLink,
],
templateUrl: './tab-riesgos-tea.html',
@@ -109,8 +111,10 @@ export class TabRiesgosTea {
(this.cutoff() ? windowStart(this.cutoff(), this.filters().window ?? 3) : ''),
);
protected readonly filtered = computed(() =>
associationRows(this.results.hasValue() ? this.results.value().rows : [], this.association())
.filter((row) => matchesTeaSearch(row, this.search())),
associationRows(
this.results.hasValue() ? this.results.value().rows : [],
this.association(),
).filter((row) => matchesTeaSearch(row, this.search())),
);
protected readonly rows = computed(() =>
this.filtered().slice(this.index() * this.size(), (this.index() + 1) * this.size()),
+18 -16
View File
@@ -1,7 +1,7 @@
@if (domain() === 'tea') {
<app-tab-riesgos-tea />
} @else {
<form class="filters card" (submit)="$event.preventDefault()">
<form class="filters worklist-filters card" (submit)="$event.preventDefault()">
<app-patient-search [(value)]="search" />
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label>
@@ -80,8 +80,12 @@
<th>Última citología</th>
<th>Último resultado de VPH</th>
<th>Última biopsia</th>
<th>Probabilidad a LIEAG+ a {{ horizon() }} {{ horizon() === 1 ? 'año' : 'años' }} (%)</th>
<th>Probabilidad a cáncer a {{ horizon() }} {{ horizon() === 1 ? 'año' : 'años' }} (%)</th>
<th>
Probabilidad a LIEAG+ a {{ horizon() }} {{ horizon() === 1 ? 'año' : 'años' }} (%)
</th>
<th>
Probabilidad a cáncer a {{ horizon() }} {{ horizon() === 1 ? 'año' : 'años' }} (%)
</th>
<th>Estudio más reciente</th>
<th>Días de toma a diagnóstico</th>
</tr>
@@ -168,17 +172,15 @@
</table>
</div>
<div class="pager">
<span class="muted">
@if (page()?.total; as total) {
Página {{ pageNumber() }} de {{ pageCount() }}, {{ total }} registros
}
</span>
<button mat-stroked-button (click)="go('previous')" [disabled]="!has('previous') || loading()">
Anterior
</button>
<button mat-stroked-button (click)="go('next')" [disabled]="!has('next') || loading()">
Siguiente
</button>
</div>
<app-pager
class="print-pagination"
[previousDisabled]="!has('previous') || loading()"
[nextDisabled]="!has('next') || loading()"
(previous)="go('previous')"
(next)="go('next')"
>
@if (page()?.total; as total) {
Página {{ pageNumber() }} de {{ pageCount() }}, {{ total }} registros
}
</app-pager>
}
-24
View File
@@ -3,18 +3,6 @@
padding-top: var(--space-4);
}
.filters {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
margin-bottom: var(--space-4);
}
// a field as wide as its label ("Horizonte de la probabilidad")
.filters mat-form-field {
min-width: 14.5rem;
}
.table-wrap {
overflow-x: auto;
padding: 0;
@@ -34,18 +22,6 @@ a {
font-size: 12px;
}
.pager {
align-items: center;
display: flex;
gap: var(--space-3);
justify-content: flex-end;
margin-top: var(--space-3);
}
.pager .muted {
margin-right: auto;
}
.worklist td small {
display: block;
white-space: nowrap;
+2 -7
View File
@@ -9,6 +9,7 @@ import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir';
import { Row, rows, windowStart } from './follow-up';
import { Pager } from './pager';
import { PatientSearch, patientSearch } from './patient-search';
import { TabRiesgosTea } from './tab-riesgos-tea';
import { Loading } from '../loading';
@@ -16,12 +17,11 @@ import { name } from './measures';
const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment'];
/** CaCu's follow-up list at a cut-off: who had a cytology in the window, her status,
* results and current risks, in the order asked for. */
@Component({
selector: 'app-tab-riesgos',
imports: [
PatientSearch,
Pager,
DecimalPipe,
FormsModule,
Loading,
@@ -45,9 +45,7 @@ export class TabRiesgos {
protected readonly horizon = signal(5);
protected readonly sort = signal('-recent');
protected readonly size = signal(20);
/** "Buscar paciente": her name, CURP or record number, as applied. */
protected readonly search = signal('');
/** A page the user moved to (`next`/`previous`), else the first. */
private readonly moved = signal<Bundle | undefined>(undefined);
protected readonly statuses = STATUSES;
@@ -80,7 +78,6 @@ export class TabRiesgos {
protected readonly page = computed(
() => this.moved() ?? (this.first.hasValue() ? this.first.value() : undefined),
);
/** The cut-off as applied (the server's default when none is given). */
protected readonly applied = computed(() => {
const self = this.page()?.link?.find((l) => l.relation === 'self')?.url;
return self ? (new URL(self).searchParams.get('follow-up-cutoff') ?? '') : '';
@@ -98,7 +95,6 @@ export class TabRiesgos {
});
protected readonly error = computed(() => this.first.error());
/** "Ventana consultada": the window's first day for the applied cut-off. */
protected readonly start = computed(() =>
this.applied() ? windowStart(this.applied(), this.window()) : '',
);
@@ -106,7 +102,6 @@ export class TabRiesgos {
protected readonly pageCount = computed(() =>
Math.max(1, Math.ceil((this.page()?.total ?? 0) / this.size())),
);
/** "Estudio más reciente": her latest cytology or HPV sample. */
protected latest(row: Row): string | undefined {
return [row.cytology?.date, row.hpv?.date]
.filter((d) => !!d)
+10 -20
View File
@@ -1,9 +1,7 @@
@if (focused(); as id) {
<button mat-stroked-button type="button" (click)="clearFocus(id)">
Ver todos los pacientes
</button>
<button mat-stroked-button type="button" (click)="clearFocus(id)">Ver todos los pacientes</button>
} @else {
<div class="filters card">
<div class="filters worklist-filters card">
<app-patient-search [(value)]="search" />
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label>
@@ -149,21 +147,13 @@
</div>
@if (!focused()) {
<nav class="pager" aria-label="Páginas de pacientes">
<span class="muted">
Página {{ pageNumber() }} de {{ pageCount() }} · {{ page()?.total ?? 0 }} registros
</span>
<button
mat-stroked-button
type="button"
(click)="go('previous')"
[disabled]="!has('previous')"
>
Anterior
</button>
<button mat-stroked-button type="button" (click)="go('next')" [disabled]="!has('next')">
Siguiente
</button>
</nav>
<app-pager
[previousDisabled]="!has('previous')"
[nextDisabled]="!has('next')"
(previous)="go('previous')"
(next)="go('next')"
>
Página {{ pageNumber() }} de {{ pageCount() }} · {{ page()?.total ?? 0 }} registros
</app-pager>
}
}
+6 -25
View File
@@ -3,24 +3,6 @@
padding-top: var(--space-4);
}
.filters,
.actions,
.pager {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-3);
}
.filters,
.actions {
margin-bottom: var(--space-4);
}
.filters mat-form-field {
min-width: 14.5rem;
}
.table-wrap {
overflow-x: auto;
padding: 0;
@@ -36,11 +18,10 @@ a {
color: var(--color-action);
}
.pager {
justify-content: flex-end;
margin-top: var(--space-3);
}
.pager .muted {
margin-right: auto;
.actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-3);
margin-bottom: var(--space-4);
}
+3 -3
View File
@@ -10,6 +10,7 @@ import { Fhir } from '../fhir';
import { Loading } from '../loading';
import { windowStart } from './follow-up';
import { name } from './measures';
import { Pager } from './pager';
import { PatientSearch, patientSearch } from './patient-search';
import {
ageMonths,
@@ -34,6 +35,7 @@ import {
MatInputModule,
MatSelectModule,
PatientSearch,
Pager,
RouterLink,
],
templateUrl: './tab-seguimiento-tea.html',
@@ -68,9 +70,7 @@ export class TabSeguimientoTea {
params: () => ({ ...this.request(), _count: this.size() }),
loader: ({ params }) => teaPatientPage(this.fhir, params),
});
private readonly moved = signal<
{ first: Bundle; page: Bundle } | undefined
>(undefined);
private readonly moved = signal<{ first: Bundle; page: Bundle } | undefined>(undefined);
protected readonly page = computed(() => {
const first = this.first.hasValue() ? this.first.value() : undefined;
const moved = this.moved();
+12 -14
View File
@@ -1,7 +1,7 @@
@if (domain() === 'tea') {
<app-tab-seguimiento-tea [patientId]="patientId()" />
} @else {
<form class="filters card" (submit)="$event.preventDefault()">
<form class="filters worklist-filters card" (submit)="$event.preventDefault()">
<app-patient-search [(value)]="search" />
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label>
@@ -106,17 +106,15 @@
</table>
</div>
<div class="pager">
<span class="muted">
@if (page()?.total; as total) {
Página {{ pageNumber() }} de {{ pageCount() }}, {{ total }} registros
}
</span>
<button mat-stroked-button (click)="go('previous')" [disabled]="!has('previous') || loading()">
Anterior
</button>
<button mat-stroked-button (click)="go('next')" [disabled]="!has('next') || loading()">
Siguiente
</button>
</div>
<app-pager
class="print-pagination"
[previousDisabled]="!has('previous') || loading()"
[nextDisabled]="!has('next') || loading()"
(previous)="go('previous')"
(next)="go('next')"
>
@if (page()?.total; as total) {
Página {{ pageNumber() }} de {{ pageCount() }}, {{ total }} registros
}
</app-pager>
}
+2 -3
View File
@@ -8,6 +8,7 @@ import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir';
import { camaRows, windowStart } from './follow-up';
import { Pager } from './pager';
import { PatientSearch, patientSearch } from './patient-search';
import { TabSeguimientoTea } from './tab-seguimiento-tea';
import { Loading } from '../loading';
@@ -15,12 +16,11 @@ import { name, PRIORITY } from './measures';
const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy'];
/** CaMa's follow-up list at a cut-off: patients whose latest mammogram in the window is
* BI-RADS 4 to 6, where their biopsy stands and how soon they should be seen. */
@Component({
selector: 'app-tab-seguimiento',
imports: [
PatientSearch,
Pager,
FormsModule,
Loading,
MatButtonModule,
@@ -42,7 +42,6 @@ export class TabSeguimiento {
protected readonly window = signal(3);
protected readonly status = signal<string>('');
protected readonly size = signal(20);
/** "Buscar paciente": her name, CURP or record number, as applied. */
protected readonly search = signal('');
private readonly moved = signal<Bundle | undefined>(undefined);
+1 -5
View File
@@ -10,18 +10,15 @@ import { HISTORY, HistoryPanel } from './pages';
interface Drawn {
panel: HistoryPanel;
/** the group's heading, on the first panel of its run */
heading?: string;
figure?: Figure;
}
/** Trazabilidad as the old tab: the domain's declared panels (pages.HISTORY), in their order,
* each measure period by period. */
@Component({
selector: 'app-tab-trazabilidad',
imports: [Loading, MatButtonToggleModule, Plot],
template: `
<section class="card filters" aria-labelledby="history-filters">
<section class="card" aria-labelledby="history-filters">
<h2 id="history-filters" class="filters-title">Filtros</h2>
<mat-button-toggle-group
[value]="type()"
@@ -110,7 +107,6 @@ export class TabTrazabilidad {
measure: measure.id!,
'reporting-period': asked.join(','),
});
// One report per period asked, in the order asked.
const found = resources<MeasureReport>(pages, 'MeasureReport');
return { panel, points: asked.map((period, i) => ({ period, r: reading(found[i]) })) };
}),
+30 -18
View File
@@ -1,13 +1,7 @@
import type {
Bundle,
DiagnosticReport,
Measure,
Observation,
Patient,
RiskAssessment,
} from 'fhir/r4';
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { EXT } from '../fhir';
import { donut, type Reading } from './measures';
import { nestedDonut, shareDonut } from './figures';
import type { Catalog } from './pages';
import {
ageMonths,
associationRows,
@@ -17,8 +11,6 @@ import {
teaWorkbook,
} from './tea-rows';
const measure: Measure = { resourceType: 'Measure', status: 'active' };
const r: Reading = { strata: {}, populations: {}, score: 12, low: 7, high: 18 };
const cssPair = 'spindles|central|CSS';
const DAY = new Date('2026-11-30T12:00:00Z');
@@ -110,14 +102,34 @@ function fixture(): Bundle {
}
describe('TEA indicators', () => {
it('builds two concentric rings from the supplied counts', () => {
const inner = { labels: ['Femenino'], values: [3] };
const outer = { labels: ['Femenino · 16-23', 'Femenino · 24-29'], values: [2, 1] };
expect(donut(measure, r, 'category', inner, outer).data).toEqual([
expect.objectContaining(outer),
expect.objectContaining(inner),
it('builds the category and group rings from the supplied counts', () => {
const catalog: Catalog = {
groups: [{ id: 'female', label: 'Femenino', color: '#123456' }],
categories: [
{ code: 'female-16-23', label: 'Femenino · 16-23', group: 'female', color: '#123456' },
{ code: 'female-24-29', label: 'Femenino · 24-29', group: 'female', color: '#123456' },
],
};
const reading = {
populations: {},
strata: {
category: {
'female-16-23': { 'initial-population': 2 },
'female-24-29': { 'initial-population': 1 },
},
},
};
expect(nestedDonut(reading, catalog, 'Pacientes').data).toEqual([
expect.objectContaining({ name: 'centro' }),
expect.objectContaining({ labels: ['Femenino'], values: [3] }),
expect.objectContaining({
labels: ['Femenino · 16-23', 'Femenino · 24-29'],
values: [2, 1],
}),
]);
expect(donut(measure, r).data).toHaveLength(1);
expect(
shareDonut(reading, catalog, 'Pacientes').data.filter((trace) => 'hole' in trace),
).toHaveLength(1);
});
it('maps every search filter and encodes closed ranges as repeated ge/le values', () => {
+3 -4
View File
@@ -1,8 +1,7 @@
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { ados2Component } from '../ados2';
import { safeName } from '../export/safe-name';
import { downloadXlsx, type Sheet } from '../export/xlsx';
import { code, ext, resources, type Fhir, type Params } from '../fhir';
import { downloadXlsx, safeName, type Sheet } from '../export';
import { code, ext, patientName, resources, type Fhir, type Params } from '../fhir';
import { name } from './measures';
import { matchesSearch } from './patient-search';
@@ -97,7 +96,7 @@ export function teaRows(page: Bundle) {
const step = ext(patient, 'tea-step')?.valueCode;
return {
patient,
name: patient.name?.[0]?.text,
name: patientName(patient),
recordNumbers: [
...new Set(
(patient.identifier ?? [])
-5
View File
@@ -1,8 +1,6 @@
import { Component, input } from '@angular/core';
import { MatProgressBarModule } from '@angular/material/progress-bar';
/** What a page or a figure shows while its data comes, as the old app did: a progress bar
* named for what loads, "Cargando …" in words, and for a figure the place it will take. */
@Component({
selector: 'app-loading',
imports: [MatProgressBarModule],
@@ -37,10 +35,7 @@ import { MatProgressBarModule } from '@angular/material/progress-bar';
host: { '[class.figure]': 'figure()' },
})
export class Loading {
/** What is loading, in words: "los indicadores", "la figura". */
readonly what = input.required<string>();
/** The whole line instead ("Calculando los indicadores…"). */
readonly text = input('');
/** A figure's skeleton under the bar. */
readonly figure = input(false);
}
-6
View File
@@ -2,7 +2,6 @@ import { Component, computed, input, signal } from '@angular/core';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
/** One scenario's row of a model's scenario summary (models.factors.scenario_row). */
export interface ScenarioFactors {
escenario: string;
n_escenario: number;
@@ -17,7 +16,6 @@ interface Entry {
robust: boolean;
}
/** A listing cell, `variable=category (robusto|sugerente, share)` separated by `;`. */
export function entries(cell: string | null | undefined): Entry[] {
return (cell ?? '')
.split(';')
@@ -26,9 +24,6 @@ export function entries(cell: string | null | undefined): Entry[] {
.map((text) => ({ text, robust: /\(\s*robusto\b/i.test(text) }));
}
/** "Factores de riesgo de este escenario", as the old record: per scenario of hers, the risk
* factors present in at least 95 % of it and those in 50 to 95 %, a robust one solid and a
* suggestive one outlined; with a horizon to choose when the model has several. */
@Component({
selector: 'app-factores',
imports: [MatFormFieldModule, MatSelectModule],
@@ -102,7 +97,6 @@ export function entries(cell: string | null | undefined): Entry[] {
`,
})
export class Factores {
/** Her scenarios' rows (every horizon when the model has several). */
readonly rows = input.required<ScenarioFactors[]>();
protected readonly chosen = signal<number | undefined>(undefined);
protected readonly horizons = computed(() =>
+3 -5
View File
@@ -11,12 +11,12 @@
} @else if (tea.value(); as t) {
@if (risk()) {
<h1>Análisis de riesgo TEA</h1>
@if (t.patient.name?.[0]?.text; as name) {
@if (patientName(t.patient); as name) {
<p class="subtitle">{{ name }}</p>
}
} @else {
<h1>
{{ t.patient.name?.[0]?.text ?? 'Paciente' }}
{{ patientName(t.patient) ?? 'Paciente' }}
<code class="muted id">{{ t.patient.id!.slice(0, 10) }}</code>
</h1>
<dl class="summary">
@@ -54,9 +54,7 @@
@for (section of teaSections(); track section.title) {
<app-tea-section [section]="section" class="wide">
@if (risk() && section.title === forestTitle) {
<mat-slide-toggle
[checked]="onlyAltered()"
(change)="onlyAltered.set($event.checked)"
<mat-slide-toggle [checked]="onlyAltered()" (change)="onlyAltered.set($event.checked)"
>Solo zonas alteradas</mat-slide-toggle
>
}
+16 -24
View File
@@ -19,9 +19,19 @@ import { Api } from '../api/api';
import { curve } from '../api/fn/models/curve';
import { readReport$Json } from '../api/fn/models/read-report-json';
import type { Domain } from '../api/models/domain';
import { code, EXT, ext, Fhir, label, resources } from '../fhir';
import {
code,
CURP,
ext,
extensions,
Fhir,
label,
patientCurp,
patientName,
resources,
} from '../fhir';
import { scenarioFigure } from '../gobernanza/figures';
import { ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up';
import { ageGroup, CAMA_AGE_GROUPS, camaRows } from '../indicadores/follow-up';
import { LABELS, name, PRIORITY } from '../indicadores/measures';
import { Figure, PALETTE, Plot } from '../plot';
import { Loading } from '../loading';
@@ -38,11 +48,9 @@ import {
Section,
} from './tea-sections';
/** An Observation's value as the screens say it, whatever its type. */
function shown(o: Observation): string {
if (o.valueBoolean !== undefined) return o.valueBoolean ? 'positivo' : 'negativo';
if (o.valueCodeableConcept) {
// The screens' own name for the code (BI-RADS 4C), else the server's display.
const c = code(o.valueCodeableConcept) ?? '';
return (c in LABELS ? name(c) : '') || label(o.valueCodeableConcept);
}
@@ -50,8 +58,6 @@ function shown(o: Observation): string {
return o.valueString ?? o.valueDateTime ?? '';
}
/** One patient: her history (conditions, procedures), her tests and results, and the
* champion models' risks with their curves. Everything read from the FHIR API. */
@Component({
selector: 'app-paciente',
imports: [
@@ -77,7 +83,6 @@ export class Paciente {
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
readonly domain = input.required<string>();
readonly id = input.required<string>();
/** The follow-up list she was opened from: its window (months) and cut-off. */
readonly ventana = input<string>();
readonly corte = input<string>();
readonly risk = input(false);
@@ -117,7 +122,6 @@ export class Paciente {
date: c.recordedDate ?? '',
kind: 'Diagnóstico',
text: label(c.code),
// the ICD-10 code a note diagnosed by (the platform's own codes stay unsaid)
code: c.code?.coding?.find((x) => x.system?.includes('icd-10'))?.code,
})),
...d.procedures.map((p) => ({
@@ -140,7 +144,6 @@ export class Paciente {
reported: ext(r, 'report-date')?.valueDate,
kind: label(r.code),
status: r.status,
// "BI-RADS 4C", not "BI-RADS: BI-RADS 4C"
results: results.map((o) => {
const [name, value] = [label(o.code), shown(o)];
return value.startsWith(name) ? value : `${name}: ${value}`;
@@ -148,7 +151,6 @@ export class Paciente {
};
});
});
/** One model's latest risk assessment per model. */
protected readonly models = computed(() => {
const latest = new Map<string, RiskAssessment>();
for (const r of this.data.value()?.risks ?? []) {
@@ -164,10 +166,7 @@ export class Paciente {
text: r.method?.text ?? '',
version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0),
index: r.occurrenceDateTime ?? '',
// the clinical scenarios of the model's report she falls in
scenarios: (r.extension ?? [])
.filter((e) => e.url === EXT + 'escenario-clinico')
.map((e) => e.valueString ?? ''),
scenarios: extensions(r, 'escenario-clinico').map((e) => e.valueString ?? ''),
predictions: (r.prediction ?? []).map((p) => ({
years: p.whenRange?.high?.value ?? 0,
p: p.probabilityDecimal ?? 0,
@@ -176,8 +175,6 @@ export class Paciente {
})),
}));
});
/** "Análisis de supervivencia" and "Análisis de recurrencia": the curves of her clinical
* scenarios, from the report of the model version that scored her. */
protected readonly survival = this.analysis('survival');
protected readonly recurrence = this.analysis('recurrence');
protected readonly recurrenceModel = computed(() =>
@@ -202,7 +199,6 @@ export class Paciente {
const mine = (all: any[]) => all.filter((e) => m.scenarios.includes(e.escenario));
if (name === 'recurrence') {
const r = (report?.['recurrencia'] ?? {}) as any;
// The risk factors of her scenarios, by horizon (the development tables).
const technical = (await this.api.invoke(readReport$Json, {
domain: domain as Domain,
name,
@@ -274,7 +270,6 @@ export class Paciente {
}),
layout: {
xaxis: { title: { text: 'Años desde la fecha índice' }, dtick: 1 },
// At least 0–5 %: a near-zero risk reads as near zero, not as a full axis.
yaxis: {
title: { text: 'Probabilidad (%)' },
range: [0, Math.max(5, this.top() * 110)],
@@ -287,12 +282,12 @@ export class Paciente {
return Math.max(0, ...this.models().flatMap((m) => m.predictions.map((p) => p.high ?? p.p)));
}
protected readonly name = name;
protected readonly patientName = patientName;
protected readonly identity = computed(() => {
const p = this.patient();
return {
name: p?.name?.[0]?.text,
curp: p?.identifier?.find((i) => i.system === CURP)?.value,
// each record number once (several sources may carry the same one)
name: patientName(p),
curp: patientCurp(p),
numbers: [
...new Set(
(p?.identifier ?? []).filter((i) => i.system !== CURP).map((i) => i.value ?? ''),
@@ -300,8 +295,6 @@ export class Paciente {
].filter(Boolean),
};
});
/** CaMa: her row on the follow-up list (window and cut-off as opened, else the widest
* window up to the last day with data), as the list shows it: the old record's card. */
private readonly listed = resource({
params: () =>
this.domain() === 'cama'
@@ -329,7 +322,6 @@ export class Paciente {
const found = this.listed.value();
const d = this.data.value();
if (!found || !d) return undefined;
// Her own latest mammogram and biopsy, on the list or not.
const latest = (study: string) =>
d.reports
.filter((r) => code(r.code) === study)
+3 -16
View File
@@ -7,8 +7,8 @@ import type {
RiskAssessment,
} from 'fhir/r4';
import { ados2Component, ados2Groups } from '../ados2';
import { code, ext, Fhir, label, resources } from '../fhir';
import { CURP } from '../indicadores/follow-up';
import { ZONE_NAMES } from '../eeg-labels';
import { code, CURP, ext, Fhir, label, resources } from '../fhir';
const NSS = 'https://isssteleon.org/fhir/sid/nss';
@@ -27,19 +27,6 @@ const metrics: Record<string, string> = {
anteroposterior_gradient: 'Gradiente anteroposterior',
};
const regions: Record<string, string> = {
frontal_left: 'Frontal izquierda',
frontal_right: 'Frontal derecha',
frontal_midline: 'Frontal medial',
central: 'Central',
parietal: 'Parietal',
temporal_left: 'Temporal izquierda',
temporal_right: 'Temporal derecha',
occipital: 'Occipital',
posterior: 'Posterior',
global: 'Global',
};
const biomarkers: Record<string, string> = {
spikes: 'paroxysmal_spikes',
spindles: 'spindles_n2',
@@ -262,7 +249,7 @@ export type Pair = {
export type Study = ReturnType<typeof study>;
export function zoneLabel(zone: string): string {
return regions[zone] ?? zone;
return zone === 'frontal_midline' ? 'Frontal medial' : (ZONE_NAMES[zone] ?? zone);
}
export function alteration(outside: number | undefined): string {
+10 -8
View File
@@ -1,6 +1,4 @@
import type { PdfContent } from '../export/pdf';
import { downloadPdf } from '../export/pdf';
import { safeName } from '../export/safe-name';
import { downloadPdf, safeName, type PdfContent } from '../export';
import type { Figure } from '../plot';
import plotly from '../plotly-bundle';
import { adosItems, adosSummary, alteration, Pair, percent, shown, TeaPatient } from './tea-data';
@@ -8,7 +6,7 @@ import { forest, headMap, probabilityCurve, zBars } from './tea-figures';
type Table = { headers: string[]; rows: string[][] };
type Chart = { title: string; figure: Figure; height?: number };
export type Block = {
type Block = {
title?: string;
fields?: string[][];
table?: Table;
@@ -20,9 +18,9 @@ export type Section = { title: string; blocks: Block[] };
export const forestTitle = 'Razones de momios por par';
export const probabilityTitle = 'Probabilidad según z';
export const calculation =
const calculation =
'El modelo estima, para cada par de métrica o zona del EEG y resultado del ADOS-2, la probabilidad de un puntaje elevado de severidad calibrada (CSS) o de un ítem alterado. La razón de momios corresponde al cambio asociado con una unidad de z. La probabilidad de referencia corresponde a z = 0, la edad media y el módulo más frecuente de la cohorte.';
export const limitations =
const limitations =
'Las estimaciones dependen de la cohorte de referencia, de la calidad del EEG y de la disponibilidad de mediciones y pares. Las asociaciones no establecen causalidad. Las probabilidades no sustituyen la evaluación clínica ni establecen un diagnóstico.';
function associationRows(pairs: Pair[]): string[][] {
@@ -150,7 +148,7 @@ export function riskSections(patient: TeaPatient, alteredOnly: boolean, pair?: P
];
}
export function probabilityRows(pairs: Pair[]): Table {
function probabilityRows(pairs: Pair[]): Table {
return {
headers: ['Par', 'Probabilidad', 'Referencia'],
rows: pairs.map((p) => [
@@ -165,7 +163,11 @@ export function teaPdfName(page: 'seguimiento' | 'riesgos', day = new Date()): s
return safeName(['tea', page, day.toISOString().slice(0, 10)]);
}
export function teaPdfContent(title: string, sections: Section[], images: (string | undefined)[]): PdfContent[] {
export function teaPdfContent(
title: string,
sections: Section[],
images: (string | undefined)[],
): PdfContent[] {
const charts = images[Symbol.iterator]();
const content: PdfContent[] = [{ text: title, fontSize: 18, bold: true }];
for (const section of sections) {
+2 -10
View File
@@ -4,7 +4,6 @@ import plotly from './plotly-bundle';
export type Figure = { data: Partial<Plotly.Data>[]; layout?: Partial<Plotly.Layout> };
/** The series colours today's charts use, in order. */
export const PALETTE = [
'#A8C243',
'#42C29C',
@@ -21,21 +20,16 @@ const LAYOUT: Partial<Plotly.Layout> = {
margin: { t: 24, r: 16, b: 48, l: 56 },
paper_bgcolor: 'rgba(0,0,0,0)',
plot_bgcolor: 'rgba(0,0,0,0)',
// Above the plot, left-aligned: Plotly reserves its room, so it never meets an axis title.
legend: { orientation: 'h', x: 0, xanchor: 'left', y: 1.02, yanchor: 'bottom' },
hoverlabel: { font: { family: 'Roboto, Arial, sans-serif', size: 13 } },
};
// Axes make room for their labels and titles; a title keeps clear of the tick labels.
// (`ticklabelstandoff` is Plotly's, newer than its published types.)
const AXIS = {
automargin: true,
title: { standoff: 12 },
ticklabelstandoff: 4, // the lowest y label and the first x label never touch
ticklabelstandoff: 4,
} as Partial<Plotly.LayoutAxis>;
/** The platform's layout under a figure's own: legend, margins and axes merged key by key,
* so a figure that sets one of their keys keeps the others. */
export function layoutOf(layout: Partial<Plotly.Layout> = {}): Partial<Plotly.Layout> {
function layoutOf(layout: Partial<Plotly.Layout> = {}): Partial<Plotly.Layout> {
const axes = Object.fromEntries(
Object.entries(layout)
.filter(([k]) => /^[xy]axis\d*$/.test(k))
@@ -56,7 +50,6 @@ export function layoutOf(layout: Partial<Plotly.Layout> = {}): Partial<Plotly.La
};
}
/** Pie labels that sit outside take the room they need instead of being clipped. */
function withRoom(data: Partial<Plotly.Data>[]): Plotly.Data[] {
return data.map((d) => (d.type === 'pie' ? { automargin: true, ...d } : d)) as Plotly.Data[];
}
@@ -66,7 +59,6 @@ const CONFIG: Partial<Plotly.Config> = {
modeBarButtonsToRemove: ['lasso2d', 'select2d'],
};
/** One Plotly chart: the figure, drawn with the platform's layout and config. */
@Component({
selector: 'app-plot',
template: '<div #host class="plot" [style.height.px]="height()"></div>',
-13
View File
@@ -49,7 +49,6 @@ const IDENTITY_FIELDS: Correction['field'][] = [
'birth_date',
'sex',
];
/** Identity fields as linkage names them (core.schema.Identity). */
const IDENTITY_TITLES: Record<string, string> = {
record_number: 'Expediente',
curp: 'CURP',
@@ -57,7 +56,6 @@ const IDENTITY_TITLES: Record<string, string> = {
full_name: 'Nombre',
};
/** The platform's hold reasons (English in its logs) as the reviewer reads them. */
const REASONS: [RegExp, (m: RegExpExecArray) => string][] = [
[/^Field required$/, () => 'falta el dato'],
[
@@ -82,7 +80,6 @@ const REASONS: [RegExp, (m: RegExpExecArray) => string][] = [
],
];
/** Bookkeeping columns, not values a reviewer judges. */
const HIDDEN = [
'_pipeline',
'_target',
@@ -95,8 +92,6 @@ const HIDDEN = [
'known_at',
];
/** /revision: what ingestion held for a person to decide. Every decision is logged and
* applied on the pipeline's next run. */
@Component({
selector: 'app-revision',
imports: [
@@ -128,9 +123,7 @@ export class Revision {
loader: ({ params }) => this.api.invoke(conflicts, { entity: params }),
});
/** The pipeline and link node whose persons are reviewed. */
protected readonly pipelines = resource({ loader: () => this.api.invoke(pipelines) });
/** The chosen pipeline; the first one until the reviewer picks another. */
protected readonly pipeline = linkedSignal<string | undefined>(
() => this.pipelines.value()?.[0]?.['pipeline_id'],
);
@@ -152,13 +145,11 @@ export class Revision {
: Promise.resolve({ to_settle: [], torn: [] } as Record<string, Row[]>),
});
/** Documents the chosen pipeline's routes don't recognise (its `otherwise` routes). */
protected readonly unrecognised = resource({
params: () => this.pipeline(),
loader: ({ params }) =>
params ? this.api.invoke(unrecognised, { pipeline: params }) : Promise.resolve([] as Row[]),
});
/** A row's fields but its route and preview, as `name: value`. */
protected details(row: Row): string {
return Object.entries(row)
.filter(([k, v]) => !['route', 'preview'].includes(k) && v !== null && v !== '')
@@ -181,7 +172,6 @@ export class Revision {
const found = row['_held'];
return Array.isArray(found) ? found.join('; ') : String(found ?? '');
}
/** The platform's field titles (the catalog's), by entity: what the page calls a field. */
protected readonly titles = resource({
loader: async () => {
const found = (await this.api.invoke(schema)) as Record<string, any>;
@@ -201,13 +191,11 @@ export class Revision {
protected title(field: string): string {
return this.titles.value()?.[this.entity()]?.[field] ?? field;
}
/** A hold's reasons as the reviewer reads them (the platform logs them in English). */
protected said(row: Row): string {
const found = row['_held'];
const all = Array.isArray(found) ? (found as string[]) : [String(found ?? '')];
return all.map((r) => this.spanish(r)).join('; ');
}
/** Why linkage proposes two records as one person, in the reviewer's words. */
protected candidateReason(reason: unknown): string {
const text = String(reason ?? '');
const typo = /^(\w+) one typo apart$/.exec(text);
@@ -272,7 +260,6 @@ export class Revision {
);
}
/** Runs the pipeline so the decisions apply, then reloads what is left. */
protected async apply(): Promise<void> {
const id = this.pipeline();
if (!id) return;