diff --git a/e2e/ficha-cacu.spec.ts b/e2e/ficha-cacu.spec.ts index e1f8de0..1969bbd 100644 --- a/e2e/ficha-cacu.spec.ts +++ b/e2e/ficha-cacu.spec.ts @@ -1015,8 +1015,8 @@ test('curvas (simulado): one series per model at its published horizons, its ban // ---- the grouped NCI comparison, the survival texts and the risk-model selection (all "simulado") ------ const SHOTS = process.env['SHOTS_DIR']; // when set, the simulated pages are saved for the report -const shot = async (page: Page, name: string) => { - if (SHOTS) await page.screenshot({ path: `${SHOTS}/SIMULADO-${name}.png`, fullPage: true }); +const shot = async (page: Page, name: string, kind = 'SIMULADO') => { + if (SHOTS) await page.screenshot({ path: `${SHOTS}/${kind}-${name}.png`, fullPage: true }); }; const institutional = (p: number, low?: number, high?: number, diff?: number) => [ part('institutional', { valueDecimal: p }), @@ -1385,3 +1385,263 @@ test('escalas (simulado): with a survival model and compatible risk models, only await expect(page.locator('[data-section=referencia-nci]')).toBeVisible(); await shot(page, 'escalas-supervivencia-y-riesgo-1440'); }); + +// ---- "Elegibilidad por escenario clínico": the decisions the backend publishes per indexed visit ---- + +const ELIGIBILITY = '**/api/cacu/fhir/Patient/*/$eligibility*'; +const SCENARIO_SYSTEM = 'https://isssteleon.org/fhir/CodeSystem/cacu-eligibility-scenario'; +const CRITERION_SYSTEM = 'https://isssteleon.org/fhir/CodeSystem/cacu-exclusion-criterion'; +const eligibilityBox = (page: Page) => page.locator('[data-section=elegibilidad]'); +const visit = ( + scenario: string, + date: string, + eligible: boolean, + criteria: string[] = [], + sample?: string, +) => + part('candidate', { + part: [ + part('scenario', { valueCoding: { system: SCENARIO_SYSTEM, code: scenario } }), + part('index-date', { valueDate: date }), + ...(sample ? [part('index-sample-id', { valueString: sample })] : []), + part('eligible', { valueBoolean: eligible }), + ...criteria.map((c) => + part('criterion', { valueCoding: { system: CRITERION_SYSTEM, code: c } }), + ), + ], + }); +const eligibilityAnswer = (status: string, ...candidates: object[]) => + answerOf( + part('status', { valueCode: status }), + part('patient', { valueReference: { reference: 'Patient/x' } }), + part('cutoff', { valueDate: '2026-12-02' }), + ...candidates, + ); +const eligibilityIs = (page: Page, body: object, status = 200) => + page.route(ELIGIBILITY, (route) => + route.fulfill({ status, contentType: 'application/fhir+json', body: JSON.stringify(body) }), + ); + +test('elegibilidad: the real answer of the backend is shown scenario by scenario, with every reason', async ({ + page, +}) => { + const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=200')).json(); + let found: { id: string; body: any } | undefined; + for (const { resource } of patients.entry) { + const body = await ( + await page.request.get(`/api/cacu/fhir/Patient/${resource.id}/$eligibility`) + ).json(); + const many = body.parameter.some( + (p: any) => + p.name === 'candidate' && p.part.filter((x: any) => x.name === 'criterion').length > 1, + ); + if (many) { + found = { id: resource.id, body }; + break; + } + } + expect(found, 'a synthetic patient with several reasons in one visit').toBeTruthy(); + await open(page, `/indicadores/cacu/pacientes/${found!.id}`); + const box = eligibilityBox(page); + await expect(box.locator('mat-card-title')).toHaveText('Elegibilidad por escenario clínico'); + const candidates = found!.body.parameter.filter((p: any) => p.name === 'candidate'); + const scenarios = new Set( + candidates.map((c: any) => c.part.find((x: any) => x.name === 'scenario').valueCoding.code), + ); + await expect(box.locator('details.scenario')).toHaveCount(scenarios.size); + await expect(box.locator('li.visit')).toHaveCount(candidates.length); + const reasons = candidates.flatMap((c: any) => c.part.filter((x: any) => x.name === 'criterion')); + await expect(box.locator('ul.why li')).toHaveCount(reasons.length); // none is dropped or merged + await expect(box).toContainText('Antecedente de cáncer cervicouterino'); + await shot(page, 'elegibilidad', 'SINTETICO-REAL'); +}); + +for (const width of [1440, 480]) { + test(`elegibilidad (simulado) at ${width} px: several scenarios and visits, eligible and not, several reasons each`, async ({ + page, + }) => { + await page.setViewportSize({ width, height: 1000 }); + const { url } = await firstRecord(page); + await eligibilityIs( + page, + eligibilityAnswer( + 'evaluated', + visit('surveillance', '2024-01-05', true, [], 'm-1'), + visit('surveillance', '2025-03-01', false, ['no_index_result', 'prior_outcome'], 'm-2'), + visit('surveillance', '2025-09-10', true, [], 'm-3'), + visit( + 'post_colposcopy', + '2023-06-01', + false, + ['cancer_history', 'outcome_by_index', 'prior_treatment', 'no_referral'], + '2023-06-01', + ), + visit('survival', '2024-12-01', true), + visit('nuevo_escenario', '2025-01-01', false, ['regla_nueva']), + ), + ); + await open(page, url); + const box = eligibilityBox(page); + const groups = box.locator('details.scenario'); + await expect(groups).toHaveCount(4); + await expect(groups.nth(1)).toContainText('Postcolposcopia'); // the backend's order is kept + await expect(groups.nth(1)).toContainText('1 visita · 0 elegibles, 1 no elegible'); + // a scenario with more than two visits is collapsed but keeps every detail in the page + const surveillance = box.locator('[data-scenario=surveillance]'); + await expect(surveillance).toContainText('3 visitas · 2 elegibles, 1 no elegible'); + expect(await surveillance.getAttribute('open')).toBeNull(); + await surveillance.locator('summary').click(); + const visits = surveillance.locator('li.visit'); + await expect(visits).toHaveCount(3); + await expect(visits.first()).toContainText('Fecha índice 2025-09-10'); + await expect(visits.first()).toContainText('Elegible'); + await expect(visits.nth(1)).toContainText('No elegible'); + await expect(visits.nth(1)).toContainText('Muestra m-2'); + await expect(visits.nth(1).locator('ul.why li')).toHaveText([ + 'Sin resultado de citología o VPH en la visita índice', + 'Resultado CIN2+ previo al índice', + ]); + // all four reasons of one visit; decisions of different visits are never combined + await expect(box.locator('[data-scenario=post_colposcopy] ul.why li')).toHaveCount(4); + await expect(visits.first().locator('ul.why')).toHaveCount(0); + await expect(box.locator('[data-scenario=survival]')).toContainText('Sin muestra asociada'); + // an unknown scenario and criterion show their code and keep it + await expect(box.locator('[data-scenario=nuevo_escenario] summary')).toContainText( + 'nuevo_escenario', + ); + await expect( + box.locator('[data-scenario=nuevo_escenario] li[data-code=regla_nueva]'), + ).toHaveText('regla_nueva'); + await box.locator('[data-scenario=nuevo_escenario] summary').click(); + await page.waitForTimeout(500); + expect(await layoutProblems(page)).toEqual([]); + expect( + await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1), + ).toBe(true); + await shot(page, `elegibilidad-varios-escenarios-${width}`); + }); +} + +const STATES: [string, () => object | undefined, number, string, string][] = [ + ['sin candidatos', () => eligibilityAnswer('no_candidate'), 200, 'none', 'Sin candidatos'], + [ + 'información no disponible (404)', + () => ({ resourceType: 'OperationOutcome', issue: [{ severity: 'error', code: 'not-found' }] }), + 404, + 'unavailable', + 'no disponible', + ], + [ + 'respuesta fuera del contrato', + () => ({ resourceType: 'Parameters', parameter: [] }), + 200, + 'unavailable', + 'no disponible', + ], + [ + 'actualización de gold requerida (409)', + () => ({ + resourceType: 'OperationOutcome', + issue: [ + { + severity: 'error', + code: 'conflict', + diagnostics: 'CaCu eligibility gold is not materialized; rebuild gold.cacu_eligibility.', + }, + ], + }), + 409, + 'gold', + 'actualizar la capa gold', + ], + [ + 'error del servidor (500)', + () => ({ resourceType: 'OperationOutcome', issue: [{ severity: 'error', code: 'exception' }] }), + 500, + 'error', + 'No se pudo consultar', + ], +]; +for (const [name, body, status, state, text] of STATES) { + test(`elegibilidad (simulado): ${name} has its own state and never reads as eligible`, async ({ + page, + }) => { + const { url } = await firstRecord(page); + await eligibilityIs(page, body()!, status); + await open(page, url); + const box = eligibilityBox(page); + await expect(box.locator(`[data-state=${state}]`)).toContainText(text); + await expect(box.locator('li.visit')).toHaveCount(0); + await expect(box).not.toContainText('Elegible'); + if (state === 'gold') await expect(box).toContainText('rebuild gold.cacu_eligibility'); + await shot(page, `elegibilidad-${state}`); + }); +} + +test('elegibilidad (simulado): no connection is a communication error', async ({ page }) => { + const { url } = await firstRecord(page); + await page.route(ELIGIBILITY, (route) => route.abort()); + await open(page, url); + await expect(eligibilityBox(page).locator('[data-state=error]')).toContainText( + 'No se pudo consultar', + ); +}); + +test('elegibilidad (simulado): the section waits for the answer and a new patient starts from nothing', async ({ + page, +}) => { + await page.goto('/indicadores/cacu'); + await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); + const links = page.locator('table.worklist tbody tr a'); + await links.first().waitFor({ timeout: 120_000 }); + const hrefs = await links.evaluateAll((els) => + els.slice(0, 2).map((e) => e.getAttribute('href')!), + ); + expect(hrefs.length).toBe(2); + const ids = hrefs.map((h) => /pacientes\/([^?]+)/.exec(h)![1]); + let releaseSecond!: () => void; + const gate = new Promise((resolve) => (releaseSecond = resolve)); + await page.route(ELIGIBILITY, async (route) => { + const mine = route.request().url().includes(ids[0]); + if (!mine) await gate; // the second patient's answer is held + await route.fulfill({ + contentType: 'application/fhir+json', + body: JSON.stringify( + mine + ? eligibilityAnswer( + 'evaluated', + visit('surveillance', '2024-01-05', false, ['prior_outcome'], 'primera'), + ) + : eligibilityAnswer( + 'evaluated', + visit('post_treatment', '2025-05-05', true, [], 'segunda'), + ), + ), + }); + }); + await open(page, hrefs[0]); + await expect(eligibilityBox(page)).toContainText('primera'); + await page.getByRole('link', { name: 'Regresar' }).click(); + await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); + await page.locator(`a[href*="${ids[1]}"]`).first().click(); + await expect(historial(page)).toBeVisible({ timeout: 120_000 }); + await expect(eligibilityBox(page).locator('[data-state=loading]')).toBeVisible(); + await expect(eligibilityBox(page)).not.toContainText('primera'); // nothing of the previous patient + releaseSecond(); + await expect(eligibilityBox(page)).toContainText('segunda'); + await expect(eligibilityBox(page)).not.toContainText('primera'); +}); + +test('elegibilidad: CaMa has no such section and never asks for it', async ({ page }) => { + let asked = false; + await page.route('**/$eligibility*', (route) => { + asked = true; + return route.abort(); + }); + const patients = await (await page.request.get('/api/cama/fhir/Patient?_count=1')).json(); + await page.goto(`/indicadores/cama/pacientes/${patients.entry[0].resource.id}`); + await expect(page.locator('app-paciente')).toBeVisible({ timeout: 120_000 }); + await expect(page.locator('app-loading')).toHaveCount(0, { timeout: 60_000 }); + await expect(page.locator('[data-section=elegibilidad]')).toHaveCount(0); + expect(asked).toBe(false); +}); diff --git a/openapi.json b/openapi.json index 07d6fef..0c55307 100644 --- a/openapi.json +++ b/openapi.json @@ -292,6 +292,7 @@ "default": "identity", "enum": [ "identity", + "cacu_eligibility_evidence", "cervical_cytology", "cervical_biopsy", "mammography", @@ -443,6 +444,7 @@ "description": "Qu\u00e9 estudio se saca del documento.", "enum": [ "identity", + "cacu_eligibility_evidence", "cervical_cytology", "cervical_biopsy", "mammography", @@ -465,6 +467,10 @@ "label": "Identidad de la persona", "value": "identity" }, + { + "label": "Evidencia cl\u00ednica para elegibilidad CaCu", + "value": "cacu_eligibility_evidence" + }, { "label": "Citolog\u00eda cervical", "value": "cervical_cytology" @@ -641,6 +647,7 @@ "entity": { "enum": [ "identity", + "cacu_eligibility_evidence", "cervical_cytology", "cervical_biopsy", "mammography", @@ -663,6 +670,10 @@ "label": "Identidad de la persona", "value": "identity" }, + { + "label": "Evidencia cl\u00ednica para elegibilidad CaCu", + "value": "cacu_eligibility_evidence" + }, { "label": "Citolog\u00eda cervical", "value": "cervical_cytology" @@ -1530,6 +1541,7 @@ "entity": { "enum": [ "identity", + "cacu_eligibility_evidence", "cervical_cytology", "cervical_biopsy", "mammography", @@ -2117,6 +2129,7 @@ "description": "En qu\u00e9 estudio de la plataforma se guarda.", "enum": [ "identity", + "cacu_eligibility_evidence", "cervical_cytology", "cervical_biopsy", "mammography", @@ -2139,6 +2152,10 @@ "label": "Identidad de la persona", "value": "identity" }, + { + "label": "Evidencia cl\u00ednica para elegibilidad CaCu", + "value": "cacu_eligibility_evidence" + }, { "label": "Citolog\u00eda cervical", "value": "cervical_cytology" @@ -4056,6 +4073,7 @@ "schema": { "enum": [ "identity", + "cacu_eligibility_evidence", "cervical_cytology", "cervical_biopsy", "mammography", @@ -4164,6 +4182,7 @@ "schema": { "enum": [ "identity", + "cacu_eligibility_evidence", "cervical_cytology", "cervical_biopsy", "mammography", @@ -5907,6 +5926,272 @@ ] } }, + "/{domain}/fhir/Patient/{id}/$eligibility": { + "get": { + "description": "The normalized cohort eligibility and exclusion reasons for one CaCu patient.", + "operationId": "cacu_eligibility", + "parameters": [ + { + "in": "path", + "name": "domain", + "required": true, + "schema": { + "$ref": "#/components/schemas/Domain" + } + }, + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "title": "Id", + "type": "string" + } + }, + { + "description": "Limit the report to one CaCu scenario", + "in": "query", + "name": "scenario", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Limit the report to one CaCu scenario", + "title": "Scenario" + } + }, + { + "description": "Only index dates up to this day", + "in": "query", + "name": "cutoff", + "required": false, + "schema": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Only index dates up to this day", + "title": "Cutoff" + } + } + ], + "responses": { + "200": { + "content": { + "application/fhir+json": { + "schema": { + "type": "object" + } + } + }, + "description": "FHIR" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Cacu Eligibility", + "tags": [ + "fhir" + ] + } + }, + "/{domain}/fhir/Patient/{id}/$reference-risk": { + "get": { + "description": "EXPERIMENTAL, off unless CACU_NCI_REFERENCE=1. The NCI/ASCCP CIN3+ reference risk of one\npatient's cytology by a cut-off, how it was resolved and, beside it, the institutional models'\nrisks when they measure the same thing. Research only: not validated, not a recommendation.", + "operationId": "reference_risk", + "parameters": [ + { + "in": "path", + "name": "domain", + "required": true, + "schema": { + "$ref": "#/components/schemas/Domain" + } + }, + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "title": "Id", + "type": "string" + } + }, + { + "description": "Only what was reported by this day", + "in": "query", + "name": "cutoff", + "required": false, + "schema": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Only what was reported by this day", + "title": "Cutoff" + } + }, + { + "description": "The cytology's sample day", + "in": "query", + "name": "sample", + "required": false, + "schema": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The cytology's sample day", + "title": "Sample" + } + } + ], + "responses": { + "200": { + "content": { + "application/fhir+json": { + "schema": { + "type": "object" + } + } + }, + "description": "FHIR" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Reference Risk", + "tags": [ + "fhir" + ] + } + }, + "/{domain}/fhir/Patient/{id}/$risk-series": { + "get": { + "description": "EXPERIMENTAL, off unless CACU_NCI_REFERENCE=1. The risk series her record can choose to\ndraw: institutional models and NCI tables, by outcome, with the published intervals.", + "operationId": "cacu_risk_series", + "parameters": [ + { + "in": "path", + "name": "domain", + "required": true, + "schema": { + "$ref": "#/components/schemas/Domain" + } + }, + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "title": "Id", + "type": "string" + } + }, + { + "description": "Only what was reported by this day", + "in": "query", + "name": "cutoff", + "required": false, + "schema": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Only what was reported by this day", + "title": "Cutoff" + } + }, + { + "description": "The cytology's sample day", + "in": "query", + "name": "sample", + "required": false, + "schema": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The cytology's sample day", + "title": "Sample" + } + } + ], + "responses": { + "200": { + "content": { + "application/fhir+json": { + "schema": { + "type": "object" + } + } + }, + "description": "FHIR" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Cacu Risk Series", + "tags": [ + "fhir" + ] + } + }, "/{domain}/fhir/Procedure": { "get": { "description": "The procedures the domain's timeline infers (CaCu: colposcopies and treatments;\nCaMa: each treatment, by its kind).", diff --git a/src/app/api/fn/fhir/cacu-eligibility.ts b/src/app/api/fn/fhir/cacu-eligibility.ts new file mode 100644 index 0000000..5b744fe --- /dev/null +++ b/src/app/api/fn/fhir/cacu-eligibility.ts @@ -0,0 +1,48 @@ +/* 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 CacuEligibility$Params { + domain: Domain; + id: string; + +/** + * Limit the report to one CaCu scenario + */ + scenario?: (string | null); + +/** + * Only index dates up to this day + */ + cutoff?: (string | null); +} + +export function cacuEligibility(http: HttpClient, rootUrl: string, params: CacuEligibility$Params, context?: HttpContext): Observable> { + const rb = new RequestBuilder(rootUrl, cacuEligibility.PATH, 'get'); + if (params) { + rb.path('domain', params.domain, {}); + rb.path('id', params.id, {}); + rb.query('scenario', params.scenario, {}); + rb.query('cutoff', params.cutoff, {}); + } + + return http.request( + rb.build({ responseType: 'json', accept: 'application/fhir+json', context }) + ).pipe( + filter((r: any): r is HttpResponse => r instanceof HttpResponse), + map((r: HttpResponse) => { + return r as StrictHttpResponse<{ + }>; + }) + ); +} + +cacuEligibility.PATH = '/{domain}/fhir/Patient/{id}/$eligibility'; diff --git a/src/app/api/fn/fhir/cacu-risk-series.ts b/src/app/api/fn/fhir/cacu-risk-series.ts new file mode 100644 index 0000000..93846ed --- /dev/null +++ b/src/app/api/fn/fhir/cacu-risk-series.ts @@ -0,0 +1,48 @@ +/* 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 CacuRiskSeries$Params { + domain: Domain; + id: string; + +/** + * Only what was reported by this day + */ + cutoff?: (string | null); + +/** + * The cytology's sample day + */ + sample?: (string | null); +} + +export function cacuRiskSeries(http: HttpClient, rootUrl: string, params: CacuRiskSeries$Params, context?: HttpContext): Observable> { + const rb = new RequestBuilder(rootUrl, cacuRiskSeries.PATH, 'get'); + if (params) { + rb.path('domain', params.domain, {}); + rb.path('id', params.id, {}); + rb.query('cutoff', params.cutoff, {}); + rb.query('sample', params.sample, {}); + } + + return http.request( + rb.build({ responseType: 'json', accept: 'application/fhir+json', context }) + ).pipe( + filter((r: any): r is HttpResponse => r instanceof HttpResponse), + map((r: HttpResponse) => { + return r as StrictHttpResponse<{ + }>; + }) + ); +} + +cacuRiskSeries.PATH = '/{domain}/fhir/Patient/{id}/$risk-series'; diff --git a/src/app/api/fn/fhir/reference-risk.ts b/src/app/api/fn/fhir/reference-risk.ts new file mode 100644 index 0000000..08f9935 --- /dev/null +++ b/src/app/api/fn/fhir/reference-risk.ts @@ -0,0 +1,48 @@ +/* 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 ReferenceRisk$Params { + domain: Domain; + id: string; + +/** + * Only what was reported by this day + */ + cutoff?: (string | null); + +/** + * The cytology's sample day + */ + sample?: (string | null); +} + +export function referenceRisk(http: HttpClient, rootUrl: string, params: ReferenceRisk$Params, context?: HttpContext): Observable> { + const rb = new RequestBuilder(rootUrl, referenceRisk.PATH, 'get'); + if (params) { + rb.path('domain', params.domain, {}); + rb.path('id', params.id, {}); + rb.query('cutoff', params.cutoff, {}); + rb.query('sample', params.sample, {}); + } + + return http.request( + rb.build({ responseType: 'json', accept: 'application/fhir+json', context }) + ).pipe( + filter((r: any): r is HttpResponse => r instanceof HttpResponse), + map((r: HttpResponse) => { + return r as StrictHttpResponse<{ + }>; + }) + ); +} + +referenceRisk.PATH = '/{domain}/fhir/Patient/{id}/$reference-risk'; diff --git a/src/app/api/fn/review/conflicts.ts b/src/app/api/fn/review/conflicts.ts index db06c9b..1e28c7c 100644 --- a/src/app/api/fn/review/conflicts.ts +++ b/src/app/api/fn/review/conflicts.ts @@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder'; export interface Conflicts$Params { - entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; + entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; } export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable; kind?: 'fhir'; diff --git a/src/app/api/models/rejection.ts b/src/app/api/models/rejection.ts index d71f3f5..8152278 100644 --- a/src/app/api/models/rejection.ts +++ b/src/app/api/models/rejection.ts @@ -2,7 +2,7 @@ /* Code generated by ng-openapi-gen DO NOT EDIT. */ export interface Rejection { - entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; + entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; reason: string; record: string; } diff --git a/src/app/api/models/target.ts b/src/app/api/models/target.ts index d06856c..4decb86 100644 --- a/src/app/api/models/target.ts +++ b/src/app/api/models/target.ts @@ -12,7 +12,7 @@ export interface Target { /** * En qué estudio de la plataforma se guarda. */ - entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; + entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; id: string; inputs?: Array; kind?: 'target'; diff --git a/src/app/paciente/eligibility.spec.ts b/src/app/paciente/eligibility.spec.ts new file mode 100644 index 0000000..a4b5971 --- /dev/null +++ b/src/app/paciente/eligibility.spec.ts @@ -0,0 +1,130 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import type { Parameters } from 'fhir/r4'; +import { eligibilityFailure, eligibilityView } from './eligibility'; + +const part = (name: string, extra: object) => ({ name, ...extra }) as any; +const SCENARIOS = 'https://isssteleon.org/fhir/CodeSystem/cacu-eligibility-scenario'; +const CRITERIA = 'https://isssteleon.org/fhir/CodeSystem/cacu-exclusion-criterion'; +const candidate = ( + scenario: string, + date: string, + eligible: boolean, + criteria: string[] = [], + sample?: string, + display?: string, +) => + part('candidate', { + part: [ + part('scenario', { valueCoding: { system: SCENARIOS, code: scenario, display } }), + part('index-date', { valueDate: date }), + ...(sample ? [part('index-sample-id', { valueString: sample })] : []), + part('eligible', { valueBoolean: eligible }), + ...criteria.map((c) => part('criterion', { valueCoding: { system: CRITERIA, code: c } })), + ], + }); +const answer = (status: string, ...candidates: object[]): Parameters => + ({ + resourceType: 'Parameters', + parameter: [ + part('status', { valueCode: status }), + part('patient', { valueReference: { reference: 'Patient/p' } }), + part('cutoff', { valueDate: '2026-12-02' }), + ...candidates, + ], + }) as Parameters; + +// Each test fails if the section merged visits, dropped a reason or read silence as eligibility. +describe('the eligibility answer as the section shows it', () => { + it('groups by scenario, keeps each visit apart, with its own decision and all its reasons', () => { + const view = eligibilityView( + answer( + 'evaluated', + candidate( + 'post_colposcopy', + '2020-08-10', + false, + ['cancer_history', 'outcome_by_index', 'prior_treatment'], + '2020-08-10', + ), + candidate('surveillance', '2024-01-05', true, [], 'a'), + candidate('surveillance', '2025-03-01', false, ['no_index_result'], 'b'), + candidate('post_colposcopy', '2022-02-02', true, [], '2022-02-02'), + ), + ); + if (view.kind !== 'evaluated') throw new Error(view.kind); + expect(view.cutoff).toBe('2026-12-02'); + expect(view.groups.map((g) => [g.code, g.text, g.visits.length])).toEqual([ + ['post_colposcopy', 'Postcolposcopia', 2], + ['surveillance', 'Vigilancia', 2], + ]); + const post = view.groups[0].visits; // newest visit first + expect(post.map((v) => [v.indexDate, v.eligible, v.reasons.map((r) => r.code)])).toEqual([ + ['2022-02-02', true, []], + ['2020-08-10', false, ['cancer_history', 'outcome_by_index', 'prior_treatment']], + ]); + expect(post[1].reasons[0].text).toBe('Antecedente de cáncer cervicouterino'); + expect(view.groups[1].visits.map((v) => v.sampleId)).toEqual(['b', 'a']); + }); + it('the backend decides: a visit it calls eligible is eligible, one with reasons is not derived', () => { + const view = eligibilityView(answer('evaluated', candidate('survival', '2025-01-01', true))); + if (view.kind !== 'evaluated') throw new Error(view.kind); + expect(view.groups[0].visits[0]).toMatchObject({ + eligible: true, + reasons: [], + sampleId: undefined, + }); + }); + it('without candidates it says so, which is not eligibility', () => { + expect(eligibilityView(answer('no_candidate'))).toEqual({ kind: 'none', cutoff: '2026-12-02' }); + }); + it('an answer that is not the contract is "unavailable", never an empty list of reasons', () => { + for (const bad of [ + null, + undefined, + {} as any, + { resourceType: 'Bundle' } as any, + answer('evaluated'), + answer('other', candidate('survival', '2025-01-01', true)), + answer('evaluated', part('candidate', { part: [] })), + ]) + expect(eligibilityView(bad)).toEqual({ kind: 'unavailable' }); + }); + it('unknown codes show the display the API gave, else the code, and keep the code', () => { + const view = eligibilityView( + answer( + 'evaluated', + candidate('new_scenario', '2025-01-01', false, ['new_rule'], undefined, 'Escenario nuevo'), + candidate('other_scenario', '2025-01-02', false, ['another_rule']), + ), + ); + if (view.kind !== 'evaluated') throw new Error(view.kind); + expect(view.groups.map((g) => [g.code, g.text])).toEqual([ + ['new_scenario', 'Escenario nuevo'], + ['other_scenario', 'other_scenario'], + ]); + expect(view.groups[1].visits[0].reasons).toEqual([ + { code: 'another_rule', text: 'another_rule' }, + ]); + }); +}); + +describe('what a failed call is', () => { + const failure = (status: number, error: unknown = null) => + eligibilityFailure(new HttpErrorResponse({ status, error })); + it('a 409 asks for the gold update and keeps the backend diagnostics', () => { + expect( + failure(409, { + resourceType: 'OperationOutcome', + issue: [{ code: 'conflict', diagnostics: 'rebuild gold.cacu_eligibility' }], + }), + ).toEqual({ kind: 'gold', text: 'rebuild gold.cacu_eligibility' }); + expect(failure(409)).toEqual({ kind: 'gold', text: undefined }); + }); + it('404 and 422 are "unavailable"; any other status or no connection is a communication error', () => { + expect(failure(404)).toEqual({ kind: 'unavailable' }); + expect(failure(422)).toEqual({ kind: 'unavailable' }); + expect(failure(500)).toEqual({ kind: 'error' }); + expect(failure(0)).toEqual({ kind: 'error' }); + expect(eligibilityFailure(new Error('boom'))).toEqual({ kind: 'error' }); + }); +}); diff --git a/src/app/paciente/eligibility.ts b/src/app/paciente/eligibility.ts new file mode 100644 index 0000000..927646a --- /dev/null +++ b/src/app/paciente/eligibility.ts @@ -0,0 +1,252 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { Component, input } from '@angular/core'; +import type { Parameters, ParametersParameter } from 'fhir/r4'; + +/** The clinical scenarios the backend publishes, as the screens name them (the API's codes stay). */ +export const SCENARIO_TEXT: Record = { + surveillance: 'Vigilancia', + pre_colposcopy: 'Precolposcopia', + post_colposcopy: 'Postcolposcopia', + post_colposcopy_second_visit: 'Segunda visita postcolposcopia', + post_treatment: 'Postratamiento', + survival: 'Supervivencia', +}; + +/** The exclusion criteria the backend publishes, as the screens say them. */ +export const CRITERION_TEXT: Record = { + hysterectomy: 'Histerectomía previa al índice', + under_18: 'Edad menor de 18 años al índice', + prior_outcome: 'Resultado CIN2+ previo al índice', + no_index_result: 'Sin resultado de citología o VPH en la visita índice', + unreported_biopsy: 'Biopsia solicitada sin resultado', + outcome_by_index: 'Resultado CIN2+ hasta la visita índice', + cancer_history: 'Antecedente de cáncer cervicouterino', + prior_treatment: 'Tratamiento previo a la visita índice', + no_referral: 'Sin resultado que sustente la referencia a colposcopia', + no_cotest: 'Sin cotest de citología y VPH en la visita índice', + no_pretreatment_biopsy: 'Sin biopsia previa al tratamiento en el periodo requerido', + outcome_before_index: 'Resultado CIN2+ entre tratamiento e índice', + no_birth_date: 'Fecha de nacimiento desconocida', + died_by_index: 'Defunción en o antes de la visita índice', +}; + +export interface Reason { + /** the API's code, untouched */ + code: string; + text: string; +} +export interface Visit { + indexDate: string; + /** the sample the visit is evaluated at, when the backend names one */ + sampleId?: string; + /** the backend's decision; it is never derived from the reasons */ + eligible: boolean; + reasons: Reason[]; +} +export interface ScenarioGroup { + code: string; + text: string; + visits: Visit[]; +} + +/** What the section can be in; none of them says "eligible" unless the backend did. */ +export type EligibilityState = + | { kind: 'loading' } + | { kind: 'error' } + | { kind: 'unavailable' } + | { kind: 'gold'; text?: string } + | { kind: 'none'; cutoff?: string } + | { kind: 'evaluated'; cutoff?: string; groups: ScenarioGroup[] }; + +type Part = ParametersParameter; +const value = (p?: Part): unknown => + p?.valueCode ?? p?.valueString ?? p?.valueDate ?? p?.valueBoolean ?? undefined; +const named = (parts: Part[] | undefined, name: string) => + (parts ?? []).filter((p) => p.name === name); +const coding = (p?: Part) => p?.valueCoding; + +/** The answer of `$eligibility`, grouped by scenario and keeping the visits apart: each visit has + * its own decision and its own reasons. A code the screens do not know shows the display the API + * gave, else the code itself. An answer that is not what the contract says is "unavailable". */ +export function eligibilityView(answer: Parameters | null | undefined): EligibilityState { + const top = answer?.parameter; + if (answer?.resourceType !== 'Parameters' || !Array.isArray(top)) return { kind: 'unavailable' }; + const status = value(named(top, 'status')[0]); + const cutoff = value(named(top, 'cutoff')[0]) as string | undefined; + const candidates = named(top, 'candidate'); + if (status === 'no_candidate' && !candidates.length) return { kind: 'none', cutoff }; + if (status !== 'evaluated' || !candidates.length) return { kind: 'unavailable' }; + const groups = new Map(); + for (const c of candidates) { + const scenario = coding(named(c.part, 'scenario')[0]); + const indexDate = value(named(c.part, 'index-date')[0]) as string | undefined; + const eligible = value(named(c.part, 'eligible')[0]); + if (!scenario?.code || !indexDate || typeof eligible !== 'boolean') + return { kind: 'unavailable' }; + const group = groups.get(scenario.code) ?? { + code: scenario.code, + text: SCENARIO_TEXT[scenario.code] ?? scenario.display ?? scenario.code, + visits: [], + }; + groups.set(scenario.code, group); + group.visits.push({ + indexDate, + sampleId: value(named(c.part, 'index-sample-id')[0]) as string | undefined, + eligible, + reasons: named(c.part, 'criterion').flatMap((r) => { + const k = coding(r); + return k?.code + ? [{ code: k.code, text: CRITERION_TEXT[k.code] ?? k.display ?? k.code }] + : []; + }), + }); + } + for (const g of groups.values()) g.visits.sort((a, b) => b.indexDate.localeCompare(a.indexDate)); + return { kind: 'evaluated', cutoff, groups: [...groups.values()] }; +} + +/** What the answer's failure says: the gold must be updated (409), the patient has no such + * operation (404, 422), or the call itself failed (anything else, including no connection). */ +export function eligibilityFailure(error: unknown): EligibilityState { + if (error instanceof HttpErrorResponse) { + if (error.status === 409) { + const issue = (error.error as { issue?: { diagnostics?: string }[] } | null)?.issue?.[0]; + return { kind: 'gold', text: issue?.diagnostics }; + } + if (error.status === 404 || error.status === 422) return { kind: 'unavailable' }; + } + return { kind: 'error' }; +} + +const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`; + +/** "Elegibilidad por escenario clínico": the decisions the backend publishes for each indexed visit, + * one scenario at a time. It shows them; it decides nothing. */ +@Component({ + selector: 'app-eligibility', + template: ` + @let s = state(); + @switch (s.kind) { + @case ('loading') { +

Consultando la elegibilidad…

+ } + @case ('error') { + + } + @case ('unavailable') { +

+ Información de elegibilidad no disponible para esta paciente. +

+ } + @case ('gold') { +

+ La elegibilidad requiere actualizar la capa gold del servidor; todavía no está disponible. +

+ @if (s.text) { +

{{ s.text }}

+ } + } + @case ('none') { +

+ Sin candidatos: la paciente no tiene visitas indexadas en estos escenarios + @if (s.cutoff) { + a la fecha de corte {{ s.cutoff }} + } + . Esto no significa que sea elegible. +

+ } + @case ('evaluated') { + @for (g of s.groups; track g.code) { +
+ + {{ g.text }} + + · {{ plural(g.visits.length, 'visita', 'visitas') }} · + {{ plural(count(g, true), 'elegible', 'elegibles') }}, + {{ plural(count(g, false), 'no elegible', 'no elegibles') }} + + +
    + @for (v of g.visits; track $index) { +
  • +

    + {{ + v.eligible ? 'Elegible' : 'No elegible' + }} + Fecha índice {{ v.indexDate }} + · {{ v.sampleId ? 'Muestra ' + v.sampleId : 'Sin muestra asociada' }} +

    + @if (v.reasons.length) { +
      + @for (r of v.reasons; track r.code) { +
    • {{ r.text }}
    • + } +
    + } +
  • + } +
+
+ } + @if (s.cutoff) { +

Visitas hasta la fecha de corte {{ s.cutoff }}.

+ } + } + } + `, + styles: ` + .note, + .detail { + font-size: 12px; + } + .state { + margin: 8px 0; + } + .scenario { + border-top: 1px solid #dce3e7; + padding: 6px 0; + } + .scenario summary { + cursor: pointer; + } + .visits { + list-style: none; + margin: 6px 0 0; + padding: 0; + } + .visit { + padding: 4px 0 4px 12px; + } + .head { + margin: 0; + } + .badge { + background: #f3d6dc; + border-radius: 10px; + color: #7a1f36; + font-size: 12px; + font-weight: 500; + margin-right: 6px; + padding: 1px 8px; + } + .badge.ok { + background: #dcefe4; + color: #1d5a3b; + } + .why { + margin: 2px 0 0; + padding-left: 22px; + } + `, +}) +export class Eligibility { + readonly state = input.required(); + protected plural = plural; + protected count(g: ScenarioGroup, eligible: boolean) { + return g.visits.filter((v) => v.eligible === eligible).length; + } +} diff --git a/src/app/paciente/paciente.html b/src/app/paciente/paciente.html index bb5b82f..21390f3 100644 --- a/src/app/paciente/paciente.html +++ b/src/app/paciente/paciente.html @@ -315,6 +315,16 @@ } + @if (domain() === 'cacu') { + + Elegibilidad por escenario clínico + + + + + } @if (domain() === 'tea') { diff --git a/src/app/paciente/paciente.ts b/src/app/paciente/paciente.ts index 98410c5..f8e4246 100644 --- a/src/app/paciente/paciente.ts +++ b/src/app/paciente/paciente.ts @@ -13,6 +13,7 @@ import type { RiskAssessment, } from 'fhir/r4'; import { Api } from '../api/api'; +import { cacuEligibility } from '../api/fn/fhir/cacu-eligibility'; import { studies as eegStudies } from '../api/fn/eeg/studies'; import { study as eegStudy } from '../api/fn/eeg/study'; import { readReport$Json } from '../api/fn/models/read-report-json'; @@ -26,6 +27,12 @@ import type { Parameters as FhirParameters } from 'fhir/r4'; import { firstValueFrom } from 'rxjs'; import { ApiConfiguration } from '../api/api-configuration'; import { ANTECEDENTS, Fact, group, split } from './record-groups'; +import { + Eligibility, + eligibilityFailure, + eligibilityView, + type EligibilityState, +} from './eligibility'; import { referenceView, ReferenceRisk, ReferenceView } from './reference-risk'; import { parseSeries, RiskSeries, Series } from './risk-series'; import { curveFigure, curveText } from './risk-curve'; @@ -89,6 +96,7 @@ function methods(figures: { figure: { data: unknown[] } }[]): string[] { Plot, RiskScales, ReferenceRisk, + Eligibility, RiskSeries, Stages, ], @@ -212,6 +220,29 @@ export class Paciente { }); /** CaCu, experimental: the NCI reference comparison of the cytology she was opened at. The API * answers 404 while the feature is off: then nothing is shown. */ + /** CaCu: the eligibility the backend publishes for each indexed visit (`$eligibility`). A failure is a + * state of the section, never an eligibility; a new patient starts from nothing (no earlier answer). */ + private readonly eligibilityData = resource({ + params: () => + this.domain() === 'cacu' ? { id: this.id(), cutoff: this.corte() } : undefined, + loader: async ({ params }): Promise => { + try { + const answer = await this.api.invoke(cacuEligibility, { + domain: 'cacu' as Domain, + id: params.id, + cutoff: params.cutoff, + }); + return eligibilityView(answer as FhirParameters); + } catch (error) { + return eligibilityFailure(error); + } + }, + }); + protected readonly eligibility = computed(() => + this.eligibilityData.isLoading() + ? { kind: 'loading' } + : (this.eligibilityData.value() ?? { kind: 'loading' }), + ); protected readonly reference = resource({ params: () => this.domain() === 'cacu' diff --git a/src/app/revision/revision.ts b/src/app/revision/revision.ts index 59972e6..5779b61 100644 --- a/src/app/revision/revision.ts +++ b/src/app/revision/revision.ts @@ -28,6 +28,7 @@ type Entity = Rejection['entity']; type Row = Record; const ENTITIES: Record = { + cacu_eligibility_evidence: 'Evidencia de elegibilidad CaCu', cervical_cytology: 'Citología cervical', cervical_biopsy: 'Biopsia cervical', clinical_note: 'Nota médica',