Compare commits

..

2 Commits

Author SHA1 Message Date
Angel Capetillo Zavala c0e4920159 CaCu follow-up list, patient record and exports: stages, filters, risk scales and PDF/XLSX
The list shows five stage nodes per patient with their provenance, filters by age and
search over the whole query, and exports the complete query to PDF and XLSX. The record
shows stage dates and intervals, history, tests and segmented risk scales with markers,
intervals and distinct horizons; absent risks stay unavailable and a zero stays a value.
2026-11-27 18:42:42 -06:00
Angel Capetillo Zavala 31400c77b1 CaCu indicators: HPV genotype, biopsy results, diagnosis timing by ICD-10 and referral PPV cards
The HPV genotype and biopsy distributions, the biopsy request confirmation and the
timing by ICD-10 code are placed beside cytology. The referral PPV cards are titled as
registered procedures and say that a colposcopy may be inferred from notes and that the
preceding cytology is a date association, not a confirmed referral. The new strata and
their values have Spanish labels.
2026-11-27 18:42:41 -06:00
148 changed files with 1361 additions and 15278 deletions
-338
View File
@@ -1,338 +0,0 @@
import { expect, type Locator, type Page, test } from '@playwright/test';
import { layoutProblems } from './layout';
import { type Simulation, simulateRounds } from './simulated-rounds';
test.beforeEach(async ({ page }) => {
const form = { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' };
expect((await page.request.post('/api/auth/login', { form })).status()).toBe(204);
});
const ROUND = { name: 'Por detección inicial y subsecuente' };
const VIEWS_LABEL = 'Lectura de la distribución citológica y del VPH por genotipo';
const VIEWS = ['General', 'Por grupo de edad', 'Por estatus de seguimiento', ROUND.name];
const TITLES = {
cytology: 'Distribución de resultados citológicos',
genotype: 'Resultados de VPH por genotipo',
biopsy: 'Resultados de biopsia cervical',
colposcopy: 'Valor predictivo positivo de la colposcopía',
ppvBiopsy: 'Valor predictivo positivo de la biopsia',
};
test('indicadores cacu: its sections in order, each card read one mode at a time', async ({
page,
}) => {
await page.goto('/indicadores/cacu');
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const headings = await tab
.locator('h2, app-readings h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([
'Indicadores de oportunidad',
'Tiempos de la ruta del tamizaje',
'Indicadores clínicos',
'Resultados de citología, VPH y biopsia',
'Distribución de resultados citológicos',
'Resultados de VPH por genotipo',
'Resultados de biopsia cervical',
'Tasa de confirmación histopatológica',
'Valor predictivo positivo de la colposcopía',
]);
const route = tab.locator('app-readings').first();
for (const mode of ['Por pasos', 'Por CIE-10', 'Acumulado desde la toma']) {
await route.getByRole('radio', { name: mode }).click();
await expect(
route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')),
).toBeVisible();
}
// one selector for the cytology distribution and the HPV by genotype; the biopsy card is apart
await expect(
tab.locator('app-readings', {
has: page.getByRole('heading', { name: 'Pacientes evaluadas por resultado de VPH' }),
}),
).toHaveCount(0);
const views = tab.getByRole('radiogroup', { name: VIEWS_LABEL });
await expect(views.getByRole('radio')).toHaveText(VIEWS);
await expect(views.getByRole('radio', { name: 'General' })).toBeChecked();
await expect(tab.getByRole('radio', { name: 'Por escenario clínico' })).toHaveCount(0);
for (const view of VIEWS.slice(1)) {
await views.getByRole('radio', { name: view }).click();
for (const card of [TITLES.cytology, TITLES.genotype]) {
const readings = tab.locator('app-readings', {
has: page.getByRole('heading', { name: card }),
});
// each card has no toggle of its own: the selector drives both
await expect(readings.getByRole('radio')).toHaveCount(0);
await expect(
readings
.locator('.group')
.first()
.or(readings.getByText(/No disponible|Sin datos en el periodo/)),
).toBeVisible();
}
}
const biopsyCard = tab.locator('app-readings', {
has: page.getByRole('heading', { name: TITLES.biopsy }),
});
await expect(biopsyCard.getByRole('radio')).toHaveCount(0);
await views.getByRole('radio', { name: 'General' }).click();
await expect(
tab
.locator('app-readings', { has: page.getByRole('heading', { name: TITLES.cytology }) })
.getByRole('table'),
).toBeVisible();
// the PPV cards keep their round tab, in the same words and order
await tab.getByRole('radio', { name: 'Colposcopía', exact: true }).click();
const colposcopy = tab.locator('app-readings', {
has: page.getByRole('heading', { name: TITLES.colposcopy }),
});
await colposcopy.getByRole('radio', ROUND).click();
await expect(
colposcopy
.getByRole('table', ROUND)
.or(colposcopy.getByText(/No disponible|Sin datos en el periodo/)),
).toBeVisible();
await tab.getByRole('radio', { name: 'Biopsia', exact: true }).click();
await tab
.locator('app-readings', {
has: page.getByRole('heading', { name: TITLES.ppvBiopsy }),
})
.getByRole('radio', ROUND)
.click();
await expect(
tab.getByRole('heading', { name: 'Valor predictivo positivo de la biopsia' }),
).toBeVisible();
await tab.getByRole('radio', { name: 'Solicitudes' }).click();
});
test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => {
await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
const list = page.locator('table.worklist tbody tr');
await expect(list.first().locator('app-stages li')).toHaveCount(5);
await list.first().getByRole('button', { name: 'Detalle' }).click();
await expect(page.locator('tr.stage-detail')).toContainText('Toma de muestra');
const answer = page.waitForResponse((r) => r.url().includes('birthdate=le'));
await page.getByLabel('Edad mínima').fill('45');
expect((await answer).ok()).toBe(true);
for (const age of await list.locator('td:nth-child(2)').allInnerTexts())
expect(parseInt(age)).toBeGreaterThanOrEqual(45);
for (const [button, file] of [
['Exportar Excel', 'seguimiento-cacu.xlsx'],
['Exportar PDF', 'seguimiento-cacu.pdf'],
]) {
const saved = page.waitForEvent('download');
await page.getByRole('button', { name: button }).click();
expect((await saved).suggestedFilename()).toBe(file);
}
await list.first().locator('a').first().click();
await expect(page.locator('[data-section=etapas]')).toContainText('Reporte de biopsia');
const record = page.waitForEvent('download');
await page.getByRole('button', { name: 'Exportar PDF' }).click();
expect((await record).suggestedFilename()).toBe('expediente-cacu.pdf');
});
// ---- Screening rounds on SIMULATED answers (see simulated-rounds.ts): the groups the contract of
// `rebuild` allows, tried on top of the API's own answers. They show how the page draws them, not the
// backend. The shared selector drives the cytology and the HPV-by-genotype cards; the PPV cards keep a tab.
const BAR = {
initial: 'rgb(95, 127, 154)',
subsequent: 'rgb(143, 167, 187)',
no_data: 'rgb(201, 205, 210)',
};
const GENOTYPE_COLOURS = {
Negativo: '#42A77E',
'VPH 16': '#DF8640',
'VPH 18': '#C29C42',
'VPH 16 y 18': '#C24269',
Positivo: '#A8C243',
};
const CYTOLOGY_COLOURS = {
Normal: '#408651',
'ASC-US': '#2778B8',
LIEBG: '#B19525',
'ASC-H': '#7955B1',
LIEAG: '#CE4778',
'Carcinoma in situ': '#AA394D',
};
async function withRounds(page: Page, how: Simulation) {
await simulateRounds(page, how);
await page.goto('/indicadores/cacu');
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible({
timeout: 3 * 60_000,
});
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const card = (title: string) =>
tab.locator('app-readings', { has: page.getByRole('heading', { name: title }) }).first();
const view = async (name: string) => {
await tab.getByRole('radiogroup', { name: VIEWS_LABEL }).getByRole('radio', { name }).click();
};
/** A PPV card on its round tab. */
const ppv = async (key: 'colposcopy' | 'ppvBiopsy') => {
await tab
.getByRole('radio', { name: key === 'colposcopy' ? 'Colposcopía' : 'Biopsia', exact: true })
.click();
const readings = card(TITLES[key]);
await readings.getByRole('radio', ROUND).click();
return readings;
};
return { tab, card, view, ppv };
}
/** The first group of independent bars of a card (the cytology and genotype breakdowns). */
const plotOf = (readings: Locator) => readings.locator('.group').first();
/** The groups of a card as the page draws them: "label<br>n = N", the width of the first bar and the colour of
* each category (the first group's rows), in hex. */
const traces = (readings: Locator) =>
readings.evaluate((el) => {
const hex = (rgb: string) =>
'#' +
(rgb.match(/\d+/g) ?? [])
.slice(0, 3)
.map((n) => Number(n).toString(16).padStart(2, '0'))
.join('')
.toUpperCase();
const groups = [...el.querySelectorAll('.group')];
return {
y: groups.map(
(g) =>
`${g.querySelector('h4')!.childNodes[0].textContent!.trim()}<br>n = ${g.querySelector('.n')!.textContent!.replace('n = ', '').trim()}`,
),
x: groups.map((g) => parseFloat((g.querySelector('.fill') as HTMLElement).style.width)),
colours: Object.fromEntries(
[...groups[0].querySelectorAll('.row')].map((r) => [
r.querySelector('.name')!.textContent!.trim(),
hex(getComputedStyle(r.querySelector('.fill')!).backgroundColor),
]),
),
};
});
for (const key of ['colposcopy', 'ppvBiopsy'] as const) {
test(`rondas (simulado) ${key}: three groups in order, each with its own colour`, async ({
page,
}) => {
const { ppv } = await withRounds(page, 'as-is');
const readings = await ppv(key);
const rows = readings.getByRole('row').filter({ has: page.getByRole('rowheader') });
await expect(rows).toHaveCount(3);
const names = await readings.getByRole('rowheader').allInnerTexts();
expect(names.map((n) => n.trim().split(/\s*\n\s*/)[0])).toEqual([
'Detección inicial',
'Detección subsecuente',
'Sin dato',
]);
const colours = await readings
.locator('tbody .bar')
.evaluateAll((els) => els.map((e) => getComputedStyle(e).backgroundColor));
expect(colours).toEqual([BAR.initial, BAR.subsequent, BAR.no_data]);
});
test(`rondas (simulado) ${key}: an empty initial group is zero patients, not hidden`, async ({
page,
}) => {
const { ppv } = await withRounds(page, 'no-initial');
const readings = await ppv(key);
const initial = readings.getByRole('row').filter({ hasText: 'Detección inicial' });
await expect(initial).toContainText('Sin pacientes en el periodo');
await expect(initial).toContainText('0/0');
});
test(`rondas (simulado) ${key}: without the stratum the card says it is not available`, async ({
page,
}) => {
const { ppv } = await withRounds(page, 'unpublished');
const readings = await ppv(key);
await expect(readings).toContainText('No disponible');
await expect(readings.getByRole('table', ROUND)).toHaveCount(0);
});
}
for (const card of ['cytology', 'genotype'] as const) {
test(`rondas (simulado) ${card}: the selector draws the rounds in order, with the category colours`, async ({
page,
}) => {
const { card: of, view } = await withRounds(page, 'as-is');
await view(ROUND.name);
const readings = of(TITLES[card]);
await expect(plotOf(readings)).toBeVisible();
const found = await traces(readings);
expect(found.y.map((l) => l.split('<br>')[0])).toEqual([
'Detección inicial',
'Detección subsecuente',
'Sin dato',
]);
expect(found.colours).toMatchObject(card === 'cytology' ? CYTOLOGY_COLOURS : GENOTYPE_COLOURS);
});
test(`rondas (simulado) ${card}: an empty initial group is an empty bar with its zero`, async ({
page,
}) => {
const { card: of, view } = await withRounds(page, 'no-initial');
await view(ROUND.name);
const found = await traces(of(TITLES[card]));
expect(found.y[0]).toBe('Detección inicial<br>n = 0');
expect(found.x[0]).toBe(0);
});
test(`rondas (simulado) ${card}: without the stratum the selector says it is not available`, async ({
page,
}) => {
const { card: of, view } = await withRounds(page, 'unpublished');
await view(ROUND.name);
await expect(of(TITLES[card])).toContainText('No disponible');
});
}
test('rondas (simulado): the genotype card never shows the incomplete positives, and says where they went', async ({
page,
}) => {
const { card, view } = await withRounds(page, 'as-is');
const readings = card(TITLES.genotype);
await expect(readings).toContainText('«Positivo»');
await expect(readings.getByRole('rowheader')).not.toContainText([
'Otro de alto riesgo',
'incompleto',
]);
const labels = await readings.getByRole('rowheader').allInnerTexts();
expect(labels.map((l) => l.trim())).toEqual([
'Negativo',
'VPH 16',
'VPH 18',
'VPH 16 y 18',
'Positivo',
]);
for (const name of VIEWS.slice(1)) {
await view(name);
const found = await traces(readings);
expect(Object.keys(found.colours)).toEqual(Object.keys(GENOTYPE_COLOURS));
}
});
for (const width of [1440, 480]) {
test(`rondas (simulado) at ${width} px: the shared selector on each view lays out cleanly`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { view, ppv } = await withRounds(page, 'as-is');
for (const name of VIEWS) {
await view(name);
await page.waitForTimeout(1200);
// every option of the selector is inside the window (it wraps on a narrow screen)
for (const box of await page
.getByRole('radiogroup', { name: VIEWS_LABEL })
.getByRole('radio')
.evaluateAll((els) =>
els.map((e) => e.closest('mat-button-toggle')!.getBoundingClientRect().right),
))
expect(box).toBeLessThanOrEqual(width);
expect(await layoutProblems(page), name).toEqual([]);
}
await ppv('colposcopy');
await ppv('ppvBiopsy');
await page.waitForTimeout(1200);
expect(await layoutProblems(page)).toEqual([]);
});
}
-974
View File
@@ -1,974 +0,0 @@
import { expect, type Locator, type Page, test } from '@playwright/test';
import { layoutProblems } from './layout';
// The individual record of CaCu: the stages inside "Historial médico" and the risk scales.
// "(simulado)" tests rewrite the API's answers in the browser to cover what the synthetic data
// do not hold (every stage state, every risk value); they show how the page draws them, not the backend.
const EXT = 'https://isssteleon.org/fhir/StructureDefinition/';
test.beforeEach(async ({ page }) => {
const form = { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' };
expect((await page.request.post('/api/auth/login', { form })).status()).toBe(204);
});
/** The record of the first patient of the risk list, as an address. */
async function firstRecord(page: Page): Promise<{ url: string; sample: string }> {
await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
const link = page.locator('table.worklist tbody tr a').first();
await link.waitFor({ timeout: 120_000 });
const url = (await link.getAttribute('href'))!;
return { url, sample: new URL(url, 'http://x').searchParams.get('citologia')! };
}
const plus = (day: string, days: number) =>
new Date(Date.parse(day) + days * 86_400_000).toISOString().slice(0, 10);
type Route = Partial<
Record<'report' | 'colposcopy' | 'request' | 'biopsy' | 'diagnosis', number>
> & {
link?: 'recorded';
/** more extensions on the report, as the backend would publish them (stage states and sources) */
extra?: object[];
};
/** The shown cytology's report carries these dates (days after its sample). */
async function withRoute(page: Page, sample: string, days: Route) {
await page.route('**/api/cacu/fhir/DiagnosticReport**', async (route) => {
const response = await route.fetch();
const body = await response.json();
for (const { resource: r } of body.entry ?? []) {
if (r.code?.coding?.[0]?.code !== 'cervical_cytology' || r.effectiveDateTime !== sample)
continue;
const names = {
report: 'report-date',
colposcopy: 'colposcopy-date',
request: 'biopsy-request-date',
biopsy: 'biopsy-date',
diagnosis: 'diagnosis-date',
} as const;
r.extension = (r.extension ?? []).filter(
(e: any) =>
!Object.values(names).some((n) => e.url === EXT + n) && e.url !== EXT + 'biopsy-link',
);
for (const [key, name] of Object.entries(names)) {
const d = days[key as keyof typeof names];
if (d !== undefined) r.extension.push({ url: EXT + name, valueDate: plus(sample, d) });
}
if (days.link) r.extension.push({ url: EXT + 'biopsy-link', valueCode: days.link });
r.extension.push(...(days.extra ?? []));
}
await route.fulfill({
response,
body: JSON.stringify(body),
contentType: 'application/fhir+json',
});
});
}
type Prediction = [years: number, p: number, low?: number, high?: number];
const risk = (
id: string,
text: string,
model: string,
index: string,
predictions: Prediction[],
) => ({
resourceType: 'RiskAssessment',
id,
status: 'final',
method: { text, coding: [{ code: model }] },
occurrenceDateTime: index,
prediction: predictions.map(([years, p, low, high]) => ({
whenRange: { high: { value: years, unit: 'a', code: 'a' } },
probabilityDecimal: p,
extension:
low === undefined
? []
: [
{ url: EXT + 'ic-bajo', valueDecimal: low },
{ url: EXT + 'ic-alto', valueDecimal: high },
],
})),
});
/** The patient has these risk assessments. */
async function withRisks(page: Page, assessments: object[]) {
await page.route('**/api/cacu/fhir/RiskAssessment**', (route) =>
route.fulfill({
contentType: 'application/fhir+json',
body: JSON.stringify({
resourceType: 'Bundle',
type: 'searchset',
entry: assessments.map((resource) => ({ resource })),
}),
}),
);
}
const historial = (page: Page) =>
page.locator('mat-card', {
has: page.locator('mat-card-title', { hasText: 'Historial médico' }),
});
const scale = (page: Page, label: string, nth = 0) =>
page.locator(`.risk-scale[data-scale="${label}"]`).nth(nth);
const IMMEDIATE = 'Riesgo inmediato (al índice)';
const FIVE = 'Riesgo a 5 años';
async function open(page: Page, url: string) {
await page.goto(url);
await expect(historial(page)).toBeVisible({ timeout: 120_000 });
await expect(page.locator('app-loading')).toHaveCount(0, { timeout: 60_000 });
}
/** Where a scale draws its marker, in % of the bar, and the figure it prints. */
async function drawn(scaleBox: Locator) {
const marker = scaleBox.locator('.risk-marker');
return {
markers: await marker.count(),
left: (await marker.count())
? await marker.evaluate((e) => (e as HTMLElement).style.left)
: undefined,
value: (await scaleBox.locator('.risk-value').count())
? (await scaleBox.locator('.risk-value').innerText()).trim()
: undefined,
grey: await scaleBox.locator('.risk-plot.unavailable').count(),
};
}
test('ficha: the five stages are a line of nodes inside "Historial médico", with the export button', async ({
page,
}) => {
const { url } = await firstRecord(page);
await open(page, url);
await expect(page.locator('mat-card-title', { hasText: 'Etapas del tamizaje' })).toHaveCount(0);
const stages = historial(page).locator('[data-section=etapas] app-stages li');
await expect(stages).toHaveCount(5);
// one row: the five nodes are level
const tops = await stages
.locator('.node')
.evaluateAll((els) => els.map((e) => Math.round(e.getBoundingClientRect().top)));
expect(new Set(tops).size).toBe(1);
// each stage says its name, state, day and both intervals, centred
const first = stages.first();
await expect(first).toContainText('Toma de muestra');
await expect(first).toContainText('Registrada');
await expect(first).toContainText('Desde anterior: —');
await expect(first).toContainText('Desde toma: 0 días');
expect(
await first.locator('.info').evaluate((e) => getComputedStyle(e.parentElement!).textAlign),
).toBe('center');
await expect(historial(page)).toContainText('a la fecha de corte');
await expect(historial(page).getByRole('button', { name: 'Exportar PDF' })).toBeVisible();
// history and tests keep their tables
await expect(historial(page).getByRole('table')).toBeVisible();
await expect(page.locator('mat-card-title', { hasText: 'Pruebas y resultados' })).toBeVisible();
});
test('ficha: the export of the record still downloads its PDF', async ({ page }) => {
const { url } = await firstRecord(page);
await open(page, url);
const saved = page.waitForEvent('download');
await historial(page).getByRole('button', { name: 'Exportar PDF' }).click();
expect((await saved).suggestedFilename()).toBe('expediente-cacu.pdf');
});
test('ficha: with no model both horizons are drawn grey, not available, without a marker', async ({
page,
}) => {
const { url } = await firstRecord(page);
await open(page, url);
for (const label of [IMMEDIATE, FIVE]) {
const box = scale(page, label);
await expect(box).toContainText('No disponible');
expect(await drawn(box)).toMatchObject({ markers: 0, grey: 1 });
await expect(box.locator('.risk-labels span')).toHaveText([
'0 %',
'25 %',
'50 %',
'75 %',
'100 %',
]);
}
await expect(
page.getByText('Divisiones numéricas descriptivas; no representan umbrales clínicos.'),
).toBeVisible();
});
test('ficha (simulado): every state of a stage, its dates and its intervals', async ({ page }) => {
const { url, sample } = await firstRecord(page);
await withRoute(page, sample, {
report: 14,
colposcopy: 30,
request: 40,
biopsy: 50,
diagnosis: 70,
link: 'recorded',
});
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
const stages = historial(page).locator('app-stages li');
const text = async (n: number) => (await stages.nth(n).innerText()).replace(/\s+/g, ' ');
expect(await text(0)).toContain(`Registrada ${sample}`);
expect(await text(1)).toContain(
`Registrada ${plus(sample, 14)} Procedencia: Formulario de citología Desde anterior: 14 días Desde toma: 14 días`,
);
// colposcopy and diagnosis are inferred from dates: their intervals say so
expect(await text(2)).toContain(
`Inferida por fechas ${plus(sample, 30)} Desde anterior: 16 días (inferido) Desde toma: 30 días (inferido)`,
);
// a recorded biopsy link is recorded; the interval since an inferred stage is still inferred
expect(await text(3)).toContain(
`Registrada ${plus(sample, 50)} Desde anterior: 20 días (inferido) Desde toma: 50 días`,
);
expect(await text(4)).toContain(
`Inferida por fechas ${plus(sample, 70)} Desde anterior: 20 días (inferido)`,
);
const state = (n: number) =>
stages
.nth(n)
.locator('.node')
.evaluate(
(e) => getComputedStyle(e).backgroundColor + '|' + getComputedStyle(e).borderTopStyle,
);
expect(await state(0)).toBe('rgb(56, 123, 102)|solid'); // recorded
expect(await state(2)).toBe('rgb(66, 105, 160)|double'); // inferred
// an inferred biopsy link: inferred as well
await page.unroute('**/api/cacu/fhir/DiagnosticReport**');
await withRoute(page, sample, {
report: 14,
colposcopy: 30,
request: 40,
biopsy: 50,
diagnosis: 70,
});
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
expect(await text(3)).toContain('Inferida por fechas');
});
test('ficha (simulado): the cut-off hides what is dated after it; a biopsy asked and not reported is pending', async ({
page,
}) => {
const { url, sample } = await firstRecord(page);
await withRoute(page, sample, {
report: 14,
colposcopy: 30,
request: 40,
biopsy: 50,
diagnosis: 70,
});
const cutoff = plus(sample, 45); // after the request, before the report
await open(page, `${url.split('?')[0]}?corte=${cutoff}&citologia=${sample}`);
const stages = historial(page).locator('app-stages li');
const states = await stages.locator('.info span:nth-child(2)').allInnerTexts();
expect(states.map((s) => s.trim())).toEqual([
'Registrada',
'Registrada',
'Inferida por fechas',
'Pendiente',
'Sin dato',
]);
await expect(historial(page)).toContainText(`a la fecha de corte ${cutoff}`);
const pending = await stages
.nth(3)
.locator('.node')
.evaluate((e) => getComputedStyle(e).backgroundColor);
expect(pending).toBe('rgb(255, 241, 201)');
const unknown = await stages
.nth(4)
.locator('.node')
.evaluate((e) => getComputedStyle(e).borderTopStyle);
expect(unknown).toBe('dashed');
await expect(stages.nth(4)).toContainText('Sin fecha');
await expect(stages.nth(4)).toContainText('Desde toma: —');
// a cut-off before the sample: nothing is known
await page.unroute('**/api/cacu/fhir/DiagnosticReport**');
await withRoute(page, sample, { report: 14 });
await open(page, `${url.split('?')[0]}?corte=${plus(sample, -1)}&citologia=${sample}`);
expect(
await historial(page).locator('app-stages li .info span:nth-child(2)').allInnerTexts(),
).toEqual(Array(5).fill('Sin dato'));
});
test('ficha (simulado): the scales draw 0, 2, 50, 98 and 100 % in place, and tell zero from absent', async ({
page,
}) => {
const { url } = await firstRecord(page);
await withRisks(page, [
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [
[0, 0],
[5, 0.5, 0.4, 0.6],
]),
risk('b', 'Recurrencia v2', 'cacu.recurrence', '2026-03-01', [
[0, 0.02, 0.01, 0.03],
[5, 0.98, 0.95, 1],
]),
risk('c', 'Otro modelo v1', 'cacu.other', '2026-04-01', [[5, 1]]), // no immediate horizon
risk('d', 'Parcial v1', 'cacu.partial', '2026-05-01', [[0, 0.5]]), // no five-year horizon
]);
await open(page, url);
await expect(
page.getByRole('heading', { name: 'Supervivencia v3 · fecha índice 2026-02-01' }),
).toBeVisible();
await expect(
page.getByRole('heading', { name: 'Recurrencia v2 · fecha índice 2026-03-01' }),
).toBeVisible();
const at = async (label: string, nth: number) => drawn(scale(page, label, nth));
// group order follows the page's models: survival, recurrence, other, partial
const groups = await page.locator('.risk-scale').count();
expect(groups).toBe(8); // both horizons of four models
const model = async (n: number) => [await at(IMMEDIATE, n), await at(FIVE, n)];
const [survival, recurrence, other, partial] = [
await model(0),
await model(1),
await model(2),
await model(3),
];
expect(survival[0]).toMatchObject({ markers: 1, left: '0%', value: '0.0 %', grey: 0 }); // a real zero
expect(survival[1]).toMatchObject({ left: '50%', value: '50.0 %' });
expect(recurrence[0]).toMatchObject({ left: '2%', value: '2.0 %' });
expect(recurrence[1]).toMatchObject({ left: '98%', value: '98.0 %' });
expect(other[0]).toMatchObject({ markers: 0, grey: 1 }); // absent, not zero
expect(other[1]).toMatchObject({ left: '100%', value: '100.0 %' });
expect(partial[0]).toMatchObject({ left: '50%' });
expect(partial[1]).toMatchObject({ markers: 0, grey: 1 });
await expect(scale(page, IMMEDIATE, 2)).toContainText('No disponible');
await expect(scale(page, FIVE, 3)).toContainText('No disponible');
await expect(scale(page, FIVE, 0)).toContainText('IC 95 %: 40.0–60.0 %');
await expect(scale(page, FIVE, 1)).toContainText('IC 95 %: 95.0–100.0 %');
await expect(scale(page, IMMEDIATE, 0)).not.toContainText('IC 95 %'); // none published, none invented
// the descriptive note stays, and the model table and curve of rebuild are still there
await expect(page.getByText('no representan umbrales clínicos')).toBeVisible();
await expect(page.getByRole('columnheader', { name: 'Probabilidad', exact: true })).toBeVisible();
});
test('ficha (simulado): the scale is drawn in four equal segments with the numeric divisions', async ({
page,
}) => {
const { url } = await firstRecord(page);
await withRisks(page, [
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [[5, 0.5, 0.4, 0.6]]),
]);
await open(page, url);
const box = scale(page, FIVE);
await expect(box.locator('.risk-labels span')).toHaveText([
'0 %',
'25 %',
'50 %',
'75 %',
'100 %',
]);
const line = await box.locator('.risk-line').evaluate((e) => getComputedStyle(e).backgroundImage);
for (const colour of [
'rgb(66, 167, 126)',
'rgb(168, 194, 67)',
'rgb(223, 134, 64)',
'rgb(194, 66, 105)',
])
expect(line).toContain(colour);
// the marker sits at 50 % of the bar
const [bar, mark] = await Promise.all([
box.locator('.risk-plot').boundingBox(),
box.locator('.risk-marker').boundingBox(),
]);
expect(Math.abs(mark!.x + mark!.width / 2 - (bar!.x + bar!.width / 2))).toBeLessThan(3);
});
for (const width of [1440, 480]) {
test(`ficha (simulado) at ${width} px: the stages and the scales lay out cleanly`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { url, sample } = await firstRecord(page);
await withRoute(page, sample, {
report: 14,
colposcopy: 30,
request: 40,
biopsy: 50,
diagnosis: 70,
link: 'recorded',
});
await withRisks(page, [
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [
[0, 0],
[5, 0.98, 0.95, 1],
]),
risk('b', 'Otro modelo v1', 'cacu.other', '2026-04-01', [[5, 1]]),
]);
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
await page.waitForTimeout(800);
expect(await layoutProblems(page)).toEqual([]);
const tops = await historial(page)
.locator('app-stages li .node')
.evaluateAll((els) => els.map((e) => Math.round(e.getBoundingClientRect().top)));
// wide: one row of nodes; narrow: a column (each below the previous)
if (width > 700) expect(new Set(tops).size).toBe(1);
else {
expect(tops).toEqual([...tops].sort((a, b) => a - b));
expect(new Set(tops).size).toBe(5);
}
expect(
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1),
).toBe(true);
});
}
const code = (name: string, valueCode: string) => ({ url: EXT + name, valueCode });
const nodeOf = (page: Page, n: number) => historial(page).locator('app-stages li').nth(n);
/** A record, by the API, whose cytology (the latest of the first patients) satisfies `wanted`. */
async function recordWhere(page: Page, wanted: (report: any) => boolean) {
const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=100')).json();
const ids: string[] = patients.entry.map((e: any) => e.resource.id);
for (let i = 0; i < ids.length; i += 25) {
const subject = ids
.slice(i, i + 25)
.map((p) => 'Patient/' + p)
.join(',');
const found = await (
await page.request.get(`/api/cacu/fhir/DiagnosticReport?_count=200&subject=${subject}`)
).json();
for (const { resource: r } of found.entry ?? [])
if (r.code?.coding?.[0]?.code === 'cervical_cytology' && wanted(r))
return {
id: r.subject.reference.split('/')[1] as string,
sample: r.effectiveDateTime as string,
};
}
throw new Error('no record with those stages in the first patients');
}
const has = (r: any, name: string) => (r.extension ?? []).some((e: any) => e.url === EXT + name);
test('ficha: the stages say what the backend demonstrates, with their sources', async ({
page,
}) => {
const { id, sample } = await recordWhere(
page,
(r) => has(r, 'stage-colposcopy-state') && has(r, 'stage-biopsy-state'),
);
await open(page, `/indicadores/cacu/pacientes/${id}?corte=2026-12-31&citologia=${sample}`);
const states = await historial(page)
.locator('app-stages li .info span:nth-child(2)')
.allInnerTexts();
expect(states[0]).toBe('Registrada');
expect(states[2]).toBe('Inferida por fechas'); // colposcopy is always inferred
expect(['Inferida por fechas', 'Registrada']).toContain(states[3]);
const colposcopy = (await nodeOf(page, 2).innerText()).replace(/\s+/g, ' ');
expect(colposcopy).toMatch(/Procedencia: (Nota clínica|Orden de biopsia)/);
expect(colposcopy).toContain('Desde anterior:');
expect((await nodeOf(page, 3).innerText()).replace(/\s+/g, ' ')).toMatch(
/Procedencia: (Asociación por fechas|Registro de la biopsia)/,
);
// the first two stages come from the form
expect(await nodeOf(page, 0).innerText()).toContain('Procedencia: Formulario de citología');
});
test('ficha (simulado): a stage the backend flags as ambiguous is drawn so, with no interval resting on it', async ({
page,
}) => {
const { url, sample } = await firstRecord(page);
await withRoute(page, sample, {
report: 14,
colposcopy: 30,
request: 40,
biopsy: 50,
diagnosis: 70,
extra: [
code('stage-biopsy-state', 'ambiguous'),
code('stage-biopsy-source', 'date-association'),
code('stage-colposcopy-state', 'inferred'),
code('stage-colposcopy-source', 'clinical-note'),
code('stage-colposcopy-source', 'biopsy-order'),
],
});
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
const biopsy = (await nodeOf(page, 3).innerText()).replace(/\s+/g, ' ');
expect(biopsy).toContain(`Ambigua ${plus(sample, 50)}`);
expect(biopsy).toContain('Procedencia: Asociación por fechas');
expect(biopsy).toContain('Desde anterior: — Desde toma: —');
expect(
await nodeOf(page, 3)
.locator('.node')
.evaluate((e) => getComputedStyle(e).borderTopStyle),
).toBe('double');
// no interval rests on the ambiguous day, so the next stage has none from the previous one either
expect((await nodeOf(page, 4).innerText()).replace(/\s+/g, ' ')).toContain('Desde anterior: —');
// a colposcopy dated by a note and a biopsy order lists both sources
expect(await nodeOf(page, 2).innerText()).toContain(
'Procedencia: Nota clínica · Orden de biopsia',
);
});
test('ficha (simulado): a biopsy the backend says is pending shows its request, not a day', async ({
page,
}) => {
const { url, sample } = await firstRecord(page);
await withRoute(page, sample, {
report: 14,
colposcopy: 30,
request: 40,
extra: [
code('stage-biopsy-state', 'pending'),
code('stage-biopsy-source', 'date-association'),
code('biopsy-link', 'inferred'),
],
});
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
const biopsy = (await nodeOf(page, 3).innerText()).replace(/\s+/g, ' ');
expect(biopsy).toContain('Pendiente');
expect(biopsy).toContain(`Solicitada el ${plus(sample, 40)}`);
expect(biopsy).toContain('Desde toma: —');
// colposcopy and diagnosis are never pending: no request is known for them
expect(
await historial(page).locator('app-stages li .info span:nth-child(2)').allInnerTexts(),
).not.toContain('Pendiente' + 'x');
const states = (
await historial(page).locator('app-stages li .info span:nth-child(2)').allInnerTexts()
).map((t) => t.trim());
expect(states.filter((t) => t === 'Pendiente')).toHaveLength(1);
});
// ---- the record's tests and its antecedents
const antecedents = (page: Page) => page.locator('[data-section=antecedentes]');
const tests = (page: Page) =>
page.locator('mat-card', {
has: page.locator('mat-card-title', { hasText: 'Pruebas y resultados' }),
});
test('ficha: antecedents and gynecologic evaluation have their own section; tests keep their results', async ({
page,
}) => {
const { id, sample } = await recordWhere(page, (r) => (r.result ?? []).length > 8);
await open(page, `/indicadores/cacu/pacientes/${id}?corte=2026-12-31&citologia=${sample}`);
const card = antecedents(page);
await expect(card).toBeVisible();
await expect(card).toContainText('no son diagnósticos confirmados');
await expect(card).toContainText(`Citología cervical · toma ${sample}`);
for (const title of [
'Detección de cáncer de cérvix',
'Condición ginecoobstétrica a la detección',
'Actualmente presenta',
'A la exploración se observa',
])
await expect(card.locator('dl.facts dt', { hasText: title })).toBeVisible();
// the earlier forms are collapsed, each with its own day
const earlier = card.locator('details.findings');
if (await earlier.count()) {
expect(await earlier.getAttribute('open')).toBeNull();
await earlier.locator('summary').click();
await expect(earlier.locator('tbody tr').first().locator('td').first()).toHaveText(
/\d{4}-\d{2}-\d{2}/,
);
}
// the tests keep date, study, report and the results of the study, without the form's antecedents
const table = tests(page);
await expect(table.getByRole('columnheader')).toHaveText([
'Toma',
'Estudio',
'Reporte',
'Resultados',
]);
const text = await table.innerText();
expect(text).toContain('Resultado (Bethesda)');
expect(text).not.toContain('Detección de cáncer de cérvix');
expect(text).not.toContain('A la exploración se observa');
// the extra findings are collapsed under their report
const findings = table.locator('details.findings').first();
await expect(findings.locator('summary')).toContainText('Hallazgos (');
expect(await findings.getAttribute('open')).toBeNull();
expect((await findings.locator('li').first().textContent())!.trim().length).toBeGreaterThan(0);
});
test('ficha (simulado): a missing antecedent says it is not documented; with none, no section', async ({
page,
}) => {
const { url } = await firstRecord(page);
const strip = (keep: string[]) =>
page.route('**/api/cacu/fhir/Observation**', async (route) => {
const response = await route.fetch();
const body = await response.json();
body.entry = (body.entry ?? []).filter((e: any) => {
const field = (e.resource.code?.coding?.[0]?.code ?? '').split('.').pop();
const antecedent = [
'screening_history',
'gynecologic_condition',
'presenting_symptom',
'cervix_appearance',
].includes(field);
return !antecedent || keep.includes(field);
});
await route.fulfill({
response,
body: JSON.stringify(body),
contentType: 'application/fhir+json',
});
});
await strip(['screening_history']);
await open(page, url);
const card = antecedents(page);
await expect(card.locator('dl.facts dd').first()).not.toHaveText('No documentado');
await expect(card.locator('dl.facts dd', { hasText: 'No documentado' })).toHaveCount(3);
await page.unroute('**/api/cacu/fhir/Observation**');
await strip([]);
await open(page, url);
await expect(antecedents(page)).toHaveCount(0);
// the record's tests are still there without them
await expect(tests(page).getByRole('table')).toBeVisible();
});
test('ficha: the PDF keeps the stages, antecedents, tests and risks', async ({ page }) => {
const { id, sample } = await recordWhere(page, (r) => (r.result ?? []).length > 8);
await open(page, `/indicadores/cacu/pacientes/${id}?corte=2026-12-31&citologia=${sample}`);
const saved = page.waitForEvent('download');
await historial(page).getByRole('button', { name: 'Exportar PDF' }).click();
const download = await saved;
expect(download.suggestedFilename()).toBe('expediente-cacu.pdf');
const file = await download.path();
expect(file).toBeTruthy();
const { readFileSync } = await import('node:fs');
const bytes = readFileSync(file!);
expect(bytes.subarray(0, 4).toString()).toBe('%PDF');
expect(bytes.length).toBeGreaterThan(5_000);
});
// ---- the NCI reference comparison (experimental) and the institutional curves ---------------------
const REFERENCE = '**/api/cacu/fhir/Patient/*/$reference-risk*';
const section = (page: Page) => page.locator('[data-section=referencia-nci]');
const value = (p: any) =>
p.valueCode ?? p.valueString ?? p.valueDate ?? p.valueInteger ?? p.valueDecimal ?? p.valueBoolean;
/** The first patients' answers of the API, to find one with a given state (the data is synthetic). */
async function referenceWhere(page: Page, status: string) {
const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=100')).json();
for (const { resource } of patients.entry) {
const answer = await page.request.get(`/api/cacu/fhir/Patient/${resource.id}/$reference-risk`);
if (!answer.ok()) throw new Error(`the reference operation answered ${answer.status()}`);
const body = await answer.json();
if (value(body.parameter.find((p: any) => p.name === 'status')) === status)
return { id: resource.id as string, body };
}
throw new Error(`no patient with the state ${status}`);
}
const part = (name: string, extra: object) => ({ name, ...extra });
const answerOf = (...parameter: object[]) => ({ resourceType: 'Parameters', parameter });
/** A resolved answer for fixtures, with the given horizons and comparisons. */
function fixture(
horizons: { years: number; reference?: number; comparison?: object[] }[],
more: object[] = [],
) {
return answerOf(
part('status', { valueCode: 'resolved' }),
part('experimental', { valueBoolean: true }),
part('cutoff', { valueDate: '2026-11-30' }),
part('scenario', {
part: [
part('table', { valueCode: 'screening' }),
part('label', { valueString: 'Tamizaje' }),
part('key', {
part: [
part('name', { valueCode: 'history' }),
part('value', { valueString: 'Cotest-negative' }),
],
}),
],
}),
part('source', {
part: [
part('id', { valueString: 'fixture-table' }),
part('file', { valueString: 'fixture.xlsx' }),
],
}),
...more,
...horizons.map((h) =>
part('horizon', {
part: [
part('years', { valueInteger: h.years }),
part('published', { valueBoolean: h.reference !== undefined }),
...(h.reference !== undefined ? [part('reference', { valueDecimal: h.reference })] : []),
...(h.comparison ?? []),
],
}),
),
);
}
const comparison = (status: string, reasons: string[], extra: object[] = []) =>
part('comparison', {
part: [
part('model', { valueCode: 'fixture.model' }),
part('title', { valueString: 'Modelo de prueba' }),
part('outcome', { valueString: 'CIN3+' }),
...extra,
part('status', { valueCode: status }),
...reasons.map((r) => part('reason', { valueCode: r })),
],
});
const answerWith = (page: Page, body: object, status = 200) =>
page.route(REFERENCE, (route) =>
route.fulfill({ status, contentType: 'application/fhir+json', body: JSON.stringify(body) }),
);
test('referencia NCI: a resolved cytology shows its reference with scenario, source and no institutional model', async ({
page,
}) => {
const { id, body } = await referenceWhere(page, 'resolved');
await open(page, `/indicadores/cacu/pacientes/${id}`);
const box = section(page);
await expect(box).toBeVisible();
await expect(box.locator('dd[data-status=resolved]')).toHaveText('Referencia disponible');
await expect(box).toContainText('Tamizaje');
await expect(box).toContainText('CIN3 o más grave (CIN3+)');
await expect(box).toContainText('Master_NCI_Risk_Table.xlsx');
const rows = box.locator('tbody tr');
await expect(rows).toHaveCount(2);
await expect(rows.first()).toContainText('Inmediato (al índice)');
await expect(rows.nth(1)).toContainText('5 años');
// the figures are the API's: percent with two decimals, and no institutional model is made up
const expected = body.parameter
.filter((p: any) => p.name === 'horizon')
.map((h: any) =>
(h.part.find((x: any) => x.name === 'reference').valueDecimal * 100).toFixed(2),
);
for (const [i, pct] of expected.entries())
await expect(rows.nth(i).locator('td').nth(2)).toContainText(`${pct} %`);
await expect(rows.first().locator('td').nth(1)).toContainText('No disponible');
await expect(rows.first().locator('td').nth(3)).toContainText('No comparable');
await expect(rows.first().locator('td').nth(3)).toContainText('Ningún modelo institucional');
// the antecedents used are collapsed
const used = box.locator('details.used');
expect(await used.getAttribute('open')).toBeNull();
await used.locator('summary').click();
await expect(used).toContainText('Fila de origen');
await expect(used).toContainText('Citología evaluada');
// the other risk displays of the record are still there, and the reference is below the scales
await expect(scale(page, FIVE)).toBeVisible();
const [scales, reference] = await Promise.all([
scale(page, FIVE).boundingBox(),
box.boundingBox(),
]);
expect(reference!.y).toBeGreaterThan(scales!.y);
await expect(
page.locator('mat-card-title', { hasText: 'Riesgos y recomendaciones' }),
).toBeVisible();
});
test('referencia NCI: a cytology the tables cannot resolve says the state and why, with no figure', async ({
page,
}) => {
const { id } = await referenceWhere(page, 'unverifiable_correspondence');
await open(page, `/indicadores/cacu/pacientes/${id}`);
const box = section(page);
await expect(box.locator('dd[data-status=unverifiable_correspondence]')).toHaveText(
'Correspondencia no verificable',
);
await expect(box.locator('ul.why li').first()).not.toBeEmpty();
await expect(box.locator('table')).toHaveCount(0);
await expect(box).not.toContainText('%');
});
test('referencia NCI: with the feature off (404) the section is not there and the record is whole', async ({
page,
}) => {
const { url } = await firstRecord(page);
await answerWith(
page,
{ resourceType: 'OperationOutcome', issue: [{ severity: 'error', code: 'not-found' }] },
404,
);
await open(page, url);
await expect(section(page)).toHaveCount(0);
await expect(scale(page, FIVE)).toBeVisible();
});
test('referencia NCI (simulado): a comparison that is valid shows the difference as institutional minus reference', async ({
page,
}) => {
const { url } = await firstRecord(page);
await answerWith(
page,
fixture([
{
years: 5,
reference: 0.0027,
comparison: [
comparison(
'comparable',
[],
[
part('institutional', { valueDecimal: 0.0127 }),
part('institutional-low', { valueDecimal: 0.005 }),
part('institutional-high', { valueDecimal: 0.02 }),
part('difference-pp', { valueDecimal: 1 }),
],
),
],
},
]),
);
await open(page, url);
const row = section(page).locator('tbody tr').first();
await expect(row).toContainText('Modelo de prueba');
await expect(row).toContainText('1.27 %');
await expect(row).toContainText('IC 95 %: 0.50–2.00 %');
await expect(row.locator('td').nth(2)).toContainText('0.27 %');
await expect(row.locator('td').nth(3)).toContainText('+1.00');
await expect(row.locator('td').nth(3)).not.toContainText('No comparable');
});
test('referencia NCI (simulado): another outcome or horizon is "No comparable" with its reasons and no difference', async ({
page,
}) => {
const { url } = await firstRecord(page);
await answerWith(
page,
fixture([
{
years: 0,
reference: 0.0001,
comparison: [
comparison(
'not_comparable',
['outcome_differs', 'horizon_not_published_by_model', 'population_not_verified'],
[part('institutional', { valueDecimal: 0.05 })],
),
],
},
{ years: 5, reference: 0.0027 },
]),
);
await open(page, url);
const first = section(page).locator('tbody tr').first();
await expect(first.locator('td').nth(3)).toContainText('No comparable');
await expect(first.locator('td').nth(3)).toContainText(
'El desenlace del modelo no es el de la tabla (CIN3+)',
);
await expect(first.locator('td').nth(3)).toContainText(
'no publica una predicción a este horizonte',
);
await expect(first.locator('td').nth(3)).not.toContainText(/[+-]\d/); // no signed difference
await expect(first.locator('td').nth(1)).toContainText('5.00 %'); // the model's own risk is shown, never subtracted
});
test('referencia NCI (simulado): a year-one reference is a year, never the immediate risk; a blank is not zero', async ({
page,
}) => {
const { url } = await firstRecord(page);
await answerWith(page, fixture([{ years: 1, reference: 0.0136 }, { years: 5 }]));
await open(page, url);
const rows = section(page).locator('tbody tr');
await expect(rows.first()).toContainText('1 año');
await expect(section(page)).not.toContainText('Inmediato');
await expect(rows.nth(1).locator('td').nth(2)).toContainText('No publicado');
await expect(rows.nth(1).locator('td').nth(2)).not.toContainText('0.00');
await expect(rows.first().locator('td').nth(2)).toContainText('1.36 %');
});
for (const width of [1440, 480]) {
test(`referencia NCI (simulado) at ${width} px: the section lays out cleanly beside the scales and curves`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { url } = await firstRecord(page);
await answerWith(
page,
fixture(
[
{
years: 0,
reference: 0.0001,
comparison: [
comparison(
'not_comparable',
['outcome_differs', 'population_not_verified'],
[part('institutional', { valueDecimal: 0.05 })],
),
],
},
{
years: 5,
reference: 0.0027,
comparison: [
comparison(
'comparable',
[],
[
part('institutional', { valueDecimal: 0.0127 }),
part('difference-pp', { valueDecimal: 1 }),
],
),
],
},
],
[part('assumption', { valueString: 'un supuesto sin verificar' })],
),
);
await withRisks(page, [
risk('a', 'Riesgo LIEAG+ v3', 'cacu.survival', '2026-06-01', [
[1, 0.08, 0.05, 0.12],
[3, 0.21, 0.15, 0.28],
[5, 0.34, 0.26, 0.44],
]),
risk('b', 'Riesgo cáncer v2', 'cacu.recurrence', '2026-06-01', [
[1, 0.002, 0.001, 0.005],
[3, 0.008],
[5, 0.015, 0.008, 0.028],
]),
]);
await open(page, url);
await section(page).locator('details.used summary').click();
await page.waitForTimeout(800);
expect(await layoutProblems(page)).toEqual([]);
expect(
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1),
).toBe(true);
});
}
test('curvas (simulado): one series per model at its published horizons, its band only where it has intervals, and no NCI data', async ({
page,
}) => {
const { url } = await firstRecord(page);
await answerWith(page, fixture([{ years: 5, reference: 0.0027 }]));
await withRisks(page, [
risk('a', 'Riesgo LIEAG+ v3', 'cacu.survival', '2026-06-01', [
[1, 0.08, 0.05, 0.12],
[3, 0.21, 0.15, 0.28],
[5, 0.34, 0.26, 0.44],
]),
risk('b', 'Riesgo cáncer v2', 'cacu.recurrence', '2026-06-01', [
[1, 0.002, 0.001, 0.005],
[3, 0.008],
[5, 0.015, 0.008, 0.028],
]),
risk('c', 'Sin intervalo v1', 'cacu.other', '2026-06-01', [
[2, 0.1],
[4, 0.2],
]),
risk('d', 'Un punto v1', 'cacu.partial', '2026-06-01', [[5, 0.5]]),
]);
await open(page, url);
const card = page.locator('details.curves');
await expect(card.locator('summary')).toHaveText('Curvas de probabilidad con su intervalo');
await expect(card).toHaveAttribute('open', '');
await expect(card.locator('li').first()).toContainText(
'Riesgo LIEAG+ (fecha índice 2026-06-01): 1 año: 8.0 % (IC 95 %: 5.0–12.0 %); 3 años: 21.0 %',
);
const plot = await card.locator('.js-plotly-plot').evaluate((e: any) => ({
names: e.data.filter((t: any) => t.showlegend !== false).map((t: any) => t.name),
series: Object.fromEntries(
e.data.filter((t: any) => t.mode?.includes('markers')).map((t: any) => [t.name, t.x]),
),
bands: e.data.filter((t: any) => t.fill === 'tonexty').map((t: any) => t.name),
ticks: e.layout.xaxis.tickvals,
title: e.layout.xaxis.title.text,
}));
expect(plot.series).toEqual({
'Riesgo LIEAG+': [1, 3, 5],
'Riesgo cáncer': [1, 3, 5],
'Sin intervalo': [2, 4],
'Un punto': [5],
});
expect(plot.bands).toEqual(['IC 95 % Riesgo LIEAG+', 'IC 95 % Riesgo cáncer']); // none for the models without intervals
expect(plot.ticks).toEqual([1, 2, 3, 4, 5]);
expect(plot.title).toBe('Horizonte (años desde la fecha índice (2026-06-01))');
// the reference is a separate table: its 0.27 % is nowhere in the figure
expect(
JSON.stringify(await card.locator('.js-plotly-plot').evaluate((e: any) => e.data)),
).not.toContain('0.27');
await expect(page.locator('[data-section=referencia-nci]')).toBeVisible();
});
-122
View File
@@ -1,122 +0,0 @@
import type { Page } from '@playwright/test';
/** What breaks a page's layout, measured in the browser: overlapping texts (also inside
* Plotly figures: legend against axis titles, tick labels), labels clipped at a figure's
* edge, labels that wrap where they should not (buttons, badges), a header taller than one
* row, text cut by its own box, and a page wider than the window. Empty: nothing found. */
export async function layoutProblems(page: Page): Promise<string[]> {
return page.evaluate(() => {
const found: string[] = [];
const box = (e: Element) => e.getBoundingClientRect();
const hit = (a: DOMRect, b: DOMRect) =>
a.width > 0 &&
b.width > 0 &&
a.left < b.right - 1 &&
b.left < a.right - 1 &&
a.top < b.bottom - 1 &&
b.top < a.bottom - 1;
const where = (el: Element) => {
const card = el.closest('mat-card, section, .card');
const h = card?.querySelector('h1,h2,h3,h4,mat-card-title');
return (h?.textContent ?? '').trim().slice(0, 60);
};
if (document.documentElement.scrollWidth > window.innerWidth + 1)
found.push(
`page overflows horizontally: ${document.documentElement.scrollWidth} > ${window.innerWidth}`,
);
for (const plot of document.querySelectorAll('.js-plotly-plot')) {
const texts = [
...plot.querySelectorAll(
'.legend, .g-xtitle text, .g-ytitle text, .xtitle, .ytitle, .gtitle',
),
];
for (let i = 0; i < texts.length; i++)
for (let j = i + 1; j < texts.length; j++)
if (
!texts[i].contains(texts[j]) &&
!texts[j].contains(texts[i]) &&
hit(box(texts[i]), box(texts[j]))
)
found.push(
`plot "${where(plot)}": ${texts[i].getAttribute('class')} overlaps ${texts[j].getAttribute('class')}`,
);
const host = box(plot);
for (const t of plot.querySelectorAll('.slicetext, .xtick text, .ytick text, .legendtext')) {
const b = box(t);
if (b.width && (b.left < host.left - 1 || b.right > host.right + 1))
found.push(`plot "${where(plot)}": text "${t.textContent}" clipped at the edge`);
}
const ticks = [...plot.querySelectorAll('.xtick text')].map(box);
for (let i = 1; i < ticks.length; i++)
if (hit(ticks[i - 1], ticks[i])) {
found.push(`plot "${where(plot)}": x tick labels overlap`);
break;
}
}
// Text elements overlapping each other (headings, labels, buttons, table cells).
const els = [
...document.querySelectorAll<HTMLElement>(
'h1,h2,h3,h4,p,label,button,a,dt,dd,th,td,mat-card-title,.mdc-tab__text-label,mat-label,li',
),
].filter(
(e: any) =>
e.offsetParent &&
box(e).width > 0 &&
box(e).height > 0 &&
!e.closest('.js-plotly-plot, .cdk-overlay-container') &&
!e.closest('details:not([open]) > :not(summary)'),
);
for (let i = 0; i < els.length; i++)
for (let j = i + 1; j < Math.min(els.length, i + 40); j++) {
const a = els[i],
b = els[j];
if (a.contains(b) || b.contains(a)) continue;
if (hit(box(a), box(b)))
found.push(
`"${(a.textContent ?? '').trim().slice(0, 30)}" overlaps "${(b.textContent ?? '').trim().slice(0, 30)}" (${where(a)})`,
);
}
// Text cut by its own box (ellipsis or overflow hidden).
for (const e of document.querySelectorAll<HTMLElement>(
'button, .mdc-tab__text-label, th, mat-label, .mat-mdc-select-value-text',
))
if (
e.offsetParent &&
e.scrollWidth > e.clientWidth + 2 &&
getComputedStyle(e).overflow !== 'visible'
)
found.push(`text cut: "${(e.textContent ?? '').trim().slice(0, 40)}"`);
const header = document.querySelector('.header');
if (header && header.getBoundingClientRect().height > 90 && window.innerWidth > 720)
found.push(
`header taller than one row: ${Math.round(header.getBoundingClientRect().height)}px`,
);
for (const b of document.querySelectorAll<HTMLElement>(
'button:not(.mat-button-toggle-button), a.mdc-button, .badge, .mat-mdc-chip',
)) {
const label = (b.querySelector('.mdc-button__label') as HTMLElement | null) ?? b;
const lines =
label.getClientRects().length &&
Math.round(
label.getBoundingClientRect().height /
parseFloat(getComputedStyle(label).lineHeight || '20'),
);
if (b.offsetParent && lines > 1 && (label.textContent ?? '').trim().length < 40)
found.push(`label wraps: "${(label.textContent ?? '').trim()}"`);
}
const icons = [
...document.querySelectorAll('header mat-icon, header a, header button, header .title'),
];
for (let i = 0; i < icons.length; i++)
for (let j = i + 1; j < icons.length; j++)
if (
!icons[i].contains(icons[j]) &&
!icons[j].contains(icons[i]) &&
hit(box(icons[i]), box(icons[j]))
)
found.push(
`header: "${(icons[i].textContent ?? '').trim().slice(0, 20)}" overlaps "${(icons[j].textContent ?? '').trim().slice(0, 20)}"`,
);
return [...new Set(found)];
});
}
+15 -241
View File
@@ -1,6 +1,4 @@
import { readFileSync } from 'node:fs';
import { expect, Page, test } from '@playwright/test';
import { layoutProblems } from './layout';
/** Every page loads from the API with no failed request and no console error. */
function watch(page: Page): string[] {
@@ -11,32 +9,6 @@ function watch(page: Page): string[] {
return problems;
}
// The pages show only to someone signed in (the API itself answers everyone).
test.beforeEach(async ({ page }) => {
const signed = await page.request.post('/api/auth/login', {
form: { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' },
});
expect(signed.status()).toBe(204);
});
test('login: the pages wait for a sign-in, and a wrong password says so', async ({ browser }) => {
const page = await browser.newPage({ baseURL: 'http://127.0.0.1:4310' });
await page.goto('/conectar');
await expect(page).toHaveURL(/\/login\?next=%2Fconectar/);
await expect(page.getByRole('heading', { name: 'Inicio de sesión' })).toBeVisible();
await page.getByRole('textbox', { name: 'Usuario' }).fill('admin@isssteleon.mx');
await page.getByRole('textbox', { name: 'Contraseña' }).fill('otra');
await page.getByRole('button', { name: 'Ingresar' }).click();
await expect(page.getByText('Usuario o contraseña incorrectos.')).toBeVisible();
await page.getByRole('textbox', { name: 'Contraseña' }).fill('solo-para-pruebas');
await page.getByRole('button', { name: 'Ingresar' }).click();
await expect(page).toHaveURL(/\/conectar$/);
await page.getByRole('button', { name: 'Cuenta' }).click();
await page.getByRole('menuitem', { name: 'Salir' }).click();
await expect(page).toHaveURL(/\/login/);
await page.close();
});
test("indicators: the KPIs are the API's MeasureReports, every tab and the patient view load", async ({
page,
}) => {
@@ -47,22 +19,21 @@ 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;
// the card says it as the old one did: "<n> pacientes"
await expect(page.locator('[data-measure="CACU_EU7"] .kpi-value')).toHaveText(
`${count.toLocaleString('es-MX')} pacientes`,
);
await expect(page.locator('[data-measure="CACU_EU7"] mat-card-subtitle')).toContainText(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 section.panel')).toHaveCount(9);
await expect(page.locator('app-tab-trazabilidad mat-card')).toHaveCount(measures.total);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
await expect(page.locator('app-tab-definiciones details')).toHaveCount(21);
await expect(page.locator('app-tab-definiciones tbody tr')).toHaveCount(measures.total);
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
@@ -73,7 +44,7 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await expect(rows).toHaveCount(Math.min(20, bundle.total));
await expect(rows.first().locator('a').first()).toHaveText(first);
await page.getByRole('button', { name: 'Siguiente' }).click();
await expect(page.getByText('Página 2 de')).toBeVisible();
await expect(page.getByText(`21–`)).toBeVisible();
await page.getByRole('button', { name: 'Anterior' }).click();
await rows.first().locator('a').first().click();
@@ -85,13 +56,13 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await page.goto('/indicadores/cama');
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
await page.getByRole('tab', { name: 'Seguimiento' }).click();
await page.locator('mat-form-field', { hasText: 'Ventana' }).click();
await page.getByRole('option', { name: '12 meses' }).click();
const camaRows = page.locator('table.worklist tbody tr');
await expect(camaRows.first()).toContainText('BI-RADS');
await page.goto('/indicadores/tea');
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
expect(problems).toEqual([]);
});
@@ -102,18 +73,13 @@ test('conectar: open the hospital pipeline, preview a source, run it to success'
await page.goto('/conectar');
await page.getByText('cacu', { exact: true }).click();
await expect(page.locator('vflow')).toBeVisible();
// a node's caption: its kind, then its name
await page.locator('.node-caption', { hasText: 'Fuente de datosPacientes' }).click();
// drawn from a fixture, read back as a guided SQLite source: the dialog edits it
await expect(page.getByRole('button', { name: 'Editar conexión' })).toBeVisible();
await page.getByText('Fuente · Patients').click();
await expect(page.locator('formly-form')).toBeVisible();
await page.getByRole('button', { name: 'Vista previa' }).click();
await expect(page.locator('.preview tr[mat-row]').first()).toBeVisible();
// A map node shows the site's codes in platform terms (its ConceptMap), editable as rows.
await page
.locator('.node-caption', { hasText: 'Traducir códigos' })
.filter({ has: page.locator('.name', { hasText: /^Citología$/ }) })
.click();
await expect(page.getByRole('heading', { name: /^Códigos del sitio/ })).toBeVisible();
await page.getByText('Mapear · cytology', { exact: true }).click();
await expect(page.getByText('Códigos del sitio')).toBeVisible();
await expect
.poll(() =>
page
@@ -126,9 +92,7 @@ test('conectar: open the hospital pipeline, preview a source, run it to success'
expect(problems).toEqual([]);
});
test('revision: what the hospital source holds, and a decision through the page', async ({
page,
}) => {
test('revision: what the hospital source holds, and a decision through the page', async ({ page }) => {
const problems = watch(page);
await page.goto('/revision');
await page.getByRole('tab', { name: 'Personas' }).click();
@@ -145,202 +109,12 @@ test('gobernanza: a version with its reports, its curves, and promotion refused
}) => {
const problems = watch(page);
await page.goto('/gobernanza/cama');
await expect(page.getByRole('heading', { name: 'Supervivencia' })).toBeVisible();
await expect(page.getByRole('heading', { name: 'survival' })).toBeVisible();
const version = page.locator('tr', { hasText: 'v1' });
await expect(version.getByRole('link', { name: 'Validación técnica' })).toBeVisible();
await version.getByRole('button', { name: 'Ver gráficas' }).click();
await expect(page.locator('app-plot .plot svg').first()).toBeVisible();
await version.getByRole('button', { name: 'Promover' }).click();
await expect(page.getByText('No se promovió')).toContainText('Validación clínica');
await expect(page.getByText('No se promovió')).toContainText('clinical_validation');
expect(problems.filter((p) => !p.includes('409'))).toEqual([]);
});
test('conectar: someone who knows nothing of databases connects the SQL Server with the dialog', async ({
page,
}) => {
const site = new URL((process.env['SITE_URL'] ?? '').replace(/^mssql\+pymssql/, 'http'));
const problems = watch(page);
await page.goto('/conectar');
await page.getByLabel('Nueva canalización').fill('asistente');
await page.getByLabel('Nueva canalización').press('Enter');
await page.getByRole('button', { name: 'Fuente de datos' }).click();
await expect(page.getByText('¿Dónde están los datos?')).toBeVisible();
await page.locator('[data-type="sqlserver"]').click();
await page.locator('[data-field="host"]').fill(site.hostname);
await page.locator('[data-field="database"]').fill(site.pathname.slice(1));
await page.locator('[data-field="user"]').fill(decodeURIComponent(site.username));
await page.locator('[data-field="password"]').fill(decodeURIComponent(site.password));
await page.getByRole('button', { name: 'Probar conexión' }).click();
await expect(page.getByText('Conexión correcta: 1 tabla.')).toBeVisible();
await page.locator('mat-select[data-field="table"]').click();
await page.getByRole('option', { name: 'ResultadoSubrogado' }).click();
await expect(page.getByText(/(Las primeras \d+ filas|La primera fila):/)).toBeVisible();
await page.getByLabel('Nombre de esta fuente').fill('Resultados');
await page.getByRole('button', { name: 'Guardar', exact: true }).last().click();
await expect(page.locator('.node-caption', { hasText: 'Resultados' })).toBeVisible();
// A wrong password says so in words, not a stack trace.
await page.getByRole('button', { name: 'Editar conexión' }).click();
await page.locator('[data-field="password"]').fill('not-it');
await page.getByRole('button', { name: 'Probar conexión' }).click();
await expect(page.getByText(/usuario o la contraseña no son correctos/)).toBeVisible();
await page.getByRole('button', { name: 'Cancelar' }).click();
await expect(page.getByRole('dialog')).toHaveCount(0);
await page.getByRole('button', { name: 'Guardar', exact: true }).click();
await expect(page.getByText('Versión 1 guardada.')).toBeVisible();
expect(problems).toEqual([]);
});
/** The old app's Indicadores tab as captured (tools/capture_pages.py): its headings from the
* opportunity section on, in order, and the kind of each plot (its traces' types). */
function captured(domain: string) {
const path = `../tests/fixtures/reference/${domain}/ui/pages.json`;
const tabs = JSON.parse(readFileSync(path, 'utf8')).tabs;
const items = (tabs['Indicadores'] ?? tabs['Resumen']) as any[]; // TEA's first tab is its summary
const from = items.findIndex((i) => i.text === 'Indicadores de oportunidad');
return items
.slice(from)
.filter((i) => ['h2', 'h3', 'plot'].includes(i.kind))
.filter((i) => !/^(cacu|cama|tea), /.test(i.text ?? '')); // a figure's machine caption
}
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
// CaCu's page is its own (Phase 6); CaMa's and TEA's follow the old one.
for (const domain of ['cama', 'tea']) {
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
page,
}) => {
const old = captured(domain);
await page.goto(`/indicadores/${domain}`);
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
const from = headings.indexOf('Indicadores de oportunidad');
expect(headings.slice(from).map(period)).toEqual(
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)),
);
// Each figure drawn is one of the old kinds (a figure with no data in the period is named).
const drawn = await tab
.locator('.js-plotly-plot')
.evaluateAll((els) =>
els.map((e: any) => (e.data ?? []).map((t: any) => t.type ?? 'scatter')),
);
const kinds = new Set(
old.filter((i) => i.kind === 'plot').map((i) => kindOf(i.traces.map((t: any) => t.type))),
);
for (const types of drawn) expect(kinds).toContain(kindOf(types));
});
}
for (const domain of ['cacu', 'cama', 'tea']) {
test(`trazabilidad ${domain}: the old tab's panels, in order, and the same kinds of plots`, async ({
page,
}) => {
const tabs = JSON.parse(
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
).tabs;
const old = (tabs['Trazabilidad'] as any[]).filter((i) =>
['h2', 'h3', 'plot'].includes(i.kind),
);
await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
const tab = page.locator('app-tab-trazabilidad');
await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings).toEqual(old.filter((i) => i.kind !== 'plot').map((i) => i.text));
const drawn = await tab
.locator('.js-plotly-plot')
.evaluateAll((els) =>
els.map((e: any) => (e.data ?? []).map((t: any) => t.type ?? 'scatter')),
);
const kinds = new Set(
old.filter((i) => i.kind === 'plot').map((i) => kindOf(i.traces.map((t: any) => t.type))),
);
for (const types of drawn) expect(kinds).toContain(kindOf(types));
});
}
for (const domain of ['cacu', 'cama', 'tea']) {
test(`datos y definiciones ${domain}: the old tab's headings and an indicator that opens`, async ({
page,
}) => {
const tabs = JSON.parse(
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
).tabs;
const old = (tabs['Datos y definiciones'] as any[])
.filter((i) => ['h2', 'h3'].includes(i.kind))
.map((i) => i.text);
await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
const tab = page.locator('app-tab-definiciones');
await expect(tab.getByRole('heading', { name: 'Catálogo de indicadores' })).toBeVisible();
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings).toEqual(old);
await tab.locator('summary').first().click();
await expect(
tab.getByRole('heading', { name: 'Tipos de periodo admitidos' }).first(),
).toBeVisible();
});
}
/** Waits for a page's data: no loading indicator left. */
async function loaded(page: Page): Promise<void> {
await expect(page.locator('app-loading, mat-progress-bar')).toHaveCount(0, {
timeout: 5 * 60_000,
});
await page.waitForTimeout(1000); // plots finish drawing
}
for (const width of [1440, 820]) {
test(`layout at ${width} px: no page has overlapping, clipped or wrapped labels`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const found: string[] = [];
const check = async (where: string) => {
await loaded(page);
for (const p of await layoutProblems(page)) found.push(`${where}: ${p}`);
};
for (const domain of ['cacu', 'cama', 'tea']) {
await page.goto(`/indicadores/${domain}`);
const tabs = page.locator('.mdc-tab');
for (let i = 0; i < (await tabs.count()); i++) {
await tabs.nth(i).click();
await check(`${domain} tab ${i + 1}`);
}
// the record of the risk list's first patient
await tabs.nth(2).click();
await loaded(page);
const first = page.locator('table a[href*="/pacientes/"]').first();
if (await first.count()) {
await first.click();
await check(`${domain} record`);
}
await page.goto(`/gobernanza/${domain}`);
await check(`${domain} gobernanza`);
}
await page.goto('/conectar');
await check('conectar');
// a pipeline open, a node chosen, in both of its panel's tabs
await page.locator('.pipelines [mat-list-item]').first().click();
await page.locator('.node-caption').first().dispatchEvent('click'); // the canvas may draw it off-screen
await check('conectar node');
await page.getByRole('tab', { name: 'Avanzado' }).click();
await check('conectar node, advanced');
await page.goto('/revision');
const tabs = page.locator('.mdc-tab');
for (let i = 0; i < (await tabs.count()); i++) {
await tabs.nth(i).click();
await check(`revision tab ${i + 1}`);
}
expect(found).toEqual([]);
});
}
-88
View File
@@ -1,88 +0,0 @@
import type { Page } from '@playwright/test';
/** SIMULATED answers. The pages read the API's aggregated MeasureReports; these helpers pass them
* through the browser and rewrite the screening-round strata, so the cards can be tried with the
* groups the contract of `rebuild` allows (stratum `round`, crossed `round-category`) without
* loading data. They prove how the page draws such answers, not what the backend computes.
*
* - `as-is`: the answers untouched, with a stratum named `screening_round` renamed `round`.
* - `no-initial`: nobody is in the initial group (the group is absent and the totals drop).
* - `unclassified`: the initial group folds into "Sin dato" (what 5740's answers look like).
* - `unpublished`: the round strata are not in the answers. */
export type Simulation = 'as-is' | 'no-initial' | 'unclassified' | 'unpublished';
type Stratum = {
value?: { text?: string };
component?: { value?: { text?: string } }[];
population?: { code?: { coding?: { code?: string }[] }; count: number }[];
};
type Stratifier = { code?: { coding?: { code?: string }[] }[]; stratum?: Stratum[] };
const named = (s: Stratifier) => (s.code ?? []).map((c) => c.coding?.[0]?.code).join('-');
const label = (x: Stratum) => x.component?.[0]?.value?.text ?? x.value?.text;
const pop = (o: { population?: Stratum['population'] }, code: string) =>
o.population?.find((p) => p.code?.coding?.[0]?.code === code);
function fold(into: Stratum, from: Stratum) {
for (const p of from.population ?? []) {
const q = pop(into, p.code!.coding![0].code!);
if (q) q.count += p.count;
else (into.population ??= []).push(structuredClone(p));
}
}
export function simulate(report: any, how: Simulation) {
const group = report?.group?.[0];
if (!group) return report;
for (const s of group.stratifier ?? ([] as Stratifier[]))
for (const c of s.code ?? []) {
const k = c.coding?.[0];
if (k?.code === 'screening_round') k.code = 'round';
}
const rounds: Stratifier[] = (group.stratifier ?? []).filter((s: Stratifier) =>
['round', 'round-category'].includes(named(s)),
);
if (how === 'unpublished')
group.stratifier = (group.stratifier ?? []).filter((s: Stratifier) => !rounds.includes(s));
if (how === 'no-initial' || how === 'unclassified')
for (const s of rounds) {
const initial = (s.stratum ?? []).filter((x) => label(x) === 'initial');
const rest = (s.stratum ?? []).filter((x) => label(x) !== 'initial');
for (const x of initial) {
if (how === 'unclassified') {
const other = x.component?.[1]?.value?.text;
const target = rest.find(
(y) => label(y) === 'no_data' && (!other || y.component?.[1]?.value?.text === other),
);
if (target) fold(target, x);
else {
(x.component ? x.component[0].value! : x.value!).text = 'no_data';
rest.push(x);
}
} else if (named(s) === 'round') {
// the group vanishes and the period's total drops by its patients: a real zero
for (const p of x.population ?? []) {
const total = pop(group, p.code!.coding![0].code!);
if (total && p.code!.coding![0].code !== 'numerator')
total.count = Math.max(0, total.count - p.count);
}
}
}
s.stratum = rest;
}
return report;
}
/** Answers every CaCu MeasureReport search through `simulate`. */
export async function simulateRounds(page: Page, how: Simulation) {
await page.route('**/api/cacu/fhir/MeasureReport**', async (route) => {
const response = await route.fetch();
const body = await response.json();
for (const entry of body.entry ?? []) simulate(entry.resource, how);
await route.fulfill({
response,
body: JSON.stringify(body),
contentType: 'application/fhir+json',
});
});
}
+1 -1
View File
@@ -3,7 +3,7 @@ server {
root /usr/share/nginx/html;
location /api/ {
proxy_pass http://api:8000/;
proxy_read_timeout 120s;
proxy_read_timeout 30s;
}
location / {
try_files $uri $uri/ /index.html;
+65 -2229
View File
File diff suppressed because it is too large Load Diff
+2 -285
View File
@@ -25,11 +25,9 @@
"d3-zoom": "3.0.0",
"material-symbols": "0.48.3",
"ngx-vflow": "2.7.0",
"pdfmake": "0.3.14",
"plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"write-excel-file": "4.1.1"
"tslib": "^2.3.0"
},
"devDependencies": {
"@angular/build": "^22.3.0",
@@ -40,7 +38,6 @@
"@types/d3-selection": "3.0.13",
"@types/d3-zoom": "3.0.9",
"@types/fhir": "0.0.44",
"@types/pdfmake": "0.3.5",
"@types/plotly.js": "3.0.15",
"jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0",
@@ -2405,30 +2402,6 @@
"@ngx-formly/core": "11.2.0"
}
},
"node_modules/@noble/ciphers": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz",
"integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/hashes": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
"integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@oxc-parser/binding-android-arm-eabi": {
"version": "0.158.0",
"resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.158.0.tgz",
@@ -3492,12 +3465,6 @@
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
"license": "MIT"
},
"node_modules/@swc/helpers": {
"version": "0.5.24",
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.24.tgz",
"integrity": "sha512-6tcXo4kA8HgGO7AVmawB57RYi/piBPYVHVcO6dXjX+SZw8GoHmi262sp4v2Ha2kNP9Cx84qei27yT+fjS1lxgg==",
"license": "Apache-2.0"
},
"node_modules/@tybys/wasm-util": {
"version": "0.10.5",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz",
@@ -3603,37 +3570,6 @@
"license": "MIT",
"peer": true
},
"node_modules/@types/node": {
"version": "26.6.11",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.11.tgz",
"integrity": "sha512-uUyQ2XLEz+EXh34lmS3GhKrkqn/8FU7KUiKRpk347At2bmnMVWss45yz8b4FG/tUtmV1tV/+TVkITItPROyeeQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~8.9.0"
}
},
"node_modules/@types/pdfkit": {
"version": "0.17.7",
"resolved": "https://registry.npmjs.org/@types/pdfkit/-/pdfkit-0.17.7.tgz",
"integrity": "sha512-VMOZDWw7HtNtLbjIuHIhVArm9PlV0gxpz32jAl1IuXWlIgbr1lKFoTsrtvEzY8a9BIpQJEE5DwNPKD50otTs6g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/pdfmake": {
"version": "0.3.5",
"resolved": "https://registry.npmjs.org/@types/pdfmake/-/pdfmake-0.3.5.tgz",
"integrity": "sha512-AQI4ISWzt7qmnKaipkikibz9x2XIvU/1zqfEHwKhBU7vP6oIhlGoLB9KsSIAryH7f9uuJebXScldb6F4ebwFxg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
"@types/pdfkit": "*"
}
},
"node_modules/@types/plotly.js": {
"version": "3.0.15",
"resolved": "https://registry.npmjs.org/@types/plotly.js/-/plotly.js-3.0.15.tgz",
@@ -3880,15 +3816,6 @@
"node": ">=12"
}
},
"node_modules/base64-js": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.8.tgz",
"integrity": "sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/baseline-browser-mapping": {
"version": "2.11.39",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.39.tgz",
@@ -3964,35 +3891,6 @@
"url": "https://github.com/sponsors/fb55"
}
},
"node_modules/brotli": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/brotli/-/brotli-1.3.3.tgz",
"integrity": "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.1.2"
}
},
"node_modules/brotli/node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/browserslist": {
"version": "4.29.6",
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz",
@@ -4221,15 +4119,6 @@
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/clone": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz",
"integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==",
"license": "MIT",
"engines": {
"node": ">=0.8"
}
},
"node_modules/colorjs.io": {
"version": "0.7.1",
"resolved": "https://registry.npmjs.org/colorjs.io/-/colorjs.io-0.7.1.tgz",
@@ -4437,12 +4326,6 @@
"node": ">=8"
}
},
"node_modules/dfa": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz",
"integrity": "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==",
"license": "MIT"
},
"node_modules/dom-serializer": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz",
@@ -4678,6 +4561,7 @@
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"dev": true,
"license": "MIT"
},
"node_modules/fast-string-truncated-width": {
@@ -4742,12 +4626,6 @@
}
}
},
"node_modules/fflate": {
"version": "0.8.3",
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
"license": "MIT"
},
"node_modules/flru": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/flru/-/flru-1.0.2.tgz",
@@ -4758,23 +4636,6 @@
"node": ">=6"
}
},
"node_modules/fontkit": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/fontkit/-/fontkit-2.0.4.tgz",
"integrity": "sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==",
"license": "MIT",
"dependencies": {
"@swc/helpers": "^0.5.12",
"brotli": "^1.3.2",
"clone": "^2.1.2",
"dfa": "^1.2.0",
"fast-deep-equal": "^3.1.3",
"restructure": "^3.0.0",
"tiny-inflate": "^1.0.3",
"unicode-properties": "^1.4.0",
"unicode-trie": "^2.0.0"
}
},
"node_modules/fs-extra": {
"version": "11.4.1",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz",
@@ -5505,16 +5366,6 @@
"url": "https://opencollective.com/parcel"
}
},
"node_modules/linebreak": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz",
"integrity": "sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==",
"license": "MIT",
"dependencies": {
"base64-js": "0.0.8",
"unicode-trie": "^2.0.0"
}
},
"node_modules/listr2": {
"version": "11.4.1",
"resolved": "https://registry.npmjs.org/listr2/-/listr2-11.4.1.tgz",
@@ -5993,12 +5844,6 @@
"@oxc-parser/binding-win32-x64-msvc": "0.158.0"
}
},
"node_modules/pako": {
"version": "0.2.9",
"resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz",
"integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==",
"license": "MIT"
},
"node_modules/parse5": {
"version": "8.1.1",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz",
@@ -6077,34 +5922,6 @@
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/pdfkit": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.20.2.tgz",
"integrity": "sha512-Q/w03ICAQyXfHNfTsg1udp0ADerdBN0s7a6XSPL7J7Ro6ABnafoBOCDBstIO9U02mvzHEV8HrvFIw5iV5ejIRA==",
"license": "MIT",
"dependencies": {
"@noble/ciphers": "^1.3.0",
"@noble/hashes": "^1.8.0",
"fflate": "^0.8.3",
"fontkit": "^2.0.4",
"linebreak": "^1.1.0",
"png-js": "^2.0.0"
}
},
"node_modules/pdfmake": {
"version": "0.3.14",
"resolved": "https://registry.npmjs.org/pdfmake/-/pdfmake-0.3.14.tgz",
"integrity": "sha512-EDyOlwiDnE8e0eITSpHwZCVAP/veWq0TxA2RyhoDO0cSLat7HEGNtKUN6UiW9+YovO2GhcWlK99Q7tj9sof9gg==",
"license": "MIT",
"dependencies": {
"linebreak": "^1.1.0",
"pdfkit": "^0.20.2",
"xmldoc": "^2.0.3"
},
"engines": {
"node": ">=20"
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -6173,14 +5990,6 @@
"integrity": "sha512-3UkyAT7/U8f3sOLavLnUjA6mqFmnqEe246GZhxT0J3TT9oZ0mh6SgwsL1yo/3/4xfmRSDFdGOxe+EsvT2XiE0g==",
"license": "MIT"
},
"node_modules/png-js": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/png-js/-/png-js-2.0.0.tgz",
"integrity": "sha512-GdzJuUMc6ZSpxFJWVxtOH1bzYHym+TOnveqUjb+VJIbZWbZzyiRGFiKhbiielfpYbgMlhHVhsJ0FTazfuRFkMA==",
"dependencies": {
"fflate": "^0.8.2"
}
},
"node_modules/postcss": {
"version": "8.5.33",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz",
@@ -6356,12 +6165,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/restructure": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/restructure/-/restructure-3.0.2.tgz",
"integrity": "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==",
"license": "MIT"
},
"node_modules/rolldown": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.1.tgz",
@@ -6860,15 +6663,6 @@
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/sax": {
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",
"integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=11.0.0"
}
},
"node_modules/saxes": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
@@ -7058,12 +6852,6 @@
"node": ">=16.0.0"
}
},
"node_modules/tiny-inflate": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz",
"integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==",
"license": "MIT"
},
"node_modules/tinybench": {
"version": "6.2.5",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.5.tgz",
@@ -7191,53 +6979,6 @@
"node": ">=22.19.0"
}
},
"node_modules/undici-types": {
"version": "8.9.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
"integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
"dev": true,
"license": "MIT"
},
"node_modules/unicode-properties": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz",
"integrity": "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.3.0",
"unicode-trie": "^2.0.0"
}
},
"node_modules/unicode-properties/node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/unicode-trie": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz",
"integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==",
"license": "MIT",
"dependencies": {
"pako": "^0.2.5",
"tiny-inflate": "^1.0.0"
}
},
"node_modules/universalify": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
@@ -7935,18 +7676,6 @@
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/write-excel-file": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/write-excel-file/-/write-excel-file-4.1.1.tgz",
"integrity": "sha512-MUnCnNtQrcZek832ZcU24uU0rSphFmKPD1DvIjXOlygVb93CV7Tme6H3jUTkxsMmjB2W7HIzERzjqTi5kui71A==",
"license": "MIT",
"dependencies": {
"fflate": "^0.8.2"
},
"engines": {
"node": ">=18"
}
},
"node_modules/xml-name-validator": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
@@ -7964,18 +7693,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/xmldoc": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/xmldoc/-/xmldoc-2.0.3.tgz",
"integrity": "sha512-6gRk4NY/Jvg67xn7OzJuxLRsGgiXBaPUQplVJ/9l99uIugxh4FTOewYz5ic8WScj7Xx/2WvhENiQKwkK9RpE4w==",
"license": "MIT",
"dependencies": {
"sax": "^1.4.3"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/xxhash-wasm": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz",
+1 -4
View File
@@ -29,11 +29,9 @@
"d3-zoom": "3.0.0",
"material-symbols": "0.48.3",
"ngx-vflow": "2.7.0",
"pdfmake": "0.3.14",
"plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"write-excel-file": "4.1.1"
"tslib": "^2.3.0"
},
"devDependencies": {
"@angular/build": "^22.3.0",
@@ -44,7 +42,6 @@
"@types/d3-selection": "3.0.13",
"@types/d3-zoom": "3.0.9",
"@types/fhir": "0.0.44",
"@types/pdfmake": "0.3.5",
"@types/plotly.js": "3.0.15",
"jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0",
-32
View File
@@ -1,32 +0,0 @@
/* 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 { Login } from '../../models/login';
export interface AuthCookieLogin$Params {
body: Login
}
export function authCookieLogin(http: HttpClient, rootUrl: string, params: AuthCookieLogin$Params, context?: HttpContext): Observable<StrictHttpResponse<any>> {
const rb = new RequestBuilder(rootUrl, authCookieLogin.PATH, 'post');
if (params) {
rb.body(params.body, 'application/x-www-form-urlencoded');
}
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<any>;
})
);
}
authCookieLogin.PATH = '/auth/login';
-29
View File
@@ -1,29 +0,0 @@
/* 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';
export interface AuthCookieLogout$Params {
}
export function authCookieLogout(http: HttpClient, rootUrl: string, params?: AuthCookieLogout$Params, context?: HttpContext): Observable<StrictHttpResponse<any>> {
const rb = new RequestBuilder(rootUrl, authCookieLogout.PATH, 'post');
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<any>;
})
);
}
authCookieLogout.PATH = '/auth/logout';
-18
View File
@@ -24,21 +24,6 @@ export interface SearchPatient$Params {
'follow-up-cutoff'?: (string | null);
'follow-up-status'?: (string | null);
/**
* each word starts a word of her name (case and accents ignored)
*/
name?: (string | null);
/**
* [system|]value: a CURP or record number (case ignored)
*/
identifier?: (string | null);
/**
* gt, ge, lt or le and a day (2000-12-31)
*/
birthdate?: Array<string>;
/**
* -recent or -risk-<outcome>
*/
@@ -71,9 +56,6 @@ export function searchPatient(http: HttpClient, rootUrl: string, params: SearchP
rb.query('follow-up-window', params['follow-up-window'], {});
rb.query('follow-up-cutoff', params['follow-up-cutoff'], {});
rb.query('follow-up-status', params['follow-up-status'], {});
rb.query('name', params.name, {});
rb.query('identifier', params.identifier, {});
rb.query('birthdate', params.birthdate, {});
rb.query('_sort', params['_sort'], {});
rb.query('risk-horizon', params['risk-horizon'], {});
rb.query('_revinclude', params['_revinclude'], {});
-32
View File
@@ -1,32 +0,0 @@
/* 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 { Browsed } from '../../models/browsed';
export interface Browse$Params {
path?: (string | null);
}
export function browse(http: HttpClient, rootUrl: string, params?: Browse$Params, context?: HttpContext): Observable<StrictHttpResponse<Browsed>> {
const rb = new RequestBuilder(rootUrl, browse.PATH, 'get');
if (params) {
rb.query('path', params.path, {});
}
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<Browsed>;
})
);
}
browse.PATH = '/ingest/sources/browse';
-34
View File
@@ -1,34 +0,0 @@
/* 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 { SignIn } from '../../models/sign-in';
export interface OauthStart$Params {
provider: string;
origin: string;
}
export function oauthStart(http: HttpClient, rootUrl: string, params: OauthStart$Params, context?: HttpContext): Observable<StrictHttpResponse<SignIn>> {
const rb = new RequestBuilder(rootUrl, oauthStart.PATH, 'get');
if (params) {
rb.path('provider', params.provider, {});
rb.query('origin', params.origin, {});
}
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<SignIn>;
})
);
}
oauthStart.PATH = '/ingest/sources/oauth/{provider}/start';
-30
View File
@@ -1,30 +0,0 @@
/* 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 { Catalog } from '../../models/catalog';
export interface SourceTypes$Params {
}
export function sourceTypes(http: HttpClient, rootUrl: string, params?: SourceTypes$Params, context?: HttpContext): Observable<StrictHttpResponse<Catalog>> {
const rb = new RequestBuilder(rootUrl, sourceTypes.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<Catalog>;
})
);
}
sourceTypes.PATH = '/ingest/sources/types';
-35
View File
@@ -1,35 +0,0 @@
/* 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 { Answers } from '../../models/answers';
import { Tested } from '../../models/tested';
export interface TestSource$Params {
limit?: number;
body: Answers
}
export function testSource(http: HttpClient, rootUrl: string, params: TestSource$Params, context?: HttpContext): Observable<StrictHttpResponse<Tested>> {
const rb = new RequestBuilder(rootUrl, testSource.PATH, 'post');
if (params) {
rb.query('limit', params.limit, {});
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<Tested>;
})
);
}
testSource.PATH = '/ingest/sources/test';
+6 -3
View File
@@ -8,13 +8,14 @@ import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { BodyUpload } from '../../models/body-upload';
import { Uploaded } from '../../models/uploaded';
export interface Upload$Params {
body: BodyUpload
}
export function upload(http: HttpClient, rootUrl: string, params: Upload$Params, context?: HttpContext): Observable<StrictHttpResponse<Uploaded>> {
export function upload(http: HttpClient, rootUrl: string, params: Upload$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, upload.PATH, 'post');
if (params) {
rb.body(params.body, 'multipart/form-data');
@@ -25,7 +26,9 @@ export function upload(http: HttpClient, rootUrl: string, params: Upload$Params,
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<Uploaded>;
return r as StrictHttpResponse<{
[key: string]: string;
}>;
})
);
}
+2 -3
View File
@@ -8,13 +8,12 @@ import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
import { Model } from '../../models/model';
export interface Models$Params {
domain: Domain;
}
export function models(http: HttpClient, rootUrl: string, params: Models$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<Model>>> {
export function models(http: HttpClient, rootUrl: string, params: Models$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<string>>> {
const rb = new RequestBuilder(rootUrl, models.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
@@ -25,7 +24,7 @@ export function models(http: HttpClient, rootUrl: string, params: Models$Params,
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<Array<Model>>;
return r as StrictHttpResponse<Array<string>>;
})
);
}
+1 -1
View File
@@ -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' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
}
export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
+1 -1
View File
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Held$Params {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
}
export function held(http: HttpClient, rootUrl: string, params: Held$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
-35
View File
@@ -1,35 +0,0 @@
/* 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';
export interface Unrecognised$Params {
pipeline: string;
}
export function unrecognised(http: HttpClient, rootUrl: string, params: Unrecognised$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
[key: string]: any;
}>>> {
const rb = new RequestBuilder(rootUrl, unrecognised.PATH, 'get');
if (params) {
rb.query('pipeline', params.pipeline, {});
}
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<{
[key: string]: any;
}>>;
})
);
}
unrecognised.PATH = '/review/unrecognised';
-35
View File
@@ -1,35 +0,0 @@
/* 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';
export interface TerminateRun$Params {
run_id: string;
}
export function terminateRun(http: HttpClient, rootUrl: string, params: TerminateRun$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, terminateRun.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<{
[key: string]: string;
}>;
})
);
}
terminateRun.PATH = '/runs/{run_id}/terminate';
-33
View File
@@ -1,33 +0,0 @@
/* 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 { UserCreate } from '../../models/user-create';
import { UserRead } from '../../models/user-read';
export interface RegisterRegister$Params {
body: UserCreate
}
export function registerRegister(http: HttpClient, rootUrl: string, params: RegisterRegister$Params, context?: HttpContext): Observable<StrictHttpResponse<UserRead>> {
const rb = new RequestBuilder(rootUrl, registerRegister.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<UserRead>;
})
);
}
registerRegister.PATH = '/users/register';
@@ -1,30 +0,0 @@
/* 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 { UserRead } from '../../models/user-read';
export interface UsersCurrentUser$Params {
}
export function usersCurrentUser(http: HttpClient, rootUrl: string, params?: UsersCurrentUser$Params, context?: HttpContext): Observable<StrictHttpResponse<UserRead>> {
const rb = new RequestBuilder(rootUrl, usersCurrentUser.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<UserRead>;
})
);
}
usersCurrentUser.PATH = '/users/me';
-31
View File
@@ -1,31 +0,0 @@
/* 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';
export interface UsersDeleteUser$Params {
id: string;
}
export function usersDeleteUser(http: HttpClient, rootUrl: string, params: UsersDeleteUser$Params, context?: HttpContext): Observable<StrictHttpResponse<void>> {
const rb = new RequestBuilder(rootUrl, usersDeleteUser.PATH, 'delete');
if (params) {
rb.path('id', params.id, {});
}
return http.request(
rb.build({ responseType: 'text', accept: '*/*', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return (r as HttpResponse<any>).clone({ body: undefined }) as StrictHttpResponse<void>;
})
);
}
usersDeleteUser.PATH = '/users/{id}';
@@ -1,33 +0,0 @@
/* 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 { UserRead } from '../../models/user-read';
import { UserUpdate } from '../../models/user-update';
export interface UsersPatchCurrentUser$Params {
body: UserUpdate
}
export function usersPatchCurrentUser(http: HttpClient, rootUrl: string, params: UsersPatchCurrentUser$Params, context?: HttpContext): Observable<StrictHttpResponse<UserRead>> {
const rb = new RequestBuilder(rootUrl, usersPatchCurrentUser.PATH, 'patch');
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<UserRead>;
})
);
}
usersPatchCurrentUser.PATH = '/users/me';
-35
View File
@@ -1,35 +0,0 @@
/* 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 { UserRead } from '../../models/user-read';
import { UserUpdate } from '../../models/user-update';
export interface UsersPatchUser$Params {
id: string;
body: UserUpdate
}
export function usersPatchUser(http: HttpClient, rootUrl: string, params: UsersPatchUser$Params, context?: HttpContext): Observable<StrictHttpResponse<UserRead>> {
const rb = new RequestBuilder(rootUrl, usersPatchUser.PATH, 'patch');
if (params) {
rb.path('id', params.id, {});
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<UserRead>;
})
);
}
usersPatchUser.PATH = '/users/{id}';
-32
View File
@@ -1,32 +0,0 @@
/* 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 { UserRead } from '../../models/user-read';
export interface UsersUser$Params {
id: string;
}
export function usersUser(http: HttpClient, rootUrl: string, params: UsersUser$Params, context?: HttpContext): Observable<StrictHttpResponse<UserRead>> {
const rb = new RequestBuilder(rootUrl, usersUser.PATH, 'get');
if (params) {
rb.path('id', params.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<UserRead>;
})
);
}
usersUser.PATH = '/users/{id}';
-28
View File
@@ -1,10 +1,6 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export type { AuthCookieLogin$Params as AuthCookieLogin$Params } from './fn/auth/auth-cookie-login';
export { authCookieLogin as authCookieLogin } from './fn/auth/auth-cookie-login';
export type { AuthCookieLogout$Params as AuthCookieLogout$Params } from './fn/auth/auth-cookie-logout';
export { authCookieLogout as authCookieLogout } from './fn/auth/auth-cookie-logout';
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';
@@ -27,18 +23,10 @@ export type { StartRun$Params as StartRun$Params } from './fn/ingest/start-run';
export { startRun as startRun } from './fn/ingest/start-run';
export type { Schema$Params as Schema$Params } from './fn/ingest/schema';
export { schema as schema } from './fn/ingest/schema';
export type { Browse$Params as Browse$Params } from './fn/ingest/browse';
export { browse as browse } from './fn/ingest/browse';
export type { OauthStart$Params as OauthStart$Params } from './fn/ingest/oauth-start';
export { oauthStart as oauthStart } from './fn/ingest/oauth-start';
export type { SourcePreview$Params as SourcePreview$Params } from './fn/ingest/source-preview';
export { sourcePreview as sourcePreview } from './fn/ingest/source-preview';
export type { SourceResources$Params as SourceResources$Params } from './fn/ingest/source-resources';
export { sourceResources as sourceResources } from './fn/ingest/source-resources';
export type { TestSource$Params as TestSource$Params } from './fn/ingest/test-source';
export { testSource as testSource } from './fn/ingest/test-source';
export type { SourceTypes$Params as SourceTypes$Params } from './fn/ingest/source-types';
export { sourceTypes as sourceTypes } from './fn/ingest/source-types';
export type { Upload$Params as Upload$Params } from './fn/ingest/upload';
export { upload as upload } from './fn/ingest/upload';
export type { Models$Params as Models$Params } from './fn/models/models';
@@ -71,28 +59,12 @@ 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 { Unrecognised$Params as Unrecognised$Params } from './fn/review/unrecognised';
export { unrecognised as unrecognised } from './fn/review/unrecognised';
export type { RunStatus$Params as RunStatus$Params } from './fn/runs/run-status';
export { runStatus as runStatus } from './fn/runs/run-status';
export type { TerminateRun$Params as TerminateRun$Params } from './fn/runs/terminate-run';
export { terminateRun as terminateRun } from './fn/runs/terminate-run';
export type { Studies$Params as Studies$Params } from './fn/eeg/studies';
export { studies as studies } from './fn/eeg/studies';
export type { Study$Params as Study$Params } from './fn/eeg/study';
export { study as study } from './fn/eeg/study';
export type { UsersCurrentUser$Params as UsersCurrentUser$Params } from './fn/users/users-current-user';
export { usersCurrentUser as usersCurrentUser } from './fn/users/users-current-user';
export type { UsersPatchCurrentUser$Params as UsersPatchCurrentUser$Params } from './fn/users/users-patch-current-user';
export { usersPatchCurrentUser as usersPatchCurrentUser } from './fn/users/users-patch-current-user';
export type { RegisterRegister$Params as RegisterRegister$Params } from './fn/users/register-register';
export { registerRegister as registerRegister } from './fn/users/register-register';
export type { UsersUser$Params as UsersUser$Params } from './fn/users/users-user';
export { usersUser as usersUser } from './fn/users/users-user';
export type { UsersDeleteUser$Params as UsersDeleteUser$Params } from './fn/users/users-delete-user';
export { usersDeleteUser as usersDeleteUser } from './fn/users/users-delete-user';
export type { UsersPatchUser$Params as UsersPatchUser$Params } from './fn/users/users-patch-user';
export { usersPatchUser as usersPatchUser } from './fn/users/users-patch-user';
export type { PostBundle$Params as PostBundle$Params } from './fn/fhir/post-bundle';
export { postBundle as postBundle } from './fn/fhir/post-bundle';
export type { SearchCondition$Params as SearchCondition$Params } from './fn/fhir/search-condition';
-22
View File
@@ -2,52 +2,30 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export type { Analysis } from './models/analysis';
export type { Answers } from './models/answers';
export type { BodyAddClinicalValidation } from './models/body-add-clinical-validation';
export type { BodyUpload } from './models/body-upload';
export type { Browsed } from './models/browsed';
export type { Catalog } from './models/catalog';
export type { Condition } from './models/condition';
export type { Correction } from './models/correction';
export type { Domain } from './models/domain';
export type { Entry } from './models/entry';
export type { ErrorModel } from './models/error-model';
export type { Extract } from './models/extract';
export type { Fhir } from './models/fhir';
export type { FieldSpec } from './models/field-spec';
export type { Group } from './models/group';
export type { Guided } from './models/guided';
export type { HttpValidationError } from './models/http-validation-error';
export type { Join } from './models/join';
export type { Link } from './models/link';
export type { Listing } from './models/listing';
export type { Login } from './models/login';
export type { Map } from './models/map';
export type { Metric } from './models/metric';
export type { Model } from './models/model';
export type { Option } from './models/option';
export type { PersonDecision } from './models/person-decision';
export type { Pipeline } from './models/pipeline';
export type { Position } from './models/position';
export type { Provider } from './models/provider';
export type { Read } from './models/read';
export type { Rejection } from './models/rejection';
export type { Relation } from './models/relation';
export type { Route } from './models/route';
export type { RunRequest } from './models/run-request';
export type { SavedPipeline } from './models/saved-pipeline';
export type { SignIn } from './models/sign-in';
export type { Site } from './models/site';
export type { Source } from './models/source';
export type { SourceRef } from './models/source-ref';
export type { SourceType } from './models/source-type';
export type { Study } from './models/study';
export type { Target } from './models/target';
export type { Tested } from './models/tested';
export type { Training } from './models/training';
export type { Uploaded } from './models/uploaded';
export type { UserCreate } from './models/user-create';
export type { UserRead } from './models/user-read';
export type { UserUpdate } from './models/user-update';
export type { ValidationError } from './models/validation-error';
export type { Version } from './models/version';
-2
View File
@@ -2,12 +2,10 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Metric } from '../models/metric';
import { Relation } from '../models/relation';
export interface Analysis {
age_months: (number | null);
id: string;
level: (string | null);
metrics: Array<Metric>;
relation?: Array<Relation>;
valid: (boolean | null);
}
-11
View File
@@ -1,11 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Answers {
answers?: {
[key: string]: any;
};
node?: (string | null);
pipeline?: (string | null);
type: string;
}
+1 -2
View File
@@ -2,6 +2,5 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface BodyUpload {
files: Array<string>;
folder?: (string | null);
file: string;
}
-9
View File
@@ -1,9 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Entry } from '../models/entry';
export interface Browsed {
entries: Array<Entry>;
parent: (string | null);
path: (string | null);
}
-19
View File
@@ -1,19 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Group } from '../models/group';
import { Option } from '../models/option';
import { Provider } from '../models/provider';
import { SourceType } from '../models/source-type';
export interface Catalog {
formats: Array<Option>;
groups: {
[key: string]: Group;
};
providers: {
[key: string]: Provider;
};
types: {
[key: string]: SourceType;
};
}
-8
View File
@@ -2,15 +2,7 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Condition {
/**
* Por ejemplo «text», el texto leído del documento.
*/
column: string;
op: 'equals' | 'contains' | 'matches' | 'present';
/**
* Lo que se busca; por ejemplo «citología».
*/
value?: string;
}
+1 -1
View File
@@ -7,7 +7,7 @@
* field (a mistyped record number) or a study's (a stage the scan made unreadable).
*/
export interface Correction {
entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
field: string;
record: string;
value: string;
-9
View File
@@ -1,9 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Entry {
kind: 'folder' | 'file';
name: string;
path: string;
size?: (number | null);
}
-8
View File
@@ -1,8 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface ErrorModel {
detail: (string | {
[key: string]: string;
});
}
+1 -24
View File
@@ -13,40 +13,17 @@ import { Position } from '../models/position';
*/
export interface Extract {
column: (string | Array<string>);
/**
* Dato → columna, sin leer el texto.
*/
columns?: {
[key: string]: string;
};
concept_map?: (string | null);
/**
* Qué estudio se saca del documento.
*/
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
formats?: {
[key: string]: string;
};
/**
* Para el modelo de lenguaje.
*/
hints?: string;
id: string;
inputs?: Array<string>;
kind?: 'extract';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
method?: 'auto' | 'llm' | 'patterns';
/**
* Dato → expresión con un grupo ( ).
*/
patterns?: {
[key: string]: string;
};
+1 -5
View File
@@ -11,14 +11,10 @@ import { Position } from '../models/position';
export interface Fhir {
column?: string;
concept_map?: (string | null);
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string;
inputs?: Array<string>;
kind?: 'fhir';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
position?: (Position | null);
}
-15
View File
@@ -1,15 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Option } from '../models/option';
export interface FieldSpec {
advanced?: boolean;
default?: any;
help?: string;
label: string;
options?: Array<Option>;
placeholder?: string;
provider?: (string | null);
required?: boolean;
type?: 'text' | 'number' | 'password' | 'select' | 'folder' | 'server_file' | 'upload' | 'url' | 'oauth' | 'table' | 'format' | 'columns';
}
-7
View File
@@ -1,7 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Group {
description: string;
title: string;
}
-14
View File
@@ -1,14 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* How the Conectar dialog drew a source: its type (core.sources) and the answers given.
* The node's dlt fields are made from them; drawn by hand ("Avanzado"), a node has none.
*/
export interface Guided {
answers?: {
[key: string]: any;
};
type: string;
}
-8
View File
@@ -11,15 +11,7 @@ export interface Join {
id: string;
inputs?: Array<string>;
kind?: 'join';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
/**
* Columna de la primera entrada = columna de la segunda.
*/
on: Array<[string, string]>;
position?: (Position | null);
}
-12
View File
@@ -16,20 +16,8 @@ export interface Link {
id: string;
inputs?: Array<string>;
kind?: 'link';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
position?: (Position | null);
/**
* Parecidos por encima de esto los ve un revisor.
*/
review?: number;
/**
* Vacío: las de siempre (mismo identificador, o misma fecha de nacimiento y nombre).
*/
rules?: Array<string>;
}
-15
View File
@@ -1,15 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* What "Probar conexión" shows: a database's tables (the resources of `source`, built
* from `args`), or the first rows the type's own node reads (files, records).
*/
export interface Listing {
args?: {
[key: string]: any;
};
kind: 'tables' | 'rows';
source?: (string | null);
}
-11
View File
@@ -1,11 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Login {
client_id?: (string | null);
client_secret?: (string | null);
grant_type?: (string | null);
password: string;
scope?: string;
username: string;
}
-20
View File
@@ -8,38 +8,18 @@ import { Position } from '../models/position';
* (core.concept_map), and its date formats.
*/
export interface Map {
/**
* La tabla de códigos del sitio.
*/
concept_map?: (string | null);
/**
* Dato de la plataforma → columna del sitio.
*/
fields: {
[key: string]: string;
};
/**
* Por ejemplo %d/%m/%Y.
*/
formats?: {
[key: string]: string;
};
id: string;
inputs?: Array<string>;
kind?: 'map';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
position?: (Position | null);
/**
* Un dato igual para todas las filas.
*/
values?: {
[key: string]: string;
};
-6
View File
@@ -1,16 +1,10 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Site } from '../models/site';
export interface Metric {
code: string;
electrodes?: Array<Site>;
median?: (number | null);
model: (string | null);
outside: (number | null);
p5?: (number | null);
p95?: (number | null);
value: number;
z: (number | null);
zones?: Array<Site>;
}
-7
View File
@@ -1,7 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Model {
name: string;
title: string;
}
-7
View File
@@ -1,7 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Option {
label: string;
value: any;
}
-17
View File
@@ -1,17 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* A sign-in button's OAuth 2.0 provider (authorization code flow).
*/
export interface Provider {
authorize_params?: {
[key: string]: string;
};
authorize_url: string;
env: string;
scope: string;
title: string;
token_url: string;
}
-8
View File
@@ -7,18 +7,10 @@ import { Position } from '../models/position';
* Files in a column (PDF, Word, Excel, scans...) to text (MarkItDown, OCRmyPDF).
*/
export interface Read {
/**
* Donde la entrada trae cada documento.
*/
column: string;
id: string;
inputs?: Array<string>;
kind?: 'read';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
position?: (Position | null);
}
+1 -1
View File
@@ -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' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
reason: string;
record: string;
}
-25
View File
@@ -1,25 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* One pair of the champion EEG–ADOS-2 association, for this EEG (models.tea.association).
*/
export interface Relation {
biomarker: string;
ci_high: (number | null);
ci_low: (number | null);
event: string;
kind: string;
metric: string;
model: string;
n: number;
observed?: (number | null);
odds_ratio: number;
outcome_code: string;
probability: number;
q: (number | null);
reference_probability: number;
z: number;
zone: string;
}
+2 -13
View File
@@ -5,24 +5,13 @@ import { Condition } from '../models/condition';
import { Position } from '../models/position';
/**
* Only the rows where every condition holds (e.g. reports titled "Citología"). An
* `otherwise` route takes the rows of its input that none of the other routes on that
* input take (documents nobody recognises, for a reviewer), then its own conditions.
* Only the rows where every condition holds (e.g. reports titled "Citología").
*/
export interface Route {
id: string;
inputs?: Array<string>;
kind?: 'route';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
/**
* Recoge lo que nadie reconoce, para revisarlo.
*/
otherwise?: boolean;
position?: (Position | null);
when?: Array<Condition>;
when: Array<Condition>;
}
-7
View File
@@ -1,7 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface SignIn {
state: string;
url: string;
}
-8
View File
@@ -1,8 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Site {
site: string;
value: number;
z: (number | null);
}
-22
View File
@@ -1,22 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { FieldSpec } from '../models/field-spec';
import { Listing } from '../models/listing';
export interface SourceType {
args?: {
[key: string]: any;
};
description: string;
fields: {
[key: string]: FieldSpec;
};
group: string;
icon: string;
listing?: (Listing | null);
primary_key?: Array<string>;
resource?: (string | null);
source: string;
then?: (string | null);
title: string;
}
-26
View File
@@ -1,7 +1,6 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Guided } from '../models/guided';
import { Position } from '../models/position';
/**
@@ -9,41 +8,16 @@ import { Position } from '../models/position';
* own primary key or `primary_key`; replaced whole when it has none.
*/
export interface Source {
/**
* Los de la fuente dlt.
*/
args?: {
[key: string]: any;
};
guided?: (Guided | null);
id: string;
inputs?: Array<string>;
kind?: 'source';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
position?: (Position | null);
/**
* Columnas que identifican una fila.
*/
primary_key?: Array<string>;
/**
* Cuál, si la fuente ofrece varios (una tabla).
*/
resource?: (string | null);
/**
* Módulo:función de la fuente dlt.
*/
source: string;
/**
* Transformador dlt para los archivos.
*/
then?: (string | null);
}
+1 -9
View File
@@ -8,18 +8,10 @@ import { Position } from '../models/position';
* one `link` node among the inputs. Rule breaks are held for review.
*/
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' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string;
inputs?: Array<string>;
kind?: 'target';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
position?: (Position | null);
}
-12
View File
@@ -1,12 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Tested {
detail?: (string | null);
message: string;
ok: boolean;
rows?: Array<{
[key: string]: any;
}>;
tables?: Array<string>;
}
-7
View File
@@ -1,7 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Uploaded {
bucket_url: string;
files: Array<string>;
}
-13
View File
@@ -1,13 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Domain } from '../models/domain';
export interface UserCreate {
domains?: Array<Domain>;
email: string;
is_active?: (boolean | null);
is_superuser?: (boolean | null);
is_verified?: (boolean | null);
name?: string;
password: string;
}
-13
View File
@@ -1,13 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Domain } from '../models/domain';
export interface UserRead {
domains?: Array<Domain>;
email: string;
id: string;
is_active?: boolean;
is_superuser?: boolean;
is_verified?: boolean;
name?: string;
}
-13
View File
@@ -1,13 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Domain } from '../models/domain';
export interface UserUpdate {
domains?: (Array<Domain> | null);
email?: (string | null);
is_active?: (boolean | null);
is_superuser?: (boolean | null);
is_verified?: (boolean | null);
name?: (string | null);
password?: (string | null);
}
+8 -21
View File
@@ -4,9 +4,7 @@
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
</a>
@if (domain(); as current) {
<span class="title">{{
section() === 'gobernanza' ? 'Gobernanza de modelos' : 'Plataforma de Indicadores'
}}</span>
<span class="title">Plataforma de Indicadores</span>
<button
mat-flat-button
class="domain"
@@ -18,29 +16,18 @@
</button>
<mat-menu #menu="matMenu">
@for (d of others(); track d) {
<a mat-menu-item [routerLink]="['/' + section(), d]">{{ labels[d] }}</a>
<a mat-menu-item [routerLink]="['/indicadores', d]">{{ labels[d] }}</a>
}
</mat-menu>
} @else {
<span class="title"></span>
}
@if (!onLogin()) {
<nav class="sections" aria-label="Secciones">
<a [routerLink]="home()" routerLinkActive="active">Indicadores</a>
<a routerLink="/conectar" routerLinkActive="active">Conectar</a>
<a routerLink="/revision" routerLinkActive="active">Revisión</a>
<a routerLink="/gobernanza" routerLinkActive="active">Gobernanza</a>
</nav>
@if (auth.user(); as u) {
<button mat-button class="user" [matMenuTriggerFor]="account" aria-label="Cuenta">
<mat-icon>account_circle</mat-icon><span class="who-name">{{ u.name || u.email }}</span>
</button>
<mat-menu #account="matMenu">
<span class="who" mat-menu-item disabled>{{ u.email }}</span>
<button mat-menu-item (click)="logout()"><mat-icon>logout</mat-icon> Salir</button>
</mat-menu>
}
}
<nav class="sections" aria-label="Secciones">
<a routerLink="/indicadores/cacu" routerLinkActive="active">Indicadores</a>
<a routerLink="/conectar" routerLinkActive="active">Conectar</a>
<a routerLink="/revision" routerLinkActive="active">Revisión</a>
<a routerLink="/gobernanza" routerLinkActive="active">Gobernanza</a>
</nav>
</header>
<main class="main">
+15 -32
View File
@@ -1,38 +1,21 @@
import { Routes } from '@angular/router';
import { domainAllowed, signedIn } from './auth/auth';
export const routes: Routes = [
{ path: 'login', loadComponent: () => import('./auth/login').then((m) => m.Login) },
{ path: '', pathMatch: 'full', redirectTo: 'indicadores/cacu' },
{
path: '',
canActivateChild: [signedIn],
children: [
{ path: '', pathMatch: 'full', redirectTo: 'indicadores/cacu' },
{
path: 'indicadores/:domain',
canActivate: [domainAllowed],
loadComponent: () => import('./indicadores/indicadores').then((m) => m.Indicadores),
},
{
path: 'indicadores/:domain/pacientes/:id',
canActivate: [domainAllowed],
loadComponent: () => import('./paciente/paciente').then((m) => m.Paciente),
},
{
path: 'conectar',
loadComponent: () => import('./conectar/conectar').then((m) => m.Conectar),
},
{
path: 'revision',
loadComponent: () => import('./revision/revision').then((m) => m.Revision),
},
{ path: 'gobernanza', pathMatch: 'full', redirectTo: 'gobernanza/cacu' },
{
path: 'gobernanza/:domain',
canActivate: [domainAllowed],
loadComponent: () => import('./gobernanza/gobernanza').then((m) => m.Gobernanza),
},
{ path: '**', redirectTo: 'indicadores/cacu' },
],
path: 'indicadores/:domain',
loadComponent: () => import('./indicadores/indicadores').then((m) => m.Indicadores),
},
{
path: 'indicadores/:domain/pacientes/:id',
loadComponent: () => import('./paciente/paciente').then((m) => m.Paciente),
},
{ path: 'conectar', loadComponent: () => import('./conectar/conectar').then((m) => m.Conectar) },
{ path: 'revision', loadComponent: () => import('./revision/revision').then((m) => m.Revision) },
{ path: 'gobernanza', pathMatch: 'full', redirectTo: 'gobernanza/cacu' },
{
path: 'gobernanza/:domain',
loadComponent: () => import('./gobernanza/gobernanza').then((m) => m.Gobernanza),
},
{ path: '**', redirectTo: 'indicadores/cacu' },
];
+1 -43
View File
@@ -21,22 +21,10 @@
.title {
flex: 1;
min-width: 0; // gives way to the switcher and the sections, on one line
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 1.25rem;
font-weight: 500;
}
// Nothing in the header wraps or shrinks: the title gives way first, then hides.
.domain,
.sections a,
.user {
flex-shrink: 0;
white-space: nowrap;
}
.domain {
--mat-button-filled-container-color: var(--color-primary);
--mat-button-filled-label-text-color: var(--color-text);
@@ -79,38 +67,8 @@
width: clamp(155px, 15vw, 185px);
}
@media (max-width: 1100px) {
@media (max-width: 720px) {
.title {
display: none;
}
.header {
justify-content: space-between;
gap: var(--space-3);
}
.sections {
gap: var(--space-3);
}
// the account by its icon alone; the switcher's name cut short if it must be
.user .who-name {
display: none;
}
.domain {
max-width: 15rem;
}
.domain ::ng-deep .mdc-button__label {
overflow: hidden;
text-overflow: ellipsis;
}
}
@media (max-width: 720px) {
.header {
flex-wrap: wrap;
padding-block: var(--space-2);
}
}
.user {
color: var(--color-text-secondary);
font-weight: 600;
}
+6 -20
View File
@@ -8,12 +8,11 @@ import { filter, map } from 'rxjs';
import { Api } from './api/api';
import { domains } from './api/fn/operations/domains';
import { Domain } from './api/models/domain';
import { Auth } from './auth/auth';
export const DOMAINS: Record<Domain, string> = {
cacu: 'Cáncer cervicouterino',
cama: 'Cáncer de mama',
tea: 'Trastorno del espectro autista',
tea: 'TEA',
};
/** The shell: header (logo, the domain's title and switcher, or the section), page, footer. */
@@ -33,7 +32,6 @@ export const DOMAINS: Record<Domain, string> = {
export class App {
private readonly api = inject(Api);
private readonly router = inject(Router);
protected readonly auth = inject(Auth);
protected readonly labels = DOMAINS;
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
private readonly url = toSignal(
@@ -43,23 +41,11 @@ export class App {
),
{ initialValue: '' },
);
/** The section and domain of a page that has one (indicators, governance): the switcher
* moves between that section's domains. */
private readonly place = computed(() => /^\/(indicadores|gobernanza)\/(\w+)/.exec(this.url()));
protected readonly section = computed(() => this.place()?.[1] ?? 'indicadores');
protected readonly domain = computed(() => this.place()?.[2] as Domain | undefined);
/** The domain of an indicator page, if this is one. */
protected readonly domain = computed(
() => /^\/indicadores\/(\w+)/.exec(this.url())?.[1] as Domain | undefined,
);
protected readonly others = computed(() =>
(this.domains.value() ?? []).filter((d) => d !== this.domain() && this.auth.canSee(d)),
(this.domains.value() ?? []).filter((d) => d !== this.domain()),
);
/** The sign-in page shows only the brand. */
protected readonly onLogin = computed(() => this.url().startsWith('/login'));
/** Where "Indicadores" goes: the first domain this user may see. */
protected readonly home = computed(
() => `/indicadores/${this.auth.user()?.domains[0] ?? 'cacu'}`,
);
protected async logout(): Promise<void> {
await this.auth.logout();
await this.router.navigateByUrl('/login');
}
}
-82
View File
@@ -1,82 +0,0 @@
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
import { Injectable, computed, inject, signal } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { firstValueFrom } from 'rxjs';
import { ApiConfiguration } from '../api/api-configuration';
import type { Domain } from '../api/models/domain';
/** Who is signed in, and the domains the app shows them. */
export interface User {
id: string;
email: string;
name: string;
is_superuser: boolean;
domains: Domain[];
}
/** The web app's sign-in (the API's fastapi-users, a session cookie). It decides only what
* the app shows: the API answers without a session. */
@Injectable({ providedIn: 'root' })
export class Auth {
private readonly http = inject(HttpClient);
private readonly root = inject(ApiConfiguration).rootUrl;
/** undefined: not asked yet; null: nobody signed in. */
private readonly current = signal<User | null | undefined>(undefined);
readonly user = this.current.asReadonly();
readonly signedIn = computed(() => !!this.current());
/** Whether the signed-in user may see the domain (an administrator sees every one). */
canSee(domain: string): boolean {
const u = this.current();
return !!u && (u.is_superuser || u.domains.includes(domain as Domain));
}
async load(): Promise<User | null> {
try {
this.current.set(await firstValueFrom(this.http.get<User>(`${this.root}/users/me`)));
} catch {
this.current.set(null);
}
return this.current() ?? null;
}
/** Signs in; a wrong user or password comes back as words for the form. */
async login(email: string, password: string): Promise<string | null> {
const body = new HttpParams().set('username', email.trim()).set('password', password);
try {
await firstValueFrom(this.http.post(`${this.root}/auth/login`, body));
} catch (e) {
if (e instanceof HttpErrorResponse && e.status === 400) {
return 'Usuario o contraseña incorrectos.';
}
return 'No hay conexión con la plataforma. Intente de nuevo.';
}
await this.load();
return null;
}
async logout(): Promise<void> {
try {
await firstValueFrom(this.http.post(`${this.root}/auth/logout`, null));
} finally {
this.current.set(null);
}
}
}
/** Pages show only to someone signed in; the others go to the sign-in page and come back. */
export const signedIn: CanActivateFn = async (_route, state) => {
const auth = inject(Auth);
const router = inject(Router); // before any await: inject works only in the guard's first turn
const user = auth.user() === undefined ? await auth.load() : auth.user();
return user ? true : router.createUrlTree(['/login'], { queryParams: { next: state.url } });
};
/** A domain's pages show only to whom may see it. */
export const domainAllowed: CanActivateFn = (route) => {
const auth = inject(Auth);
const domain = route.paramMap.get('domain');
if (!domain || auth.canSee(domain)) return true;
const first = auth.user()?.domains[0];
return inject(Router).createUrlTree(first ? ['/indicadores', first] : ['/login']);
};
-49
View File
@@ -1,49 +0,0 @@
<section class="login" aria-labelledby="login-title">
<div class="box">
<img class="logo" src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
<h1 class="title" id="login-title">Inicio de sesión</h1>
<form class="form" (ngSubmit)="enter()" novalidate>
<mat-form-field appearance="outline" class="field" subscriptSizing="dynamic">
<input
matInput
name="email"
[(ngModel)]="email"
placeholder="Usuario"
aria-label="Usuario"
autocomplete="username"
autocapitalize="none"
spellcheck="false"
/>
</mat-form-field>
<mat-form-field appearance="outline" class="field" subscriptSizing="dynamic">
<input
matInput
name="password"
[(ngModel)]="password"
[type]="show() ? 'text' : 'password'"
placeholder="Contraseña"
aria-label="Contraseña"
autocomplete="current-password"
/>
<button
mat-icon-button
matSuffix
type="button"
class="eye"
(click)="show.set(!show())"
[attr.aria-label]="show() ? 'Ocultar contraseña' : 'Mostrar contraseña'"
[attr.aria-pressed]="show()"
>
<mat-icon>{{ show() ? 'visibility_off' : 'visibility' }}</mat-icon>
</button>
</mat-form-field>
@if (error(); as message) {
<p class="error" role="alert">{{ message }}</p>
}
<button type="submit" class="enter" [disabled]="!email.trim() || !password || sending()">
{{ sending() ? 'Ingresando…' : 'Ingresar' }}
</button>
</form>
<p class="legal">©{{ year }} Todos los derechos reservados.</p>
</div>
</section>
-141
View File
@@ -1,141 +0,0 @@
:host {
display: flex;
flex: 1;
min-width: 0;
--login-background: #f8f9fa;
--login-border: #e9ecef;
}
.login {
align-items: center;
display: flex;
flex: 1;
justify-content: center;
padding: 72px 24px 56px;
}
.box {
display: flex;
flex-direction: column;
gap: 16px;
max-width: 340px;
width: 100%;
}
/* The brand opens the screen and is the biggest thing on it. */
.logo {
align-self: center;
animation: logo-in 600ms ease-out both;
display: block;
width: 260px;
}
@keyframes logo-in {
from {
opacity: 0;
transform: translateY(-8px);
}
}
@media (prefers-reduced-motion: reduce) {
.logo {
animation: none;
}
}
/* The title between two rules. */
.title {
align-items: center;
color: var(--color-text);
display: flex;
font-family: var(--font-heading);
font-size: 1.375rem;
font-weight: 600;
gap: 16px;
margin: 0 0 8px;
white-space: nowrap;
&::before,
&::after {
background: var(--color-border);
content: '';
flex: 1;
height: 1px;
}
}
.form {
display: flex;
flex-direction: column;
gap: 12px;
}
.field {
--mat-form-field-container-height: 44px;
--mat-form-field-container-vertical-padding: 12px;
width: 100%;
}
.eye {
color: var(--color-text-secondary);
}
.error {
color: var(--mat-sys-error);
font-size: 0.875rem;
margin: -4px 0 0;
}
/* One column with the fields; its border turns to the action color once the form is complete. */
.enter {
align-items: center;
background: var(--login-background);
border: 1px solid var(--login-border);
border-radius: 10px;
color: var(--color-text-secondary);
cursor: default;
display: flex;
font: inherit;
font-size: 0.9375rem;
font-weight: 500;
justify-content: center;
margin-top: 8px;
min-height: 46px;
transition:
background-color 260ms ease,
border-color 260ms ease,
color 260ms ease;
width: 100%;
&:not(:disabled) {
border-color: var(--color-action);
color: var(--color-text);
cursor: pointer;
}
&:hover:not(:disabled) {
background: var(--color-action-hover);
}
&:focus-visible {
outline: 2px solid var(--color-action);
outline-offset: 2px;
}
}
.legal {
color: var(--color-text-secondary);
font-size: 0.8125rem;
margin: 16px 0 0;
text-align: center;
}
@media (max-width: 600px) {
.login {
padding: 48px 16px;
}
.logo {
width: 208px;
}
}
-42
View File
@@ -1,42 +0,0 @@
import { Component, inject, input, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { Router } from '@angular/router';
import { Auth } from './auth';
/** "Inicio de sesión": the brand, two fields and one button. */
@Component({
selector: 'app-login',
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
templateUrl: './login.html',
styleUrl: './login.scss',
})
export class Login {
private readonly auth = inject(Auth);
private readonly router = inject(Router);
/** Where to go once signed in (the page that asked for it). */
readonly next = input<string>('');
protected email = '';
protected password = '';
protected readonly show = signal(false);
protected readonly sending = signal(false);
protected readonly error = signal('');
protected readonly year = new Date().getFullYear();
protected async enter(): Promise<void> {
if (!this.email.trim() || !this.password || this.sending()) return;
this.sending.set(true);
this.error.set('');
const problem = await this.auth.login(this.email, this.password);
this.sending.set(false);
if (problem) {
this.error.set(problem);
return;
}
const first = this.auth.user()?.domains[0] ?? 'cacu';
await this.router.navigateByUrl(this.next() || `/indicadores/${first}`);
}
}
+15 -68
View File
@@ -29,9 +29,7 @@
</span>
@if (pipelineId()) {
@for (k of kinds; track k[0]) {
<button mat-stroked-button (click)="add(k[0])" [matTooltip]="help[k[0]]">
<mat-icon>add</mat-icon>{{ k[1] }}
</button>
<button mat-stroked-button (click)="add(k[0])"><mat-icon>add</mat-icon>{{ k[1] }}</button>
}
<span class="spacer"></span>
<button mat-stroked-button (click)="save()">Guardar</button>
@@ -72,7 +70,10 @@
<mat-icon>delete</mat-icon>
</button>
</div>
<p class="help">{{ help[d.kind ?? 'source'] }}</p>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="full">
<mat-label>Id</mat-label>
<input matInput [value]="d.id" (change)="rename($any($event.target).value)" />
</mat-form-field>
@if (d.inputs?.length) {
<div class="inputs">
Entradas:
@@ -83,71 +84,17 @@
}
</div>
} @else if (d.kind !== 'source') {
<p class="muted">Conecte una flecha desde otro nodo para darle entrada.</p>
<p class="muted">Una flecha desde otro nodo le da su entrada.</p>
}
<formly-form
[form]="form"
[fields]="fields()"
[model]="model"
(modelChange)="edited($event)"
/>
@if (conceptMap(d); as cm) {
<app-concept-map-editor [id]="cm" />
}
<mat-tab-group class="panel-tabs" animationDuration="0ms" mat-stretch-tabs="false">
<mat-tab label="Configuración">
@if (d.kind === 'source') {
@if (guided(d)) {
<div class="source-summary">
<p>
<mat-icon>check_circle</mat-icon>
{{ d.label || d.id }}
</p>
<button mat-flat-button (click)="connectSource(d.id)">
<mat-icon>edit</mat-icon> Editar conexión
</button>
</div>
} @else {
<p class="muted">
Esta fuente no corresponde a ningún tipo del asistente. Edítela en «Avanzado» o
vuelva a conectarla con el asistente.
</p>
<button mat-stroked-button (click)="connectSource(d.id)">
<mat-icon>cable</mat-icon> Conectar con el asistente
</button>
}
}
<formly-form
[form]="form"
[fields]="fields()"
[model]="model"
[options]="formOptions"
(modelChange)="edited($event)"
/>
@if (conceptMap(d); as cm) {
<app-concept-map-editor [id]="cm" />
}
</mat-tab>
<mat-tab label="Avanzado">
<p class="hint">
Para personal técnico: el nodo completo como lo guarda la plataforma.
@if (guided(d)) {
Si cambia su fuente aquí, deja de editarse con el asistente.
}
</p>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="full">
<mat-label>Id</mat-label>
<input matInput [value]="d.id" (change)="rename($any($event.target).value)" />
<mat-hint>Nombre interno: minúsculas, números y _.</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="full raw">
<mat-label>Nodo (JSON)</mat-label>
<textarea
matInput
rows="16"
[value]="raw(d)"
(input)="rawDraft.set($any($event.target).value)"
></textarea>
</mat-form-field>
@if (rawError()) {
<p class="error" role="alert">{{ rawError() }}</p>
}
<button mat-stroked-button [disabled]="rawDraft() === undefined" (click)="applyRaw()">
Aplicar
</button>
</mat-tab>
</mat-tab-group>
<button mat-stroked-button (click)="show()">Vista previa</button>
@if (preview(); as rows) {
<div class="preview">
-83
View File
@@ -109,86 +109,3 @@ h2 {
width: auto;
}
}
.help {
color: var(--color-text-secondary);
font-size: 13px;
margin: 0 0 var(--space-2);
}
.source-summary {
align-items: center;
background: var(--color-background, #f7f8f6);
border: 1px solid var(--color-border);
border-radius: 8px;
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
justify-content: space-between;
margin-bottom: var(--space-2);
padding: var(--space-2);
p {
align-items: center;
display: flex;
font-weight: 500;
gap: 6px;
margin: 0;
}
p mat-icon {
color: var(--color-success, #2e7d32);
}
}
// The canvas's nodes: the kind small on top, the name below in two lines at most.
:host ::ng-deep default-node {
box-sizing: border-box;
overflow: hidden;
padding: 4px 10px;
display: flex;
align-items: center;
}
:host ::ng-deep .node-caption {
min-width: 0;
width: 100%;
line-height: 1.2;
}
:host ::ng-deep .node-caption .kind {
display: block;
font-size: 10px;
color: var(--color-text-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
:host ::ng-deep .node-caption .name {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
font-size: 12px;
font-weight: 500;
overflow-wrap: anywhere;
}
.panel-tabs {
margin-top: var(--space-2);
}
.panel-tabs .hint {
color: var(--color-text-secondary);
font-size: 12px;
margin: var(--space-3) 0;
}
.raw textarea {
font-family: monospace;
font-size: 12px;
}
.error {
color: var(--mat-sys-error);
font-size: 13px;
}
// Fields in the panel keep their hints clear of the next field's label.
:host ::ng-deep .panel mat-form-field {
margin-bottom: var(--space-3);
}
+12 -150
View File
@@ -1,23 +1,12 @@
import { HttpErrorResponse } from '@angular/common/http';
import {
Component,
computed,
effect,
inject,
resource,
signal,
WritableSignal,
} from '@angular/core';
import { Component, computed, inject, resource, signal, WritableSignal } from '@angular/core';
import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list';
import { MatDialog } from '@angular/material/dialog';
import { MatTabsModule } from '@angular/material/tabs';
import { MatTableModule } from '@angular/material/table';
import { MatTooltipModule } from '@angular/material/tooltip';
import { FormlyFieldConfig, FormlyForm, provideFormlyCore } from '@ngx-formly/core';
import { FormlyJsonschema } from '@ngx-formly/core/json-schema';
import { withFormlyMaterial } from '@ngx-formly/material';
@@ -35,7 +24,6 @@ import type { Pipeline } from '../api/models/pipeline';
import type { Source } from '../api/models/source';
import { ConceptMapEditor } from './concept-map-editor';
import { FORMLY_TYPES, nodeSchema } from './schema-form';
import { SourceDialog, SourceDialogData, SourceDialogResult } from './source-dialog';
type Doc = Pipeline['nodes'][number];
type Kind = NonNullable<Doc['kind']>;
@@ -59,29 +47,16 @@ function canvasNode(id: string, point: { x: number; y: number }, label: string):
};
}
/** Each step's name and what it does, in the operator's words (the canvas and its panel). */
export const KINDS: Record<Kind, string> = {
source: 'Fuente de datos',
read: 'Leer documentos',
route: 'Separar por tipo',
map: 'Traducir códigos',
extract: 'Extraer datos',
fhir: 'Leer FHIR',
source: 'Fuente',
read: 'Leer',
route: 'Filtrar',
map: 'Mapear',
extract: 'Extraer',
fhir: 'FHIR',
join: 'Unir',
link: 'Identificar a la persona',
target: 'Guardar en la plataforma',
};
export const HELP: Record<Kind, string> = {
source: 'De dónde vienen los datos: una base de datos, una carpeta, la nube o una API.',
read: 'Extrae el texto de cada documento (PDF, Word, escaneos con OCR).',
route:
'Deja pasar solo los documentos o filas que cumplen una condición; por ejemplo, las citologías.',
map: 'Cambia los códigos del hospital por los de la plataforma, con una tabla de equivalencias.',
extract: 'Extrae de cada documento los datos de un estudio: fechas, resultados, nombres.',
fhir: 'Lee los paquetes FHIR que envía un sistema y extrae sus estudios.',
join: 'Une dos entradas que se refieren al mismo registro; por ejemplo, un resultado con su orden.',
link: 'Reconoce a qué paciente pertenece cada registro, aunque su nombre venga escrito distinto.',
target: 'Guarda los estudios ya revisados en la plataforma.',
link: 'Vincular',
target: 'Destino',
};
const ID = /^[a-z][a-z0-9_]*$/;
@@ -98,9 +73,7 @@ const ID = /^[a-z][a-z0-9_]*$/;
MatIconModule,
MatInputModule,
MatListModule,
MatTabsModule,
MatTableModule,
MatTooltipModule,
Vflow,
ConceptMapEditor,
],
@@ -112,12 +85,7 @@ const ID = /^[a-z][a-z0-9_]*$/;
export class Conectar {
private readonly api = inject(Api);
private readonly jsonschema = inject(FormlyJsonschema);
private readonly dialog = inject(MatDialog);
protected readonly kinds = Object.entries(KINDS) as [Kind, string][];
protected readonly help = HELP;
/** "Avanzado": the selected node as JSON, as edited and not applied yet. */
protected readonly rawDraft = signal<string | undefined>(undefined);
protected readonly rawError = signal('');
protected readonly list = resource({ loader: () => this.api.invoke(pipelines) });
private readonly schema = resource({ loader: () => this.api.invoke(schema) });
@@ -141,20 +109,6 @@ export class Conectar {
return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status);
});
/** What the node forms share: each entity's fields by their titles (the catalog's). */
protected readonly formOptions = { formState: { fields: {} as Record<string, unknown> } };
private readonly titles = effect(() => {
const entities = (this.schema.value()?.['entities'] ?? {}) as Record<
string,
{ properties?: Record<string, { title?: string }> }
>;
this.formOptions.formState.fields = Object.fromEntries(
Object.entries(entities).map(([e, s]) => [
e,
Object.fromEntries(Object.entries(s.properties ?? {}).map(([f, p]) => [f, p.title ?? f])),
]),
);
});
protected form = new UntypedFormGroup({});
protected model: Record<string, unknown> = {};
/** The selected node's form, generated from its kind's JSON Schema. */
@@ -204,47 +158,10 @@ export class Conectar {
}
protected add(kind: Kind): void {
if (kind === 'source') {
void this.connectSource();
return;
}
this.place(kind, {});
}
/** "Fuente de datos": the dialog walks the operator through it; editing reopens it. */
protected async connectSource(id?: string): Promise<void> {
const doc = id ? (this.docs().find((d) => d.id === id) as Source | undefined) : undefined;
const data: SourceDialogData = {
pipeline: this.pipelineId(),
node: doc?.id,
guided: doc?.guided ?? null,
label: doc?.label ?? '',
};
const ref = this.dialog.open<SourceDialog, SourceDialogData, SourceDialogResult>(SourceDialog, {
data,
width: '760px',
maxWidth: '96vw',
maxHeight: '92vh',
autoFocus: false,
});
const result = await new Promise<SourceDialogResult | undefined>((done) =>
ref.afterClosed().subscribe(done),
);
if (!result) return;
if (doc) {
this.update(doc.id, (d) => ({ ...d, guided: result.guided, label: result.label }) as Doc);
this.select(doc.id);
} else {
this.place('source', { guided: result.guided, label: result.label });
}
this.message.set('Fuente lista. Guarde la canalización para conservarla.');
}
private place(kind: Kind, fields: Record<string, unknown>): void {
let n = 1;
while (this.docs().some((d) => d.id === `${kind}_${n}`)) n++;
const id = `${kind}_${n}`;
const doc = { id, kind, inputs: [], ...fields } as unknown as Doc;
const doc = { id, kind, inputs: [] } as unknown as Doc;
this.docs.update((ds) => [...ds, doc]);
this.nodes.update((ns) => [
...ns,
@@ -287,13 +204,6 @@ export class Conectar {
);
this.form = new UntypedFormGroup({});
this.preview.set(undefined);
this.rawDraft.set(undefined);
this.rawError.set('');
}
/** A source the dialog drew (its answers make its dlt fields). */
protected guided(d: Doc): Source['guided'] {
return d.kind === 'source' ? ((d as Source).guided ?? undefined) : undefined;
}
/** The form's values into the selected node. */
@@ -309,40 +219,6 @@ export class Conectar {
);
}
/** The node as the platform keeps it (its place on the canvas aside). */
protected raw(d: Doc): string {
const { position, ...rest } = d as Doc & { position?: unknown };
return JSON.stringify(rest, null, 2);
}
/** "Aplicar": the edited JSON becomes the node. Its kind stays; its id changes with the
* Id field (so the arrows follow). A source whose dlt fields change is drawn by hand from
* then on (unless a catalog type makes it exactly: the platform reads it back). */
protected applyRaw(): void {
const d = this.doc();
const text = this.rawDraft();
if (!d || text === undefined) return;
let parsed: Record<string, unknown>;
try {
parsed = JSON.parse(text);
} catch {
this.rawError.set('El texto no es JSON válido.');
return;
}
if (parsed['kind'] !== d.kind) {
this.rawError.set(`El tipo del nodo es «${d.kind}» y no cambia aquí.`);
return;
}
if (d.kind === 'source') {
const dlt = ['source', 'args', 'resource', 'then'] as const;
const before = d as unknown as Record<string, unknown>;
if (dlt.some((k) => JSON.stringify(parsed[k]) !== JSON.stringify(before[k])))
delete parsed['guided'];
}
this.update(d.id, () => ({ ...parsed, id: d.id, kind: d.kind }) as unknown as Doc);
this.select(d.id);
}
protected rename(to: string): void {
const from = this.selected();
if (!from || from === to || !ID.test(to) || this.docs().some((d) => d.id === to)) return;
@@ -420,7 +296,7 @@ export class Conectar {
? await this.api.invoke(sourcePreview, { limit: 20, body: doc as Source })
: await this.api.invoke(nodeRows, { pipeline_id: id, node_id: doc.id, limit: 50 });
this.preview.set(rows);
this.message.set(rows.length ? '' : 'Sin filas: ejecute la canalización.');
this.message.set(rows.length ? '' : 'Sin filas todavía: ejecute la canalización.');
} catch (e) {
this.message.set(problem(e));
}
@@ -446,14 +322,7 @@ export class Conectar {
}
function text(d: Doc): string {
// ngx-vflow draws a node's text as HTML: the kind above, the name below (two lines at
// most; the whole of it on hover). The name is the operator's text, so it is escaped.
const kind = KINDS[d.kind ?? 'source'];
const name = escape(d.label || d.id);
return (
`<div class="node-caption" title="${kind} · ${name}">` +
`<span class="kind">${kind}</span><span class="name">${name}</span></div>`
);
return `${KINDS[d.kind ?? 'source']} · ${d.label || d.id}`;
}
/** Each node's distance from the sources: its column when it has no saved position. */
@@ -480,10 +349,3 @@ function problem(e: unknown): string {
}
return String(e);
}
function escape(text: string): string {
return text.replace(
/[&<>"']/g,
(c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!,
);
}
+3 -15
View File
@@ -16,12 +16,6 @@ const PIPELINE = {
when: { type: 'array', items: { $ref: '#/$defs/Condition' } },
resource: { anyOf: [{ type: 'string' }, { type: 'null' }], title: 'Resource' },
values: { type: 'object', additionalProperties: { type: 'string' }, title: 'Values' },
on: {
type: 'array',
items: { type: 'array', prefixItems: [{ type: 'string' }, { type: 'string' }] },
},
extra: { type: 'object', title: 'Extra' },
source: { type: 'string', advanced: true },
},
},
},
@@ -31,7 +25,7 @@ describe('node forms from the pipeline schema', () => {
const schema = nodeSchema(PIPELINE, 'route') as any;
it('leaves out what the canvas edits', () => {
expect(Object.keys(schema.properties)).toEqual(['when', 'resource', 'values', 'on']);
expect(Object.keys(schema.properties)).toEqual(['when', 'resource', 'values']);
expect(schema.required).toEqual(['when']);
});
@@ -40,13 +34,7 @@ describe('node forms from the pipeline schema', () => {
expect(schema.properties.resource.type).toBe('string');
});
it('edits maps of texts and pairs as rows', () => {
expect(schema.properties.values.widget.formlyConfig.type).toBe('map');
expect(schema.properties.on.widget.formlyConfig.type).toBe('pairs');
});
it('leaves JSON-only values and advanced fields to the "Avanzado" tab', () => {
expect(schema.properties.extra).toBeUndefined();
expect(schema.properties.source).toBeUndefined();
it('edits maps as JSON', () => {
expect(schema.properties.values.widget.formlyConfig.type).toBe('json');
});
});
+2 -236
View File
@@ -3,7 +3,6 @@ import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { ReactiveFormsModule } from '@angular/forms';
import {
ConfigOption,
@@ -28,29 +27,11 @@ export function nodeSchema(pipeline: Schema, kind: string): Schema {
)!;
const node = structuredClone(defs[name]);
for (const field of CANVAS_FIELDS) delete node.properties?.[field];
// The panel says what the kind does (in Spanish); the class's own docstring is for code.
delete node.title;
delete node.description;
// What a guided dialog fills, or what only JSON can say, is for the "Avanzado" tab.
for (const [field, value] of Object.entries(node.properties ?? {})) {
const simple = simplify(value as Schema, defs) as Schema & { widget?: unknown };
if ((value as { advanced?: boolean }).advanced || isJson(simple))
delete node.properties![field];
}
node.required = (node.required ?? []).filter(
(f) => !CANVAS_FIELDS.includes(f) && f in (node.properties ?? {}),
);
node.required = (node.required ?? []).filter((f) => !CANVAS_FIELDS.includes(f));
delete node.additionalProperties;
return simplify(node, defs);
}
function isJson(schema: Schema): boolean {
return (
(schema as { widget?: { formlyConfig?: { type?: string } } }).widget?.formlyConfig?.type ===
'json'
);
}
function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
if (schema.$ref) {
const { $ref, ...rest } = schema;
@@ -64,34 +45,6 @@ function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
return simplify({ ...kept[0], ...rest }, defs);
}
}
const values = schema.additionalProperties as Schema | boolean | undefined;
if (
schema.type === 'object' &&
!schema.properties &&
typeof values === 'object' &&
values.type === 'string'
) {
const byField = (schema as { keys?: string }).keys === 'field';
return {
title: schema.title,
description: schema.description,
default: schema.default,
widget: { formlyConfig: { type: 'map', props: { fieldKeys: byField } } },
} as Schema;
}
const pair = schema.items as Schema | undefined;
if (
schema.type === 'array' &&
(pair?.prefixItems as Schema[] | undefined)?.length === 2 &&
(pair!.prefixItems as Schema[]).every((p) => p.type === 'string')
) {
return {
title: schema.title,
description: schema.description,
default: schema.default,
widget: { formlyConfig: { type: 'pairs' } },
} as Schema;
}
const isMap = schema.type === 'object' && !schema.properties;
const isTuple =
schema.type === 'array' &&
@@ -164,7 +117,7 @@ export class ArrayType extends FieldArrayType {}
imports: [MatFormFieldModule, MatInputModule, ReactiveFormsModule],
template: `
<mat-form-field appearance="outline" class="json">
<mat-label>{{ props.label }}</mat-label>
<mat-label>{{ props.label }} (JSON)</mat-label>
<textarea
matInput
rows="4"
@@ -199,198 +152,11 @@ export class JsonType extends FieldType<FormlyFieldConfig> {
}
}
/** A map of names to texts (fields to columns, fields to patterns, date formats): a row
* per entry, its name and its text, to add or remove. */
@Component({
selector: 'app-formly-map',
imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule, MatSelectModule],
template: `
<div class="legend">{{ props.label }}</div>
@if (props.description) {
<p class="hint">{{ props.description }}</p>
}
@for (row of rows(); track $index; let i = $index) {
<div class="row">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="key">
<mat-label>{{ props['fieldKeys'] ? 'Dato' : 'Nombre' }}</mat-label>
@if (props['fieldKeys']) {
<mat-select [value]="row[0]" (selectionChange)="edit(i, $event.value, row[1])">
@for (o of keyOptions(row[0]); track o[0]) {
<mat-option [value]="o[0]">{{ o[1] }}</mat-option>
}
</mat-select>
} @else {
<input
matInput
[value]="row[0]"
(change)="edit(i, $any($event.target).value, row[1])"
/>
}
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="value">
<mat-label>Valor</mat-label>
<input matInput [value]="row[1]" (change)="edit(i, row[0], $any($event.target).value)" />
</mat-form-field>
<button mat-icon-button type="button" (click)="remove(i)" aria-label="Quitar">
<mat-icon>close</mat-icon>
</button>
</div>
}
<button mat-stroked-button type="button" (click)="add()">
<mat-icon>add</mat-icon> Agregar
</button>
`,
styles: `
.legend {
font-weight: 500;
margin: 12px 0 4px;
}
.hint {
color: var(--color-text-secondary);
font-size: 12px;
margin: 0 0 8px;
}
.row {
display: grid;
grid-template-columns: 1fr auto;
column-gap: 4px;
row-gap: 6px;
padding: 8px 0;
border-bottom: 1px solid var(--color-border);
}
.key,
.value {
min-width: 0;
grid-column: 1;
}
.row button {
grid-column: 2;
grid-row: 1 / span 2;
align-self: center;
}
`,
})
export class MapType extends FieldType<FormlyFieldConfig> {
/** The platform fields a key can be, by title: the node's study's, or every study's when
* it names none (formState.fields: entity -> field -> title). */
protected keyOptions(current: string): [string, string][] {
const all = (this.options?.formState?.fields ?? {}) as Record<string, Record<string, string>>;
const entity = (this.model as Record<string, unknown> | undefined)?.['entity'] as
string | undefined;
const titles: Record<string, string> = entity
? (all[entity] ?? {})
: Object.assign({}, ...Object.values(all));
const options = Object.entries(titles);
if (current && !(current in titles)) options.unshift([current, current]);
return options;
}
protected rows(): [string, string][] {
return Object.entries((this.formControl.value ?? {}) as Record<string, string>);
}
private save(rows: [string, string][]): void {
this.formControl.setValue(Object.fromEntries(rows.filter(([k]) => k !== '')));
this.formControl.markAsDirty();
}
protected edit(i: number, key: string, value: string): void {
const rows = this.rows();
rows[i] = [key.trim(), value];
this.save(rows);
}
protected add(): void {
// a new row needs a key before it is kept: the first field not used yet, or a new name
const rows = this.rows();
const used = new Set(rows.map(([k]) => k));
const free = this.props['fieldKeys']
? this.keyOptions('').find(([k]) => !used.has(k))?.[0]
: undefined;
let n = rows.length + 1;
while (used.has(`campo_${n}`)) n++;
this.save([...rows, [free ?? `campo_${n}`, '']]);
}
protected remove(i: number): void {
this.save(this.rows().filter((_, j) => j !== i));
}
}
/** Pairs of names (a join's columns, the first input's = the second's): a row per pair. */
@Component({
selector: 'app-formly-pairs',
imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
template: `
<div class="legend">{{ props.label }}</div>
@if (props.description) {
<p class="hint">{{ props.description }}</p>
}
@for (row of rows(); track $index; let i = $index) {
<div class="row">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="half">
<mat-label>Primera entrada</mat-label>
<input matInput [value]="row[0]" (change)="edit(i, 0, $any($event.target).value)" />
</mat-form-field>
<span>=</span>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="half">
<mat-label>Segunda entrada</mat-label>
<input matInput [value]="row[1]" (change)="edit(i, 1, $any($event.target).value)" />
</mat-form-field>
<button mat-icon-button type="button" (click)="remove(i)" aria-label="Quitar">
<mat-icon>close</mat-icon>
</button>
</div>
}
<button mat-stroked-button type="button" (click)="add()">
<mat-icon>add</mat-icon> Agregar
</button>
`,
styles: `
.legend {
font-weight: 500;
margin: 12px 0 4px;
}
.hint {
color: var(--color-text-secondary);
font-size: 12px;
margin: 0 0 8px;
}
.row {
display: flex;
gap: 6px;
align-items: center;
margin-bottom: 6px;
}
.half {
flex: 1;
min-width: 0;
}
`,
})
export class PairsType extends FieldType<FormlyFieldConfig> {
protected rows(): [string, string][] {
return ((this.formControl.value ?? []) as [string, string][]).map((r) => [r[0], r[1]]);
}
private save(rows: [string, string][]): void {
this.formControl.setValue(rows);
this.formControl.markAsDirty();
}
protected edit(i: number, side: 0 | 1, value: string): void {
const rows = this.rows();
rows[i][side] = value.trim();
this.save(rows);
}
protected add(): void {
this.save([...this.rows(), ['', '']]);
}
protected remove(i: number): void {
this.save(this.rows().filter((_, j) => j !== i));
}
}
export const FORMLY_TYPES: ConfigOption = {
types: [
{ name: 'object', component: ObjectType },
{ name: 'array', component: ArrayType },
{ name: 'json', component: JsonType },
{ name: 'map', component: MapType },
{ name: 'pairs', component: PairsType },
{ name: 'enum', extends: 'select' },
{ name: 'string', extends: 'input' },
{ name: 'number', extends: 'input', defaultOptions: { props: { type: 'number' } } },
-388
View File
@@ -1,388 +0,0 @@
@if (!type()) {
<h2 mat-dialog-title>¿Dónde están los datos?</h2>
<mat-dialog-content>
@if (catalog.isLoading()) {
<div class="loading" role="status">
<mat-spinner diameter="32" /> <span>Cargando opciones…</span>
</div>
}
@for (g of groups(); track g.id) {
<section class="group">
<h3>{{ g.title }}</h3>
<p class="hint">{{ g.description }}</p>
<div class="types">
@for (t of g.types; track t.id) {
<button type="button" class="type" (click)="pick(t.id)" [attr.data-type]="t.id">
<mat-icon>{{ icon(t.icon) }}</mat-icon>
<span class="type-title">{{ t.title }}</span>
<span class="type-text">{{ t.description }}</span>
</button>
}
</div>
</section>
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button mat-dialog-close>Cancelar</button>
</mat-dialog-actions>
} @else {
<h2 mat-dialog-title class="with-icon">
<mat-icon>{{ icon(type()!.icon) }}</mat-icon> {{ type()!.title }}
</h2>
<mat-dialog-content>
<p class="hint">{{ type()!.description }}</p>
<ng-template #field let-name let-f="f">
@switch (f.type === 'server_file' ? 'folder' : f.type) {
@case ('password') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<input
matInput
[type]="showPassword()[name] ? 'text' : 'password'"
[ngModel]="isMasked(name) ? '' : text(name)"
(ngModelChange)="set(name, $event)"
[placeholder]="isMasked(name) ? 'Guardada (escriba para cambiarla)' : f.placeholder"
[attr.data-field]="name"
autocomplete="off"
/>
<button
mat-icon-button
matSuffix
type="button"
(click)="togglePassword(name)"
[attr.aria-label]="showPassword()[name] ? 'Ocultar' : 'Mostrar'"
>
<mat-icon>{{ showPassword()[name] ? 'visibility_off' : 'visibility' }}</mat-icon>
</button>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
}
@case ('number') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<input
matInput
type="number"
[ngModel]="text(name)"
(ngModelChange)="setNumber(name, $event)"
[attr.data-field]="name"
/>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
}
@case ('select') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<mat-select [ngModel]="value(name)" (ngModelChange)="set(name, $event)">
@for (o of f.options; track o.value) {
<mat-option [value]="o.value">{{ o.label }}</mat-option>
}
</mat-select>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
}
@case ('format') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<mat-select
[ngModel]="value(name)"
(ngModelChange)="set(name, $event)"
[attr.data-field]="name"
>
@for (o of formats(); track o.value) {
<mat-option [value]="o.value">{{ o.label }}</mat-option>
}
</mat-select>
</mat-form-field>
}
@case ('table') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
@if (tables().length) {
<mat-select
[ngModel]="value(name)"
(ngModelChange)="set(name, $event); test()"
[attr.data-field]="name"
>
@for (t of tables(); track t) {
<mat-option [value]="t">{{ t }}</mat-option>
}
</mat-select>
} @else {
<input
matInput
[ngModel]="text(name)"
(ngModelChange)="set(name, $event)"
[attr.data-field]="name"
/>
}
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
}
@case ('columns') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<mat-select
multiple
[ngModel]="listed(name)"
(ngModelChange)="set(name, $event.length ? $event : null)"
[attr.data-field]="name"
placeholder="Todas"
>
@for (c of columnOptions(name); track c) {
<mat-option [value]="c">{{ c }}</mat-option>
}
</mat-select>
<mat-hint>{{
columnOptions(name).length ? f.help : 'Pulse «Probar conexión» para ver las columnas.'
}}</mat-hint>
</mat-form-field>
}
@case ('folder') {
<div class="picker">
<mat-form-field appearance="outline" class="grow">
<mat-label>{{ f.label }}</mat-label>
<input
matInput
[ngModel]="text(name)"
(ngModelChange)="set(name, $event)"
[attr.data-field]="name"
/>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
<button mat-stroked-button type="button" (click)="openFolder(name, text(name) || null)">
<mat-icon>folder_open</mat-icon> Examinar…
</button>
</div>
@if (browsing(); as b) {
@if (b.field === name) {
<div class="browser" role="group" aria-label="Carpetas del servidor">
<div class="browser-head">
@if (b.at.path) {
<button
mat-icon-button
type="button"
(click)="openFolder(name, b.at.parent)"
aria-label="Subir"
>
<mat-icon>arrow_upward</mat-icon>
</button>
<code>{{ b.at.path }}</code>
} @else {
<span class="hint">Carpetas habilitadas en el servidor</span>
}
</div>
<ul>
@for (e of b.at.entries; track e.path) {
<li>
@if (e.kind === 'folder') {
<button type="button" class="entry" (click)="openFolder(name, e.path)">
<mat-icon>folder</mat-icon> {{ e.name }}
</button>
} @else if (browsingFiles()) {
<button type="button" class="entry" (click)="chooseFile(e.path)">
<mat-icon>description</mat-icon> {{ e.name }}
</button>
} @else {
<span class="entry file"
><mat-icon>description</mat-icon> {{ e.name }}</span
>
}
</li>
} @empty {
<li class="hint">Vacía.</li>
}
</ul>
<div class="browser-actions">
<button mat-button type="button" (click)="browsing.set(undefined)">Cerrar</button>
@if (!browsingFiles()) {
<button
mat-flat-button
type="button"
[disabled]="!b.at.path"
(click)="chooseFolder()"
>
Elegir esta carpeta
</button>
}
</div>
</div>
}
}
}
@case ('upload') {
<div
class="drop"
(dragover)="$event.preventDefault()"
(drop)="dropped(name, $event)"
[attr.data-field]="name"
>
<mat-icon>cloud_upload</mat-icon>
<p>Arrastre aquí los archivos, o</p>
<div class="drop-buttons">
<button mat-stroked-button type="button" (click)="files.click()">
Elegir archivos
</button>
<button mat-stroked-button type="button" (click)="folder.click()">
Elegir una carpeta
</button>
</div>
<input #files type="file" multiple hidden (change)="upload(name, files.files)" />
<input
#folder
type="file"
webkitdirectory
hidden
(change)="upload(name, folder.files)"
/>
@if (uploading(); as u) {
@if (u.field === name) {
<mat-progress-bar mode="determinate" [value]="u.percent" />
<span class="hint">Subiendo… {{ u.percent }} %</span>
}
}
@if (uploaded()[name]?.length) {
<p class="ok">
<mat-icon>check_circle</mat-icon> {{ uploaded()[name].length }} archivos subidos
</p>
} @else if (text(name)) {
<p class="ok"><mat-icon>check_circle</mat-icon> Archivos ya subidos</p>
}
</div>
}
@case ('oauth') {
<div class="signin">
@if (account(name); as who) {
<p class="ok"><mat-icon>check_circle</mat-icon> Conectado como {{ who }}</p>
<button mat-button type="button" (click)="signIn(name, f.provider)">
Usar otra cuenta
</button>
} @else {
<button mat-flat-button type="button" (click)="signIn(name, f.provider)">
<mat-icon>login</mat-icon>
Iniciar sesión con {{ catalog.value()?.providers?.[f.provider]?.title }}
</button>
}
@if (f.help) {
<p class="hint">{{ f.help }}</p>
}
</div>
}
@default {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<input
matInput
[ngModel]="text(name)"
(ngModelChange)="set(name, $event)"
[placeholder]="f.placeholder"
[attr.data-field]="name"
/>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
}
}
</ng-template>
<div class="fields">
@for (e of fields(); track e[0]) {
<ng-container *ngTemplateOutlet="field; context: { $implicit: e[0], f: e[1] }" />
}
</div>
@if (more().length) {
<mat-expansion-panel class="more">
<mat-expansion-panel-header>Más opciones</mat-expansion-panel-header>
<div class="fields">
@for (e of more(); track e[0]) {
<ng-container *ngTemplateOutlet="field; context: { $implicit: e[0], f: e[1] }" />
}
</div>
</mat-expansion-panel>
}
<div class="test">
<button
mat-stroked-button
type="button"
(click)="test()"
[disabled]="testing() || missing().length > 0"
>
<mat-icon>network_check</mat-icon> Probar conexión
</button>
@if (testing()) {
<mat-spinner diameter="24" /> <span role="status">Conectando…</span>
} @else if (missing().length) {
<span class="hint">Falta: {{ missing().join(', ') }}</span>
}
</div>
@if (problem()) {
<p class="error" role="alert"><mat-icon>error</mat-icon> {{ problem() }}</p>
}
@if (tested(); as t) {
<div class="result" [class.bad]="!t.ok" role="status">
<p>
<mat-icon>{{ t.ok ? 'check_circle' : 'error' }}</mat-icon> {{ t.message }}
</p>
@if (t.detail) {
<details>
<summary>Respuesta de la fuente</summary>
<pre>{{ t.detail }}</pre>
</details>
}
@if (t.tables?.length) {
<p class="hint">Elija una tabla arriba para ver sus primeras filas.</p>
}
@if (t.rows?.length) {
<p class="hint">
{{
t.rows!.length === 1
? 'La primera fila:'
: 'Las primeras ' + t.rows!.length + ' filas:'
}}
</p>
<div class="rows">
<table mat-table [dataSource]="t.rows!">
@for (c of columns(); track c) {
<ng-container [matColumnDef]="c">
<th mat-header-cell *matHeaderCellDef>{{ c }}</th>
<td mat-cell *matCellDef="let row">{{ cell(row[c]) }}</td>
</ng-container>
}
<tr mat-header-row *matHeaderRowDef="columns()"></tr>
<tr mat-row *matRowDef="let row; columns: columns()"></tr>
</table>
</div>
}
</div>
}
<mat-form-field appearance="outline" class="full name">
<mat-label>Nombre de esta fuente</mat-label>
<input matInput [ngModel]="label()" (ngModelChange)="label.set($event)" />
<mat-hint>Cómo se verá en el diagrama.</mat-hint>
</mat-form-field>
</mat-dialog-content>
<mat-dialog-actions>
@if (!data.guided) {
<button mat-button type="button" (click)="back()">
<mat-icon>arrow_back</mat-icon> Otro tipo
</button>
}
<span class="spacer"></span>
<button mat-button mat-dialog-close>Cancelar</button>
<button mat-flat-button type="button" (click)="save()" [disabled]="!ready()">Guardar</button>
</mat-dialog-actions>
}
-230
View File
@@ -1,230 +0,0 @@
:host {
display: block;
}
.with-icon {
align-items: center;
display: flex;
gap: var(--space-2);
}
.hint {
color: var(--color-text-secondary);
font-size: 13px;
margin: 0 0 var(--space-2);
}
.loading,
.test {
align-items: center;
display: flex;
gap: var(--space-2);
margin: var(--space-2) 0;
}
.group h3 {
font-size: 15px;
font-weight: 600;
margin: var(--space-3) 0 2px;
}
.types {
display: grid;
gap: var(--space-2);
grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
}
.type {
align-items: start;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: 10px;
cursor: pointer;
display: grid;
font: inherit;
gap: 2px 10px;
grid-template-columns: auto 1fr;
padding: 12px;
text-align: left;
&:hover,
&:focus-visible {
border-color: var(--color-primary);
box-shadow: 0 0 0 1px var(--color-primary);
}
mat-icon {
color: var(--color-primary);
grid-row: span 2;
}
}
.type-title {
font-weight: 600;
}
.type-text {
color: var(--color-text-secondary);
font-size: 12.5px;
line-height: 1.35;
}
.fields {
display: flex;
flex-direction: column;
gap: 12px;
}
.full,
.grow {
width: 100%;
}
.picker {
align-items: start;
display: flex;
gap: var(--space-2);
.grow {
flex: 1;
}
button {
margin-top: 10px;
}
}
.browser {
border: 1px solid var(--color-border);
border-radius: 8px;
padding: var(--space-2);
ul {
list-style: none;
margin: 0;
max-height: 220px;
overflow-y: auto;
padding: 0;
}
}
.browser-head,
.browser-actions {
align-items: center;
display: flex;
gap: var(--space-2);
}
.browser-actions {
justify-content: flex-end;
}
.entry {
align-items: center;
background: none;
border: 0;
cursor: pointer;
display: flex;
font: inherit;
gap: 6px;
padding: 4px 2px;
text-align: left;
width: 100%;
&.file {
color: var(--color-text-secondary);
cursor: default;
}
&:not(.file):hover {
color: var(--color-primary);
}
}
.drop {
align-items: center;
border: 2px dashed var(--color-border);
border-radius: 10px;
display: flex;
flex-direction: column;
gap: var(--space-1, 4px);
padding: var(--space-3);
text-align: center;
mat-progress-bar {
width: 100%;
}
}
.drop-buttons {
display: flex;
gap: var(--space-2);
}
.signin {
display: flex;
flex-direction: column;
gap: var(--space-1, 4px);
align-items: flex-start;
}
.ok,
.error,
.result p {
align-items: center;
display: flex;
gap: 6px;
margin: var(--space-1, 4px) 0;
}
.ok mat-icon,
.result mat-icon {
color: var(--color-success, #2e7d32);
}
.error,
.result.bad p {
color: var(--color-error, #b3261e);
mat-icon {
color: inherit;
}
}
.result {
border: 1px solid var(--color-border);
border-radius: 8px;
margin-top: var(--space-2);
padding: var(--space-2);
pre {
font-size: 12px;
white-space: pre-wrap;
}
}
.rows {
max-height: 260px;
overflow: auto;
td,
th {
font-size: 12px;
max-width: 260px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.more {
margin: var(--space-2) 0;
}
.name {
margin-top: var(--space-3);
}
.spacer {
flex: 1;
}
-361
View File
@@ -1,361 +0,0 @@
import { NgTemplateOutlet } from '@angular/common';
import { HttpClient, HttpErrorResponse, HttpEventType } from '@angular/common/http';
import { Component, computed, inject, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSelectModule } from '@angular/material/select';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatTableModule } from '@angular/material/table';
import { Api } from '../api/api';
import { ApiConfiguration } from '../api/api-configuration';
import { browse } from '../api/fn/ingest/browse';
import { oauthStart } from '../api/fn/ingest/oauth-start';
import { sourceTypes } from '../api/fn/ingest/source-types';
import { testSource } from '../api/fn/ingest/test-source';
import type { Browsed } from '../api/models/browsed';
import type { FieldSpec } from '../api/models/field-spec';
import type { Guided } from '../api/models/guided';
import type { SourceType } from '../api/models/source-type';
import type { Tested } from '../api/models/tested';
import type { Uploaded } from '../api/models/uploaded';
/** What the dialog is opened with: the source being edited, if any. */
export interface SourceDialogData {
pipeline?: string;
node?: string;
guided?: Guided | null;
label?: string;
}
const NONE: string[] = [];
/** What it gives back: the dialog's answers (the node's dlt fields are made from them). */
export interface SourceDialogResult {
guided: Guided;
label: string;
}
/** The catalog's generic icon words, as Material Symbols. */
const ICONS: Record<string, string> = {
database: 'database',
upload: 'upload_file',
folder: 'folder_open',
link: 'link',
'folder-network': 'lan',
server: 'dns',
cloud: 'cloud',
onedrive: 'cloud',
sharepoint: 'groups',
'google-drive': 'add_to_drive',
web: 'api',
fhir: 'local_hospital',
};
const MASK = '********';
/** "Nueva fuente": the operator picks what kind of source the data is in, answers only what
* that kind needs (in plain words, with pickers and sign-in buttons), tests the connection,
* picks a table if there are several, sees the first rows, and saves. No dlt, no JSON. */
@Component({
selector: 'app-source-dialog',
imports: [
FormsModule,
NgTemplateOutlet,
MatButtonModule,
MatDialogModule,
MatExpansionModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatProgressBarModule,
MatProgressSpinnerModule,
MatSelectModule,
MatSlideToggleModule,
MatTableModule,
],
templateUrl: './source-dialog.html',
styleUrl: './source-dialog.scss',
})
export class SourceDialog {
private readonly api = inject(Api);
private readonly http = inject(HttpClient);
private readonly root = inject(ApiConfiguration).rootUrl;
private readonly ref = inject(MatDialogRef<SourceDialog, SourceDialogResult>);
protected readonly data = inject<SourceDialogData>(MAT_DIALOG_DATA, { optional: true }) ?? {};
protected readonly catalog = resource({ loader: () => this.api.invoke(sourceTypes) });
protected readonly groups = computed(() => {
const c = this.catalog.value();
if (!c) return [];
return Object.entries(c.groups).map(([id, g]) => ({
id,
...g,
types: Object.entries(c.types)
.filter(([, t]) => t.group === id)
.map(([tid, t]) => ({ id: tid, ...t })),
}));
});
protected readonly typeId = signal<string | undefined>(this.data.guided?.type);
protected readonly type = computed<SourceType | undefined>(() => {
const id = this.typeId();
return id ? this.catalog.value()?.types[id] : undefined;
});
protected readonly answers = signal<Record<string, unknown>>({
...(this.data.guided?.answers ?? {}),
});
protected readonly label = signal(this.data.label ?? '');
protected readonly fields = computed(() => entries(this.type()).filter(([, f]) => !f.advanced));
protected readonly more = computed(() => entries(this.type()).filter(([, f]) => f.advanced));
protected readonly showPassword = signal<Record<string, boolean>>({});
protected readonly testing = signal(false);
/** The tables the last listing found: kept while one is picked and its rows shown. */
protected readonly tableList = signal<string[]>([]);
protected readonly tested = signal<Tested | undefined>(undefined);
protected readonly columns = computed(() => Object.keys(this.tested()?.rows?.[0] ?? {}));
protected readonly browsing = signal<{ field: string; at: Browsed } | undefined>(undefined);
protected readonly uploading = signal<{ field: string; percent: number } | undefined>(undefined);
protected readonly uploaded = signal<Record<string, string[]>>({});
protected readonly problem = signal('');
icon(name: string): string {
return ICONS[name] ?? 'input';
}
protected pick(id: string): void {
const t = this.catalog.value()!.types[id];
this.typeId.set(id);
this.answers.set(
Object.fromEntries(
Object.entries(t.fields)
.filter(([, f]) => f.default !== null && f.default !== undefined)
.map(([k, f]) => [k, f.default]),
),
);
if (!this.label()) this.label.set(t.title);
this.tested.set(undefined);
this.problem.set('');
}
protected back(): void {
this.typeId.set(undefined);
this.tested.set(undefined);
this.problem.set('');
}
protected value(name: string): unknown {
return this.answers()[name];
}
protected text(name: string): string {
const v = this.answers()[name];
return v === null || v === undefined ? '' : String(v);
}
protected set(name: string, value: unknown): void {
this.answers.update((a) => ({ ...a, [name]: value }));
if (this.type()?.fields[name]?.type === 'table') return;
this.tested.set(undefined); // another connection: test again
this.tableList.set([]);
}
protected setNumber(name: string, value: string): void {
this.set(name, value === '' ? null : Number(value));
}
protected togglePassword(name: string): void {
this.showPassword.update((s) => ({ ...s, [name]: !s[name] }));
}
protected isMasked(name: string): boolean {
return this.answers()[name] === MASK;
}
protected formats() {
return this.catalog.value()?.formats ?? [];
}
protected account(name: string): string | undefined {
const a = this.answers()[name] as { user?: string } | undefined;
return a ? (a.user ?? 'cuenta conectada') : undefined;
}
/** "Probar conexión": what the source holds, in plain words. */
protected async test(): Promise<void> {
const type = this.typeId();
if (!type) return;
this.testing.set(true);
this.problem.set('');
try {
const found = await this.api.invoke(testSource, {
limit: 20,
body: {
type,
answers: this.cleaned(),
pipeline: this.data.pipeline,
node: this.data.node,
},
});
this.tested.set(found);
if (found.tables?.length) this.tableList.set(found.tables);
} catch (e) {
this.problem.set(message(e));
} finally {
this.testing.set(false);
}
}
/** A list answer (the columns picked), as a list. */
protected listed(name: string): string[] {
const v = this.value(name);
return Array.isArray(v) ? (v as string[]) : NONE; // a new list each time renders forever
}
/** The columns to pick from: the first rows', and those already picked. */
protected columnOptions(name: string): string[] {
return [...new Set([...this.columns(), ...this.listed(name)])];
}
/** The tables a database listed, for its table field. */
protected tables(): string[] {
return this.tableList();
}
/** Server folders, under the roots the operator mounted. */
protected async openFolder(field: string, path?: string | null): Promise<void> {
try {
const at = await this.api.invoke(browse, path ? { path } : {});
this.browsing.set({ field, at });
} catch (e) {
this.problem.set(message(e));
}
}
protected chooseFolder(): void {
const b = this.browsing();
if (b?.at.path) this.set(b.field, b.at.path);
this.browsing.set(undefined);
}
protected chooseFile(path: string): void {
const b = this.browsing();
if (b) this.set(b.field, path);
this.browsing.set(undefined);
}
/** Whether the field being browsed takes a file (else a folder). */
protected readonly browsingFiles = computed(() => {
const b = this.browsing();
return !!b && this.type()?.fields[b.field]?.type === 'server_file';
});
/** Files or a whole folder from this computer, sent with progress; a folder keeps its
* subfolders. More files can be added to the same set. */
protected upload(field: string, list: FileList | null): void {
if (!list?.length) return;
const body = new FormData();
for (const file of Array.from(list)) {
body.append('files', file, file.webkitRelativePath || file.name);
}
const folder = this.answers()[field];
if (typeof folder === 'string' && folder) body.append('folder', folder);
this.uploading.set({ field, percent: 0 });
this.problem.set('');
this.http
.post<Uploaded>(`${this.root}/ingest/uploads`, body, {
reportProgress: true,
observe: 'events',
})
.subscribe({
next: (event) => {
if (event.type === HttpEventType.UploadProgress && event.total) {
this.uploading.set({ field, percent: Math.round((100 * event.loaded) / event.total) });
} else if (event.type === HttpEventType.Response && event.body) {
this.set(field, event.body.bucket_url);
this.uploaded.update((u) => ({
...u,
[field]: [...(u[field] ?? []), ...event.body!.files],
}));
}
},
error: (e) => {
this.uploading.set(undefined);
this.problem.set(message(e));
},
complete: () => this.uploading.set(undefined),
});
}
protected dropped(field: string, event: DragEvent): void {
event.preventDefault();
this.upload(field, event.dataTransfer?.files ?? null);
}
/** "Iniciar sesión con …": the provider's page in a window; it hands the account back. */
protected async signIn(field: string, provider: string): Promise<void> {
this.problem.set('');
let started;
try {
started = await this.api.invoke(oauthStart, { provider, origin: location.origin });
} catch (e) {
this.problem.set(message(e));
return;
}
const popup = window.open(started.url, 'isssteleon-oauth', 'width=520,height=680');
const listen = (event: MessageEvent) => {
const m = event.data as { type?: string; state?: string; account?: unknown; error?: string };
if (event.origin !== location.origin || m?.type !== 'isssteleon-oauth') return;
if (m.state !== started.state) return;
window.removeEventListener('message', listen);
if (m.error) this.problem.set(m.error);
else this.set(field, m.account);
popup?.close();
};
window.addEventListener('message', listen);
}
protected cell(v: unknown): string {
return typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v ?? '');
}
/** Answers without empty ones (a default takes their place on the server). */
private cleaned(): Record<string, unknown> {
return Object.fromEntries(
Object.entries(this.answers()).filter(([, v]) => v !== '' && v !== null && v !== undefined),
);
}
protected readonly missing = computed(() =>
entries(this.type())
.filter(([k, f]) => f.required && f.type !== 'table' && isEmpty(this.answers()[k]))
.filter(([, f]) => f.default === null || f.default === undefined)
.map(([, f]) => f.label),
);
protected readonly ready = computed(
() =>
!this.missing().length &&
entries(this.type())
.filter(([, f]) => f.type === 'table' && f.required)
.every(([k]) => !isEmpty(this.answers()[k])),
);
protected save(): void {
const type = this.typeId();
if (!type || !this.ready()) return;
this.ref.close({
guided: { type, answers: this.cleaned() },
label: this.label() || this.type()!.title,
});
}
}
function entries(t: SourceType | undefined): [string, FieldSpec][] {
return Object.entries(t?.fields ?? {});
}
function isEmpty(v: unknown): boolean {
return v === '' || v === null || v === undefined;
}
function message(e: unknown): string {
if (e instanceof HttpErrorResponse) {
const d = e.error?.detail;
if (typeof d === 'string') return d;
if (e.status === 0) return 'No hay conexión con la plataforma. Intente de nuevo.';
return JSON.stringify(d ?? e.message);
}
return String(e);
}
-144
View File
@@ -1,144 +0,0 @@
import type { Figure } from './plot';
/** The EEG metrics (models.tea.eeg.biomarkers.CODES), as the pages name them. */
export const METRIC_NAMES: Record<string, string> = {
posterior_rhythm: 'Ritmo posterior (Hz)',
spindles_n2: 'Husos de sueño N2 (por min)',
spindles_n3: 'Husos de sueño N3 (por min)',
paroxysmal_spikes: 'Picos paroxísticos (por min)',
anteroposterior_gradient: 'Gradiente anteroposterior',
};
/** The zones the metrics are summed over (models.tea.eeg.spindles.ZONES). */
export const ZONE_NAMES: Record<string, string> = {
frontal_left: 'Frontal izquierda',
frontal_right: 'Frontal derecha',
frontal_midline: 'Frontal media',
central: 'Central',
parietal: 'Parietal',
temporal_left: 'Temporal izquierda',
temporal_right: 'Temporal derecha',
occipital: 'Occipital',
posterior: 'Posterior',
global: 'Global',
};
/** The association's biomarkers (core.tea.association.BIOMARKERS). */
export const BIOMARKER_NAMES: Record<string, string> = {
spikes: 'Picos paroxísticos',
spindles: 'Husos de sueño N2',
posterior_rhythm: 'Ritmo posterior',
gradient: 'Gradiente anteroposterior',
};
/** ADOS-2 items by their number (core.tea.association.ITEMS), and the CSS. */
export const OUTCOME_NAMES: Record<string, string> = {
ados2_item_01: 'Vocalización espontánea dirigida a otros',
ados2_item_02: 'Señalar',
ados2_item_03: 'Gestos',
ados2_item_04: 'Contacto visual inusual',
ados2_item_05: 'Expresiones faciales dirigidas a otros',
ados2_item_06: 'Integración de la mirada con otras conductas',
ados2_item_07: 'Disfrute compartido en la interacción',
ados2_item_08: 'Respuesta al nombre',
ados2_item_09: 'Búsqueda de atención cuando se le ignora',
ados2_item_10: 'Pedir',
ados2_item_11: 'Mostrar',
ados2_item_12: 'Iniciación espontánea de la atención conjunta',
ados2_item_13: 'Respuesta a la atención conjunta',
ados2_item_14: 'Calidad de los acercamientos sociales',
ados2_item_15: 'Cantidad de acercamientos sociales al cuidador',
ados2_item_16: 'Cantidad de comunicación social recíproca',
ados2_item_17: 'Calidad general de la relación',
ados2_item_18: 'Entonación de vocalizaciones o verbalizaciones',
ados2_item_19: 'Uso estereotipado o idiosincrático de palabras',
ados2_item_20: 'Interés sensorial inusual',
ados2_item_21: 'Manierismos de manos y dedos',
ados2_item_22: 'Intereses repetitivos o conductas estereotipadas',
CSS: 'Puntuación de severidad (CSS)',
};
/** Where each electrode of the 10-20 system sits on a head seen from above (nose up). */
const AT: Record<string, [number, number]> = {
Fp1: [-0.31, 0.95], Fp2: [0.31, 0.95],
F7: [-0.81, 0.59], F3: [-0.4, 0.53], Fz: [0, 0.5], F4: [0.4, 0.53], F8: [0.81, 0.59],
T3: [-1, 0], C3: [-0.5, 0], Cz: [0, 0], C4: [0.5, 0], T4: [1, 0],
T5: [-0.81, -0.59], P3: [-0.4, -0.53], Pz: [0, -0.5], P4: [0.4, -0.53], T6: [0.81, -0.59],
O1: [-0.31, -0.95], O2: [0.31, -0.95],
}; // prettier-ignore
export interface Site {
site: string;
value: number;
z?: number | null;
}
/** Her electrodes on the head, coloured by how far each is from its age curve (z, blue
* below and red above), or by her own value where no curve scores electrodes. */
export function headMap(electrodes: Site[]): Figure {
const placed = electrodes.filter((e) => AT[e.site]);
const scored = placed.some((e) => e.z !== null && e.z !== undefined);
const colour = placed.map((e) => (scored ? (e.z ?? 0) : e.value));
const ring = Array.from({ length: 73 }, (_, i) => (i * 2 * Math.PI) / 72);
return {
data: [
{
x: ring.map((t) => 1.12 * Math.sin(t)),
y: ring.map((t) => 1.12 * Math.cos(t)),
mode: 'lines',
line: { color: '#9aa0a6', width: 1 },
hoverinfo: 'skip',
showlegend: false,
},
{
x: [-0.12, 0, 0.12],
y: [1.1, 1.24, 1.1],
mode: 'lines',
line: { color: '#9aa0a6', width: 1 },
hoverinfo: 'skip',
showlegend: false,
},
{
x: placed.map((e) => AT[e.site][0]),
y: placed.map((e) => AT[e.site][1]),
text: placed.map((e) => e.site),
customdata: colour,
mode: 'markers+text',
textposition: 'top center',
marker: {
size: 22,
color: colour,
colorscale: 'RdBu',
reversescale: true,
...(scored ? { cmin: -3, cmax: 3, cmid: 0 } : {}),
colorbar: { title: { text: scored ? 'z' : 'valor' }, thickness: 10 },
line: { color: '#ffffff', width: 1 },
},
hovertemplate: scored ? '%{text}: z = %{customdata:.2f}<extra></extra>'
: '%{text}: %{customdata:.3f}<extra></extra>', // prettier-ignore
showlegend: false,
},
],
layout: {
xaxis: { visible: false, range: [-1.35, 1.35], scaleanchor: 'y' },
yaxis: { visible: false, range: [-1.25, 1.35] },
margin: { l: 10, r: 10, t: 10, b: 10 },
},
} as Figure;
}
/** The zones, most affected first: by how far from the age curve, else by value. */
export function byDeviation(zones: Site[]): Site[] {
const scored = zones.some((z) => z.z !== null && z.z !== undefined);
return [...zones].sort((a, b) =>
scored ? Math.abs(b.z ?? 0) - Math.abs(a.z ?? 0) : b.value - a.value,
);
}
/** An EEG's quality level (models.tea.eeg.checks): how much of it the analysis could use. */
export const LEVEL_NAMES: Record<string, string> = {
complete: 'registro completo',
partial: 'registro parcial: menos de la mitad limpio',
no_ear_reference: 'sin referencia auricular',
not_analyzable: 'no analizable',
};
+20
View File
@@ -0,0 +1,20 @@
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);
}
-69
View File
@@ -1,69 +0,0 @@
import type { Content, TDocumentDefinitions } from 'pdfmake/interfaces';
/** A table to save, as the page shows it: its headers and rows, and what it was asked with. */
export interface Sheet {
title: string;
query?: [string, string][];
head: string[];
rows: string[][];
}
/** Every cell is text: nothing in it runs as a formula. */
export async function saveExcel(sheet: Sheet, file: string): Promise<void> {
const { default: write } = await import('write-excel-file/browser');
const text = (value: string) => ({ value, type: String });
const head = sheet.head.map((value) => ({ ...text(value), fontWeight: 'bold' as const }));
await write([
{ sheet: 'Resultados', data: [head, ...sheet.rows.map((r) => r.map(text))] },
{ sheet: 'Consulta', data: (sheet.query ?? []).map((q) => q.map(text)) },
]).toFile(`${file}.xlsx`);
}
/** The tables on the institutional page: logo, date and page numbers. */
export async function savePdf(sheets: Sheet[], file: string, wide = false): Promise<void> {
const [pdfmake, fonts, logo] = await Promise.all([
import('pdfmake/build/pdfmake'),
import('pdfmake/build/vfs_fonts'),
fetch('assets/branding/isssteleon-logo.png').then((r) => r.blob()),
]);
const image = await new Promise<string>((done, fail) => {
const reader = new FileReader();
reader.onload = () => done(reader.result as string);
reader.onerror = () => fail(reader.error);
reader.readAsDataURL(logo);
});
const made = new Date().toLocaleString('es-MX', { dateStyle: 'medium', timeStyle: 'short' });
const definition: TDocumentDefinitions = {
pageSize: 'LETTER',
pageOrientation: wide ? 'landscape' : 'portrait',
pageMargins: [36, 60, 36, 40],
defaultStyle: { fontSize: 7.5 },
header: { image, width: 110, margin: [36, 18, 0, 0] },
footer: (page, pages) => ({
columns: [
`Generado: ${made}`,
{ text: 'Confidencial, uso interno', alignment: 'center' },
{ text: `Página ${page} de ${pages}`, alignment: 'right' },
],
margin: [36, 12],
fontSize: 7,
}),
content: sheets.flatMap((s): Content[] => [
{ text: s.title, fontSize: 13, bold: true, margin: [0, 10, 0, 4] },
...(s.query ?? []).map(([k, v]) => ({ text: [{ text: `${k}: `, bold: true }, v] })),
s.rows.length
? {
layout: 'lightHorizontalLines',
margin: [0, 6, 0, 0],
table: {
headerRows: 1,
dontBreakRows: true,
body: [s.head.map((text) => ({ text, bold: true })), ...s.rows],
},
}
: 'Sin registros.',
]),
};
pdfmake.default.addVirtualFileSystem(fonts.default);
await pdfmake.default.createPdf(definition).download(`${file}.pdf`);
}
+9 -9
View File
@@ -1,4 +1,4 @@
import { interpretabilityFigures, scenarioFigure } from './figures';
import { interpretabilityFigures } from './figures';
describe('governance figures', () => {
it('draws a survival report as curves with bands and the model points', () => {
@@ -13,7 +13,7 @@ describe('governance figures', () => {
expect((found.figure.data[2] as any).error_y.array[0]).toBeCloseTo(0.05);
});
it('leaves the survival scenarios to the patient record, which draws them whole', () => {
it("draws each survival scenario after the cohort's curves, titled with its deaths", () => {
const scenario = {
escenario: 'HER2+ · ≥60 años · estadio III–IV (Alto)',
n: 1142,
@@ -30,14 +30,14 @@ describe('governance figures', () => {
predicted: { name: 'Modelo', months: [6], survival: [0.9], low: [0.8], high: [0.95] },
escenarios: [scenario],
});
expect(found.length).toBe(1); // the cohort's curves only
const drawn = scenarioFigure(scenario.escenario, scenario, scenario.horizons_months, 'S(t)');
expect(drawn.figure.data.length).toBe(5); // band, KM, Weibull, fractional, points
expect((drawn.figure.data[4] as any).x).toEqual([6, 12, 18]);
expect(found.length).toBe(2);
expect(found[1].title).toContain('fallecidos = 308');
expect(found[1].figure.data.length).toBe(5); // band, KM, Weibull, fractional, points
expect((found[1].figure.data[4] as any).x).toEqual([6, 12, 18]);
});
it('leaves recurrence scenarios to the patient record', () => {
const found = interpretabilityFigures({
it('draws a recurrence scenario: KM band, both Weibulls and the model points', () => {
const [found] = interpretabilityFigures({
kind: 'scenarios',
recurrencia: {
horizons_months: [12, 36],
@@ -55,7 +55,7 @@ describe('governance figures', () => {
],
},
});
expect(found).toEqual([]);
expect(found.figure.data.length).toBe(5); // band, KM, Weibull, fractional, points
});
it('draws an age curve with its centile band', () => {
+24 -66
View File
@@ -1,6 +1,5 @@
import type { Figure } from '../plot';
import { PALETTE } from '../plot';
import { BIOMARKER_NAMES, OUTCOME_NAMES, ZONE_NAMES } from '../eeg-labels';
/** A curve with its band, as the reports give them. */
interface Band {
@@ -71,7 +70,15 @@ export function interpretabilityFigures(
},
},
},
// Its clinical scenarios are drawn in the patient record (Análisis de supervivencia).
// Its clinical scenarios, those with enough deaths to draw.
...((report['escenarios'] ?? []) as any[]).map((e) =>
scenarioFigure(
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`,
e,
e.horizons_months,
'Supervivencia S(t)',
),
),
];
}
case 'subgroups':
@@ -140,8 +147,17 @@ export function interpretabilityFigures(
},
];
}
case 'scenarios': // recurrence: its scenarios are drawn in the patient record
return [];
case 'scenarios':
return (report['recurrencia']['escenarios'] as any[])
.slice(0, 6)
.map((e) =>
scenarioFigure(
`${e.cohorte_nombre} · ${e.escenario} (n = ${e.n}, ${e.recaidas} recaídas)`,
e,
report['recurrencia']['horizons_months'],
'Supervivencia libre de recaída',
),
);
case 'age_curves': {
// The metric's own curve; a topography has only electrodes: its first one.
const value = report['curves']['value'] ?? Object.values(report['curves'])[0];
@@ -189,70 +205,14 @@ export function interpretabilityFigures(
},
];
}
case 'associations': {
// Each estimated pair's odds ratio with its 95 % interval, clearest first.
const rows = (report['rows'] as any[])
.filter((r) => r.odds_ratio !== null)
.sort((a, b) => (a.q ?? 1) - (b.q ?? 1));
const label = (r: any) =>
`${BIOMARKER_NAMES[r.biomarker] ?? r.biomarker} · ${ZONE_NAMES[r.zone] ?? r.zone} → ${
OUTCOME_NAMES[r.outcome_code] ?? r.outcome_code
}`;
return [
{
title: `Asociaciones con el ADOS-2 (${report['children']} niños, nivel ${
report['level'] === 'item' ? 'reactivo' : 'dominio'
})`,
figure: {
data: [
{
type: 'scatter',
mode: 'markers',
x: rows.map((r) => r.odds_ratio),
y: rows.map(label),
error_x: {
type: 'data',
symmetric: false,
array: rows.map((r) => (r.ci_high ?? r.odds_ratio) - r.odds_ratio),
arrayminus: rows.map((r) => r.odds_ratio - (r.ci_low ?? r.odds_ratio)),
},
marker: {
color: rows.map((r) => ((r.q ?? 1) < 0.05 ? PALETTE[2] : '#9aa0a6')),
size: 9,
},
customdata: rows.map((r) => r.q),
hovertemplate: 'OR %{x:.2f} · q %{customdata:.3f}<extra>%{y}</extra>',
showlegend: false,
},
],
layout: {
xaxis: { title: { text: 'Razón de momios (escala log)' }, type: 'log' },
yaxis: { automargin: true, autorange: 'reversed' },
shapes: [
{
type: 'line',
x0: 1,
x1: 1,
yref: 'paper',
y0: 0,
y1: 1,
line: { color: '#9aa0a6', dash: 'dot' },
},
],
height: Math.max(320, 22 * rows.length + 80),
},
},
},
];
}
default:
return [];
}
}
/** One clinical scenario: Kaplan-Meier with its band, the classic and fractional Weibull,
* and the model's points with their bootstrap band (also a patient's, in her record). */
export function scenarioFigure(
* and the model's points with their bootstrap band. */
function scenarioFigure(
title: string,
e: any,
horizons: number[],
@@ -286,10 +246,8 @@ export function scenarioFigure(
points('LR + HBN combinado (IC 95 % bootstrap)', horizons, e.points.COMB),
],
layout: {
// One label per month with every curve's survival there, as percentages.
hovermode: 'x unified',
xaxis: { title: { text: 'Meses desde el diagnóstico' }, hoverformat: '.0f' },
yaxis: { title: { text: yTitle }, tickformat: '.1~%', hoverformat: '.1%' },
xaxis: { title: { text: 'Meses desde el diagnóstico' } },
yaxis: { title: { text: yTitle } },
},
},
};
+34 -68
View File
@@ -1,6 +1,10 @@
<section class="page">
<h1>{{ labels[domain()] ?? domain() }}</h1>
<p class="muted subtitle">Versiones, informes, promoción y ejecuciones de sus modelos.</p>
<h1>Gobernanza de modelos</h1>
<nav class="domains" aria-label="Dominios">
@for (d of domains.value() ?? []; track d) {
<a [routerLink]="['/gobernanza', d]" [class.active]="d === domain()">{{ labels[d] ?? d }}</a>
}
</nav>
<form class="card actions" (submit)="$event.preventDefault()">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
@@ -13,44 +17,13 @@
name="asOf"
/>
</mat-form-field>
@if (confirming(); as c) {
<span class="confirm" role="alert">
{{
c === 'train'
? '¿Entrenar todos los modelos de este dominio ahora?'
: '¿Calcular los riesgos de todas las pacientes con los modelos en producción?'
}}
<button mat-flat-button type="button" (click)="start(c)">Sí, iniciar</button>
<button mat-button type="button" (click)="confirming.set(undefined)">Cancelar</button>
</span>
} @else {
<button
mat-flat-button
type="button"
[disabled]="running()"
(click)="confirming.set('train')"
>
Entrenar
</button>
<button
mat-stroked-button
type="button"
[disabled]="running()"
(click)="confirming.set('score')"
>
Calcular riesgos
</button>
@if (domain() === 'tea') {
<button mat-stroked-button type="button" [disabled]="running()" (click)="analyzeEegs()">
Analizar EEG
</button>
}
<button mat-flat-button type="button" (click)="start('train')">Entrenar</button>
<button mat-stroked-button type="button" (click)="start('score')">Calcular riesgos</button>
@if (domain() === 'tea') {
<button mat-stroked-button type="button" (click)="analyzeEegs()">Analizar EEG</button>
}
@if (run(); as r) {
<span class="muted" role="status">{{ r.kind }}: {{ STATUS[r.status] ?? r.status }}</span>
@if (running()) {
<button mat-button type="button" class="stop" (click)="stop()">Detener</button>
}
<span class="muted" role="status">{{ r.kind }}: {{ r.status }}</span>
}
</form>
@if (message()) {
@@ -58,21 +31,19 @@
}
@if (models.isLoading()) {
<app-loading what="los modelos" />
<p class="muted">Cargando modelos…</p>
} @else if (!models.value()?.length) {
<p class="muted empty">Sin modelos entrenados en este dominio.</p>
<p class="muted empty">Este dominio todavía no tiene modelos entrenados.</p>
}
@for (m of models.value() ?? []; track m.name) {
<div class="card model">
<h2>
{{ m.title }} <code class="muted code">{{ m.name }}</code>
</h2>
<h2>{{ m.name }}</h2>
<table class="plain">
<thead>
<tr>
<th>Versión</th>
<th>Creada</th>
<th>Datos</th>
<th>Entrenamiento / prueba</th>
<th>Informes</th>
<th>Validación clínica</th>
<th></th>
@@ -88,37 +59,32 @@
}
</td>
<td>{{ v.created | date: 'yyyy-MM-dd HH:mm' }}</td>
<td class="nowrap">{{ sizes(v) }}</td>
<td class="num">
{{ v.metrics['n_train'] | number }} / {{ v.metrics['n_test'] | number }}
</td>
<td>
<div class="reports">
@for (r of v.reports; track r) {
<a [href]="reportUrl(m.name, v.version, r)" target="_blank" rel="noopener">{{
reportNames[r] ?? r
}}</a>
}
@if (v.reports.includes('interpretability')) {
<button
mat-button
type="button"
(click)="chosen.set({ name: m.name, version: v.version })"
>
Ver gráficas
</button>
}
</div>
@for (r of v.reports; track r) {
<a [href]="reportUrl(m.name, v.version, r)" target="_blank" rel="noopener">{{
reportNames[r] ?? r
}}</a>
}
@if (v.reports.includes('interpretability')) {
<button
mat-button
type="button"
(click)="chosen.set({ name: m.name, version: v.version })"
>
Ver gráficas
</button>
}
</td>
<td>
@if (!v.reports.includes('clinical_validation')) {
<input
#file
type="file"
hidden
[attr.aria-label]="'Validación clínica de ' + m.title + ' v' + v.version"
[attr.aria-label]="'Validación clínica de ' + m.name + ' v' + v.version"
(change)="upload(m.name, v.version, $event)"
/>
<button mat-stroked-button type="button" (click)="file.click()">
Subir validación clínica
</button>
} @else {
Agregada
}
@@ -139,7 +105,7 @@
@if (chosen(); as c) {
<div class="card">
<h2>Interpretabilidad · {{ titleOf(c.name) }} v{{ c.version }}</h2>
<h2>Interpretabilidad · {{ c.name }} v{{ c.version }}</h2>
@for (f of figures(); track f.title) {
<h3>{{ f.title }}</h3>
<app-plot [figure]="f.figure" [height]="360" />
+12 -32
View File
@@ -1,8 +1,18 @@
:host {
display: block;
}
.subtitle {
margin: 4px 0 var(--space-4);
h1 {
text-align: center;
}
.domains {
display: flex;
justify-content: center;
gap: var(--space-4);
margin-bottom: var(--space-4);
}
.domains a.active {
font-weight: 600;
text-decoration: underline;
}
.actions {
display: flex;
@@ -20,7 +30,6 @@
white-space: nowrap;
}
.badge {
white-space: nowrap;
margin-left: var(--space-2);
padding: 2px 8px;
border-radius: 999px;
@@ -36,32 +45,3 @@ td a {
padding: 48px 0;
text-align: center;
}
.reports {
display: flex;
flex-wrap: wrap;
align-items: center;
column-gap: var(--space-3);
row-gap: 2px;
}
.reports a {
margin-right: 0;
}
h2 .code {
font-size: 12px;
font-weight: 400;
margin-left: var(--space-2);
}
.confirm {
display: inline-flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
padding: 4px 4px 4px 12px;
border-radius: 8px;
background: var(--color-surface-warning, #fdf3dc);
}
td button {
white-space: nowrap;
}
+18 -64
View File
@@ -1,4 +1,3 @@
import { METRIC_NAMES } from '../eeg-labels';
import { HttpErrorResponse } from '@angular/common/http';
import { DatePipe, DecimalPipe } from '@angular/common';
import { Component, computed, inject, input, resource, signal } from '@angular/core';
@@ -6,6 +5,7 @@ import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { RouterLink } from '@angular/router';
import { Api } from '../api/api';
import { ApiConfiguration } from '../api/api-configuration';
import { addClinicalValidation } from '../api/fn/models/add-clinical-validation';
@@ -16,16 +16,15 @@ import { readReport$Json } from '../api/fn/models/read-report-json';
import { score } from '../api/fn/models/score';
import { train } from '../api/fn/models/train';
import { versions } from '../api/fn/models/versions';
import { domains } from '../api/fn/operations/domains';
import { studies } from '../api/fn/eeg/studies';
import { study } from '../api/fn/eeg/study';
import { terminateRun } from '../api/fn/runs/terminate-run';
import { runStatus } from '../api/fn/runs/run-status';
import type { Domain } from '../api/models/domain';
import type { Version } from '../api/models/version';
import { DOMAINS } from '../app';
import { Plot } from '../plot';
import { interpretabilityFigures } from './figures';
import { Loading } from '../loading';
const REPORTS: Record<string, string> = {
technical_validation: 'Validación técnica',
@@ -39,13 +38,13 @@ const REPORTS: Record<string, string> = {
@Component({
selector: 'app-gobernanza',
imports: [
Loading,
DatePipe,
DecimalPipe,
FormsModule,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
RouterLink,
Plot,
],
templateUrl: './gobernanza.html',
@@ -58,15 +57,15 @@ export class Gobernanza {
protected readonly labels = DOMAINS as Record<string, string>;
protected readonly reportNames = REPORTS;
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
private readonly refreshed = signal(0);
protected readonly models = resource({
params: () => ({ domain: this.domain() as Domain, at: this.refreshed() }),
loader: async ({ params: { domain } }) => {
const found = await this.api.invoke(models, { domain });
const names = await this.api.invoke(models, { domain });
return Promise.all(
found.map(async ({ name, title }) => ({
names.map(async (name) => ({
name,
title,
versions: await this.api.invoke(versions, { domain, name }),
})),
);
@@ -92,43 +91,15 @@ export class Gobernanza {
params: () => this.eeg(),
loader: ({ params }) => this.api.invoke(study, { eeg_id: params }),
});
protected readonly metricNames = METRIC_NAMES;
protected readonly asOf = signal('');
protected readonly run = signal<{ id: string; kind: string; status: string } | undefined>(
undefined,
);
/** The run "Entrenar" or "Calcular riesgos" will start once confirmed. */
protected readonly confirming = signal<'train' | 'score' | undefined>(undefined);
protected readonly running = computed(() => {
const r = this.run();
return !!r && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(r.status);
});
protected readonly STATUS: Record<string, string> = {
QUEUED: 'en cola',
NOT_STARTED: 'por iniciar',
STARTING: 'iniciando',
STARTED: 'en curso',
SUCCESS: 'terminado',
FAILURE: 'con error',
CANCELING: 'deteniéndose',
CANCELED: 'detenido',
protected readonly metricNames: Record<string, string> = {
posterior_rhythm: 'Ritmo posterior (Hz)',
spindles_n2: 'Husos de sueño N2 (por min)',
spindles_n3: 'Husos de sueño N3 (por min)',
paroxysmal_spikes: 'Picos paroxísticos (por min)',
anteroposterior_gradient: 'Gradiente anteroposterior',
};
/** A model's title by its name, for messages. */
protected titleOf(name: string): string {
return this.models.value()?.find((m) => m.name === name)?.title ?? name;
}
/** What a version learned from, as its metrics say it (each kind of model its own). */
protected sizes(v: Version): string {
const m = v.metrics;
const n = (x: number) => x.toLocaleString('es-MX');
if (m['n_train'] !== undefined)
return `${n(m['n_train'])} entrenamiento / ${n(m['n_test'] ?? 0)} prueba`;
if (m['n_reference'] !== undefined) return `${n(m['n_reference'])} EEG de referencia`;
if (m['children'] !== undefined) return `${n(m['children'])} niños`;
const c = Object.entries(m).find(([k]) => k.endsWith('c_index_cox'));
if (c) return `C-index ${c[1].toFixed(3)}`;
return '—';
}
protected readonly asOf = signal('');
protected readonly run = signal<{ kind: string; status: string } | undefined>(undefined);
protected readonly message = signal('');
protected champion(v: Version): boolean {
@@ -149,27 +120,18 @@ export class Gobernanza {
// OpenAPI's binary is typed as a string; the request builder sends the File as is.
body: { file: file as unknown as string },
});
this.message.set(`Validación clínica agregada a ${this.titleOf(name)} v${version}.`);
this.message.set(`Validación clínica agregada a ${name} v${version}.`);
this.refreshed.update((n) => n + 1);
}
protected async promote(name: string, version: number): Promise<void> {
try {
await this.api.invoke(promote, { domain: this.domain() as Domain, name, version });
this.message.set(`${this.titleOf(name)} v${version} es ahora la versión en producción.`);
this.message.set(`${name} v${version} es ahora la versión en producción.`);
this.refreshed.update((n) => n + 1);
} catch (e) {
const detail = e instanceof HttpErrorResponse ? e.error?.detail : undefined;
// "<model> v1 has no clinical_validation, interpretability": the reports it lacks
const missing = /has no (.+)$/.exec(String(detail ?? ''))?.[1];
this.message.set(
missing
? `No se promovió: faltan informes (${missing
.split(', ')
.map((r) => this.reportNames[r] ?? r)
.join(', ')}).`
: `No se promovió: ${detail ?? 'error de la plataforma'}`,
);
this.message.set(`No se promovió: ${detail ?? 'error'}`);
}
}
@@ -181,22 +143,14 @@ export class Gobernanza {
private async follow(run_id: string, label: string): Promise<void> {
for (;;) {
const status = (await this.api.invoke(runStatus, { run_id }))['status'] as string;
this.run.set({ id: run_id, kind: label, status });
this.run.set({ kind: label, status });
if (['SUCCESS', 'FAILURE', 'CANCELED'].includes(status)) break;
await new Promise((r) => setTimeout(r, 2000));
}
this.refreshed.update((n) => n + 1);
}
protected async stop(): Promise<void> {
const r = this.run();
if (!r) return;
const found = await this.api.invoke(terminateRun, { run_id: r.id });
this.run.set({ ...r, status: found['status'] });
}
protected async start(kind: 'train' | 'score'): Promise<void> {
this.confirming.set(undefined);
const domain = this.domain() as Domain;
const { run_id } =
kind === 'train'
-330
View File
@@ -1,330 +0,0 @@
import { bars, grouped, hiddenNote, Mode, unavailable } from './bars';
import { scenarioBars } from './figures';
import { Reading } from './measures';
describe('bars', () => {
it('list every category, so the shares add up', () => {
const r: Reading = {
populations: {},
strata: {
category: { a: { 'initial-population': 3 }, other: { 'initial-population': 1 } },
},
};
const catalog = [{ code: 'a', label: 'A', color: '#000' }];
const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog }, () => r)!;
expect(t.rows.map((x) => x.cells)).toEqual([
['3', '75.0 %'],
['1', '25.0 %'],
]);
});
it('a group with no patients has no rate', () => {
const r: Reading = {
populations: {},
strata: { s: { initial: { numerator: 0, denominator: 0 } } },
};
const mode = { kind: 'shares', label: 'x', measure: 'M', stratum: 's', order: ['initial'] };
expect(bars(mode as any, () => r)!.rows[0].cells).toEqual(['0/0', '—']);
});
describe('screening rounds (complete)', () => {
const ORDER = ['initial', 'subsequent', 'no_data'];
const cell = (numerator: number, denominator: number) => ({ numerator, denominator });
const ppv = (strata: Record<string, any>, total: number): Reading => ({
populations: { 'initial-population': total, denominator: total },
strata: { round: strata },
});
const mode = {
kind: 'shares',
label: 'x',
measure: 'M',
stratum: 'round',
order: ORDER,
complete: true,
} as const;
it('lists the three groups in order with their own counts', () => {
const r = ppv({ no_data: cell(1, 4), subsequent: cell(6, 10), initial: cell(0, 6) }, 20);
const t = bars(mode, () => r)!;
expect(t.rows.map((x) => x.label)).toEqual([
'Detección inicial',
'Detección subsecuente',
'Sin dato',
]);
expect(t.rows.map((x) => x.cells)).toEqual([
['0/6', '0.0 %'],
['6/10', '60.0 %'],
['1/4', '25.0 %'],
]);
expect(t.note).toBeUndefined();
});
it('a group the report leaves out is zero patients when the counts add up', () => {
const r = ppv({ no_data: cell(0, 3), subsequent: cell(6, 10) }, 13);
const initial = bars(mode, () => r)!.rows[0];
expect(initial.cells).toEqual(['0/0', '—']);
expect(initial.hint).toBe('Sin pacientes en el periodo');
});
it('a group left out is not available when the counts do not add up', () => {
const r = ppv({ subsequent: cell(6, 10) }, 13);
const t = bars(mode, () => r)!;
expect(t.rows[0].cells).toEqual(['—', '—']);
expect(t.rows[0].hint).toBe('No disponible');
expect(t.note).toContain('no concilian');
});
it('a zero numerator over a positive denominator is 0 %, a zero denominator has no rate', () => {
const r = ppv({ initial: cell(0, 5), subsequent: cell(0, 0), no_data: cell(2, 3) }, 8);
const t = bars(mode, () => r)!;
expect(t.rows[0].cells).toEqual(['0/5', '0.0 %']);
expect(t.rows[1].cells).toEqual(['0/0', '—']);
expect(t.rows[1].hint).toBe('Sin pacientes en el periodo');
});
it('warns when only "Sin dato" holds patients', () => {
const r = ppv({ no_data: cell(3, 7) }, 7);
const t = bars(mode, () => r)!;
expect(t.rows[2].cells).toEqual(['3/7', '42.9 %']);
expect(t.note).toContain('información no registrada');
});
it('draws nothing without patients and says "No disponible" without the stratifier', () => {
expect(bars(mode, () => ppv({}, 0))).toBeUndefined();
expect(unavailable(mode, () => ppv({}, 0))).toBeUndefined();
expect(unavailable(mode, () => ppv({}, 9))).toContain('No disponible');
expect(bars(mode, () => ppv({}, 9))).toBeUndefined();
});
it('a cell that is not whole or has a numerator above its denominator is not available', () => {
const r = ppv({ initial: cell(5, 3), subsequent: cell(1, 2), no_data: cell(0, 1) }, 6);
expect(bars(mode, () => r)!.rows[0].hint).toBe('No disponible');
});
it('VPH positives: groups from the crossed cells, absent ones reconciled', () => {
const r: Reading = {
populations: { 'initial-population': 12 },
strata: {
'round-category': {
'subsequent|positive': { 'initial-population': 3 },
'subsequent|negative': { 'initial-population': 7 },
'no_data|negative': { 'initial-population': 2 },
},
},
};
const t = bars(
{
kind: 'positives',
label: 'x',
measure: 'M',
stratum: 'round',
order: ORDER,
complete: true,
},
() => r,
)!;
expect(t.rows.map((x) => x.cells)).toEqual([
['0/0', '—'],
['3/10', '30.0 %'],
['0/2', '0.0 %'],
]);
});
});
describe('cytology by round', () => {
const cats = [
{ code: 'NILM', label: 'Normal', color: '#0a0', group: '' },
{ code: 'HSIL', label: 'LIEAG', color: '#a00', group: '' },
];
const reading = (cells: Record<string, number>, total: number): Reading => ({
populations: { 'initial-population': total },
strata: {
'round-category': Object.fromEntries(
Object.entries(cells).map(([k, n]) => [k, { 'initial-population': n }]),
),
},
});
const draw = (r: Reading) =>
scenarioBars(
r,
{ groups: [], categories: cats },
'round',
(c) =>
c === 'initial'
? 'Detección inicial'
: c === 'subsequent'
? 'Detección subsecuente'
: 'Sin dato',
['initial', 'subsequent', 'no_data'],
{ fill: true },
);
it('keeps the order and shows each bar with its n, an empty one included', () => {
const f = draw(
reading({ 'subsequent|NILM': 6, 'subsequent|HSIL': 2, 'no_data|NILM': 2 }, 10),
);
const y = (f.data[0] as any).y;
expect(y).toEqual([
'Detección inicial<br>n = 0',
'Detección subsecuente<br>n = 8',
'Sin dato<br>n = 2',
]);
expect((f.data[0] as any).x).toEqual([0, 75, 100]);
});
it('leaves out a group that does not reconcile', () => {
const f = draw(reading({ 'subsequent|NILM': 6 }, 10));
expect((f.data[0] as any).y).toEqual(['Detección subsecuente<br>n = 6']);
});
});
});
describe('shared views of cytology and HPV by genotype', () => {
const HPV = [
{ code: 'negative', label: 'Negativo', color: '#42A77E', group: '' },
{ code: 'positive_other', label: 'Positivo', color: '#A8C243', group: '' },
];
const reading = (cells: Record<string, number>): Reading => ({
populations: { 'initial-population': Object.values(cells).reduce((a, b) => a + b, 0) },
strata: {
category: {
negative: { 'initial-population': 5 },
positive_other: { 'initial-population': 2 },
positive_incomplete: { 'initial-population': 3 },
},
'age_group-category': Object.fromEntries(
Object.entries(cells).map(([k, n]) => [k, { 'initial-population': n }]),
),
},
});
const counts: Mode = {
kind: 'counts',
label: 'General',
measure: 'M',
catalog: HPV,
hidden: { codes: ['positive_incomplete', 'inconsistent'], unit: 'reportes' },
};
it('does not list a hidden category but keeps it in the total and the percentages', () => {
const t = bars(counts, () => reading({}))!;
expect(t.rows.map((x) => x.label)).toEqual(['Negativo', 'Positivo']);
expect(t.rows.map((x) => x.cells)).toEqual([
['5', '50.0 %'],
['2', '20.0 %'],
]); // of 10 reports
expect(t.note).toBe(
'3 reportes (Positivo con genotipificación incompleta) no se muestran desglosados; están incluidos en el total y en los porcentajes.',
);
});
it('says nothing when no report is hidden', () => {
const r: Reading = {
populations: {},
strata: { category: { negative: { 'initial-population': 1 } } },
};
expect(hiddenNote(counts, () => r)).toBeUndefined();
});
it('a figure by groups is not available without its breakdown, and counts every record of the group on request', () => {
const mode = {
kind: 'figure',
label: 'Por grupo de edad',
measure: 'M',
figure: 'scenarios',
stratum: 'age_group',
catalog: HPV,
} as const;
const noBreakdown: Reading = {
populations: { 'initial-population': 4 },
strata: { category: {} },
};
expect(unavailable(mode, () => noBreakdown)).toBe(
'No disponible: el informe de este periodo no publica el desglose «Por grupo de edad».',
);
const r: Reading = {
populations: { 'initial-population': 10 },
strata: {
'age_group-category': {
'25-34|negative': { 'initial-population': 4 },
'25-34|positive_other': { 'initial-population': 1 },
'25-34|positive_incomplete': { 'initial-population': 5 },
},
},
};
const label = (c: string) => c;
const own = scenarioBars(r, { groups: [], categories: HPV }, 'age_group', label, ['25-34']);
const all = scenarioBars(r, { groups: [], categories: HPV }, 'age_group', label, ['25-34'], {
ofAll: true,
});
expect((own.data[0] as any).x).toEqual([80]); // 4 of the 5 the catalog draws
expect((all.data[0] as any).x).toEqual([40]); // 4 of the group's 10 reports
expect((all.data[0] as any).y).toEqual(['25-34<br>n = 10']);
});
});
describe('independent bars by group', () => {
const cats = [
{ code: 'NILM', label: 'Normal', color: '#408651' },
{ code: 'HSIL', label: 'LIEAG', color: '#CE4778' },
];
const mode = (more: object = {}): Mode =>
({
kind: 'grouped',
label: 'x',
measure: 'M',
catalog: cats,
stratum: 'round',
order: ['initial', 'subsequent', 'no_data'],
unit: 'pacientes',
...more,
}) as Mode;
const reading = (cells: Record<string, number>, total?: number): Reading => ({
populations: { 'initial-population': total ?? Object.values(cells).reduce((a, b) => a + b, 0) },
strata: {
'round-category': Object.fromEntries(
Object.entries(cells).map(([k, n]) => [k, { 'initial-population': n }]),
),
},
});
it('draws one bar per category in each group: count, denominator and percent over its own records', () => {
const g = grouped(mode(), () =>
reading({ 'initial|NILM': 3, 'initial|HSIL': 1, 'subsequent|NILM': 6 }),
)!;
expect(g.groups.map((x) => [x.label, x.total])).toEqual([
['Detección inicial', 4],
['Detección subsecuente', 6],
]);
expect(g.groups[0].rows.map((r) => [r.label, r.text, r.percent, r.color])).toEqual([
['Normal', '3/4 · 75.0 %', 75, '#408651'],
['LIEAG', '1/4 · 25.0 %', 25, '#CE4778'],
]);
expect(g.groups[1].rows.map((r) => r.text)).toEqual(['6/6 · 100.0 %', '0/6 · 0.0 %']); // a zero numerator is 0 %
});
it('an empty group has no percent; with complete it is drawn only when the counts reconcile', () => {
const empty = grouped(mode({ complete: true }), () =>
reading({ 'subsequent|NILM': 2, 'no_data|HSIL': 1 }),
)!;
expect(empty.groups.map((x) => x.code)).toEqual(['initial', 'subsequent', 'no_data']);
expect(empty.groups[0]).toMatchObject({ total: 0, hint: 'Sin pacientes en el grupo' });
expect(empty.groups[0].rows.map((r) => [r.text, r.percent])).toEqual([
['0/0 · —', undefined],
['0/0 · —', undefined],
]);
expect(empty.note).toContain('una categoría en cero significa');
const unreconciled = grouped(mode({ complete: true }), () =>
reading({ 'subsequent|NILM': 2 }, 5),
)!;
expect(unreconciled.groups.map((x) => x.code)).toEqual(['subsequent']);
expect(unreconciled.note).toContain('no concilian');
const open = grouped(mode(), () => reading({ 'subsequent|NILM': 2 }))!;
expect(open.groups.map((x) => x.code)).toEqual(['subsequent']); // without complete: only the listed groups
});
it('each group may count all its records, hidden categories included', () => {
const r = reading({ 'initial|NILM': 2, 'initial|positive_incomplete': 2 });
const own = grouped(mode(), () => r)!;
const all = grouped(mode({ ofAll: true }), () => r)!;
expect(own.groups[0].total).toBe(2);
expect(all.groups[0].total).toBe(4);
expect(all.groups[0].rows[0].text).toBe('2/4 · 50.0 %');
});
it('is not available without the breakdown, and draws nothing without records', () => {
const none: Reading = { populations: { 'initial-population': 4 }, strata: {} };
expect(grouped(mode(), () => none)).toBeUndefined();
expect(unavailable(mode(), () => none)).toContain('No disponible');
expect(grouped(mode(), () => reading({}, 0))).toBeUndefined();
});
it('says that unclassified records leave a classified group empty, and warns when none is classified', () => {
const lone = grouped(mode({ complete: true }), () => reading({ 'no_data|NILM': 3 }))!;
expect(lone.note).toContain('información no registrada');
});
});
-449
View File
@@ -1,449 +0,0 @@
import { CIE10 } from './cie10';
import { NEUTRAL_DARK } from './cacu-palette';
import { name, Reading } from './measures';
/** A category as drawn: its code in the report, its name and its colour. */
export type Category = { code: string; label: string; color: string };
/** One way of reading a card, as bars from the reports, or a figure. */
export type Mode = { label: string; caption?: string } & (
| { kind: 'counts'; measure: string; catalog: Category[]; hidden?: Hidden }
| {
kind: 'shares';
measure: string;
stratum: string;
order: string[];
complete?: boolean;
colors?: Colors;
}
| {
kind: 'positives';
measure: string;
stratum: string;
order: string[];
complete?: boolean;
colors?: Colors;
}
| { kind: 'signs'; measure: string; strata: string[]; colors?: Colors }
| {
kind: 'grouped';
measure: string;
/** the categories drawn in each group, in this order (each in its own colour) */
catalog: Category[];
/** the groups' stratifier (its crossed cells `<stratum>-category`) and their order */
stratum: string;
order: string[];
/** what the records are called ("pacientes", "reportes") */
unit: string;
/** draw an empty group of `order` when the counts reconcile (see `reconciles`) */
complete?: boolean;
/** each group's denominator is all its records, not only those of the catalog's categories */
ofAll?: boolean;
hidden?: Hidden;
}
| { kind: 'days'; steps: { label: string; measure: string }[]; tint?: Tint }
| { kind: 'days-by'; measure: string; stratum: string; tint?: Tint }
| {
kind: 'figure';
measure: string;
figure: 'donut' | 'scenarios';
/** a donut's colour by part (a category, or numerator and rest); none: the page's palette */
colors?: Colors;
catalog?: Category[];
/** the stratifier a scenarios figure crosses with the category (default: the follow-up status) */
stratum?: string;
order?: string[];
/** draw the groups of `order` the report leaves out as zero (see `reconciles`) */
complete?: boolean;
/** each bar is the share of all the group's records, not only of those the catalog draws */
ofAll?: boolean;
hidden?: Hidden;
}
);
/** Categories a card does not draw: their records stay in the total and in the percentages. */
export type Hidden = { codes: string[]; unit: string };
/** A colour by category code (the category decides it, not its place in the report). */
export type Colors = Record<string, string>;
/** The colours of a median bar and of the marks of its quartiles. */
export type Tint = { bar: string; mark: string };
/** One category of a group as an independent bar of 0 to 100 %: its records over the group's. */
export interface GroupRow {
label: string;
color: string;
count: number;
/** the group's records (the denominator) */
of: number;
/** none when the group has no records: a rate over nothing is not drawn */
percent?: number;
/** "2/5 · 40.0 %"; "0/0 · —" for an empty group */
text: string;
}
export interface Group {
code: string;
label: string;
/** the group's records */
total: number;
/** why the group has no figures */
hint?: string;
rows: GroupRow[];
}
export interface Groups {
groups: Group[];
note?: string;
}
/** One bar: its length and quartile marks in % of the scale, and its cells of text. */
export interface Bar {
label: string;
/** why the row has no figures: no patients in the group, or not available */
hint?: string;
color?: string;
width: number;
marks: number[];
cells: string[];
}
export interface Bars {
head: string[];
rows: Bar[];
/** the colour of the quartile marks, when the card has its own */
markColor?: string;
/** what the reader must know to take the rows right */
note?: string;
}
export const NOT_AVAILABLE = 'No disponible';
export const NO_PATIENTS = 'Sin pacientes en el periodo';
const EMPTY_ROUND =
'Hay pacientes sin clasificación de ronda («Sin dato»): una categoría en cero significa que no hay pacientes clasificadas en esa ronda según la información disponible.';
const NO_ROUND =
'Ninguna paciente del periodo tiene clasificación de detección inicial o subsecuente: los grupos en cero reflejan información no registrada, no ausencia de pacientes.';
const whole = (n: unknown): n is number => typeof n === 'number' && Number.isInteger(n) && n >= 0;
/** A group the report does not list is zero patients only when the groups it lists add up to every
* patient of the period (the report leaves out empty groups); otherwise it is not available. */
export function reconciles(listed: number[], total: number): boolean {
return listed.every(whole) && whole(total) && listed.reduce((t, n) => t + n, 0) === total;
}
/** The patients of a reading: its cohort, or the denominator of a proportion. */
export const patients = (r?: Reading) =>
r?.populations['initial-population'] ?? r?.populations['denominator'] ?? 0;
/** Why a card of a "complete" mode, or a figure by groups, has nothing to draw though its period
* has records: the report does not publish the breakdown. Undefined when there is nothing to say. */
export function unavailable(
mode: Mode,
of: (measure: string) => Reading | undefined,
): string | undefined {
const groups = mode.kind === 'grouped' || (mode.kind === 'figure' && mode.figure === 'scenarios');
const complete = 'complete' in mode && mode.complete;
if (!(groups || complete) || !('stratum' in mode) || !mode.stratum) return undefined;
const r = of(mode.measure);
if (!patients(r)) return undefined;
const key = mode.kind === 'shares' ? mode.stratum : `${mode.stratum}-category`;
return Object.keys(r?.strata[key] ?? {}).length
? undefined
: `${NOT_AVAILABLE}: el informe de este periodo no publica el desglose «${mode.label}».`;
}
/** What a card says about the categories it does not draw: how many records they hold and that
* they stay in the total and the percentages. Undefined when none is in the period. */
export function hiddenNote(
mode: Mode,
of: (measure: string) => Reading | undefined,
): string | undefined {
if (!('hidden' in mode) || !mode.hidden) return undefined;
const { codes, unit } = mode.hidden;
const cells = of(mode.measure)?.strata['category'] ?? {};
const found = codes.filter((c) => size(cells[c]));
if (!found.length) return undefined;
const n = found.reduce((t, c) => t + size(cells[c]), 0);
const names = found.map((c) => name(c)).join(', ');
const one = n === 1;
return `${n} ${one ? unit.replace(/s$/, '') : unit} (${names}) ${one ? 'no se muestra desglosado; está incluido' : 'no se muestran desglosados; están incluidos'} en el total y en los porcentajes.`;
}
const pct = (n: number, of: number) => (of ? `${((100 * n) / of).toFixed(1)} %` : '—');
const size = (cell?: Record<string, number>) => cell?.['initial-population'] ?? 0;
const days = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
/** The bars of a mode; none when the period has nothing to draw. */
export function bars(mode: Mode, of: (measure: string) => Reading | undefined): Bars | undefined {
switch (mode.kind) {
case 'counts': {
const cells = of(mode.measure)?.strata['category'] ?? {};
const total = Object.values(cells).reduce((n, c) => n + size(c), 0);
if (!total) return undefined;
// a category outside the catalog is listed after it, so the shares add up
const hidden = mode.hidden?.codes ?? [];
const named = mode.catalog.map((c) => c.code);
const rest = Object.keys(cells).filter((c) => !named.includes(c) && !hidden.includes(c));
const all = [
...mode.catalog.filter((c) => !hidden.includes(c.code)),
...rest.map((code) => ({ code, label: name(code), color: NEUTRAL_DARK })),
];
const most = Math.max(...Object.values(cells).map(size));
return {
head: ['n', '%'],
rows: all.map(({ code, label, color }) => {
const n = size(cells[code]);
const cols = [`${n}`, pct(n, total)];
return { label, color, width: (100 * n) / most, marks: [], cells: cols };
}),
note: hiddenNote(mode, of),
};
}
case 'shares': {
const r = of(mode.measure);
const cells = r?.strata[mode.stratum] ?? {};
if (!mode.complete)
return ratios(
mode.order
.filter((c) => cells[c])
.map((c) => [
name(c),
cells[c]['numerator'] ?? 0,
cells[c]['denominator'] ?? 0,
mode.colors?.[c],
]),
);
if (!patients(r) || !Object.keys(cells).length) return undefined;
const sound = (c: string) =>
whole(cells[c]?.['numerator']) &&
whole(cells[c]?.['denominator']) &&
cells[c]['numerator'] <= cells[c]['denominator'];
const ok = reconciles(
Object.keys(cells).map((c) => cells[c]['denominator']),
patients(r),
);
return complete(
mode.order,
Object.keys(cells),
ok,
(c) => (sound(c) ? [cells[c]['numerator'], cells[c]['denominator']] : undefined),
mode.colors,
);
}
case 'positives': {
const r = of(mode.measure);
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
const found = new Set(Object.keys(cells).map((k) => k.split('|')[0]));
if (!mode.complete)
return ratios(
mode.order
.filter((c) => found.has(c))
.map((c) => {
const positive = size(cells[`${c}|positive`]);
return [name(c), positive, positive + size(cells[`${c}|negative`]), mode.colors?.[c]];
}),
);
if (!patients(r) || !found.size) return undefined;
const ok = reconciles(
Object.values(cells).map((c) => c['initial-population']),
patients(r),
);
return complete(
mode.order,
[...found],
ok,
(c) => {
const positive = size(cells[`${c}|positive`]);
return [positive, positive + size(cells[`${c}|negative`])];
},
mode.colors,
);
}
case 'signs': {
const strata = of(mode.measure)?.strata ?? {};
return ratios(
mode.strata
.filter((s) => Object.keys(strata[s] ?? {}).length)
.map((s) => {
const positive = size(strata[s]['positive']);
return [name(s), positive, positive + size(strata[s]['negative']), mode.colors?.[s]];
}),
);
}
case 'days':
return medians(
mode.steps.map(({ label, measure }) => {
const r = of(measure);
return { label, n: r?.populations['measure-observation'] ?? 0, score: r };
}),
mode.tint,
);
case 'days-by': {
const r = of(mode.measure);
const cells = r?.strata[mode.stratum] ?? {};
return medians(
Object.keys(cells)
.map((c) => ({
label: CIE10[c] ? `${c} · ${CIE10[c]}` : name(c),
n: cells[c]['measure-observation'] ?? 0,
score: r?.scores?.[mode.stratum]?.[c],
}))
.sort((a, b) => b.n - a.n),
mode.tint,
);
}
default:
return undefined;
}
}
/** The groups of a grouped mode: each group (an age group, a follow-up status, a screening round) with
* one independent bar per category over the group's own records. A group the report leaves out is
* drawn empty only when the listed ones add up to every record of the period (`complete`). */
export function grouped(
mode: Mode,
of: (measure: string) => Reading | undefined,
): Groups | undefined {
if (mode.kind !== 'grouped') return undefined;
const r = of(mode.measure);
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
const found = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))];
if (!patients(r) || !found.length) return undefined;
const n = (g: string, c: string) => size(cells[`${g}|${c}`]);
const reconciled = reconciles(
Object.values(cells).map((c) => c['initial-population']),
patients(r),
);
const codes = [
...mode.order.filter((g) => found.includes(g) || (mode.complete && reconciled)),
...found.filter((g) => !mode.order.includes(g)),
];
const total = (g: string) =>
mode.ofAll
? Object.entries(cells)
.filter(([k]) => k.split('|')[0] === g)
.reduce((t, [, c]) => t + size(c), 0)
: mode.catalog.reduce((t, c) => t + n(g, c.code), 0);
const groups: Group[] = codes.map((code) => {
const den = total(code);
return {
code,
label: name(code),
total: den,
hint: den ? undefined : `Sin ${mode.unit} en el grupo`,
rows: mode.catalog.map((c) => {
const count = n(code, c.code);
const percent = den ? (100 * count) / den : undefined;
return {
label: c.label,
color: c.color,
count,
of: den,
percent,
text: `${count}/${den} · ${percent === undefined ? '—' : percent.toFixed(1) + ' %'}`,
};
}),
};
});
let note = hiddenNote(mode, of);
if (mode.complete) {
const unclassified = total('no_data');
const classified = groups.filter((g) => g.code !== 'no_data');
const none = classified.every((g) => !g.total);
const sentence = !reconciled
? 'Los conteos del informe no concilian con el total: los grupos ausentes no se muestran como cero.'
: none && unclassified
? NO_ROUND
: unclassified && classified.some((g) => !g.total)
? EMPTY_ROUND
: undefined;
note = [sentence, note].filter(Boolean).join(' ') || undefined;
}
return { groups, note };
}
/** Every group of a stratifier the card names, in its order: those the report lists with their
* counts; those it leaves out as no patients when the counts add up to the period's patients,
* else as not available. "Sin dato" keeps its own counts. */
function complete(
order: string[],
listed: string[],
reconciled: boolean,
counts: (code: string) => [number, number] | undefined,
colors: Colors = {},
): Bars {
const extra = listed.filter((c) => !order.includes(c));
const rows: Bar[] = [...order, ...extra].map((code) => {
const label = name(code);
const color = colors[code];
if (!listed.includes(code))
return reconciled
? { label, color, hint: NO_PATIENTS, width: 0, marks: [], cells: ['0/0', '—'] }
: { label, color, hint: NOT_AVAILABLE, width: 0, marks: [], cells: ['—', '—'] };
const found = counts(code);
if (!found)
return { label, color, hint: NOT_AVAILABLE, width: 0, marks: [], cells: ['—', '—'] };
const [n, total] = found;
return {
label,
color,
hint: total ? undefined : NO_PATIENTS,
width: total ? (100 * n) / total : 0,
marks: [],
cells: [`${n}/${total}`, pct(n, total)],
};
});
const classified = order.filter((c) => c !== 'no_data' && listed.includes(c));
const empty = classified.filter((c) => !(counts(c)?.[1] ?? 0));
const none = empty.length === classified.length;
const unclassified = counts('no_data')?.[1] ?? 0;
return {
head: ['n/N', '%'],
rows,
note: !reconciled
? 'Los conteos del informe no concilian con el total de pacientes: los grupos ausentes no se muestran como cero.'
: none && listed.includes('no_data')
? NO_ROUND
: unclassified &&
(empty.length || order.some((c) => !listed.includes(c) && c !== 'no_data'))
? EMPTY_ROUND
: undefined,
};
}
function ratios(rows: [string, number, number, string?][]): Bars | undefined {
if (!rows.length) return undefined;
return {
head: ['n/N', '%'],
rows: rows.map(([label, n, total, color]) => ({
label,
color,
width: total ? (100 * n) / total : 0,
marks: [],
cells: [`${n}/${total}`, pct(n, total)],
})),
};
}
type Score = { score?: number; low?: number; high?: number };
function medians(
rows: { label: string; n: number; score?: Score }[],
tint?: Tint,
): Bars | undefined {
if (!rows.some((r) => r.score?.score !== undefined)) return undefined;
const top = Math.max(...rows.flatMap((r) => [r.score?.score ?? 0, r.score?.high ?? 0])) || 1;
const at = (v: number) => (100 * v) / top;
return {
head: ['Mediana', 'n', 'Q1–Q3'],
markColor: tint?.mark,
rows: rows.map(({ label, n, score: s }) => {
if (s?.score === undefined) return { label, width: 0, marks: [], cells: ['—', `${n}`, '—'] };
const spread = s.low !== undefined && s.high !== undefined ? [s.low, s.high] : [];
return {
label,
color: tint?.bar,
width: at(s.score),
marks: spread.map(at),
cells: [`${days(s.score)} días`, `${n}`, spread.map(days).join('–') || '—'],
};
}),
};
}
-76
View File
@@ -1,76 +0,0 @@
import { bars, Mode } from './bars';
import {
BIOPSY_COLORS,
CYTOLOGY_COLORS,
HPV_COLORS,
NEUTRAL,
PPV_CYTOLOGY_COLORS,
PPV_DONUT,
PPV_LEVEL_COLORS,
REQUEST_COLORS,
ROUND_COLORS,
STEEL,
} from './cacu-palette';
import type { Measure } from 'fhir/r4';
import { donut, Reading } from './measures';
const VPH = { negative: HPV_COLORS['negative'], positive: HPV_COLORS['positive_other'] };
describe('CaCu palette', () => {
it('a PPV group has the colour of its category elsewhere on the page', () => {
expect(PPV_CYTOLOGY_COLORS['ascus_plus']).toBe(CYTOLOGY_COLORS['ASC-US']);
expect(PPV_CYTOLOGY_COLORS['lsil_plus']).toBe(CYTOLOGY_COLORS['LSIL']);
expect(PPV_CYTOLOGY_COLORS['hsil_plus']).toBe(CYTOLOGY_COLORS['HSIL']);
expect(PPV_LEVEL_COLORS['cin1_plus']).toBe(BIOPSY_COLORS['LSIL']);
expect(PPV_LEVEL_COLORS['cin2_plus']).toBe(BIOPSY_COLORS['HSIL']);
expect(PPV_LEVEL_COLORS['carcinoma']).toBe(BIOPSY_COLORS['carcinoma']);
expect(HPV_COLORS['hpv_16']).toBe(HPV_COLORS['positive_16']);
expect(HPV_COLORS['hpv_18']).toBe(HPV_COLORS['positive_18']);
expect(HPV_COLORS['positive']).toBe(HPV_COLORS['positive_other']);
expect(REQUEST_COLORS['high_grade']).toBe(CYTOLOGY_COLORS['HSIL']);
});
it('"Sin dato" and what is not classified are neutral everywhere', () => {
for (const colors of [
CYTOLOGY_COLORS,
HPV_COLORS,
BIOPSY_COLORS,
ROUND_COLORS,
PPV_CYTOLOGY_COLORS,
])
expect(colors['no_data']).toBe(NEUTRAL);
expect(REQUEST_COLORS['pending']).toBe(NEUTRAL);
expect(PPV_DONUT['rest']).toBe(NEUTRAL);
expect(ROUND_COLORS['initial']).toBe(STEEL);
});
it('a donut colours by category, not by place in the report', () => {
const measure = { scoring: { coding: [{ code: 'cohort' }] } } as unknown as Measure;
const cells = (order: string[]): Reading => ({
populations: {},
strata: { category: Object.fromEntries(order.map((c) => [c, { 'initial-population': 1 }])) },
});
const colours = (order: string[]) =>
(donut(measure, cells(order), 'category', VPH).data[0] as any).marker.colors;
expect(colours(['negative', 'positive'])).toEqual([VPH['negative'], VPH['positive']]);
expect(colours(['positive', 'negative'])).toEqual([VPH['positive'], VPH['negative']]);
});
it('bars take their colour from the mode by group, absent groups included', () => {
const r: Reading = {
populations: { 'initial-population': 5 },
strata: { round: { subsequent: { numerator: 1, denominator: 5 } } },
};
const mode: Mode = {
kind: 'shares',
label: 'x',
measure: 'M',
stratum: 'round',
order: ['initial', 'subsequent', 'no_data'],
complete: true,
colors: ROUND_COLORS,
};
expect(bars(mode, () => r)!.rows.map((x) => x.color)).toEqual([
ROUND_COLORS['initial'],
ROUND_COLORS['subsequent'],
ROUND_COLORS['no_data'],
]);
});
});
-88
View File
@@ -1,88 +0,0 @@
/** The colours of CaCu's charts, by category. A colour names a category (never a position in a
* report, never a threshold), so the same category looks the same on every card; neutral greys
* are for what is absent or not classified. They live here, not in the shared palette, so that no
* other domain (CaMa, TEA) takes them. */
/** Not classified, or no data. */
export const NEUTRAL = '#C9CDD2';
/** Not classified, a little darker: what a report names but a card does not. */
export const NEUTRAL_DARK = '#9AA3AB';
/** The steel tones of the groups that are not results: rounds, ages, follow-up status. */
export const STEEL = '#5F7F9A';
export const STEEL_MID = '#8FA7BB';
export const STEEL_LIGHT = '#B5C5D3';
/** Cytology by Bethesda category. */
export const CYTOLOGY_COLORS: Record<string, string> = {
NILM: '#408651',
'ASC-US': '#2778B8',
LSIL: '#B19525',
'ASC-H': '#7955B1',
HSIL: '#CE4778',
CIS: '#AA394D',
no_data: NEUTRAL,
};
/** HPV by genotype; `positive` (any high-risk type) is the colour of "positive other". */
export const HPV_COLORS: Record<string, string> = {
negative: '#42A77E',
positive_16: '#DF8640',
positive_18: '#C29C42',
positive_16_18: '#C24269',
positive_other: '#A8C243',
positive_incomplete: '#9C42C2',
inconsistent: '#687786',
positive: '#A8C243',
hpv_16: '#DF8640',
hpv_18: '#C29C42',
no_data: NEUTRAL,
};
/** Biopsy by the grade it states; the levels of a PPV (that grade or worse) take its colour. */
export const BIOPSY_COLORS: Record<string, string> = {
normal: '#408651',
LSIL: '#B19525',
HSIL: '#CE4778',
CIS: '#AA394D',
carcinoma: '#8D4C79',
cin1_plus: '#B19525',
cin2_plus: '#CE4778',
no_data: NEUTRAL,
};
/** What became of the biopsy requests: high grade is the colour of LIEAG, the rest steel. */
export const REQUEST_COLORS: Record<string, string> = {
high_grade: '#CE4778',
below_high_grade: STEEL_MID,
pending: NEUTRAL,
no_grade: NEUTRAL_DARK,
};
/** Detection round: steel tones; "Sin dato" is neutral. */
export const ROUND_COLORS: Record<string, string> = {
initial: STEEL,
subsequent: STEEL_MID,
no_data: NEUTRAL,
};
/** Referral PPV groups: cytology and histology levels by the colour of their category, HPV by
* genotype. */
export const PPV_CYTOLOGY_COLORS: Record<string, string> = {
ascus_plus: CYTOLOGY_COLORS['ASC-US'],
lsil_plus: CYTOLOGY_COLORS['LSIL'],
hsil_plus: CYTOLOGY_COLORS['HSIL'],
no_data: NEUTRAL,
};
export const PPV_LEVEL_COLORS: Record<string, string> = {
cin1_plus: BIOPSY_COLORS['LSIL'],
cin2_plus: BIOPSY_COLORS['HSIL'],
carcinoma: BIOPSY_COLORS['carcinoma'],
};
/** The whole of a PPV card as a donut: the colours of its two parts. */
export const PPV_DONUT: Record<string, string> = { numerator: '#6A8000', rest: NEUTRAL };
/** Median bars of the screening route, and the marks of their quartiles. */
export const DURATION = '#42A77E';
export const QUARTILE = '#17324D';
+44
View File
@@ -0,0 +1,44 @@
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
@@ -0,0 +1,55 @@
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 };
}
-19
View File
@@ -1,19 +0,0 @@
/** The ICD-10 codes a cervical diagnosis is dated by (core.cacu DIAGNOSIS_ICD10). */
export const CIE10: Record<string, string> = {
Z014: 'Examen ginecológico',
Z124: 'Pesquisa de tumor del cuello uterino',
B977: 'Papilomavirus',
R876: 'Citología cervical anormal',
N870: 'Displasia cervical leve',
N871: 'Displasia cervical moderada',
N872: 'Displasia cervical severa',
N879: 'Displasia cervical no especificada',
D060: 'Carcinoma in situ del endocérvix',
D061: 'Carcinoma in situ del exocérvix',
D067: 'Carcinoma in situ de otras partes del cuello',
D069: 'Carcinoma in situ del cuello',
C530: 'Cáncer del endocérvix',
C531: 'Cáncer del exocérvix',
C538: 'Cáncer de sitios contiguos del cuello',
C539: 'Cáncer del cuello uterino',
};
-477
View File
@@ -1,477 +0,0 @@
import { type Figure, PALETTE } from '../plot';
import { reconciles } from './bars';
import { name, type Reading } from './measures';
import type { Catalog, Category, HistoryPanel } from './pages';
const OLIVE = '#A8C243';
const ROSE = '#C24269';
const count = (n: number) => n.toLocaleString('es-MX');
const percent = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
function rgba(hex: string, alpha: number): string {
const v = parseInt(hex.slice(1), 16);
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`;
}
/** A category's count in the report (the composition's `category` stratum). */
function counted(r: Reading, code: string): number {
return r.strata['category']?.[code]?.['initial-population'] ?? 0;
}
/** Groups inside, their categories outside, the total in the centre. */
export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figure {
const values = catalog.categories.map((c) => counted(r, c.code));
const total = values.reduce((a, b) => a + b, 0);
const groups = catalog.groups.map((g) =>
catalog.categories.reduce((n, c, i) => n + (c.group === g.id ? values[i] : 0), 0),
);
const faded = new Set(catalog.faded ?? []);
const share = (n: number) => (total ? `${percent((100 * n) / total)} %` : '');
const common = {
type: 'pie',
sort: false,
direction: 'clockwise',
rotation: 0,
showlegend: false,
textinfo: 'text',
textposition: 'inside',
insidetextorientation: 'horizontal',
};
return {
data: [
{
...common,
name: 'centro',
values: [1],
labels: ['centro'],
domain: { x: [0.32, 0.68], y: [0.32, 0.68] },
text: [`<b>${count(total)}</b><br>${center}`],
marker: { colors: ['#FFFFFF'] },
hoverinfo: 'skip',
},
{
...common,
name: 'grupos',
values: groups,
labels: catalog.groups.map((g) => g.label),
hole: 0.62,
domain: { x: [0.16, 0.84], y: [0.16, 0.84] },
text: groups.map((n, i) =>
total && n / total >= 0.05 ? `${catalog.groups[i].label}<br>${share(n)}` : '',
),
marker: {
colors: catalog.groups.map((g) =>
rgba(
g.color,
catalog.categories.some((c) => c.group === g.id && !faded.has(c.code)) ? 1 : 0.3,
),
),
line: { color: '#FFFFFF', width: 2 },
},
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
},
{
...common,
name: 'categorias',
values,
labels: catalog.categories.map((c) => c.label),
hole: 0.74,
domain: { x: [0, 1], y: [0, 1] },
// along the thin ring, so a label fits its slice
insidetextorientation: 'tangential',
text: values.map((n, i) => (total && n / total >= 0.05 ? catalog.categories[i].label : '')),
marker: {
colors: catalog.categories.map((c) => rgba(c.color, faded.has(c.code) ? 0.3 : 1)),
line: { color: '#FFFFFF', width: 2 },
},
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
},
] as Partial<Plotly.Data>[],
layout: { margin: { t: 10, l: 10, r: 10, b: 10 } },
};
}
/** Each clinical scenario's results as shares of its patients, one stacked bar each. */
export function scenarioBars(
r: Reading,
catalog: Catalog,
stratum: string,
label: (code: string) => string,
/** the groups in this order (the ones the report lists, then any other) */
order?: string[],
options: {
/** draw an empty group of `order` when the counts reconcile (see `reconciles`) */
fill?: boolean;
/** a bar is the share of all the group's records, not only of those the catalog draws */
ofAll?: boolean;
} = {},
): Figure {
const cells = r.strata[`${stratum}-category`] ?? {};
const found = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))];
const listed = Object.values(cells).map((c) => c['initial-population']);
const empty = reconciles(listed, r.populations['initial-population'] ?? 0);
const scenarios = order
? [
...order.filter((s) => found.includes(s) || (options.fill && empty)),
...found.filter((s) => !order.includes(s)),
]
: found.sort((a, b) => label(a).localeCompare(label(b), 'es'));
const n = (s: string, c: string) => cells[`${s}|${c}`]?.['initial-population'] ?? 0;
const totals = scenarios.map((s) =>
options.ofAll
? Object.entries(cells)
.filter(([k]) => k.split('|')[0] === s)
.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0)
: catalog.categories.reduce((t, c) => t + n(s, c.code), 0),
);
const y = order
? scenarios.map((s, i) => `${label(s)}<br>n = ${totals[i]}`)
: scenarios.map(label);
return {
data: catalog.categories.map((c) => ({
type: 'bar',
orientation: 'h',
name: c.label,
y,
x: scenarios.map((s, i) => (totals[i] ? (100 * n(s, c.code)) / totals[i] : 0)),
customdata: scenarios.map((s) => n(s, c.code)),
marker: { color: c.color },
hovertemplate: `${c.label}<br>%{y}: %{customdata} (%{x:.1f} %)<extra></extra>`,
})) as Partial<Plotly.Data>[],
layout: {
barmode: 'stack',
xaxis: {
title: {
text: order
? options.ofAll
? '% de los reportes del grupo'
: '% de pacientes con resultado'
: '% de pacientes del escenario con resultado',
},
ticksuffix: ' %',
range: [0, 100.5],
dtick: 20,
},
yaxis: {
type: 'category',
autorange: 'reversed',
categoryorder: 'array',
categoryarray: y,
automargin: true,
},
},
};
}
/** Wilson score interval at 95 %, in percent. */
export function wilson(k: number, n: number): [number, number] {
const z = 1.959963984540054;
const p = k / n;
const d = 1 + (z * z) / n;
const c = (p + (z * z) / (2 * n)) / d;
const h = (z * Math.sqrt((p * (1 - p)) / n + (z * z) / (4 * n * n))) / d;
return [100 * (c - h), 100 * (c + h)];
}
/** Per cytology result: of the women with a biopsy, the share whose biopsy is a positive,
* with its 95 % interval; a result nobody had a biopsy for is named, not drawn. */
export function rateDots(
r: Reading,
spec: { stratum: string; rows: Category[]; positive: string[]; axis: string; colored?: boolean },
): Figure {
const cells = r.strata[`${spec.stratum}-category`] ?? {};
const rows = spec.rows.map((row) => {
const of = Object.entries(cells).filter(([k]) => k.split('|')[0] === row.code);
const biopsied = of.filter(([k]) => !['no_biopsy', 'no_data'].includes(k.split('|')[1]));
const den = biopsied.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
const k = biopsied
.filter(([key]) => spec.positive.includes(key.split('|')[1]))
.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
const rate = den ? (100 * k) / den : null;
const [low, high] = den ? wilson(k, den) : [null, null];
return { row, k, den, rate, low, high };
});
const y = rows.map((x) => x.row.label);
return {
data: [
{
type: 'scatter',
mode: 'markers',
name: 'tasas',
y,
x: rows.map((x) => x.rate),
marker: { size: 12, color: spec.colored ? rows.map((x) => x.row.color) : ROSE },
cliponaxis: false,
error_x: {
type: 'data',
symmetric: false,
color: ROSE,
thickness: 2,
width: 6,
array: rows.map((x) => (x.rate === null ? 0 : x.high! - x.rate)),
arrayminus: rows.map((x) => (x.rate === null ? 0 : x.rate - x.low!)),
},
hovertemplate: '%{y}: %{x:.1f} %<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
margin: { t: 24, r: 110, b: 56, l: 56 },
yaxis: {
type: 'category',
categoryorder: 'array',
categoryarray: [...y].reverse(),
automargin: true,
},
xaxis: { range: [0, 100], ticksuffix: ' %', zeroline: false, title: { text: spec.axis } },
annotations: rows.map((x) => ({
x: 1,
xref: 'paper',
xanchor: 'left',
xshift: 8,
y: x.row.label,
yref: 'y',
showarrow: false,
align: 'left',
text: x.den
? `<b>${percent(x.rate!)} %</b><br>${x.k}/${x.den}`
: spec.colored
? 'Sin pacientes'
: 'Sin biopsias',
})),
},
};
}
const decimal = (n: number) => n.toLocaleString('es-MX', { maximumFractionDigits: 2 });
/** A card's template filled from its measure's reading in the period: {n} counted, {obs}
* measured, {median} {q1} {q3} days, {num} {den} {pct}. */
export function fill(template: string, r: Reading): string {
const p = r.populations;
const values: Record<string, string> = {
n: count(p['initial-population'] ?? 0),
obs: count(p['measure-observation'] ?? 0),
median: r.score === undefined ? '' : decimal(r.score),
q1: decimal(r.low ?? r.score ?? 0),
q3: decimal(r.high ?? r.score ?? 0),
num: count(p['numerator'] ?? 0),
den: count(p['denominator'] ?? 0),
pct: r.score === undefined ? '' : percent(r.score * 100),
};
return template.replace(/\{(\w+)\}/g, (_, k) => values[k] ?? '');
}
/** A duration's quartile box in the period. */
export function boxFigure(r: Reading, period: string): Figure {
const q1 = r.low ?? r.score!;
const q3 = r.high ?? r.score!;
return {
data: [
{
type: 'box',
name: 'Total',
x: [period],
q1: [q1],
median: [r.score!],
q3: [q3],
lowerfence: [q1],
upperfence: [q3],
marker: { color: '#4269C2' },
fillcolor: 'rgba(66,105,194,0.55)',
hovertemplate: `Q1 ${decimal(q1)} · mediana ${decimal(r.score!)} · Q3 ${decimal(q3)} días<extra></extra>`,
} as Partial<Plotly.Data>,
],
layout: { showlegend: false, yaxis: { title: { text: 'días' }, rangemode: 'tozero' } },
};
}
/** One ring: the categories' shares, the total in the centre. */
export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure {
const values = catalog.categories.map((c) => counted(r, c.code));
const total = values.reduce((a, b) => a + b, 0);
return {
data: [
{
type: 'pie',
hole: 0.54,
sort: false,
direction: 'clockwise',
labels: catalog.categories.map((c) => c.label),
values,
marker: {
colors: catalog.categories.map((c) => c.color),
line: { color: '#FFFFFF', width: 2 },
},
// an empty slice says nothing (its label would sit on its neighbours')
texttemplate: values.map((v) => (v ? '%{label}<br>%{percent}' : '')),
textposition: 'outside',
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
margin: { t: 30, l: 60, r: 60, b: 30 },
annotations: [
{
text: `<b>${count(total)}</b><br>${center}`,
showarrow: false,
x: 0.5,
y: 0.5,
xref: 'paper',
yref: 'paper',
},
],
},
};
}
/** A category's count per bar, one bar each, in the period. */
export function countBars(r: Reading, catalog: Catalog, axis: string, period: string): Figure {
const y = catalog.categories.map((c) => c.label);
return {
data: [
{
type: 'bar',
orientation: 'h',
name: period,
y,
x: catalog.categories.map((c) => counted(r, c.code)),
marker: { color: catalog.categories.map((c) => c.color) },
texttemplate: '%{x}',
textposition: 'outside',
hovertemplate: '%{y}: %{x}<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
xaxis: { title: { text: axis }, rangemode: 'tozero' },
yaxis: { type: 'category', autorange: 'reversed', automargin: true },
},
};
}
const AGE_COLORS = ['#A8C243', '#42C29C', '#9C42C2', '#4269C2'];
/** "16-23" as the screens say it: "16 a 23 meses". */
export const ageLabel = (band: string) => band.replace(/^(\d+)-(\d+)$/, '$1 a $2 meses');
function ages(r: Reading): [string, Record<string, number>][] {
return Object.entries(r.strata['age_group'] ?? {}).sort(
([a], [b]) => parseInt(a, 10) - parseInt(b, 10),
);
}
/** By age group: the numerator and the rest of the denominator, stacked. */
export function ageStack(r: Reading, names: [string, string]): Figure {
const rows = ages(r);
const x = rows.map(([a]) => ageLabel(a));
return {
data: [
{
type: 'bar',
name: names[0],
x,
y: rows.map(([, c]) => c['numerator'] ?? 0),
marker: { color: AGE_COLORS[0] },
},
{
type: 'bar',
name: names[1],
x,
y: rows.map(([, c]) => (c['denominator'] ?? 0) - (c['numerator'] ?? 0)),
marker: { color: AGE_COLORS[1] },
},
] as Partial<Plotly.Data>[],
layout: {
barmode: 'stack',
xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
yaxis: { title: { text: 'Pacientes' }, rangemode: 'tozero' },
},
};
}
/** By age group: the numerator's share of the denominator, one bar each. */
export function ageShare(r: Reading, axis: string): Figure {
const rows = ages(r);
return {
data: [
{
type: 'bar',
x: rows.map(([a]) => ageLabel(a)),
y: rows.map(([, c]) =>
c['denominator'] ? (100 * (c['numerator'] ?? 0)) / c['denominator'] : 0,
),
marker: { color: rows.map((_, i) => AGE_COLORS[i % AGE_COLORS.length]) },
texttemplate: '%{y:.1f} %',
textposition: 'outside',
hovertemplate: '%{x}: %{y:.1f} %<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
yaxis: { title: { text: axis }, range: [0, 100], ticksuffix: ' %' },
},
};
}
/** A Trazabilidad panel's figure (pages.HISTORY), as the old tab drew it: stacked bars by
* category, or a line with its band (95 % interval, or first to third quartile) drawn as one
* closed shape. */
export function historyFigure(
panel: HistoryPanel,
series: { label: string; r: Reading | undefined }[],
line: string,
xTitle: string,
): Figure {
const x = series.map((s) => s.label);
const layout = (y: string) => ({
xaxis: { title: { text: xTitle }, type: 'category' as const },
yaxis: { title: { text: y } },
});
if (panel.kind === 'stack') {
const found = [...new Set(series.flatMap((s) => Object.keys(s.r?.strata['category'] ?? {})))];
const declared = panel.series ?? [];
const named = [
...declared,
...found
.filter((c) => !declared.some((d) => d.code === c))
.map((c, i) => ({ code: c, label: name(c), color: PALETTE[i % PALETTE.length] })),
];
return {
data: named.map((c) => ({
type: 'bar',
name: c.label,
x,
y: series.map((s) => s.r?.strata['category']?.[c.code]?.['initial-population'] ?? 0),
marker: { color: c.color },
})),
layout: { ...layout(panel.axis ?? 'Pacientes'), barmode: 'stack' },
};
}
const k = panel.kind === 'percent' ? 100 : 1;
const at = (v?: number) => (v === undefined ? null : v * k);
return {
data: [
{
x: [...x, ...[...x].reverse()],
y: [...series.map((s) => at(s.r?.high)), ...[...series].reverse().map((s) => at(s.r?.low))],
mode: 'lines',
fill: 'toself',
fillcolor: line + '33',
line: { width: 0 },
name: panel.kind === 'percent' ? 'Intervalo de confianza' : 'Primer a tercer cuartil',
hoverinfo: 'skip',
},
{
x,
y: series.map((s) => at(s.r?.score)),
mode: 'lines+markers',
name: panel.kind === 'percent' ? 'Porcentaje' : 'Mediana',
line: { color: line },
marker: { color: line },
},
],
layout: layout(panel.kind === 'percent' ? 'Porcentaje' : 'Días'),
};
}
-52
View File
@@ -1,52 +0,0 @@
import type { Sheet } from '../export';
import { STATES } from '../paciente/stages';
import type { Row } from './follow-up';
import { name } from './measures';
const NONE = 'No disponible';
const HEAD = [
'Paciente',
'CURP',
'Edad',
'Estatus',
'Etapas',
'Última citología',
'VPH',
'Biopsia',
'LIEAG+',
'Cáncer',
'Días a diagnóstico',
];
/** A cytology's result, or why it has none. */
export function cytologyResult(c: NonNullable<Row['cytology']>): string {
if (c.result) return name(c.result);
return c.adequacy === 'unsatisfactory' ? 'Insatisfactoria' : 'Pendiente';
}
const percent = (p?: number) => (p === undefined ? NONE : `${(100 * p).toFixed(1)} %`);
/** The follow-up list as a table to save, with the query it answers. */
export function followUpSheet(rows: Row[], query: [string, string][]): Sheet {
return {
title: 'Resultados de seguimiento',
query: [...query, ['Registros', `${rows.length}`]],
head: HEAD,
rows: rows.map((r) => [
r.name ?? r.patient.id!.slice(0, 10),
r.curp ?? NONE,
`${r.age ?? NONE}`,
name(r.status),
r.stages
.filter((s) => s.state !== 'unknown')
.map((s) => `${s.label}: ${s.day ?? STATES[s.state]}`)
.join('\n'),
r.cytology ? `${cytologyResult(r.cytology)} (${r.cytology.date})` : NONE,
r.hpv ? `${r.hpv.positive ? 'Positivo' : 'Negativo'} (${r.hpv.date})` : NONE,
r.biopsy ? `${name(r.biopsy.histology ?? '') || 'Sin grado'} (${r.biopsy.date})` : NONE,
percent(r.risk.cin2),
percent(r.risk.cancer),
`${r.daysToDiagnosis ?? NONE}`,
]),
};
}

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