Compare commits

..

4 Commits

50 changed files with 1758 additions and 842 deletions
+3 -5
View File
@@ -19,21 +19,19 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
r.url().includes('measure=cacu-eu7') &&
!r.url().includes('%2C'),
);
const catalog = page.waitForResponse((r) => r.url().endsWith('/cacu/fhir/Measure'));
await page.goto('/indicadores/cacu');
const measures = await (await catalog).json();
const eu7 = await (await report).json();
const count = eu7.entry[0].resource.group[0].population.find(
(p: any) => p.code.coding[0].code === 'initial-population',
).count;
await expect(page.locator('[data-measure="CACU_EU7"] mat-card-subtitle')).toContainText(String(count));
await expect(page.locator('[data-measure="CACU_EU7"] .kpi-value')).toHaveText(String(count));
await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
await expect(page.locator('app-tab-trazabilidad mat-card')).toHaveCount(measures.total);
await expect(page.locator('app-tab-trazabilidad mat-card')).toHaveCount(14);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
await expect(page.locator('app-tab-definiciones tbody tr')).toHaveCount(measures.total);
await expect(page.locator('app-tab-definiciones tbody tr')).toHaveCount(14);
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
+1230 -5
View File
File diff suppressed because it is too large Load Diff
+36
View File
@@ -0,0 +1,36 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { AnalyzeRequest } from '../../models/analyze-request';
export interface AnalyzeEegs$Params {
body: AnalyzeRequest
}
export function analyzeEegs(http: HttpClient, rootUrl: string, params: AnalyzeEegs$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, analyzeEegs.PATH, 'post');
if (params) {
rb.body(params.body, 'application/json');
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: string;
}>;
})
);
}
analyzeEegs.PATH = '/tea/eegs/analyze';
@@ -0,0 +1,36 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Health } from '../../models/health';
export interface ExecutionHealth$Params {
mode?: ('sync' | 'local' | 'remote' | null);
scheduler?: (string | null);
reference?: (string | null);
}
export function executionHealth(http: HttpClient, rootUrl: string, params?: ExecutionHealth$Params, context?: HttpContext): Observable<StrictHttpResponse<Health>> {
const rb = new RequestBuilder(rootUrl, executionHealth.PATH, 'get');
if (params) {
rb.query('mode', params.mode, {});
rb.query('scheduler', params.scheduler, {});
rb.query('reference', params.reference, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<Health>;
})
);
}
executionHealth.PATH = '/execution/health';
@@ -0,0 +1,30 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Options } from '../../models/options';
export interface ExecutionOptions$Params {
}
export function executionOptions(http: HttpClient, rootUrl: string, params?: ExecutionOptions$Params, context?: HttpContext): Observable<StrictHttpResponse<Options>> {
const rb = new RequestBuilder(rootUrl, executionOptions.PATH, 'get');
if (params) {
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<Options>;
})
);
}
executionOptions.PATH = '/execution/options';
+3
View File
@@ -7,10 +7,12 @@ import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Analyze } from '../../models/analyze';
import { Domain } from '../../models/domain';
export interface Analyze$Params {
domain: Domain;
body?: Analyze
}
export function analyze(http: HttpClient, rootUrl: string, params: Analyze$Params, context?: HttpContext): Observable<StrictHttpResponse<{
@@ -19,6 +21,7 @@ export function analyze(http: HttpClient, rootUrl: string, params: Analyze$Param
const rb = new RequestBuilder(rootUrl, analyze.PATH, 'post');
if (params) {
rb.path('domain', params.domain, {});
rb.body(params.body, 'application/json');
}
return http.request(
+36
View File
@@ -0,0 +1,36 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface ExportModels$Params {
domain: Domain;
names?: (Array<string> | null);
versions?: 'champion' | 'latest' | 'all';
}
export function exportModels(http: HttpClient, rootUrl: string, params: ExportModels$Params, context?: HttpContext): Observable<StrictHttpResponse<any>> {
const rb = new RequestBuilder(rootUrl, exportModels.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.query('names', params.names, {});
rb.query('versions', params.versions, {});
}
return http.request(
rb.build({ responseType: 'blob', accept: 'application/zip', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<any>;
})
);
}
exportModels.PATH = '/models/{domain}/export';
+41
View File
@@ -0,0 +1,41 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { BodyImportModels } from '../../models/body-import-models';
import { Domain } from '../../models/domain';
export interface ImportModels$Params {
domain: Domain;
sha256: string;
body: BodyImportModels
}
export function importModels(http: HttpClient, rootUrl: string, params: ImportModels$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, importModels.PATH, 'post');
if (params) {
rb.path('domain', params.domain, {});
rb.query('sha256', params.sha256, {});
rb.body(params.body, 'multipart/form-data');
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: string;
}>;
})
);
}
importModels.PATH = '/models/{domain}/import';
+32
View File
@@ -0,0 +1,32 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Cancel } from '../../models/cancel';
export interface CancelRun$Params {
run_id: string;
}
export function cancelRun(http: HttpClient, rootUrl: string, params: CancelRun$Params, context?: HttpContext): Observable<StrictHttpResponse<Cancel>> {
const rb = new RequestBuilder(rootUrl, cancelRun.PATH, 'post');
if (params) {
rb.path('run_id', params.run_id, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<Cancel>;
})
);
}
cancelRun.PATH = '/runs/{run_id}/cancel';
+39
View File
@@ -0,0 +1,39 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
import { RunSummary } from '../../models/run-summary';
export interface RunHistory$Params {
job?: (string | null);
domain?: (Domain | null);
limit?: number;
before?: (string | null);
}
export function runHistory(http: HttpClient, rootUrl: string, params?: RunHistory$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<RunSummary>>> {
const rb = new RequestBuilder(rootUrl, runHistory.PATH, 'get');
if (params) {
rb.query('job', params.job, {});
rb.query('domain', params.domain, {});
rb.query('limit', params.limit, {});
rb.query('before', params.before, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<Array<RunSummary>>;
})
);
}
runHistory.PATH = '/runs';
+3 -6
View File
@@ -7,14 +7,13 @@ import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Run } from '../../models/run';
export interface RunStatus$Params {
run_id: string;
}
export function runStatus(http: HttpClient, rootUrl: string, params: RunStatus$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
export function runStatus(http: HttpClient, rootUrl: string, params: RunStatus$Params, context?: HttpContext): Observable<StrictHttpResponse<Run>> {
const rb = new RequestBuilder(rootUrl, runStatus.PATH, 'get');
if (params) {
rb.path('run_id', params.run_id, {});
@@ -25,9 +24,7 @@ export function runStatus(http: HttpClient, rootUrl: string, params: RunStatus$P
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: string;
}>;
return r as StrictHttpResponse<Run>;
})
);
}
+14
View File
@@ -5,6 +5,10 @@ export type { Domains$Params as Domains$Params } from './fn/operations/domains';
export { domains as domains } from './fn/operations/domains';
export type { Health$Params as Health$Params } from './fn/operations/health';
export { health as health } from './fn/operations/health';
export type { ExecutionHealth$Params as ExecutionHealth$Params } from './fn/execution/execution-health';
export { executionHealth as executionHealth } from './fn/execution/execution-health';
export type { ExecutionOptions$Params as ExecutionOptions$Params } from './fn/execution/execution-options';
export { executionOptions as executionOptions } from './fn/execution/execution-options';
export type { ConceptMaps$Params as ConceptMaps$Params } from './fn/ingest/concept-maps';
export { conceptMaps as conceptMaps } from './fn/ingest/concept-maps';
export type { GetConceptMap$Params as GetConceptMap$Params } from './fn/ingest/get-concept-map';
@@ -33,6 +37,10 @@ export type { Models$Params as Models$Params } from './fn/models/models';
export { models as models } from './fn/models/models';
export type { Analyze$Params as Analyze$Params } from './fn/models/analyze';
export { analyze as analyze } from './fn/models/analyze';
export type { ExportModels$Params as ExportModels$Params } from './fn/models/export-models';
export { exportModels as exportModels } from './fn/models/export-models';
export type { ImportModels$Params as ImportModels$Params } from './fn/models/import-models';
export { importModels as importModels } from './fn/models/import-models';
export type { Score$Params as Score$Params } from './fn/models/score';
export { score as score } from './fn/models/score';
export type { Train$Params as Train$Params } from './fn/models/train';
@@ -59,10 +67,16 @@ export type { DecidePersons$Params as DecidePersons$Params } from './fn/review/d
export { decidePersons as decidePersons } from './fn/review/decide-persons';
export type { Reject$Params as Reject$Params } from './fn/review/reject';
export { reject as reject } from './fn/review/reject';
export type { RunHistory$Params as RunHistory$Params } from './fn/runs/run-history';
export { runHistory as runHistory } from './fn/runs/run-history';
export type { RunStatus$Params as RunStatus$Params } from './fn/runs/run-status';
export { runStatus as runStatus } from './fn/runs/run-status';
export type { CancelRun$Params as CancelRun$Params } from './fn/runs/cancel-run';
export { cancelRun as cancelRun } from './fn/runs/cancel-run';
export type { Studies$Params as Studies$Params } from './fn/eeg/studies';
export { studies as studies } from './fn/eeg/studies';
export type { AnalyzeEegs$Params as AnalyzeEegs$Params } from './fn/eeg/analyze-eegs';
export { analyzeEegs as analyzeEegs } from './fn/eeg/analyze-eegs';
export type { Study$Params as Study$Params } from './fn/eeg/study';
export { study as study } from './fn/eeg/study';
export type { PostBundle$Params as PostBundle$Params } from './fn/fhir/post-bundle';
+15
View File
@@ -2,30 +2,45 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export type { Analysis } from './models/analysis';
export type { Analyze } from './models/analyze';
export type { AnalyzeRequest } from './models/analyze-request';
export type { BodyAddClinicalValidation } from './models/body-add-clinical-validation';
export type { BodyImportModels } from './models/body-import-models';
export type { BodyUpload } from './models/body-upload';
export type { Cancel } from './models/cancel';
export type { Condition } from './models/condition';
export type { Correction } from './models/correction';
export type { Domain } from './models/domain';
export type { Edf } from './models/edf';
export type { Execution } from './models/execution';
export type { Extract } from './models/extract';
export type { Fhir } from './models/fhir';
export type { Health } from './models/health';
export type { HttpValidationError } from './models/http-validation-error';
export type { Join } from './models/join';
export type { Link } from './models/link';
export type { Map } from './models/map';
export type { Metric } from './models/metric';
export type { Options } from './models/options';
export type { PersonDecision } from './models/person-decision';
export type { Pipeline } from './models/pipeline';
export type { Position } from './models/position';
export type { Progress } from './models/progress';
export type { Read } from './models/read';
export type { Rejection } from './models/rejection';
export type { Route } from './models/route';
export type { Run } from './models/run';
export type { RunRequest } from './models/run-request';
export type { RunSummary } from './models/run-summary';
export type { SavedPipeline } from './models/saved-pipeline';
export type { Scope } from './models/scope';
export type { Source } from './models/source';
export type { SourceRef } from './models/source-ref';
export type { Step } from './models/step';
export type { Study } from './models/study';
export type { Target } from './models/target';
export type { Tasks } from './models/tasks';
export type { Training } from './models/training';
export type { ValidationError } from './models/validation-error';
export type { Version } from './models/version';
export type { Worker } from './models/worker';
+9
View File
@@ -0,0 +1,9 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Execution } from '../models/execution';
import { Scope } from '../models/scope';
export interface AnalyzeRequest {
execution?: (Execution | null);
scope?: Scope;
}
+7
View File
@@ -0,0 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Execution } from '../models/execution';
export interface Analyze {
execution?: (Execution | null);
}
+6
View File
@@ -0,0 +1,6 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface BodyImportModels {
file: string;
}
+8
View File
@@ -0,0 +1,8 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Cancel {
id: string;
state: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelling' | 'cancelled';
status: string;
}
+28
View File
@@ -0,0 +1,28 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Position } from '../models/position';
/**
* EDF files (a column of file hashes) to the facts their header holds: patient code, sex,
* birth date, recording date, record code, duration and channel count, as `edf_*` columns.
* An unreadable file keeps its row with `edf_error` set.
*
* Use a filesystem source (`dlt.sources.filesystem:filesystem`) with the uploads folder as
* `bucket_url`, `file_glob: "*.edf"`, and `then: "persistance.readers:read_bytes"`. Read its
* `content` column with this node. Map `edf_patient_code`, `edf_birth_date`, and `edf_sex` to
* identity's `record_number`, `birth_date`, and `sex`, using the site's formats and ConceptMap.
*
* The patient code must match the hospital's record number including its prefix. Feed the
* identity map into the pipeline's link node alongside the hospital identity source. Map
* `edf_study_date` to `study_date` (format `%Y-%m-%d`), `edf_record_code` to `lab_record_id`,
* and `content` to `edf`, then feed that map and the link into a target with entity `eeg`.
*/
export interface Edf {
column: string;
id: string;
inputs?: Array<string>;
kind?: 'edf';
label?: string;
position?: (Position | null);
}
+11
View File
@@ -0,0 +1,11 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* What a request or a job config carries: None means the deployment's default.
*/
export interface Execution {
mode?: ('sync' | 'local' | 'remote' | null);
scheduler?: (string | null);
}
+20
View File
@@ -0,0 +1,20 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Health {
dashboard_ok?: (boolean | null);
dashboard_url?: (string | null);
error?: (string | null);
expected_workers?: (number | null);
latency_ms?: (number | null);
mode: 'sync' | 'local' | 'remote';
reachable: boolean;
reference?: ({
[key: string]: any;
} | null);
scheduler: (string | null);
threads?: (number | null);
version_error?: (string | null);
versions_ok?: (boolean | null);
workers?: (number | null);
}
+7
View File
@@ -0,0 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Options {
default_mode: 'sync' | 'local' | 'remote';
schedulers: Array<string>;
}
+2 -1
View File
@@ -1,6 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Edf } from '../models/edf';
import { Extract } from '../models/extract';
import { Fhir } from '../models/fhir';
import { Join } from '../models/join';
@@ -11,5 +12,5 @@ import { Route } from '../models/route';
import { Source } from '../models/source';
import { Target } from '../models/target';
export interface Pipeline {
nodes: Array<(Source | Read | Route | Map | Extract | Fhir | Join | Link | Target)>;
nodes: Array<(Source | Read | Route | Map | Extract | Edf | Fhir | Join | Link | Target)>;
}
+21
View File
@@ -0,0 +1,21 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Tasks } from '../models/tasks';
import { Worker } from '../models/worker';
/**
* The run tag's JSON; the API returns it as it is.
*/
export interface Progress {
done: number;
elapsed_s: number;
eta_s: (number | null);
mode: 'sync' | 'local' | 'remote';
phase: string;
scheduler: (string | null);
tasks?: (Tasks | null);
total: number;
updated_at: string;
workers?: Array<Worker>;
}
+12
View File
@@ -0,0 +1,12 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface RunSummary {
domain: (string | null);
ended: (number | null);
id: string;
job: string;
started: (number | null);
state: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelling' | 'cancelled';
status: string;
}
+19
View File
@@ -0,0 +1,19 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Progress } from '../models/progress';
import { Step } from '../models/step';
export interface Run {
domain: (string | null);
ended: (number | null);
error: (string | null);
id: string;
info: Array<string>;
job: string;
progress: (Progress | null);
started: (number | null);
state: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelling' | 'cancelled';
status: string;
steps: Array<Step>;
warnings: Array<string>;
}
+13
View File
@@ -0,0 +1,13 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* Which EEGs an analysis takes: the pending ones, the first `n` of them, or the named
* ones (re-analysis), each named by the `id` that `/tea/eegs` shows.
*/
export interface Scope {
ids?: Array<string>;
mode?: 'pending' | 'first_n' | 'ids';
n?: (number | null);
}
+9
View File
@@ -0,0 +1,9 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Step {
ended: (number | null);
key: string;
started: (number | null);
status: string;
}
+10
View File
@@ -0,0 +1,10 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Tasks {
erred?: number;
memory?: number;
processing?: number;
queued?: number;
waiting?: number;
}
+2
View File
@@ -1,7 +1,9 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Execution } from '../models/execution';
export interface Training {
as_of?: (string | null);
execution?: (Execution | null);
models?: Array<string>;
}
+11
View File
@@ -0,0 +1,11 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Worker {
cpu_pct: number;
executing: number;
memory_bytes: number;
memory_limit: (number | null);
name: string;
threads: number;
}
+10 -3
View File
@@ -47,7 +47,9 @@ function canvasNode(id: string, point: { x: number; y: number }, label: string):
};
}
export const KINDS: Record<Kind, string> = {
/** The kinds the palette offers. A kind the canvas has no form for yet (`edf`, Phase 5) is left
* out of the palette and shown by its raw name when a saved pipeline has one. */
export const KINDS: Partial<Record<Kind, string>> = {
source: 'Fuente',
read: 'Leer',
route: 'Filtrar',
@@ -312,7 +314,7 @@ export class Conectar {
return 'concept_map' in d ? (d.concept_map ?? undefined) : undefined;
}
protected kindLabel(kind: Doc['kind']): string {
return KINDS[kind ?? 'source'];
return kindName(kind);
}
protected cell(value: unknown): string {
return typeof value === 'object' && value !== null
@@ -322,7 +324,12 @@ export class Conectar {
}
function text(d: Doc): string {
return `${KINDS[d.kind ?? 'source']} · ${d.label || d.id}`;
return `${kindName(d.kind)} · ${d.label || d.id}`;
}
function kindName(kind: Doc['kind']): string {
const k = kind ?? 'source';
return KINDS[k] ?? k;
}
/** Each node's distance from the sources: its column when it has no saved position. */
-20
View File
@@ -1,20 +0,0 @@
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
export interface ExportStage { state: string; provenance?: string; label?: string; date?: string; prev?: string; start?: string }
export interface ExportRiskScale { label: string; value?: number; low?: number; high?: number; outcome?: string; model?: string; horizon?: string }
export interface ExportDocument { title: string; parameters: string[][]; columns: string[]; rows: string[][]; timeline?: ExportStage[]; row_stages?: ExportStage[][]; risk_scales?: ExportRiskScale[]; }
export async function downloadDocument(http: HttpClient, format: 'pdf' | 'xlsx', doc: ExportDocument) {
let blob: Blob;
try { blob = await firstValueFrom(http.post(`/api/cacu/exports/${format}`, doc, {responseType:'blob'})); }
catch (error) {
if (error instanceof HttpErrorResponse && error.error instanceof Blob) {
try { const body = JSON.parse(await error.error.text()); if (typeof body.detail === 'string') throw new Error(body.detail); }
catch (parsed) { if (parsed instanceof Error && !(parsed instanceof SyntaxError)) throw parsed; }
}
throw error;
}
const url = URL.createObjectURL(blob);
const a = document.createElement('a'); a.href = url; a.download = `cacu-${format === 'pdf' ? 'reporte.pdf' : 'seguimiento.xlsx'}`; a.click();
setTimeout(() => URL.revokeObjectURL(url), 60000);
}
-44
View File
@@ -1,44 +0,0 @@
import { describe, expect, it } from 'vitest';
import { biopsyDistribution, cytologyDistribution, hpvDistribution } from './cacu-results';
import { Reading } from './measures';
const report = (population: number, counts: Record<string, number>): Reading => ({
populations: { 'initial-population': population },
strata: { category: Object.fromEntries(Object.entries(counts).map(([k, n]) => [k, { 'initial-population': n }])) },
});
describe('reportes clínicos', () => {
it('counts HPV reports and retains inconsistent and zero categories', () => {
const d = hpvDistribution(report(4, { negative: 2, positive_16: 1, inconsistent: 1 }))!;
expect(d.total).toBe(4);
expect(d.rows.map((r) => r.count)).toEqual([2, 1, 0, 0, 0, 0, 1]);
expect(d.outside).toBe(0);
});
it('excludes missing or unclassifiable histology from the denominator', () => {
const d = biopsyDistribution(report(5, { normal: 1, HSIL: 2, no_data: 1, unclassified: 1 }))!;
expect(d.total).toBe(3);
expect(d.noData).toBe(1);
expect(d.outside).toBe(2);
});
it('does not fabricate a report or accept mismatched counts', () => {
expect(hpvDistribution(undefined)).toBeUndefined();
expect(biopsyDistribution(report(2, { normal: 1 }))).toBeUndefined();
expect(hpvDistribution(report(0, {}))?.total).toBe(0);
});
});
describe('citología EU7', () => {
it('uses eligible results as denominator and preserves outside counts and zero categories', () => {
const result = cytologyDistribution(report(10, { NILM: 6, HSIL: 2, no_data: 2 }))!;
expect(result.total).toBe(8);
expect(result.outside).toBe(2);
expect(result.rows.map((r) => r.count)).toEqual([6, 0, 0, 0, 2, 0]);
});
it('supports an empty population without inventing percentages', () => {
expect(cytologyDistribution(report(0, {}))).toMatchObject({ total: 0, max: 0, outside: 0 });
});
it('rejects absent or inconsistent distributions', () => {
expect(cytologyDistribution(undefined)).toBeUndefined();
expect(cytologyDistribution(report(3, { NILM: 2 }))).toBeUndefined();
});
});
-55
View File
@@ -1,55 +0,0 @@
import { Reading } from './measures';
const CATEGORIES = [
['NILM', 'Normal', '#408651'],
['ASC-US', 'ASC-US', '#2778B8'],
['LSIL', 'LIEBG', '#B19525'],
['ASC-H', 'ASC-H', '#7955B1'],
['HSIL', 'LIEAG', '#CE4778'],
['CIS', 'Carcinoma in situ', '#AA394D'],
] as const;
/** EU7 selects one sample per patient. Unknown categories stay outside the denominator. */
export function cytologyDistribution(reading: Reading | undefined) {
return distribution(reading, CATEGORIES);
}
const HPV = [
['negative', 'Negativo', '#42a77e'],
['positive_16', 'Positivo 16 exclusivamente', '#df8640'],
['positive_18', 'Positivo 18 exclusivamente', '#c29c42'],
['positive_16_18', 'Positivo 16 y 18', '#c24269'],
['positive_other', 'Positivo sin detección de 16/18', '#a8c243'],
['positive_incomplete', 'Positivo con genotipificación incompleta', '#9c42c2'],
['inconsistent', 'No clasificable o inconsistente', '#687786'],
] as const;
const BIOPSY = [
['normal', 'Normal', '#408651'],
['LSIL', 'LIEBG (CIN 1)', '#B19525'],
['HSIL', 'LIEAG (CIN 2 y 3)', '#CE4778'],
['CIS', 'Carcinoma in situ', '#AA394D'],
['carcinoma', 'Carcinoma invasor', '#8D4C79'],
] as const;
export function hpvDistribution(reading: Reading | undefined) {
const result = distribution(reading, HPV);
return result && { ...result, total: result.total + result.outside };
}
export const biopsyDistribution = (reading: Reading | undefined) => distribution(reading, BIOPSY);
function distribution(reading: Reading | undefined, categories: readonly (readonly [string, string, string])[]) {
const cells = reading?.strata['category'];
const population = reading?.populations['initial-population'];
if (!cells || population === undefined) return undefined;
const counts = Object.values(cells).map((cell) => cell['initial-population']);
if (counts.some((n) => n === undefined || !Number.isInteger(n) || n < 0) ||
counts.reduce((a, b) => a + b, 0) !== population) return undefined;
const rows = categories.map(([code, label, color]) => ({
label, color, count: cells[code]?.['initial-population'] ?? 0,
}));
const total = rows.reduce((sum, row) => sum + row.count, 0);
const max = Math.max(0, ...rows.map((row) => row.count));
return { rows, total, outside: population - total, max,
noData: cells['no_data']?.['initial-population'] ?? 0 };
}
+2 -26
View File
@@ -1,32 +1,8 @@
import '@angular/compiler';
import { describe, expect, it, vi } from 'vitest';
vi.mock('../plot', () => ({ PALETTE: [] }));
import type { Patient, RiskAssessment } from 'fhir/r4';
import { ageGroup, currentRisk, exactAge, patientLabel, patientName, rows, windowStart } from './follow-up';
import type { RiskAssessment } from 'fhir/r4';
import { ageGroup, currentRisk, windowStart } from './follow-up';
import { periods } from './measures';
describe('follow-up list', () => {
it('uses synthetic FHIR names consistently and keeps the patient id as fallback', () => {
const patient: Patient = { resourceType: 'Patient', id: 'abcdef123456', name: [{ text: ' Ana Ejemplo ' }] };
const page = { resourceType: 'Bundle' as const, type: 'searchset' as const, entry: [{ resource: patient, search: { mode: 'match' as const } }] };
expect(rows(page, '2026-01-01', '2026-11-27', 5)[0].name).toBe('Ana Ejemplo');
expect(patientLabel(patient)).toBe('Ana Ejemplo');
expect(patientName({ ...patient, name: [{ given: ['Ana', 'María'], family: 'Ejemplo' }] })).toBe('Ana María Ejemplo');
expect(patientLabel({ ...patient, name: [{ text: ' ' }] })).toBe('abcdef1234');
});
it('calculates completed years only from valid full dates', () => {
expect(exactAge('1980-11-23', '2026-11-22')).toBe(45);
expect(exactAge('1980-11-23', '2026-11-23')).toBe(46);
expect(exactAge('2000-02-29', '2025-02-28')).toBe(24);
expect(exactAge('2000-02', '2026-01-01')).toBeUndefined();
expect(exactAge('2001-02-29', '2026-01-01')).toBeUndefined();
expect(exactAge('2027-01-01', '2026-01-01')).toBeUndefined();
});
it('keeps a missing prediction separate from zero', () => {
const risk = (p?: number): RiskAssessment => ({resourceType:'RiskAssessment', status:'final', subject:{}, occurrenceDateTime:'2026-01-01', method:{coding:[{code:'cacu.cin2_pim'}]}, prediction:[{probabilityDecimal:p,whenRange:{high:{value:5}}}]});
expect(currentRisk([risk()], 'cin2', 5)).toBeUndefined();
expect(currentRisk([risk(0)], 'cin2', 5)).toBe(0);
});
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
+5 -41
View File
@@ -1,6 +1,5 @@
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { code, ext, resources } from '../fhir';
import { routeFacts, StageFacts } from '../paciente/stages';
/** One row of the follow-up list: what the list shows of a patient at the cut-off. */
export interface Row {
@@ -9,9 +8,7 @@ export interface Row {
curp?: string;
status: string;
ageGroup: string;
age?: number;
stageFacts: StageFacts;
cytology?: { date: string; reportDate?: string; result?: string; adequacy?: string };
cytology?: { date: string; result?: string; adequacy?: string };
hpv?: { date: string; positive: boolean; types1618?: boolean };
daysToDiagnosis?: number;
biopsy?: { date: string; histology?: string };
@@ -20,36 +17,6 @@ export interface Row {
export const CURP = 'https://isssteleon.org/fhir/sid/curp';
/** Prefer the supplied FHIR display text, then a structured name, then the next name. */
export function patientName(patient: Patient | undefined): string | undefined {
for (const name of patient?.name ?? []) {
const text = name.text?.trim();
if (text) return text;
const parts = [...(name.given ?? []), name.family ?? ''].map(part => part.trim()).filter(Boolean);
if (parts.length) return parts.join(' ');
}
return undefined;
}
export function patientLabel(patient: Patient | undefined): string {
return patientName(patient) ?? patient?.id?.slice(0, 10) ?? 'No disponible';
}
/** Completed years on a full, valid calendar date; partial dates are unknown. */
export function exactAge(birth: string | undefined, cutoff: string | undefined): number | undefined {
const parse = (text?: string): [number, number, number] | undefined => {
if (!text || !/^\d{4}-\d{2}-\d{2}$/.test(text)) return undefined;
const [y, m, d] = text.split('-').map(Number);
if (y < 1 || m < 1 || m > 12 || d < 1) return undefined;
const leap = y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0);
if (d > [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1]) return undefined;
return [y, m, d];
};
const b = parse(birth), c = parse(cutoff);
if (!b || !c || birth! > cutoff!) return undefined;
return c[0] - b[0] - (c[1] < b[1] || (c[1] === b[1] && c[2] < b[2]) ? 1 : 0);
}
const AGE_GROUPS: [number, number][] = [
[25, 34],
[35, 44],
@@ -82,7 +49,7 @@ export function currentRisk(
.filter((r) => code(r.method)?.startsWith(`cacu.${outcome}`))
.flatMap((r) =>
(r.prediction ?? [])
.filter((p) => p.whenRange?.high?.value === horizon && p.probabilityDecimal !== undefined)
.filter((p) => p.whenRange?.high?.value === horizon)
.map((p) => ({ r, p })),
);
if (!mine.length) return undefined;
@@ -93,7 +60,7 @@ export function currentRisk(
return Math.max(
...mine
.filter((x) => x.r.occurrenceDateTime === latest)
.map((x) => x.p.probabilityDecimal!),
.map((x) => x.p.probabilityDecimal ?? 0),
);
}
@@ -132,15 +99,12 @@ 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: patientName(patient),
name: patient.name?.[0]?.text,
curp: patient.identifier?.find((i) => i.system === CURP)?.value,
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
ageGroup: ageGroup(patient.birthDate, cutoff),
age: exactAge(patient.birthDate, cutoff),
stageFacts: routeFacts(last),
cytology: last && {
date: last.effectiveDateTime!,
reportDate: ext(last, 'report-date')?.valueDate,
result: code(lastResults.get('cervical_cytology.result')?.valueCodeableConcept),
adequacy: code(lastResults.get('cervical_cytology.adequacy')?.valueCodeableConcept),
},
@@ -222,7 +186,7 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] {
.at(-1);
return {
patient,
name: patientName(patient),
name: patient.name?.[0]?.text,
curp: patient.identifier?.find((i) => i.system === CURP)?.value,
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
priority: ext(patient, 'follow-up-priority')?.valueCoding?.code ?? '',
-23
View File
@@ -44,14 +44,12 @@ export function periodTypes(measure: Measure): PeriodType[] {
/** What one report says: its counts, its score and interval, and its strata. */
export interface Reading {
error?: boolean;
populations: Record<string, number>;
score?: number;
low?: number;
high?: number;
unit?: string;
strata: Record<string, Record<string, Record<string, number>>>;
stratumScores?: Record<string, Record<string, { median: number; low?: number; high?: number }>>;
}
function counts(group: {
@@ -67,13 +65,11 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
if (!group) return undefined;
const score = group.measureScore;
const strata: Reading['strata'] = {};
const stratumScores: NonNullable<Reading['stratumScores']> = {};
for (const s of group.stratifier ?? []) {
const name = code(s.code?.[0]) ?? s.code?.[0]?.text ?? '';
strata[name] = Object.fromEntries(
(s.stratum ?? []).map((x) => [x.value?.text ?? '', counts(x)]),
);
stratumScores[name] = Object.fromEntries((s.stratum ?? []).filter(x => x.measureScore?.value !== undefined).map(x => [x.value?.text ?? '', {median: x.measureScore!.value!, low: ext(x.measureScore, 'q1')?.valueDecimal, high: ext(x.measureScore, 'q3')?.valueDecimal}]));
}
return {
populations: counts(group),
@@ -82,7 +78,6 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal,
unit: score?.unit,
strata,
stratumScores,
};
}
@@ -121,13 +116,6 @@ const LABELS: Record<string, string> = {
good: 'Bueno',
bad: 'Malo',
not_analyzed: 'Sin analizar',
'ASCUS+': 'Citología ASC-US o mayor',
'LSIL+': 'Citología LIEBG o mayor',
'HSIL+': 'Citología LIEAG o mayor',
'LIEBG+': 'Histología LIEBG o mayor',
'LIEAG+': 'Histología LIEAG o mayor',
initial: 'Tamizaje inicial',
subsequent: 'Tamizaje subsecuente',
...Object.fromEntries(
['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
),
@@ -140,18 +128,7 @@ export const STRATA: Record<string, string> = {
follow_up_status: 'Estatus de seguimiento',
result: 'Citología de alto grado',
birads: 'BI-RADS de la mastografía',
referral_cytology: 'Citología previa asociada por fechas',
histology_level: 'Nivel de histología confirmado',
screening_round: 'Tamizaje inicial o subsecuente',
result_initial: 'Resultado en tamizaje inicial',
result_subsequent: 'Resultado en tamizaje subsecuente',
};
/** Measures whose server title says "referral": the data record procedures, not issued referrals. */
export const PPV_NOTES: Record<string, { title: string; note: string }> = {
CACU_VPP_COLPOSCOPIA: { title: 'VPP tras colposcopía registrada', note: 'De las pacientes con colposcopía registrada en el periodo (puede inferirse de notas clínicas), las que tienen histología LIEBG o mayor. Se muestra la citología previa más reciente en los 365 días anteriores: es una asociación por fechas, no un vínculo clínico confirmado ni una referencia emitida.' },
CACU_VPP_BIOPSIA: { title: 'VPP tras biopsia registrada', note: 'De las pacientes con biopsia reportada en el periodo, las que tienen histología LIEBG o mayor. La citología previa es una asociación por fechas, no un vínculo clínico confirmado ni una referencia emitida. Su denominador difiere del de las solicitudes de biopsia registradas.' },
};
export const measureTitle = (m: { name?: string; title?: string }) => PPV_NOTES[m.name ?? '']?.title ?? m.title ?? m.name ?? '';
export const name = (value: string) => LABELS[value] ?? value;
export function formatScore(measure: Measure, r: Reading | undefined): string {
-33
View File
@@ -1,33 +0,0 @@
import { describe, expect, it } from 'vitest';
import { PPV_NOTES, STRATA, measureTitle, name } from './measures';
describe('referral PPV wording', () => {
it('never presents procedures or date associations as confirmed referrals', () => {
for (const measure of ['CACU_VPP_COLPOSCOPIA', 'CACU_VPP_BIOPSIA']) {
const { title, note } = PPV_NOTES[measure];
expect(title).toContain('registrada');
expect(title.toLowerCase()).not.toContain('referencia');
expect(note).toContain('asociación por fechas');
expect(note).toContain('no un vínculo clínico confirmado');
expect(measureTitle({ name: measure, title: 'VPP de la referencia' })).toBe(title);
}
expect(PPV_NOTES['CACU_VPP_COLPOSCOPIA'].note).toContain('inferirse de notas');
});
it('keeps the server title for other measures', () => {
expect(measureTitle({ name: 'CACU_EU7', title: 'Pacientes evaluadas' })).toBe('Pacientes evaluadas');
});
it('names the new strata and their values in Spanish', () => {
for (const code of ['referral_cytology', 'histology_level', 'screening_round', 'result_initial', 'result_subsequent'])
expect(STRATA[code]).toBeTruthy();
expect(name('ASCUS+')).toBe('Citología ASC-US o mayor');
expect(name('LSIL+')).toBe('Citología LIEBG o mayor');
expect(name('HSIL+')).toBe('Citología LIEAG o mayor');
expect(name('LIEBG+')).toBe('Histología LIEBG o mayor');
expect(name('LIEAG+')).toBe('Histología LIEAG o mayor');
expect(name('invasive')).toBe('Carcinoma invasor');
expect(name('initial')).toBe('Tamizaje inicial');
expect(name('subsequent')).toBe('Tamizaje subsecuente');
});
});
+3 -154
View File
@@ -52,7 +52,7 @@
@if (layout().route.length) {
<mat-card appearance="outlined" class="route">
<mat-card-header>
<mat-card-title>{{ domain() === 'cacu' ? 'Tiempos de la ruta del tamizaje' : 'Ruta del tamizaje' }}</mat-card-title>
<mat-card-title>Ruta del tamizaje</mat-card-title>
<mat-button-toggle-group
[value]="routeView()"
(change)="routeView.set($event.value)"
@@ -60,172 +60,21 @@
>
<mat-button-toggle value="sample">Acumulado desde la toma</mat-button-toggle>
<mat-button-toggle value="step">Por pasos</mat-button-toggle>
@if (domain() === 'cacu') { <mat-button-toggle value="icd10">Desglose por CIE-10</mat-button-toggle> }
</mat-button-toggle-group>
</mat-card-header>
<mat-card-content>
@if (domain() !== 'cacu') { <app-plot [figure]="route()" [height]="260" /> }
@else if (routeView() === 'icd10') {
<p class="muted">Desglose exploratorio basado en la asociación temporal existente; no confirma un vínculo clínico entre la toma y el diagnóstico.</p>
@if (reports.isLoading()) { <p class="muted">Calculando…</p> }
@else if (icd(); as r) {
<p class="muted">{{ r.populations['measure-observation'] ?? 0 }} observaciones · escala 0 a {{ icdMax() }} días.</p>
<table class="distribution route-table" aria-label="Tiempos por CIE-10"><thead><tr><th>CIE-10 y descripción</th><th>Mediana</th><th>Observaciones</th><th>Q1–Q3</th></tr></thead><tbody>
@for (row of icdRows(); track row.label) {
<tr><th scope="row">{{ row.label }}<span class="bar-track duration-track" aria-hidden="true"><span class="bar" [style.width.%]="icdMax() ? 100 * row.median / icdMax() : 0"></span><span class="quartile" [style.left.%]="icdMax() ? 100 * (row.low ?? 0) / icdMax() : 0"></span><span class="quartile" [style.left.%]="icdMax() ? 100 * (row.high ?? 0) / icdMax() : 0"></span></span></th><td>{{ row.median }} días</td><td>{{ row.count }}</td><td>{{ row.low }}–{{ row.high }}</td></tr>
} @empty { <tr><td colspan="4">Sin observaciones en el periodo.</td></tr> }
</tbody></table>
} @else { <p class="muted">Desglose no disponible en este servidor o periodo.</p> }
} @else {
@if (routeView() === 'step') {
<p class="muted">Representación ilustrativa: las barras se desplazan según las medianas publicadas por tramo; no representan la duración acumulada observada de una misma cohorte.</p>
<app-plot [figure]="stepRoute()" [height]="stepRouteHeight()" />
<details class="route-values">
<summary>Cuartiles y valores por tramo</summary>
<p class="muted">Q1, mediana y Q3 corresponden a las observaciones disponibles de cada tramo. Los tramos sin datos se indican como no disponibles.</p>
<table class="distribution route-table" aria-label="Valores estadísticos de tiempos por tramo">
<thead><tr><th>Tramo</th><th>Mediana</th><th>Observaciones</th><th>Q1–Q3</th></tr></thead>
<tbody>@for (row of routeRows(); track row.label) {
<tr><th scope="row">{{ row.label }}</th><td>{{ row.reading?.score !== undefined ? row.reading!.score + ' días' : '—' }}</td>
<td>{{ row.reading?.score !== undefined ? (row.reading?.populations?.['measure-observation'] ?? '—') : '—' }}</td>
<td>{{ row.reading?.low !== undefined && row.reading?.high !== undefined ? row.reading!.low + '–' + row.reading!.high : '—' }}</td></tr>
}</tbody>
</table>
</details>
} @else {
<p class="muted">Escala: 0 a {{ routeMax() }} días. Las marcas indican el primer y tercer cuartil.</p>
<table class="distribution route-table" aria-label="Tiempos de la ruta del tamizaje">
<thead><tr><th>Etapa</th><th>Mediana</th><th>Observaciones</th><th>Q1–Q3</th></tr></thead>
<tbody>
@for (row of routeRows(); track row.label) {
<tr><th scope="row">{{ row.label }}
@if (row.reading?.score !== undefined) {
<span class="bar-track duration-track" aria-hidden="true">
<span class="bar" [style.width.%]="routeMax() ? 100 * row.reading!.score! / routeMax() : 0"></span>
@if (row.reading!.low !== undefined && row.reading!.high !== undefined) {
<span class="quartile" [style.left.%]="routeMax() ? 100 * row.reading!.low! / routeMax() : 0"></span>
<span class="quartile" [style.left.%]="routeMax() ? 100 * row.reading!.high! / routeMax() : 0"></span>
}
</span>
}
</th><td>{{ row.reading?.score !== undefined ? row.reading!.score + ' días' : '—' }}</td>
<td>{{ row.reading?.populations?.['measure-observation'] ?? '—' }}</td>
<td>{{ row.reading?.low !== undefined && row.reading?.high !== undefined ? row.reading!.low + '–' + row.reading!.high : '—' }}</td></tr>
}
</tbody>
</table>
}
}
<app-plot [figure]="route()" [height]="260" />
</mat-card-content>
</mat-card>
}
<h2>Indicadores clínicos</h2>
@if (domain() === 'cacu') {
<mat-card appearance="outlined" class="results-card">
<mat-card-header><mat-card-title>Resultados de citología, VPH y biopsia</mat-card-title></mat-card-header>
<mat-card-content class="results-grid">
<section aria-labelledby="cytology-title">
<h3 id="cytology-title">Distribución de resultados citológicos</h3>
@if (reports.isLoading()) {
<p class="muted">Calculando…</p>
} @else if (cytology(); as distribution) {
<p class="muted">{{ distribution.total }} pacientes con resultado elegible · {{ distribution.outside }} fuera de la distribución</p>
<p class="muted">Una muestra por paciente en el periodo; se prioriza la última válida. Los porcentajes usan los resultados elegibles.</p>
<p class="muted">Escala de las barras: 0 a {{ distribution.max }} pacientes.</p>
<table class="distribution" aria-label="Distribución de resultados citológicos">
<thead><tr><th>Categoría</th><th>Pacientes</th><th>%</th></tr></thead>
<tbody>
@for (row of distribution.rows; track row.label) {
<tr>
<th scope="row"><span class="distribution-label">{{ row.label }}</span><span class="bar-track" aria-hidden="true"><span class="bar" [style.width.%]="distribution.max ? 100 * row.count / distribution.max : 0" [style.background]="row.color"></span></span></th>
<td>{{ row.count }}</td>
<td>{{ distribution.total ? (100 * row.count / distribution.total).toFixed(1) + ' %' : '—' }}</td>
</tr>
}
</tbody>
</table>
@if (!distribution.total) { <p class="muted">Sin resultados elegibles en el periodo.</p> }
} @else {
<p class="muted">{{ hasCytologyMeasure() ? 'Distribución no disponible para este periodo.' : 'Medida no publicada por el servidor.' }}</p>
}
</section>
<section aria-labelledby="hpv-title">
<h3 id="hpv-title">Resultados de VPH por genotipo</h3>
@if (reports.isLoading()) { <p class="muted">Calculando…</p> }
@else if (hpv(); as d) {
<p class="muted">{{ d.total }} reportes VPH elegibles · periodo por fecha de toma. {{ d.outside }} fuera de las categorías mostradas.</p>
<p class="muted">Escala de las barras: 0 a {{ d.max }} reportes. El contrato actual no representa resultados indeterminados.</p>
<table class="distribution" aria-label="Resultados de VPH por genotipo">
<thead><tr><th>Categoría</th><th>Reportes</th><th>%</th></tr></thead>
<tbody>
@for (row of d.rows; track row.label) {
@if (row.label === 'No clasificable o inconsistente') { <tr><th scope="row">Indeterminado</th><td colspan="2">No disponible en el contrato actual</td></tr> }
<tr><th scope="row"><span class="distribution-label">{{ row.label }}</span><span class="bar-track" aria-hidden="true"><span class="bar" [style.width.%]="d.max ? 100 * row.count / d.max : 0" [style.background]="row.color"></span></span></th>
<td>{{ row.count }}</td><td>{{ d.total ? (100 * row.count / d.total).toFixed(1) + ' %' : '—' }}</td></tr>
}
</tbody>
</table>
@if (!d.total) { <p class="muted">Sin reportes elegibles en el periodo.</p> }
} @else { <p class="muted">{{ hasHpvMeasure() ? 'Distribución no disponible para este periodo.' : 'Distribución no publicada por el servidor.' }}</p> }
</section>
<section class="biopsy" aria-labelledby="biopsy-title">
<h3 id="biopsy-title">Resultado de la biopsia</h3>
@if (reports.isLoading()) { <p class="muted">Calculando…</p> }
@else if (biopsy(); as d) {
<p class="muted">{{ d.total }} reportes con histología clasificable · periodo por fecha de reporte.</p>
<p class="muted">{{ d.noData }} reportes sin grado · {{ d.outside - d.noData }} con grado no clasificable. Las órdenes sin reporte no están incluidas.</p>
<p class="muted">Escala de las barras: 0 a {{ d.max }} reportes.</p>
<table class="distribution" aria-label="Resultados de biopsia cervical">
<thead><tr><th>Categoría</th><th>Reportes</th><th>%</th></tr></thead>
<tbody>
@for (row of d.rows; track row.label; let i = $index) {
@if (i === 0) { <tr class="group"><th scope="rowgroup" colspan="3">Menor que LIEAG · {{ d.rows[0].count + d.rows[1].count }}</th></tr> }
@if (i === 2) { <tr class="group"><th scope="rowgroup" colspan="3">LIEAG o más · {{ d.rows[2].count + d.rows[3].count + d.rows[4].count }}</th></tr> }
<tr><th scope="row"><span class="distribution-label">{{ row.label }}</span><span class="bar-track" aria-hidden="true"><span class="bar" [style.width.%]="d.max ? 100 * row.count / d.max : 0" [style.background]="row.color"></span></span></th>
<td>{{ row.count }}</td><td>{{ d.total ? (100 * row.count / d.total).toFixed(1) + ' %' : '—' }}</td></tr>
}
</tbody>
</table>
@if (!d.total) { <p class="muted">Sin reportes con grado clasificable en el periodo.</p> }
} @else { <p class="muted">{{ hasBiopsyMeasure() ? 'Distribución no disponible para este periodo.' : 'Distribución general no publicada por el servidor.' }}</p> }
</section>
</mat-card-content>
</mat-card>
<div class="confirmation-cards">
<mat-card appearance="outlined"><mat-card-header><mat-card-title>Tasa de confirmación histopatológica de referencia a colposcopia</mat-card-title></mat-card-header>
<mat-card-content><p>No disponible: no se identifican las referencias emitidas a colposcopia. Las colposcopias inferidas no acreditan ese denominador.</p></mat-card-content>
</mat-card>
<mat-card appearance="outlined"><mat-card-header><mat-card-title>Tasa de confirmación histopatológica de referencia a biopsia</mat-card-title></mat-card-header>
<mat-card-content>
<p>La tasa de referencias emitidas no está disponible: no se acreditó la cobertura de referencias ni las cancelaciones.</p>
<p class="muted">Aproximación distinta: estudios con solicitud de biopsia registrada, por fecha de solicitud.</p>
@if (reports.isLoading()) { <p class="muted">Calculando…</p> }
@else if (!requestsMeasure()) { <p>No disponible: medida no publicada por el servidor.</p> }
@else if (requests()?.error) { <p role="alert">Error al consultar las solicitudes de biopsia.</p> }
@else if (requests(); as r) {
@if (validRequests()) {
@if (r.populations['initial-population']; as total) {
<p>Denominador: {{ total }} solicitudes registradas (no pacientes).</p>
<p>LIEAG o más: {{ category(r, 'high_grade') }} / {{ total }} · {{ (100 * category(r, 'high_grade') / total).toFixed(1) }} %</p>
<p>Menor que LIEAG: {{ category(r, 'below_high_grade') }} / {{ total }} · {{ (100 * category(r, 'below_high_grade') / total).toFixed(1) }} %</p>
<p class="muted">Pendientes: {{ category(r, 'pending') }} · Sin grado: {{ category(r, 'no_grade') }} · No clasificables: {{ category(r, 'unclassified') }} · Fechas inconsistentes: {{ category(r, 'inconsistent') }} · Registros fusionados ambiguos: {{ category(r, 'ambiguous') }}.</p>
} @else { <p>Sin solicitudes registradas en el periodo; porcentaje no calculable (denominador 0).</p> }
} @else { <p role="alert">Los datos de solicitudes recibidos están incompletos o son inconsistentes.</p> }
} @else { <p>No disponible para este periodo.</p> }
</mat-card-content>
</mat-card>
</div>
}
<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>{{ measureTitle(m) }}</mat-card-title>
<mat-card-title>{{ m.title }}</mat-card-title>
<mat-card-subtitle>{{ score(m) }} · {{ detail(m) }}</mat-card-subtitle>
@if (ppvNote(m); as note) { <mat-card-subtitle class="ppv-note">{{ note }}</mat-card-subtitle> }
@if (domain() === 'cacu' && m.name === 'CACU_EU7') { <mat-card-subtitle>El tamizaje inicial o subsecuente es el que declara el formulario o se deduce de la ruta; «Sin dato» si no consta.</mat-card-subtitle> }
@if (domain() === 'cacu' && m.name === 'CACU_CONFIRMACION_CITOLOGIA') { <mat-card-subtitle>Pacientes con citología ASC-H, LIEAG o carcinoma in situ; incluye casos sin biopsia.</mat-card-subtitle> }
</mat-card-header>
<mat-card-content>
@for (f of figureSets().get(m.name!) ?? []; track f.title) {
-35
View File
@@ -78,46 +78,11 @@ h2 {
gap: var(--space-3);
justify-content: space-between;
}
.route-toggle { flex-wrap: wrap; max-width: 100%; }
.route-values summary { color: var(--color-text-secondary); cursor: pointer; padding: var(--space-2) 0; }
.route-values summary:focus-visible { outline: 2px solid var(--color-action); outline-offset: 2px; }
.route-table td { font-variant-numeric: tabular-nums; }
.route-table th:first-child { width: 70%; }
.duration-track { position: relative; }
.duration-track .bar { background: #42a77e; }
.quartile { position: absolute; top: -3px; width: 2px; height: 14px; background: #17324d; }
.confirmation-cards { display: grid; grid-template-columns: 1fr; gap: var(--space-4); margin-bottom: var(--space-4); }
.confirmation-cards { align-items: start; }
.confirmation-cards p { margin: var(--space-2) 0; }
@media (min-width: 850px) { .confirmation-cards { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.clinical {
display: grid;
gap: var(--space-4);
grid-template-columns: 1fr;
align-items: start;
}
.results-card { margin-bottom: var(--space-4); }
.results-grid { display: grid; gap: var(--space-4); grid-template-columns: 1fr; }
.results-grid section { min-width: 0; }
.results-grid h3 { font-size: 1rem; font-weight: 500; margin: var(--space-3) 0; }
.results-grid p { font-size: 13px; margin: var(--space-2) 0; }
.distribution { border-collapse: collapse; width: 100%; font-size: 13px; }
.distribution th { font-weight: 500; text-align: left; }
.distribution td, .distribution thead th:not(:first-child) { text-align: right; white-space: nowrap; padding-left: 12px; }
.distribution tbody th { padding: 5px 0; }
.distribution .group th { background: #edf2f4; padding: 6px 8px; font-weight: 600; }
.bar-track { display: block; height: 8px; background: #eef1f3; margin-top: 3px; }
.bar { display: block; height: 100%; }
.results-grid .distribution tbody th:has(.distribution-label) { display: flex; align-items: center; gap: 10px; }
.results-grid .distribution-label { flex: 0 1 45%; min-width: 0; }
.results-grid .bar-track { flex: 1; min-width: 40px; height: 16px; margin: 0; }
.results-grid .distribution td { padding-left: 8px; }
@media (min-width: 850px) {
.results-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.biopsy { grid-column: 1 / -1; }
}
@media (min-width: 1304px) {
+7 -92
View File
@@ -8,7 +8,6 @@ import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot';
import { LAYOUTS } from './layout';
import { biopsyDistribution, cytologyDistribution, hpvDistribution } from './cacu-results';
import {
detail,
donut,
@@ -22,8 +21,6 @@ import {
Reading,
scoring,
STRATA,
PPV_NOTES,
measureTitle,
strataBars,
} from './measures';
@@ -52,7 +49,7 @@ export class TabIndicadores {
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' | 'icd10'>('sample');
protected readonly routeView = signal<'sample' | 'step'>('sample');
protected readonly layout = computed(
() => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' },
@@ -67,7 +64,6 @@ export class TabIndicadores {
const placed = new Set([
...this.layout().kpis,
...this.layout().route.flatMap((s) => [s.fromSample, s.fromStep]),
...(this.domain() === 'cacu' ? ['CACU_VPH_GENOTIPO', 'CACU_BIOPSIA_RESULTADOS', 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION', 'CACU_TIEMPO_DIAGNOSTICO_CIE10'] : []),
]);
return this.measures().filter((m) => !placed.has(m.name!));
});
@@ -98,19 +94,11 @@ export class TabIndicadores {
if (!params.period) return new Map<string, Reading | undefined>();
const found = await Promise.all(
params.measures.map(async (m) => {
try {
const page = await this.fhir.search(params.domain, 'MeasureReport', {
measure: m.id!,
'reporting-period': params.period,
});
return [m.name!, reading(resources<MeasureReport>(page, 'MeasureReport')[0])] as const;
} catch (error) {
if (params.domain === 'cacu' && m.name === 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION')
return [m.name, { populations: {}, strata: {}, error: true } as Reading] as const;
if (params.domain === 'cacu' && ['CACU_VPH_GENOTIPO', 'CACU_BIOPSIA_RESULTADOS', 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION', 'CACU_TIEMPO_DIAGNOSTICO_CIE10'].includes(m.name!))
return [m.name!, undefined] as const;
throw error;
}
const page = await this.fhir.search(params.domain, 'MeasureReport', {
measure: m.id!,
'reporting-period': params.period,
});
return [m.name!, reading(resources<MeasureReport>(page, 'MeasureReport')[0])] as const;
}),
);
return new Map(found);
@@ -153,64 +141,6 @@ export class TabIndicadores {
}),
);
});
protected readonly routeRows = computed(() => {
const view = this.routeView();
return this.layout().route.map((s) => {
const m = this.byName().get(view === 'sample' ? s.fromSample : s.fromStep);
return { label: view === 'sample' ? s.label : s.step, reading: m && this.r(m) };
});
});
protected readonly routeMax = computed(() => Math.max(0, ...this.routeRows().map(({reading}) =>
Math.max(reading?.score ?? 0, reading?.high ?? 0))));
/** Illustrative cascade of the published step medians; missing steps do not advance the offset. */
protected readonly stepRoute = computed<Figure>(() => {
const rows = this.routeRows().filter(row => row.reading?.score !== undefined);
let offset = 0;
const bars = rows.map((row, index) => {
const score = row.reading!.score!;
const base = offset;
offset += score;
return { label: row.label, count: row.reading!.populations['measure-observation'] ?? 0, score, base,
color: index === 0 ? '#C9CDD2' : '#A8C243' };
});
const max = Math.max(1, offset);
return {
data: [{ type: 'bar', orientation: 'h', y: bars.map(row => `${row.label}<br>n = ${row.count}`),
x: bars.map(row => row.score), base: bars.map(row => row.base),
marker: { color: bars.map(row => row.color) }, text: bars.map(row => `+${row.score} d`),
textposition: 'inside', insidetextanchor: 'start', textfont: { color: '#081839' },
cliponaxis: false, hovertemplate: '%{y}<br>Mediana del tramo: %{x} días<extra></extra>' }],
layout: { autosize: true, showlegend: false, bargap: 0.48,
height: Math.max(210, bars.length * 76 + 94), margin: { t: 12, l: 8, r: 28, b: 52 },
xaxis: { title: { text: 'Días' }, range: [0, max * 1.12], nticks: 5, fixedrange: true, zeroline: false },
yaxis: { autorange: 'reversed', type: 'category', automargin: true, fixedrange: true } },
};
});
protected readonly stepRouteHeight = computed(() => Math.max(210,
this.routeRows().filter(row => row.reading?.score !== undefined).length * 76 + 94));
protected readonly icd = computed(() => this.reports.value()?.get('CACU_TIEMPO_DIAGNOSTICO_CIE10'));
protected readonly icdRows = computed(() => {
const r = this.icd();
return Object.entries(r?.stratumScores?.['diagnosis_code'] ?? {}).map(([label, score]) => ({
label: label.replace('sin_codigo', 'Sin código disponible').replace('ambiguo', 'Diagnóstico ambiguo'),
count: r?.strata['diagnosis_code']?.[label]?.['measure-observation'] ?? 0, ...score,
}));
});
protected readonly icdMax = computed(() => Math.max(0, ...this.icdRows().map(r => Math.max(r.median, r.high ?? 0))));
protected readonly requestsMeasure = computed(() => this.byName().has('CACU_BIOPSIA_SOLICITUD_CONFIRMACION'));
protected readonly requests = computed(() => this.reports.value()?.get('CACU_BIOPSIA_SOLICITUD_CONFIRMACION'));
protected readonly validRequests = computed(() => {
const r = this.requests();
const total = r?.populations['initial-population'];
const cells = r?.strata['category'];
if (!r || r.error || total === undefined || !cells) return false;
const counts = Object.values(cells).map((cell) => cell['initial-population']);
return Number.isInteger(total) && total >= 0 && counts.every((n) => Number.isInteger(n) && n >= 0)
&& counts.reduce((sum, n) => sum + n, 0) === total;
});
protected category(r: Reading, key: string): number {
return r.strata['category']?.[key]?.['initial-population'] ?? 0;
}
/** Each clinical card's figures, built once per loaded period. */
protected readonly figureSets = computed(
@@ -220,15 +150,6 @@ export class TabIndicadores {
),
);
protected readonly cytology = computed(() =>
cytologyDistribution(this.reports.value()?.get('CACU_EU7')),
);
protected readonly hasCytologyMeasure = computed(() => this.byName().has('CACU_EU7'));
protected readonly hpv = computed(() => hpvDistribution(this.reports.value()?.get('CACU_VPH_GENOTIPO')));
protected readonly biopsy = computed(() => biopsyDistribution(this.reports.value()?.get('CACU_BIOPSIA_RESULTADOS')));
protected readonly hasHpvMeasure = computed(() => this.byName().has('CACU_VPH_GENOTIPO'));
protected readonly hasBiopsyMeasure = computed(() => this.byName().has('CACU_BIOPSIA_RESULTADOS'));
/** 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 [];
@@ -239,9 +160,7 @@ export class TabIndicadores {
if (kind === 'continuous-variable')
return [{ title: 'Mediana y cuartiles', figure: medians([{ label: m.title!, r }]) }];
return [
...(this.domain() === 'cacu' && m.name === 'CACU_EU7' && this.cytology()
? []
: [{ title: kind === 'proportion' ? 'Numerador y resto' : 'Por categoría', figure: donut(m, r) }]),
{ 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),
@@ -249,8 +168,4 @@ export class TabIndicadores {
];
}
protected readonly name = name;
protected readonly measureTitle = measureTitle;
protected ppvNote(m: Measure): string | undefined {
return PPV_NOTES[m.name ?? '']?.note;
}
}
+7 -20
View File
@@ -1,12 +1,4 @@
<div class="export-actions"><button mat-stroked-button (click)="exportList('xlsx')" [disabled]="exporting() || !page() || invalidAge() || queryLoading() || loading()">Exportar Excel (.xlsx)</button><button mat-stroked-button (click)="exportList('pdf')" [disabled]="exporting() || !page() || invalidAge() || queryLoading() || loading()">Exportar PDF</button></div>
@if (exportMessage()) { <p role="alert">{{ exportMessage() }}</p> }
<form class="filters card" (submit)="$event.preventDefault()">
@if (globalFilters()) {
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Buscar nombre o identificador</mat-label><input matInput [ngModel]="search()" (ngModelChange)="search.set($event)" name="search" /></mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Edad mínima</mat-label><input matInput type="number" min="0" max="150" step="1" [ngModel]="ageMin()" (ngModelChange)="ageMin.set($event)" name="ageMin" /></mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Edad máxima</mat-label><input matInput type="number" min="0" max="150" step="1" [ngModel]="ageMax()" (ngModelChange)="ageMax.set($event)" name="ageMax" /></mat-form-field>
<button mat-stroked-button type="button" (click)="ageMin.set(null); ageMax.set(null)">Limpiar edades</button>
}
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label>
<input
@@ -46,7 +38,7 @@
<mat-label>Orden</mat-label>
<mat-select [value]="sort()" (selectionChange)="sort.set($event.value)">
<mat-option value="-recent">Estudio más reciente</mat-option>
<mat-option value="-risk-cin2">Mayor riesgo de CIN2+</mat-option>
<mat-option value="-risk-cin2">Mayor riesgo de LIEAG+</mat-option>
<mat-option value="-risk-cancer">Mayor riesgo de cáncer</mat-option>
</mat-select>
</mat-form-field>
@@ -59,8 +51,6 @@
</mat-select>
</mat-form-field>
</form>
@if (invalidAge()) { <p role="alert">Indique edades enteras entre 0 y 150; la mínima no puede superar la máxima. El rango no está aplicado.</p> }
@if (!globalFilters() && !capabilities.isLoading()) { <p class="muted">El servidor no declara búsqueda global ni filtros de edad.</p> }
@if (error()) {
<p class="muted" role="alert">No se pudo leer la lista de seguimiento.</p>
@@ -71,13 +61,12 @@
<thead>
<tr>
<th>Paciente</th>
<th>Edad</th>
<th>Grupo de edad</th>
<th>Estatus</th>
<th>Etapas</th>
<th>Última citología</th>
<th>VPH</th>
<th>Biopsia</th>
<th>Riesgo CIN2+ ({{ horizon() }} a)</th>
<th>Riesgo LIEAG+ ({{ horizon() }} a)</th>
<th>Riesgo cáncer ({{ horizon() }} a)</th>
<th>Días toma → diagnóstico</th>
</tr>
@@ -86,16 +75,15 @@
@for (row of rows(); track row.patient.id) {
<tr>
<td>
<a [routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]" [queryParams]="{ corte: applied(), muestra: row.cytology?.date }">{{
patientLabel(row.patient)
<a [routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]">{{
row.name ?? row.patient.id!.slice(0, 10)
}}</a>
@if (row.curp) {
<div class="muted curp">{{ row.curp }}</div>
}
</td>
<td>{{ row.age ?? 'No disponible' }}</td>
<td>{{ row.ageGroup }}</td>
<td>{{ name(row.status) }}</td>
<td><div class="stage-compact"><app-stages [sample]="row.cytology?.date" [report]="row.cytology?.result ? row.cytology?.reportDate : undefined" [cutoff]="applied()" [facts]="row.stageFacts" /><button class="stage-toggle" type="button" [attr.aria-label]="expanded() === row.patient.id ? 'Ocultar etapas' : 'Mostrar etapas'" [attr.aria-expanded]="expanded() === row.patient.id" (click)="expanded.set(expanded() === row.patient.id ? undefined : row.patient.id)"><span [class.open]="expanded() === row.patient.id" aria-hidden="true">⌄</span></button></div></td>
<td>
@if (row.cytology; as c) {
{{ c.date }} ·
@@ -134,10 +122,9 @@
</td>
<td class="num">{{ row.daysToDiagnosis ?? '—' }}</td>
</tr>
@if (expanded() === row.patient.id) { <tr><td colspan="10"><app-stages [sample]="row.cytology?.date" [report]="row.cytology?.result ? row.cytology?.reportDate : undefined" [cutoff]="applied()" [facts]="row.stageFacts" [detail]="true" /></td></tr> }
} @empty {
<tr>
<td colspan="10" class="muted">
<td colspan="9" class="muted">
{{ page() ? 'Nadie en la lista con estos filtros.' : 'Cargando…' }}
</td>
</tr>
-5
View File
@@ -40,8 +40,3 @@ a {
.pager .muted {
margin-right: auto;
}
.export-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; margin-bottom: 12px; }
.stage-compact { display:flex; align-items:center; gap:0; }
.stage-toggle { display:grid; place-items:center; flex:0 0 32px; width:32px; height:32px; border:0; background:transparent; color:#385c6c; cursor:pointer; padding:0; }
.stage-toggle:focus-visible { outline:2px solid #2778b8; outline-offset:2px; }
.stage-toggle span { display:block; font-size:18px; line-height:1; transition:transform 120ms ease; }.stage-toggle span.open { transform:rotate(180deg); }
+2 -69
View File
@@ -8,13 +8,8 @@ import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir';
import { patientLabel, rows, windowStart } from './follow-up';
import { rows, windowStart } from './follow-up';
import { name } from './measures';
import { Stages } from '../paciente/stages';
import { stages } from '../paciente/stages';
import { HttpClient } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
import { downloadDocument } from '../export-document';
const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment'];
@@ -30,16 +25,12 @@ const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment']
MatInputModule,
MatSelectModule,
RouterLink,
Stages,
],
templateUrl: './tab-riesgos.html',
styleUrl: './tab-riesgos.scss',
})
export class TabRiesgos {
private readonly fhir = inject(Fhir);
private readonly http = inject(HttpClient);
protected readonly exporting = signal(false);
protected readonly exportMessage = signal('');
readonly domain = input.required<string>();
protected readonly cutoff = signal<string>('');
@@ -48,29 +39,11 @@ export class TabRiesgos {
protected readonly horizon = signal(5);
protected readonly sort = signal('-recent');
protected readonly size = signal(20);
protected readonly ageMin = signal<number | null>(null);
protected readonly ageMax = signal<number | null>(null);
protected readonly search = signal('');
protected readonly expanded = signal<string | undefined>(undefined);
protected readonly invalidAge = computed(() => {
const a = this.ageMin(), b = this.ageMax();
return [a,b].some(n => n !== null && (!Number.isInteger(n) || n < 0 || n > 150)) || (a !== null && b !== null && a > b);
});
protected readonly capabilities = resource({
params: () => this.domain(),
loader: async ({params}) => this.fhir.search(params, 'metadata') as Promise<any>,
});
protected readonly globalFilters = computed(() => {
const patient = this.capabilities.value()?.rest?.flatMap((r: any) => r.resource ?? []).find((r: any) => r.type === 'Patient');
const names = new Set<string>((patient?.searchParam ?? []).map((x: any) => x.name));
return ['follow-up-age-min','follow-up-age-max','follow-up-search'].every(n => names.has(n));
});
/** A page the user moved to (`next`/`previous`), else the first. */
private readonly moved = signal<Bundle | undefined>(undefined);
protected readonly statuses = STATUSES;
protected readonly name = name;
protected readonly patientLabel = patientLabel;
private readonly first = resource({
params: () => ({
@@ -81,9 +54,6 @@ export class TabRiesgos {
'risk-horizon': this.horizon(),
_sort: this.sort(),
_count: this.size(),
'follow-up-age-min': this.globalFilters() && !this.invalidAge() ? this.ageMin() ?? undefined : undefined,
'follow-up-age-max': this.globalFilters() && !this.invalidAge() ? this.ageMax() ?? undefined : undefined,
'follow-up-search': this.globalFilters() ? this.search().trim().replace(/\s+/g, ' ') || undefined : undefined,
}),
loader: ({ params: { domain, ...params } }) => {
this.moved.set(undefined);
@@ -95,7 +65,6 @@ export class TabRiesgos {
},
});
protected readonly loading = signal(false);
protected readonly queryLoading = computed(() => this.first.isLoading());
protected readonly page = computed(() => this.moved() ?? this.first.value());
/** The cut-off as applied (the server's default when none is given). */
protected readonly applied = computed(() => {
@@ -115,40 +84,6 @@ export class TabRiesgos {
});
protected readonly error = computed(() => this.first.error());
protected async exportList(format: 'xlsx' | 'pdf'): Promise<void> {
if (!this.page() || this.invalidAge() || !this.applied() || this.queryLoading() || this.loading()) return;
const total = this.page()!.total ?? 0, limit = format === 'pdf' ? 1000 : 5000;
if (total > limit) { this.exportMessage.set(`La consulta tiene ${total} pacientes; el límite para ${format.toUpperCase()} es ${limit}. Ajuste los filtros.`); return; }
const cutoff = this.applied(), months = this.window(), horizon = this.horizon();
const params = {'follow-up-window': months, 'follow-up-cutoff': cutoff, 'follow-up-status': this.status() || undefined,
'risk-horizon': horizon, _sort: this.sort(), _count: 200,
'follow-up-age-min': this.globalFilters() ? this.ageMin() ?? undefined : undefined,
'follow-up-age-max': this.globalFilters() ? this.ageMax() ?? undefined : undefined,
'follow-up-search': this.globalFilters() ? this.search().trim().replace(/\s+/g,' ') || undefined : undefined,
_revinclude: ['DiagnosticReport:subject','RiskAssessment:subject'], '_include:iterate':'DiagnosticReport:result'};
this.exporting.set(true); this.exportMessage.set('');
try {
const caps = await firstValueFrom(this.http.get<{xlsx_limit:number;pdf_limit:number}>('/api/cacu/exports/capabilities'));
if (total > (format === 'pdf' ? caps.pdf_limit : caps.xlsx_limit)) throw new Error('La consulta supera el límite del servidor.');
const pages = await this.fhir.all(this.domain(), 'Patient', params);
const all = pages.flatMap(page => rows(page, windowStart(cutoff, months), cutoff, horizon));
if (all.length !== total || new Set(all.map(r => r.patient.id)).size !== total || pages.some(p => p.total !== total))
throw new Error('La consulta cambió durante la exportación; vuelva a intentarlo.');
const pct = (n?: number) => n === undefined ? 'No disponible' : `${(100*n).toFixed(1)} %`;
const sortLabels: Record<string,string> = {'-recent':'Estudio más reciente','-risk-cin2':'Mayor riesgo de CIN2+','-risk-cancer':'Mayor riesgo de cáncer'};
const routes = all.map(r => stages(r.cytology?.date,r.cytology?.result ? r.cytology.reportDate : undefined,cutoff,r.stageFacts));
await downloadDocument(this.http, format, {title:'Resultados de seguimiento', parameters:[['Fecha de corte',cutoff],['Ventana consultada',`${windowStart(cutoff,months)} al ${cutoff} (${months} ${months === 1 ? 'mes' : 'meses'})`],['Estatus de seguimiento',params['follow-up-status'] ? name(params['follow-up-status']) : 'Todos'],['Orden',sortLabels[params._sort] ?? params._sort],['Horizonte de la probabilidad',`${horizon} ${horizon === 1 ? 'año' : 'años'}`],['Nombre o identificador contiene',params['follow-up-search'] || 'Todos'],['Edad mínima (años)',String(params['follow-up-age-min'] ?? 'Sin límite')],['Edad máxima (años)',String(params['follow-up-age-max'] ?? 'Sin límite')],['Registros',String(total)]],
columns:['Paciente','Edad','Estatus','Etapas','Última citología','VPH','Biopsia','Riesgo CIN2+','Riesgo cáncer','Días a diagnóstico'],
row_stages: routes.map(route => route.map(s => ({state:s.state, ...(s.provenance ? {provenance:s.provenance} : {}), ...(s.date ? {date:s.date} : {})}))),
rows:all.map((r,i)=>[`${patientLabel(r.patient)}${r.curp ? '\n'+r.curp : ''}`,String(r.age ?? 'No disponible'),name(r.status),
routes[i].map(s=>`${s.label}: ${s.state}${s.date ? ' '+s.date : ''}${s.provenance ? ' ('+s.provenance+')' : ''}`).join('\n'),
r.cytology ? `${r.cytology.date} · ${r.cytology.result ? name(r.cytology.result) : r.cytology.adequacy === 'unsatisfactory' ? 'Insatisfactoria' : 'Pendiente'}` : '—',
r.hpv ? `${r.hpv.positive ? 'Positivo' : 'Negativo'}${r.hpv.types1618 ? ' (16/18)' : ''}` : '—',
r.biopsy ? `${r.biopsy.date} · ${name(r.biopsy.histology ?? '') || 'Sin dato'}` : '—',pct(r.risk.cin2),pct(r.risk.cancer),String(r.daysToDiagnosis ?? '—')])});
} catch (error) { this.exportMessage.set(error instanceof Error ? error.message : 'No se pudo generar la exportación.'); }
finally { this.exporting.set(false); }
}
protected has(relation: 'next' | 'previous'): boolean {
return !!this.page()?.link?.some((l) => l.relation === relation);
}
@@ -158,10 +93,8 @@ export class TabRiesgos {
const next = page && this.fhir.follow(this.domain(), page, relation);
if (!next) return;
this.loading.set(true);
const signature = JSON.stringify([this.cutoff(), this.window(), this.status(), this.horizon(), this.sort(), this.size(), this.ageMin(), this.ageMax(), this.search()]);
try {
const found = await next;
if (signature === JSON.stringify([this.cutoff(), this.window(), this.status(), this.horizon(), this.sort(), this.size(), this.ageMin(), this.ageMax(), this.search()])) this.moved.set(found);
this.moved.set(await next);
} finally {
this.loading.set(false);
}
+2 -23
View File
@@ -1,6 +1,4 @@
<section class="page">
@if (domain() === 'cacu' && patient()) { <div class="export-actions"><button mat-stroked-button [disabled]="exporting()" (click)="exportPatient()">Exportar ficha PDF</button></div> }
@if (exportError()) { <p role="alert">{{ exportError() }}</p> }
<a mat-button [routerLink]="['/indicadores', domain()]"
><mat-icon>arrow_back</mat-icon> Regresar</a
>
@@ -8,8 +6,7 @@
<p class="muted" role="alert">No se encontró la paciente.</p>
} @else if (patient(); as p) {
<h1>
{{ identity().name ?? p.id?.slice(0, 10) ?? 'No disponible' }} @if (identity().name && p.id) { <code class="muted">{{ p.id.slice(0, 10) }}</code> }
@if (domain() === 'cacu') { · Edad: {{ exactAge(p.birthDate, cutoff) ?? 'No disponible' }} }
{{ identity().name ?? 'Paciente' }} <code class="muted">{{ p.id!.slice(0, 10) }}</code>
</h1>
<dl class="summary">
<div>
@@ -46,7 +43,6 @@
<mat-card appearance="outlined">
<mat-card-header><mat-card-title>Historial médico</mat-card-title></mat-card-header>
<mat-card-content>
@if (domain() === 'cacu') { <app-stages [sample]="sample" [report]="sampleReportDate()" [cutoff]="cutoff" [facts]="sampleFacts()" [detail]="true" /> }
<table class="plain">
<thead>
<tr>
@@ -112,24 +108,7 @@
><mat-card-title>Riesgos y recomendaciones</mat-card-title></mat-card-header
>
<mat-card-content>
@if (domain() === 'cacu') {
<p class="muted">Divisiones numéricas descriptivas; no representan umbrales clínicos.</p>
@for (model of riskScales(); track model.model) {
<h3>{{ model.outcome }} · {{ model.model }} · fecha índice {{ model.index }}</h3>
@for (scale of [{label: 'Riesgo inmediato (al índice)', value: model.immediate}, {label: 'Riesgo a 5 años', value: model.five}]; track scale.label) {
<div class="risk-scale">
<p><strong>{{ scale.label }}</strong> @if (scale.value; as v) { @if (v.low !== undefined && v.high !== undefined) { · IC 95 %: {{ v.low * 100 | number:'1.1-2' }}–{{ v.high * 100 | number:'1.1-2' }} % } } @else { · No disponible }</p>
<div class="risk-plot" [class.unavailable]="!scale.value"><div class="risk-line" aria-hidden="true"></div>@if (scale.value; as v) { <span class="risk-marker" [style.left.%]="v.value * 100" aria-hidden="true"></span><strong class="risk-value" [style.left]="'clamp(2.5rem, '+ (v.value * 100) +'%, calc(100% - 2.5rem))'">{{ v.value * 100 | number:'1.1-2' }} %</strong> }</div>
<div class="risk-labels"><span>0 %</span><span>25 %</span><span>50 %</span><span>75 %</span><span>100 %</span></div>
</div>
}
} @empty {
@for (label of ['Riesgo inmediato', 'Riesgo a 5 años']; track label) {
<div class="risk-scale"><p><strong>{{ label }}</strong> · No disponible</p><div class="risk-plot unavailable"><div class="risk-line" aria-hidden="true"></div></div><div class="risk-labels"><span>0 %</span><span>25 %</span><span>50 %</span><span>75 %</span><span>100 %</span></div></div>
}
<p class="muted">Ningún modelo vigente la ha evaluado.</p>
}
} @else if (models().length) {
@if (models().length) {
<table class="plain">
<thead>
<tr>
+2 -13
View File
@@ -18,12 +18,12 @@
.cards {
display: grid;
gap: var(--space-4);
grid-template-columns: minmax(0, 1fr);
grid-template-columns: 1fr;
}
@media (min-width: 1100px) {
.cards {
grid-template-columns: repeat(2, minmax(0, 1fr));
grid-template-columns: repeat(2, 1fr);
}
.wide {
grid-column: 1 / -1;
@@ -33,14 +33,3 @@
mat-card-content {
overflow-x: auto;
}
:host .risk-scale { max-width: 740px; margin: 8px 0 14px; }
:host .risk-scale p { margin: 0; }
:host .risk-plot { position: relative; padding-top: 24px; }
:host .risk-line { height: 16px; background: linear-gradient(to right, #42a77e 0 25%, #a8c243 25% 50%, #df8640 50% 75%, #c24269 75% 100%); }
:host .unavailable .risk-line { background: repeating-linear-gradient(to right, #d9dfe2 0, #d9dfe2 calc(25% - 1px), #fff calc(25% - 1px), #fff 25%); }
:host .risk-marker { position: absolute; bottom: -2px; width: 3px; height: 20px; background: #17324d; transform: translateX(-50%); }
:host .risk-value { position: absolute; top: 1px; transform: translateX(-50%); white-space: nowrap; color: #17324d; font-size: 13px; }
:host .risk-labels { display: flex; justify-content: space-between; font-size: 12px; margin-top: 3px; }
.export-actions { display: flex; justify-content: flex-end; margin-bottom: 12px; }
:host .cards, :host .wide { min-width: 0; }
+5 -82
View File
@@ -4,7 +4,6 @@ import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import { RouterLink } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import type {
Condition,
DiagnosticReport,
@@ -14,14 +13,9 @@ import type {
RiskAssessment,
} from 'fhir/r4';
import { code, ext, Fhir, label, resources } from '../fhir';
import { CURP, exactAge, patientLabel, patientName } from '../indicadores/follow-up';
import { CURP } from '../indicadores/follow-up';
import { name } from '../indicadores/measures';
import { Figure, PALETTE, Plot } from '../plot';
import { horizonRisk } from './risk-scale';
import { daysBetween, routeFacts, stages, Stages } from './stages';
import { HttpClient } from '@angular/common/http';
import { downloadDocument } from '../export-document';
import { firstValueFrom } from 'rxjs';
/** An Observation's value as the screens say it, whatever its type. */
function shown(o: Observation): string {
@@ -36,19 +30,12 @@ function shown(o: Observation): string {
* champion models' risks with their curves. Everything read from the FHIR API. */
@Component({
selector: 'app-paciente',
imports: [DecimalPipe, MatButtonModule, MatCardModule, MatIconModule, RouterLink, Plot, Stages],
imports: [DecimalPipe, MatButtonModule, MatCardModule, MatIconModule, RouterLink, Plot],
templateUrl: './paciente.html',
styleUrl: './paciente.scss',
})
export class Paciente {
private readonly route = inject(ActivatedRoute);
protected readonly exactAge = exactAge;
protected readonly cutoff = this.route.snapshot.queryParamMap.get('corte') ?? undefined;
protected readonly sample = this.route.snapshot.queryParamMap.get('muestra') ?? undefined;
private readonly fhir = inject(Fhir);
private readonly http = inject(HttpClient);
protected readonly exporting = signal(false);
protected readonly exportError = signal('');
readonly domain = input.required<string>();
readonly id = input.required<string>();
@@ -57,16 +44,10 @@ export class Paciente {
loader: async ({ params: { domain, id } }) => {
const subject = { subject: `Patient/${id}`, _count: 200 };
const [patient, conditions, procedures, reports, observations, risks] = await Promise.all([
domain === 'cacu' && this.cutoff
? this.fhir.search(domain, 'Patient', {_id:id, 'follow-up-cutoff':this.cutoff}).then(bundle => {
const patient = resources<Patient>(bundle, 'Patient', 'match')[0];
if (!patient) throw new Error('Paciente no encontrada');
return patient;
})
: this.fhir.read<Patient>(domain, 'Patient', id),
this.fhir.read<Patient>(domain, 'Patient', id),
this.fhir.all(domain, 'Condition', subject),
this.fhir.all(domain, 'Procedure', subject),
this.fhir.all(domain, 'DiagnosticReport', { ...subject, 'stage-cutoff': domain === 'cacu' ? this.cutoff : undefined }),
this.fhir.all(domain, 'DiagnosticReport', subject),
this.fhir.all(domain, 'Observation', subject),
this.fhir.all(domain, 'RiskAssessment', subject),
]);
@@ -83,53 +64,6 @@ export class Paciente {
},
});
protected readonly patient = computed(() => this.data.value()?.patient);
protected readonly sampleReportDate = computed(() => {
const d = this.data.value();
const report = d?.reports.find(r => code(r.code) === 'cervical_cytology' && r.effectiveDateTime === this.sample);
const hasResult = (report?.result ?? []).some(ref => {
const observation = d?.observations.get(ref.reference?.split('/')[1] ?? '');
return code(observation?.code) === 'cervical_cytology.result' && !!code(observation?.valueCodeableConcept);
});
return hasResult ? ext(report, 'report-date')?.valueDate : undefined;
});
protected readonly sampleFacts = computed(() => routeFacts(this.data.value()?.reports.find(r => code(r.code) === 'cervical_cytology' && r.effectiveDateTime === this.sample)));
protected async exportPatient(): Promise<void> {
const patient = this.patient(); if (!patient) return;
this.exporting.set(true); this.exportError.set('');
try {
await firstValueFrom(this.http.get('/api/cacu/exports/capabilities'));
const timeline = stages(this.sample, this.sampleReportDate(), this.cutoff, this.sampleFacts());
const entries: string[][] = [
['Identificador', patient.id ?? 'No disponible'],
['Paciente', patientLabel(patient)],
['CURP', this.identity().curp ?? 'No disponible'],
['Expedientes', this.identity().numbers.join(', ') || 'No disponible'],
['Nacimiento', patient.birthDate ?? 'No disponible'],
['Edad al corte', String(exactAge(patient.birthDate,this.cutoff) ?? 'No disponible')],
['Estatus', this.status() || 'No disponible'],
...timeline.map((s,i) => ['Etapa', `${s.label}: ${s.state}${s.provenance ? ' · '+s.provenance : ''}; fecha ${s.date ?? '—'}; desde anterior ${daysBetween(i ? timeline[i-1].date : undefined,s.date) ?? '—'} días; desde toma ${daysBetween(timeline[0].date,s.date) ?? '—'} días`]),
...this.history().map(h => ['Historial', `${h.date} · ${h.kind} · ${h.text}${h.code ? ' ('+h.code+')' : ''}`]),
...this.tests().map(t => ['Pruebas', `${t.date} · ${t.kind} · ${t.reported ?? 'Pendiente'} · ${t.results.join(' · ') || '—'}`]),
];
const lastStage = timeline.map(s => s.date).filter((d): d is string => !!d).sort().at(-1);
if (lastStage) entries.splice(7 + timeline.length, 0, ['Etapas', `Tiempo transcurrido desde el último evento mostrado: ${daysBetween(lastStage,this.cutoff) ?? '—'} días (incluye asociaciones inferidas)`]);
const risk = this.riskScales();
if (!risk.length) entries.push(['Riesgo', 'Inmediato: No disponible · 5 años: No disponible']);
for (const r of risk) for (const [label, value] of [['Inmediato',r.immediate],['5 años',r.five]] as const)
entries.push(['Riesgo', `${r.outcome} · ${r.model} · ${label}: ${value ? (value.value*100).toFixed(2)+' %' : 'No disponible'}${value?.low !== undefined && value.high !== undefined ? ' · IC 95 % '+(value.low*100).toFixed(2)+'–'+(value.high*100).toFixed(2)+' %' : ''}`]);
const pct2 = (n: number) => (n*100).toFixed(2)+' %';
const scale = (r: (typeof risk)[number], label: string, v: (typeof risk)[number]['immediate']) => ({label:`${r.outcome} · ${r.model} · ${label}: ${v ? pct2(v.value) : 'No disponible'}`, outcome:r.outcome, model:r.model, horizon:label,
...(v ? {value:v.value, ...(v.low !== undefined && v.high !== undefined ? {low:v.low, high:v.high} : {})} : {})});
const scales = risk.length ? risk.flatMap(r => [scale(r,'Inmediato',r.immediate), scale(r,'5 años',r.five)]) : [{label:'Riesgo inmediato: No disponible'}, {label:'Riesgo a 5 años: No disponible'}];
const interval = (d?: number, inferred?: boolean) => d === undefined ? '—' : `${d} días${inferred ? ' (inferido)' : ''}`;
const isInferred = (x?: {provenance?: string}) => x?.provenance === 'Inferida temporalmente';
const route = timeline.map((s,i) => ({state:s.state, label:s.label, ...(s.provenance ? {provenance:s.provenance} : {}), ...(s.date ? {date:s.date} : {}),
prev: interval(daysBetween(i ? timeline[i-1].date : undefined, s.date), isInferred(s) || (i > 0 && isInferred(timeline[i-1]))),
start: interval(daysBetween(timeline[0].date, s.date), isInferred(s))}));
await downloadDocument(this.http,'pdf',{title:'Ficha individual',parameters:[['Corte (edad, estatus y etapas)',this.cutoff ?? 'No disponible'],['Historial y riesgos','Información longitudinal disponible; no filtrada por corte histórico']],columns:['Sección','Información'],rows:entries,timeline:route,risk_scales:scales});
} catch (error) { this.exportError.set(error instanceof Error ? `No se pudo generar la ficha PDF: ${error.message}` : 'No se pudo generar la ficha PDF.'); }
finally { this.exporting.set(false); }
}
protected readonly error = computed(() => this.data.error());
protected readonly loading = computed(() => this.data.isLoading());
protected readonly history = computed(() => {
@@ -189,17 +123,6 @@ export class Paciente {
})),
}));
});
protected readonly riskScales = computed(() => {
const latest = new Map<string, RiskAssessment>();
for (const risk of this.data.value()?.risks ?? []) {
const key = code(risk.method) ?? '';
if (!key.startsWith('cacu.cin2') && !key.startsWith('cacu.cancer')) continue;
if (!latest.has(key) || (latest.get(key)!.occurrenceDateTime ?? '') < (risk.occurrenceDateTime ?? '')) latest.set(key, risk);
}
return [...latest.entries()].map(([model, risk]) => ({model, index: risk.occurrenceDateTime,
outcome: model.startsWith('cacu.cin2') ? 'CIN2+' : 'Cáncer',
immediate: horizonRisk(risk, 0), five: horizonRisk(risk, 5)}));
});
protected readonly shown = signal<string | undefined>(undefined);
protected readonly curve = computed<Figure>(() => {
const models = this.models().filter((m) => m.predictions.length > 1);
@@ -253,7 +176,7 @@ export class Paciente {
protected readonly identity = computed(() => {
const p = this.patient();
return {
name: patientName(p),
name: p?.name?.[0]?.text,
curp: p?.identifier?.find((i) => i.system === CURP)?.value,
numbers: (p?.identifier ?? []).filter((i) => i.system !== CURP).map((i) => i.value),
};
-14
View File
@@ -1,14 +0,0 @@
import type { RiskAssessment } from 'fhir/r4';
/** Only an explicitly published horizon is eligible; zero remains a real value. */
export function horizonRisk(risk: RiskAssessment, years: number) {
const p = (risk.prediction ?? []).find(x => x.whenRange?.high?.value === years &&
x.whenRange.high.code === 'a' && x.probabilityDecimal !== undefined &&
x.probabilityDecimal >= 0 && x.probabilityDecimal <= 1);
if (!p) return undefined;
const value = p.probabilityDecimal!;
const get = (suffix: string) => p.extension?.find(e => e.url.endsWith('/' + suffix))?.valueDecimal;
const low = get('ic-bajo'), high = get('ic-alto');
return {value, low: low !== undefined && low >= 0 && low <= 1 ? low : undefined,
high: high !== undefined && high >= 0 && high <= 1 ? high : undefined};
}
-29
View File
@@ -1,29 +0,0 @@
import '@angular/compiler';
import { describe, expect, it } from 'vitest';
import type { RiskAssessment } from 'fhir/r4';
import { stages, daysBetween } from './stages';
import { horizonRisk } from './risk-scale';
describe('stages and explicit risk horizons', () => {
it('keeps zero day intervals and does not fill later stages', () => {
const s = stages('2026-01-01', '2026-01-01', '2026-02-01');
expect(daysBetween(s[0].date, s[1].date)).toBe(0);
expect(s.slice(2).every(x => x.date === undefined)).toBe(true);
expect(stages('2026-01-01', '2027-01-01', '2026-02-01')[1].date).toBeUndefined();
});
it('distinguishes inferred, structured, pending and ambiguous stages', () => {
const a = stages('2026-01-01', undefined, '2026-02-01', {
colposcopy: {state:'inferred',date:'2026-01-03'}, biopsy:{state:'pending'}, diagnosis:{state:'ambiguous'} });
expect(a.map(x => x.state)).toEqual(['Registrada','Desconocida','Registrada','Pendiente','Ambigua']);
expect(a[2].provenance).toBe('Inferida temporalmente');
expect(stages('2026-01-01',undefined,'2026-02-01',{biopsy:{state:'structured',date:'2026-01-04'}})[3].provenance).toBe('Vínculo estructurado');
});
it('uses only a published horizon and preserves zero', () => {
const r: RiskAssessment = {resourceType:'RiskAssessment', status:'final', subject:{},
prediction:[{probabilityDecimal:0,whenRange:{high:{value:0,code:'a'}}},
{probabilityDecimal:0.2,whenRange:{high:{value:3,code:'a'}}}]};
expect(horizonRisk(r,0)?.value).toBe(0);
expect(horizonRisk(r,5)).toBeUndefined();
expect(horizonRisk({...r,prediction:[]},0)).toBeUndefined();
});
});
-44
View File
@@ -1,44 +0,0 @@
import { Component, computed, input } from '@angular/core';
import type { DiagnosticReport } from 'fhir/r4';
import { ext } from '../fhir';
export type StageFact = {state?: string; date?: string};
export type StageFacts = Record<string, StageFact>;
export function routeFacts(report?: DiagnosticReport): StageFacts {
return Object.fromEntries(['colposcopy','biopsy','diagnosis'].map(k => [k, {state: ext(report, `stage-${k}-state`)?.valueCode, date: ext(report, `stage-${k}-date`)?.valueDate}]));
}
export function stages(sample?: string, report?: string, cutoff?: string, facts: StageFacts = {}) {
const valid = (d?: string) => !!d && !!cutoff && /^\d{4}-\d{2}-\d{2}$/.test(d) && d <= cutoff;
const start = valid(sample) ? sample : undefined;
const result = start && valid(report) && report! >= start ? report : undefined;
const later = (label: string, key: string) => {
const f = facts[key];
const state = f?.state === 'pending' ? 'Pendiente' : f?.state === 'ambiguous' ? 'Ambigua' :
(f?.state === 'inferred' || f?.state === 'structured') && valid(f.date) && start && f.date! >= start ? 'Registrada' : 'Desconocida';
return {label, date: state === 'Registrada' ? f.date : undefined, state, provenance: state === 'Registrada' ? (f.state === 'inferred' ? 'Inferida temporalmente' : 'Vínculo estructurado') : undefined};
};
return [{label:'Toma de muestra',date:start,state:start?'Registrada':'Desconocida',provenance:undefined}, {label:'Resultado de citología',date:result,state:result?'Registrada':'Desconocida',provenance:undefined}, later('Colposcopia','colposcopy'),later('Reporte de biopsia','biopsy'),later('Diagnóstico','diagnosis')];
}
export function daysBetween(a?: string,b?: string): number | undefined {
if (!a || !b) return undefined;
const x=Date.parse(a+'T00:00:00Z'), y=Date.parse(b+'T00:00:00Z');
return Number.isFinite(x) && Number.isFinite(y) && y >= x ? (y-x)/86400000 : undefined;
}
@Component({selector:'app-stages', template: `
<div class="stage-line" [class.detailed]="detail()" [attr.aria-label]="summary()">
@for (s of items(); track s.label; let i = $index) {
<div class="stage"><span class="node" [class.registered]="s.state === 'Registrada'" [class.inferred]="s.provenance === 'Inferida temporalmente'" [class.pending]="s.state === 'Pendiente'" [class.ambiguous]="s.state === 'Ambigua'" [attr.title]="s.label + ': ' + s.state + (s.provenance ? ' · ' + s.provenance : '')"></span>
@if (detail()) { <div class="stage-detail"><strong>{{ s.label }}</strong><span>{{ s.state }}{{ s.provenance ? ' · ' + s.provenance : '' }}</span><span>{{ s.date ?? 'Sin fecha' }}</span><span class="interval">Desde anterior: {{ days(i ? items()[i-1].date : undefined, s.date) ?? '—' }}{{ i && days(items()[i-1].date, s.date) !== undefined && (s.provenance === 'Inferida temporalmente' || items()[i-1].provenance === 'Inferida temporalmente') ? ' días (inferido)' : (days(i ? items()[i-1].date : undefined, s.date) !== undefined ? ' días' : '') }}</span><span class="interval">Desde toma: {{ days(items()[0].date, s.date) ?? '—' }}{{ days(items()[0].date, s.date) !== undefined && s.provenance === 'Inferida temporalmente' ? ' días (inferido)' : (days(items()[0].date, s.date) !== undefined ? ' días' : '') }}</span></div> }
</div>
}
</div>
`, styles: `:host{display:block;min-width:150px}.stage-line{display:flex;align-items:flex-start}.stage{position:relative;flex:0 0 37px}.stage:not(:last-child)::after{content:'';position:absolute;top:9px;left:20px;right:0;border-top:1px solid #667b8a}.node{display:block;width:18px;height:18px;box-sizing:border-box;border:2px dashed #667b8a;border-radius:50%;background:white;position:relative;z-index:1}.registered{background:#387b66;border-style:solid}.inferred{background:#4269a0;border-style:double}.pending{background:#fff1c9;border-style:solid}.ambiguous{border-style:double;border-color:#a84460}.stage:last-child{flex-basis:18px}.detailed{background:#fff;border:1px solid #dce3e7;border-radius:8px;padding:18px 12px}.detailed .stage,.detailed .stage:last-child{flex:1;min-width:0;text-align:center}.detailed .node{margin:0 auto}.detailed .stage:not(:last-child)::after{left:calc(50% + 9px);right:calc(-50% + 9px)}.stage-detail{display:flex;flex-direction:column;gap:3px;padding:8px 4px 0;font-size:12px;color:#60717d;overflow-wrap:anywhere}.stage-detail strong{color:#243d4b}.interval{font-weight:600;color:#365b69}@media(max-width:700px){.detailed{display:block}.detailed .stage{display:flex;gap:12px;padding-bottom:10px}.detailed .stage::after{top:18px;left:9px;bottom:0;right:auto;border-top:0;border-left:1px solid #667b8a}.detailed .node{margin:0}.detailed .stage{text-align:left}.stage-detail{padding:0}.node{flex:none}}`})
export class Stages {
readonly sample = input<string>(); readonly report = input<string>(); readonly cutoff = input<string>(); readonly detail = input(false);
readonly facts = input<StageFacts>({});
protected readonly items = computed(() => stages(this.sample(),this.report(),this.cutoff(),this.facts()));
protected readonly summary = computed(() => this.items().map(x=>x.label+': '+x.state+(x.provenance?' · '+x.provenance:'')).join('; '));
protected readonly lastDate = computed(() => this.items().map(x=>x.date).filter((x):x is string=>!!x).sort().at(-1));
protected readonly days = daysBetween;
}