Compare commits

..

1 Commits

Author SHA1 Message Date
rockdrigo 00d03656ef Rebuild: Angular 22 shell with Material, Plotly and the generated API client
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 11:18:13 -06:00
52 changed files with 2969 additions and 3872 deletions
+3 -4
View File
@@ -1,4 +1,3 @@
node_modules/
dist/
.angular/
.git/
node_modules
dist
.angular
-4
View File
@@ -1,4 +0,0 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
"recommendations": ["angular.ng-template"]
}
-20
View File
@@ -1,20 +0,0 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "ng serve",
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: start",
"url": "http://localhost:4200/"
},
{
"name": "ng test",
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: test",
"url": "http://localhost:9876/debug.html"
}
]
}
-42
View File
@@ -1,42 +0,0 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "start",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "Changes detected"
},
"endsPattern": {
"regexp": "bundle generation (complete|failed)"
}
}
}
},
{
"type": "npm",
"script": "test",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "Changes detected"
},
"endsPattern": {
"regexp": "bundle generation (complete|failed)"
}
}
}
}
]
}
+7 -7
View File
@@ -1,10 +1,10 @@
FROM node:22-slim
FROM node:24-alpine AS build
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm install
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npx ng build
EXPOSE 4200
CMD ["npx", "ng", "serve", "--host", "0.0.0.0", "--port", "4200"]
FROM nginx:1.29-alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist/webapp/browser /usr/share/nginx/html
-59
View File
@@ -1,59 +0,0 @@
# WebApp
This project was generated using [Angular CLI](https://github.com/angular/angular-cli) version 22.1.8.
## Development server
To start a local development server, run:
```bash
ng serve
```
Once the server is running, open your browser and navigate to `http://localhost:4200/`. The application will automatically reload whenever you modify any of the source files.
## Code scaffolding
Angular CLI includes powerful code scaffolding tools. To generate a new component, run:
```bash
ng generate component component-name
```
For a complete list of available schematics (such as `components`, `directives`, or `pipes`), run:
```bash
ng generate --help
```
## Building
To build the project run:
```bash
ng build
```
This will compile your project and store the build artifacts in the `dist/` directory. By default, the production build optimizes your application for performance and speed.
## Running unit tests
To execute unit tests with the [Vitest](https://vitest.dev/) test runner, use the following command:
```bash
ng test
```
## Running end-to-end tests
For end-to-end (e2e) testing, run:
```bash
ng e2e
```
Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs.
## Additional Resources
For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.
+5 -9
View File
@@ -2,12 +2,11 @@
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"cli": {
"packageManager": "npm",
"analytics": false
"packageManager": "npm"
},
"newProjectRoot": "projects",
"projects": {
"WebApp": {
"webapp": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
@@ -30,9 +29,7 @@
"input": "public"
}
],
"styles": [
"src/styles.scss"
]
"styles": ["src/styles.scss"]
},
"configurations": {
"production": {
@@ -60,13 +57,12 @@
},
"serve": {
"builder": "@angular/build:dev-server",
"options": { "proxyConfig": "proxy.conf.json" },
"configurations": {
"production": {
"buildTarget": "WebApp:build:production"
"buildTarget": "webapp:build:production"
},
"development": {
"buildTarget": "WebApp:build:development"
"buildTarget": "webapp:build:development"
}
},
"defaultConfiguration": "development"
+6
View File
@@ -0,0 +1,6 @@
{
"$schema": "node_modules/ng-openapi-gen/ng-openapi-gen-schema.json",
"input": "openapi.json",
"output": "src/app/api",
"ignoreUnusedModels": false
}
+11
View File
@@ -0,0 +1,11 @@
server {
listen 80;
root /usr/share/nginx/html;
location /api/ {
proxy_pass http://api:8000/;
proxy_read_timeout 30s;
}
location / {
try_files $uri $uri/ /index.html;
}
}
+162
View File
@@ -0,0 +1,162 @@
{
"components": {
"schemas": {
"Domain": {
"enum": [
"cacu",
"cama",
"tea"
],
"title": "Domain",
"type": "string"
},
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ValidationError"
},
"title": "Detail",
"type": "array"
}
},
"title": "HTTPValidationError",
"type": "object"
},
"ValidationError": {
"properties": {
"ctx": {
"title": "Context",
"type": "object"
},
"input": {
"title": "Input"
},
"loc": {
"items": {
"anyOf": [
{
"type": "string"
},
{
"type": "integer"
}
]
},
"title": "Location",
"type": "array"
},
"msg": {
"title": "Message",
"type": "string"
},
"type": {
"title": "Error Type",
"type": "string"
}
},
"required": [
"loc",
"msg",
"type"
],
"title": "ValidationError",
"type": "object"
}
}
},
"info": {
"title": "ISSSTELEON",
"version": "0.0.0"
},
"openapi": "3.1.0",
"paths": {
"/domains": {
"get": {
"operationId": "domains",
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"items": {
"$ref": "#/components/schemas/Domain"
},
"title": "Response Domains",
"type": "array"
}
}
},
"description": "Successful Response"
}
},
"summary": "Domains"
}
},
"/health": {
"get": {
"operationId": "health",
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"additionalProperties": {
"type": "string"
},
"title": "Response Health",
"type": "object"
}
}
},
"description": "Successful Response"
}
},
"summary": "Health"
}
},
"/runs/{run_id}": {
"get": {
"operationId": "run_status",
"parameters": [
{
"in": "path",
"name": "run_id",
"required": true,
"schema": {
"title": "Run Id",
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"additionalProperties": {
"type": "string"
},
"title": "Response Run Status",
"type": "object"
}
}
},
"description": "Successful Response"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Run Status"
}
}
}
}
+2065 -2688
View File
File diff suppressed because it is too large Load Diff
+19 -17
View File
@@ -1,35 +1,37 @@
{
"name": "web-app",
"name": "webapp",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"start": "ng serve --proxy-config proxy.conf.json",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
"test": "ng test",
"api": "ng-openapi-gen -c ng-openapi-gen.json"
},
"private": true,
"packageManager": "npm@11.17.0",
"packageManager": "npm@11.20.0",
"dependencies": {
"@angular/cdk": "^22.1.7",
"@angular/common": "^22.1.0",
"@angular/compiler": "^22.1.0",
"@angular/core": "^22.1.0",
"@angular/forms": "^22.1.0",
"@angular/material": "^22.1.7",
"@angular/platform-browser": "^22.1.0",
"@angular/router": "^22.1.0",
"@angular/cdk": "^22.3.0",
"@angular/common": "^22.3.0",
"@angular/compiler": "^22.3.0",
"@angular/core": "^22.3.0",
"@angular/forms": "^22.3.0",
"@angular/material": "^22.3.0",
"@angular/platform-browser": "^22.3.0",
"@angular/router": "^22.3.0",
"plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
},
"devDependencies": {
"@angular/build": "^22.1.8",
"@angular/cli": "^22.1.8",
"@angular/compiler-cli": "^22.1.0",
"jsdom": "^28.0.0",
"@angular/build": "^22.3.0",
"@angular/cli": "^22.3.0",
"@angular/compiler-cli": "^22.3.0",
"jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0",
"prettier": "^3.8.1",
"typescript": "~6.0.2",
"vitest": "^4.0.8"
"vitest": "^5.0.0"
}
}
+1 -4
View File
@@ -1,4 +1 @@
{
"/tea/**": { "target": "http://127.0.0.1:5000", "secure": false },
"/health": { "target": "http://127.0.0.1:5000", "secure": false }
}
{ "/api": { "target": "http://127.0.0.1:5711", "pathRewrite": { "^/api": "" } } }
+27
View File
@@ -0,0 +1,27 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Injectable } from '@angular/core';
/**
* Provides the ApiConfiguration configuration object with a given root URL.
*/
export function provideApiConfiguration(rootUrl: string) {
var config = new ApiConfiguration();
config.rootUrl = rootUrl;
return {
provide: ApiConfiguration,
useValue: config
};
}
/**
* Global configuration
*/
@Injectable({
providedIn: 'root',
})
export class ApiConfiguration {
rootUrl: string = '';
}
+64
View File
@@ -0,0 +1,64 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Injectable } from '@angular/core';
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable, firstValueFrom } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { ApiConfiguration } from './api-configuration';
import { StrictHttpResponse } from './strict-http-response';
export type ApiFnOptional<P, R> = (http: HttpClient, rootUrl: string, params?: P, context?: HttpContext) => Observable<StrictHttpResponse<R>>;
export type ApiFnRequired<P, R> = (http: HttpClient, rootUrl: string, params: P, context?: HttpContext) => Observable<StrictHttpResponse<R>>;
/**
* Helper service to call API functions directly
*/
@Injectable({ providedIn: 'root' })
export class Api {
constructor(
private config: ApiConfiguration,
private http: HttpClient
) {
}
private _rootUrl?: string;
/**
* Returns the root url for API operations. If not set directly here,
* will fallback to `ApiConfiguration.rootUrl`.
*/
get rootUrl(): string {
return this._rootUrl || this.config.rootUrl;
}
/**
* Sets the root URL for API operations
*/
set rootUrl(rootUrl: string) {
this._rootUrl = rootUrl;
}
/**
* Executes an API call, returning the response body only
*/
invoke<P, R>(fn: ApiFnRequired<P, R>, params: P, context?: HttpContext): Promise<R>;
invoke<P, R>(fn: ApiFnOptional<P, R>, params?: P, context?: HttpContext): Promise<R>;
async invoke<P, R>(fn: ApiFnRequired<P, R> | ApiFnOptional<P, R>, params: P, context?: HttpContext): Promise<R> {
const resp = this.invoke$Response(fn, params, context);
return (await resp).body;
}
/**
* Executes an API call, returning the entire response
*/
invoke$Response<P, R>(fn: ApiFnRequired<P, R>, params: P, context?: HttpContext): Promise<StrictHttpResponse<R>>;
invoke$Response<P, R>(fn: ApiFnOptional<P, R>, params?: P, context?: HttpContext): Promise<StrictHttpResponse<R>>;
invoke$Response<P, R>(fn: ApiFnRequired<P, R> | ApiFnOptional<P, R>, params: P, context?: HttpContext): Promise<StrictHttpResponse<R>> {
const obs = fn(this.http, this.rootUrl, params, context)
.pipe(
filter(r => r instanceof HttpResponse),
map(r => r as StrictHttpResponse<R>));
return firstValueFrom(obs);
}
}
+30
View File
@@ -0,0 +1,30 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface Domains$Params {
}
export function domains(http: HttpClient, rootUrl: string, params?: Domains$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<Domain>>> {
const rb = new RequestBuilder(rootUrl, domains.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<Array<Domain>>;
})
);
}
domains.PATH = '/domains';
+33
View File
@@ -0,0 +1,33 @@
/* 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 Health$Params {
}
export function health(http: HttpClient, rootUrl: string, params?: Health$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, health.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<{
[key: string]: string;
}>;
})
);
}
health.PATH = '/health';
+35
View File
@@ -0,0 +1,35 @@
/* 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 RunStatus$Params {
run_id: string;
}
export function runStatus(http: HttpClient, rootUrl: string, params: RunStatus$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, runStatus.PATH, 'get');
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;
}>;
})
);
}
runStatus.PATH = '/runs/{run_id}';
+9
View File
@@ -0,0 +1,9 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export type { Domains$Params as Domains$Params } from './fn/operations/domains';
export { domains as domains } from './fn/operations/domains';
export type { Health$Params as Health$Params } from './fn/operations/health';
export { health as health } from './fn/operations/health';
export type { RunStatus$Params as RunStatus$Params } from './fn/operations/run-status';
export { runStatus as runStatus } from './fn/operations/run-status';
+6
View File
@@ -0,0 +1,6 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export type { Domain } from './models/domain';
export type { HttpValidationError } from './models/http-validation-error';
export type { ValidationError } from './models/validation-error';
+13
View File
@@ -0,0 +1,13 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Domain } from './domain';
/**
* Each possible value of `Domain`
*/
export const DOMAIN: Domain[] = [
'cacu',
'cama',
'tea'
];
+5
View File
@@ -0,0 +1,5 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export type Domain = 'cacu' | 'cama' | 'tea';
@@ -0,0 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { ValidationError } from '../models/validation-error';
export interface HttpValidationError {
detail?: Array<ValidationError>;
}
+11
View File
@@ -0,0 +1,11 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface ValidationError {
ctx?: {
};
input?: any;
loc: Array<(string | number)>;
msg: string;
type: string;
}
+369
View File
@@ -0,0 +1,369 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpRequest, HttpParameterCodec, HttpParams, HttpHeaders, HttpContext } from '@angular/common/http';
/**
* Custom parameter codec to correctly handle the plus sign in parameter
* values. See https://github.com/angular/angular/issues/18261
*/
class ParameterCodec implements HttpParameterCodec {
encodeKey(key: string): string {
return encodeURIComponent(key);
}
encodeValue(value: string): string {
return encodeURIComponent(value);
}
decodeKey(key: string): string {
return decodeURIComponent(key);
}
decodeValue(value: string): string {
return decodeURIComponent(value);
}
}
const ParameterCodecInstance = new ParameterCodec();
/**
* Defines the options for appending a parameter
*/
interface ParameterOptions {
style?: string;
explode?: boolean;
}
/**
* Base class for a parameter
*/
abstract class Parameter {
constructor(public name: string, public value: any, public options: ParameterOptions, defaultStyle: string, defaultExplode: boolean) {
this.options = options || {};
if (this.options.style === null || this.options.style === undefined) {
this.options.style = defaultStyle;
}
if (this.options.explode === null || this.options.explode === undefined) {
this.options.explode = defaultExplode;
}
}
serializeValue(value: any, separator = ','): string {
if (value === null || value === undefined) {
return '';
} else if (value instanceof Array) {
return value.map(v => this.serializeValue(v).split(separator).join(encodeURIComponent(separator))).join(separator);
} else if (typeof value === 'object') {
const array: string[] = [];
for (const key of Object.keys(value)) {
let propVal = value[key];
if (propVal !== null && propVal !== undefined) {
propVal = this.serializeValue(propVal).split(separator).join(encodeURIComponent(separator));
if (this.options.explode) {
array.push(`${key}=${propVal}`);
} else {
array.push(key);
array.push(propVal);
}
}
}
return array.join(separator);
} else {
return String(value);
}
}
}
/**
* A parameter in the operation path
*/
class PathParameter extends Parameter {
constructor(name: string, value: any, options: ParameterOptions) {
super(name, value, options, 'simple', false);
}
append(path: string): string {
let value = this.value;
if (value === null || value === undefined) {
value = '';
}
let prefix = this.options.style === 'label' ? '.' : '';
let separator = this.options.explode ? prefix === '' ? ',' : prefix : ',';
let alreadySerialized = false;
if (this.options.style === 'matrix') {
// The parameter name is just used as prefix, except in some cases...
prefix = `;${this.name}=`;
if (this.options.explode && typeof value === 'object') {
prefix = ';';
if (value instanceof Array) {
// For arrays we have to repeat the name for each element
value = value.map(v => `${this.name}=${this.serializeValue(v, ';')}`);
value = value.join(';');
alreadySerialized = true;
} else {
// For objects we have to put each the key / value pairs
value = this.serializeValue(value, ';');
alreadySerialized = true
}
}
}
value = prefix + (alreadySerialized ? value : this.serializeValue(value, separator));
// Replace both the plain variable and the corresponding variant taking in the prefix and explode into account
path = path.replace(`{${this.name}}`, value);
path = path.replace(`{${prefix}${this.name}${this.options.explode ? '*' : ''}}`, value);
return path;
}
// @ts-ignore
serializeValue(value: any, separator = ','): string {
var result = typeof value === 'string' ? encodeURIComponent(value) : super.serializeValue(value, separator);
result = result.replace(/%3D/g, '=');
result = result.replace(/%3B/g, ';');
result = result.replace(/%2C/g, ',');
return result;
}
}
/**
* A parameter in the query
*/
class QueryParameter extends Parameter {
constructor(name: string, value: any, options: ParameterOptions) {
super(name, value, options, 'form', true);
}
append(params: HttpParams): HttpParams {
if (this.value instanceof Array) {
// Array serialization
if (this.options.explode) {
for (const v of this.value) {
params = params.append(this.name, this.serializeValue(v));
}
} else {
const separator = this.options.style === 'spaceDelimited'
? ' ' : this.options.style === 'pipeDelimited'
? '|' : ',';
return params.append(this.name, this.serializeValue(this.value, separator));
}
} else if (this.value !== null && typeof this.value === 'object') {
// Object serialization
if (this.options.style === 'deepObject') {
// Append a parameter for each key, in the form `name[key]`
for (const key of Object.keys(this.value)) {
const propVal = this.value[key];
if (propVal !== null && propVal !== undefined) {
params = params.append(`${this.name}[${key}]`, this.serializeValue(propVal));
}
}
} else if (this.options.explode) {
// Append a parameter for each key without using the parameter name
for (const key of Object.keys(this.value)) {
const propVal = this.value[key];
if (propVal !== null && propVal !== undefined) {
params = params.append(key, this.serializeValue(propVal));
}
}
} else {
// Append a single parameter whose values are a comma-separated list of key,value,key,value...
const array: any[] = [];
for (const key of Object.keys(this.value)) {
const propVal = this.value[key];
if (propVal !== null && propVal !== undefined) {
array.push(key);
array.push(propVal);
}
}
params = params.append(this.name, this.serializeValue(array));
}
} else if (this.value !== null && this.value !== undefined) {
// Plain value
params = params.append(this.name, this.serializeValue(this.value));
}
return params;
}
}
/**
* A parameter in the HTTP request header
*/
class HeaderParameter extends Parameter {
constructor(name: string, value: any, options: ParameterOptions) {
super(name, value, options, 'simple', false);
}
append(headers: HttpHeaders): HttpHeaders {
if (this.value !== null && this.value !== undefined) {
if (this.value instanceof Array) {
for (const v of this.value) {
headers = headers.append(this.name, this.serializeValue(v));
}
} else {
headers = headers.append(this.name, this.serializeValue(this.value));
}
}
return headers;
}
}
/**
* Helper to build http requests from parameters
*/
export class RequestBuilder {
private _path = new Map<string, PathParameter>();
private _query = new Map<string, QueryParameter>();
private _header = new Map<string, HeaderParameter>();
_bodyContent: any | null;
_bodyContentType?: string;
constructor(
public rootUrl: string,
public operationPath: string,
public method: string) {
}
/**
* Sets a path parameter
*/
path(name: string, value: any, options?: ParameterOptions): void {
this._path.set(name, new PathParameter(name, value, options || {}));
}
/**
* Sets a query parameter
*/
query(name: string, value: any, options?: ParameterOptions): void {
this._query.set(name, new QueryParameter(name, value, options || {}));
}
/**
* Sets a header parameter
*/
header(name: string, value: any, options?: ParameterOptions): void {
this._header.set(name, new HeaderParameter(name, value, options || {}));
}
/**
* Sets the body content, along with the content type
*/
body(value: any, contentType = 'application/json'): void {
if (value instanceof Blob) {
this._bodyContentType = value.type;
} else {
this._bodyContentType = contentType;
}
if (this._bodyContentType === 'application/x-www-form-urlencoded' && value !== null && typeof value === 'object') {
// Handle URL-encoded data
const pairs: Array<[string, string]> = [];
for (const key of Object.keys(value)) {
let val = value[key];
if (!(val instanceof Array)) {
val = [val];
}
for (const v of val) {
const formValue = this.formDataValue(v);
if (formValue !== null) {
pairs.push([key, formValue]);
}
}
}
this._bodyContent = pairs.map(p => `${encodeURIComponent(p[0])}=${encodeURIComponent(p[1])}`).join('&');
} else if (this._bodyContentType === 'multipart/form-data') {
// Handle multipart form data
const formData = new FormData();
if (value !== null && value !== undefined) {
for (const key of Object.keys(value)) {
const val = value[key];
if (val instanceof Array) {
for (const v of val) {
const toAppend = this.formDataValue(v);
if (toAppend !== null) {
formData.append(key, toAppend);
}
}
} else {
const toAppend = this.formDataValue(val);
if (toAppend !== null) {
formData.set(key, toAppend);
}
}
}
}
this._bodyContent = formData;
} else {
// The body is the plain content
this._bodyContent = value;
}
}
private formDataValue(value: any): any {
if (value === null || value === undefined) {
return null;
}
if (value instanceof Blob) {
return value;
}
if (typeof value === 'object') {
return new Blob([JSON.stringify(value)], {type: 'application/json'})
}
return String(value);
}
/**
* Builds the request with the current set parameters
*/
build<T = any>(options?: {
/** Which content types to accept */
accept?: string;
/** The expected response type */
responseType?: 'json' | 'text' | 'blob' | 'arraybuffer';
/** Whether to report progress on uploads / downloads */
reportProgress?: boolean;
/** Allow passing HttpContext for HttpClient */
context?: HttpContext;
}): HttpRequest<T> {
options = options || {};
// Path parameters
let path = this.operationPath;
for (const pathParam of this._path.values()) {
path = pathParam.append(path);
}
const url = this.rootUrl + path;
// Query parameters
let httpParams = new HttpParams({
encoder: ParameterCodecInstance
});
for (const queryParam of this._query.values()) {
httpParams = queryParam.append(httpParams);
}
// Header parameters
let httpHeaders = new HttpHeaders();
if (options.accept) {
httpHeaders = httpHeaders.append('Accept', options.accept);
}
for (const headerParam of this._header.values()) {
httpHeaders = headerParam.append(httpHeaders);
}
// Request content headers
if (this._bodyContentType && !(this._bodyContent instanceof FormData)) {
httpHeaders = httpHeaders.set('Content-Type', this._bodyContentType);
}
// Perform the request
return new HttpRequest<T>(this.method.toUpperCase(), url, this._bodyContent, {
params: httpParams,
headers: httpHeaders,
responseType: options.responseType,
reportProgress: options.reportProgress,
context: options.context
});
}
}
+11
View File
@@ -0,0 +1,11 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpResponse } from '@angular/common/http';
/**
* Constrains the http response to not have the body defined as `T | null`, but `T` only.
*/
export type StrictHttpResponse<T> = HttpResponse<T> & {
readonly body: T;
}
+4 -2
View File
@@ -1,12 +1,14 @@
import { provideHttpClient } from '@angular/common/http';
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideApiConfiguration } from './api/api-configuration';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
provideHttpClient()
]
provideHttpClient(),
provideApiConfiguration('/api'),
],
};
+15 -3
View File
@@ -1,7 +1,19 @@
<mat-toolbar color="primary">
<span>{{ title }}</span>
<mat-toolbar class="bar">
<span class="brand">ISSSTELEON</span>
<mat-button-toggle-group
aria-label="Dominio"
[value]="domain()"
(change)="domain.set($event.value)"
>
@for (d of domains.value() ?? []; track d) {
<mat-button-toggle [value]="d">{{ labels[d] }}</mat-button-toggle>
}
</mat-button-toggle-group>
<span class="spacer"></span>
<span class="status" [class.down]="health.error()">
API {{ health.value()?.['status'] ?? (health.error() ? 'sin conexión' : '…') }}
</span>
</mat-toolbar>
<main>
<router-outlet />
</main>
-16
View File
@@ -1,16 +0,0 @@
import { routes } from './app.routes';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { IndicadoresPage } from './features/indicadores/indicadores-page';
it('permite acceso directo a /indicadores sin guard ni autenticación', async () => {
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] });
const harness = await RouterTestingHarness.create();
await harness.navigateByUrl('/indicadores', IndicadoresPage);
expect(harness.routeNativeElement?.textContent).toContain('Dashboard de indicadores');
const http = TestBed.inject(HttpTestingController);
http.expectOne('/tea/indicadores').flush([]);
http.verify();
});
+1 -3
View File
@@ -1,5 +1,3 @@
import { Routes } from '@angular/router';
export const routes: Routes = [
{ path: 'indicadores', loadComponent: () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage) },
];
export const routes: Routes = [];
+18 -2
View File
@@ -1,3 +1,19 @@
main {
padding: 1.5rem;
.bar {
gap: 16px;
}
.brand {
font-weight: 500;
}
.spacer {
flex: 1;
}
.status {
font-size: 14px;
opacity: 0.8;
}
.status.down {
color: var(--mat-sys-error);
}
main {
padding: 16px;
}
+6 -17
View File
@@ -1,25 +1,14 @@
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { App } from './app';
describe('App', () => {
beforeEach(async () => {
it('creates the shell', async () => {
await TestBed.configureTestingModule({
imports: [App],
})
.compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(App);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it('should render the toolbar title', async () => {
const fixture = TestBed.createComponent(App);
await fixture.whenStable();
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('mat-toolbar')?.textContent).toContain('ISSSTELEON');
providers: [provideHttpClient(), provideHttpClientTesting()],
}).compileComponents();
expect(TestBed.createComponent(App).componentInstance).toBeTruthy();
});
});
+16 -5
View File
@@ -1,13 +1,24 @@
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { Component, inject, resource, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatToolbarModule } from '@angular/material/toolbar';
import { RouterOutlet } from '@angular/router';
import { Api } from './api/api';
import { domains } from './api/fn/operations/domains';
import { health } from './api/fn/operations/health';
import { Domain } from './api/models/domain';
const LABELS: Record<Domain, string> = { cacu: 'CaCu', cama: 'CaMa', tea: 'TEA' };
@Component({
imports: [RouterOutlet, MatToolbarModule],
selector: 'app-root',
styleUrl: './app.scss',
imports: [RouterOutlet, MatToolbarModule, MatButtonToggleModule],
templateUrl: './app.html',
styleUrl: './app.scss',
})
export class App {
protected readonly title = 'ISSSTELEON';
private readonly api = inject(Api);
protected readonly labels = LABELS;
protected readonly domain = signal<Domain>('cacu');
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
protected readonly health = resource({ loader: () => this.api.invoke(health) });
}
@@ -1,79 +0,0 @@
<section class="dashboard" aria-labelledby="dashboard-title">
<header>
<span class="domain">Dominio TEA · Investigación</span>
<h1 id="dashboard-title">Dashboard de indicadores</h1>
<p>Explora las figuras de indicadores TEA generadas por el servicio de reportes.</p>
</header>
<p class="notice">Uso exclusivo de investigación. No usar para decisiones clínicas.</p>
@if (catalogLoading()) {
<mat-progress-bar mode="indeterminate" aria-label="Cargando catálogo" />
<p role="status">Cargando catálogo de indicadores…</p>
} @else if (catalogError()) {
<mat-card class="state" role="alert"><p>{{ catalogError() }}</p>
<button mat-stroked-button (click)="retryCatalog()">Reintentar catálogo</button></mat-card>
} @else if (!catalog().length) {
<mat-card class="state"><p role="status">No hay indicadores disponibles en el catálogo.</p>
<button mat-stroked-button (click)="retryCatalog()">Actualizar catálogo</button></mat-card>
} @else {
<mat-card class="filters" aria-label="Selección de figura">
<div class="fields">
<mat-form-field class="indicator"><mat-label>Indicador</mat-label>
<mat-select [ngModel]="indicadorId" (ngModelChange)="selectIndicador($event)">
@for (item of catalog(); track item.id) { <mat-option [value]="item.id">{{ item.titulo }}</mat-option> }
</mat-select>
</mat-form-field>
<mat-form-field><mat-label>Figura</mat-label>
<mat-select [ngModel]="figuraId" (ngModelChange)="selectFigura($event)" [disabled]="!selected?.figuras?.length">
@for (figure of selected?.figuras ?? []; track $index) { <mat-option [value]="figure">{{ figure }}</mat-option> }
</mat-select>
</mat-form-field>
<mat-form-field><mat-label>Periodos</mat-label>
<mat-select [ngModel]="periodMode" (ngModelChange)="changePeriodMode($event)">
<mat-option value="todos">Todos los periodos con reporte</mat-option>
<mat-option value="manual">Selección manual</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field><mat-label>Tema de la figura</mat-label>
<mat-select [ngModel]="tema" (ngModelChange)="changeTema($event)">
<mat-option value="claro">Claro</mat-option><mat-option value="oscuro">Oscuro</mat-option>
</mat-select>
</mat-form-field>
@if (periodMode === 'manual') {
<mat-form-field class="periods"><mat-label>Semestres (AAAA-S1,AAAA-S2)</mat-label>
<input matInput [ngModel]="periodText" (ngModelChange)="changePeriodText($event)" [attr.aria-invalid]="!!periodError" aria-describedby="period-help" />
<mat-hint id="period-help">Escribe los semestres a consultar. Su disponibilidad depende de los reportes.</mat-hint>
</mat-form-field>
}
</div>
@if (periodError) { <p class="validation" role="alert">{{ periodError }}</p> }
<p class="contract">Contrato: {{ selected?.contrato }} · Las figuras conservan las notas y categorías del servicio.</p>
</mat-card>
@if (selected) {
<section class="interpretation" aria-labelledby="interpretation-title">
<h2 id="interpretation-title">Cómo leer esta figura · {{ selected?.contrato }}</h2>
<ul>
@for (line of interpretation; track $index) { <li>{{ line }}</li> }
</ul>
<p class="period-note">Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.</p>
</section>
}
<mat-card class="figure-card" [class.dark]="tema === 'oscuro'" aria-label="Resultado de la selección" [attr.aria-busy]="result().status === 'loading'">
@if (result().status === 'loading') {
<mat-progress-bar mode="indeterminate" aria-label="Cargando figura" />
<p class="state" role="status">Cargando figura…</p>
} @else if (result().status === 'error') {
<div class="state" role="alert"><p>{{ result().message }}</p>
<button mat-stroked-button (click)="requestFigure()">Reintentar solicitud</button></div>
} @else if (result().figure; as figure) {
@if (hasNoVisibleValues(figure)) {
<p class="state" role="status">No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.</p>
}
<h2 class="figure-title">{{ selected?.titulo }}</h2>
<app-plotly-chart [figure]="figure" />
} @else {
<p class="state" role="status">{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}</p>
}
</mat-card>
}
</section>
@@ -1,29 +0,0 @@
:host { display: block; }
.dashboard { max-width: 1440px; margin: 0 auto; }
h1 { font: var(--mat-sys-headline-large); margin: .65rem 0; }
header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
.domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); }
.notice { padding: 1rem 1.25rem; border-left: 4px solid var(--mat-sys-primary); background: var(--mat-sys-surface-container); border-radius: 8px; }
.filters { padding: 1.5rem; margin: 1.5rem 0; }
.fields { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .75rem 1rem; }
.indicator { grid-column: span 2; }
.periods { grid-column: 1 / -1; margin-bottom: 1rem; }
mat-form-field { width: 100%; min-width: 0; }
.contract { color: var(--mat-sys-on-surface-variant); margin: .5rem 0 0; }
.interpretation { padding: 1rem 1.25rem; margin-bottom: 1.5rem; border-radius: 8px; background: var(--mat-sys-surface-container-low); color: var(--mat-sys-on-surface); font: var(--mat-sys-body-medium); line-height: 1.5; overflow-wrap: anywhere; }
.interpretation h2 { margin: 0 0 .5rem; font: var(--mat-sys-title-small); }
.interpretation ul { margin: 0; padding-left: 1.25rem; }
.interpretation li + li { margin-top: .25rem; }
.period-note { margin: .75rem 0 0; color: var(--mat-sys-on-surface-variant); }
.validation { color: var(--mat-sys-error); }
.figure-card { overflow: hidden; min-width: 0; }
.figure-title { display: none; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); overflow-wrap: anywhere; }
.state { padding: 1.25rem; margin: 0; }
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; }
@media (max-width: 850px) { .figure-title { display: block; } .fields { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 550px) {
.fields { grid-template-columns: minmax(0, 1fr); }
.indicator { grid-column: auto; }
.filters, .interpretation { padding: 1rem; }
h1 { font: var(--mat-sys-headline-medium); }
}
@@ -1,170 +0,0 @@
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { By } from '@angular/platform-browser';
import { PlotlyFigure } from './indicadores.models';
import { Component } from '@angular/core';
import { IndicadoresPage } from './indicadores-page';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
@Component({ selector: 'app-plotly-chart', inputs: ['figure'], template: '' })
class ChartStub { figure?: PlotlyFigure; }
const catalog = [
{ id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'] },
{ id: 'i2', titulo: 'Dos', contrato: 'C3r', figuras: ['box'] },
{ id: 'empty', titulo: 'Sin figuras', contrato: 'C1', figuras: [] },
];
describe('IndicadoresPage', () => {
let page: IndicadoresPage;
let http: HttpTestingController;
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadoresPage, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
fixture = TestBed.createComponent(IndicadoresPage);
page = fixture.componentInstance;
http = TestBed.inject(HttpTestingController);
});
afterEach(() => { fixture.destroy(); http.verify(); });
function load() { http.expectOne('/tea/indicadores').flush(catalog); }
function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); }
it('presenta carga y elige una primera figura válida desde el catálogo', () => {
expect(page.catalogLoading()).toBe(true);
load();
expect(page.indicadorId).toBe('i1');
expect(page.figuraId).toBe('f1');
expect(page.result().status).toBe('loading');
const request = figure();
expect(request.request.params.has('periodos')).toBe(false);
request.flush({ data: [], layout: {} });
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('No hay valores visibles');
expect(fixture.nativeElement.textContent).toContain('Uso exclusivo de investigación');
});
it.each([
['C1', ['proporción observada', 'Wilson al 95 %', 'denominadores pequeños', '100 % no implica certeza poblacional']],
['C2', ['composición porcentual', 'distribución de cada grupo y periodo', 'SIN_DATO']],
['C3r', ['Q1, mediana y Q3', 'no contiene observaciones individuales', 'min/max', 'derivados de Q1 y Q3', 'no deben interpretarse como los extremos observados de los pacientes']],
['C4', ['No hay una explicación específica', 'no se infiere su significado estadístico']],
['toString', ['No hay una explicación específica']],
])('explica el contrato %s y conserva el aviso de investigación', (contract, expected) => {
http.expectOne('/tea/indicadores').flush([{ ...catalog[0], contrato: contract }]);
figure().flush({ data: [], layout: {} });
fixture.detectChanges();
const help = fixture.nativeElement.querySelector('.interpretation').textContent;
for (const text of expected) expect(help).toContain(text);
if (contract === 'C3r') {
expect(help).toContain('Los límites de dibujo no representan necesariamente extremos observados');
expect(help).not.toMatch(/serving|corrección|fase independiente/i);
}
expect(fixture.nativeElement.querySelector('.notice').textContent).toContain('Uso exclusivo de investigación. No usar para decisiones clínicas.');
expect(help).toContain('Un periodo puede tener reportes calculados sin valores estadísticos representables');
});
it('actualiza la explicación al cambiar indicador, incluso durante la carga', () => {
load(); figure().flush({ data: [], layout: {} }); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('Wilson');
page.selectIndicador('i2'); fixture.detectChanges();
const help = fixture.nativeElement.querySelector('.interpretation').textContent;
expect(help).toContain('min/max'); expect(help).not.toContain('Wilson');
figure().flush({ data: [], layout: {} });
});
it('entrega al gráfico el JSON íntegro sin modificarlo al presentar la ayuda', () => {
load();
const received: PlotlyFigure = {
data: [{ type: 'scatter', x: ['grupo'], y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], marker: { color: '#123456' } }],
layout: { yaxis: { range: [0, 100] }, annotations: [{ text: 'Nota del servicio' }], showlegend: true },
config: { staticPlot: false }, frames: [], extra: { preserved: true },
};
const original = JSON.stringify(received);
figure().flush(received); fixture.detectChanges();
expect(JSON.stringify(received)).toBe(original);
expect(page.result().figure).toEqual(received);
const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance as ChartStub;
expect(chart.figure).toBe(page.result().figure);
expect(JSON.stringify(chart.figure)).toBe(original);
});
it('muestra catálogo vacío y permite recargar', () => {
http.expectOne('/tea/indicadores').flush([]);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles');
page.retryCatalog();
load();
figure().flush({ data: [], layout: {} });
});
it('cancela solicitudes previas al cambiar indicador y no muestra figura antigua', () => {
load();
const old = figure();
page.selectIndicador('i2');
expect(old.cancelled).toBe(true);
expect(page.figuraId).toBe('box');
expect(page.result().figure).toBeUndefined();
figure().flush({ data: [{ type: 'box', median: [2] }], layout: {} });
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
expect(page.result().figure?.data[0]['median']).toEqual([2]);
});
it('soporta varias figuras, volver al indicador y selección sin figuras', () => {
load(); figure().flush({ data: [], layout: {} });
page.selectFigura('f2');
expect(figure().request.url).toContain('/i1/figuras/f2');
// Cancel the previous request and verify its cancellation explicitly below.
page.selectIndicador('empty');
expect(page.figuraId).toBe('');
expect(page.result().status).toBe('idle');
page.selectIndicador('i1');
expect(page.figuraId).toBe('f1');
figure().flush({ data: [], layout: {} });
});
it('valida manuales antes del HTTP y vuelve a Todos sin query', () => {
load(); figure().flush({ data: [], layout: {} });
page.changePeriodMode('manual');
expect(page.periodError).not.toBe('');
http.expectNone(req => req.url.includes('/figuras/'));
page.changePeriodText('2025-S1, 2025-S2');
const manual = figure();
expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2');
page.changePeriodText('2025-S3');
expect(manual.cancelled).toBe(true);
expect(page.result().figure).toBeUndefined();
page.changePeriodMode('todos');
const all = figure();
expect(all.request.params.has('periodos')).toBe(false);
all.flush({ data: [], layout: {} });
});
it('cancela figuras al cambiar tema rápidamente', () => {
load();
const old = figure();
page.changeTema('oscuro');
const dark = figure();
expect(old.cancelled).toBe(true);
expect(dark.request.params.get('tema')).toBe('oscuro');
page.changeTema('claro');
expect(dark.cancelled).toBe(true);
figure().flush({ data: [], layout: {} });
});
it.each([
[400, 'rechazó los parámetros'], [404, 'reportes no están disponibles'], [500, 'error interno'],
])('controla HTTP %i con cuerpo no uniforme y permite reintentar', (status, message) => {
load();
figure().flush('<html>error privado</html>', { status: status as number, statusText: 'Error' });
expect(page.result().status).toBe('error');
expect(page.result().message).toContain(message);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).not.toContain('error privado');
page.requestFigure();
figure().flush({ data: [], layout: {} });
expect(page.result().status).toBe('ready');
});
it('distingue conexión fallida y cancela HTTP al destruirse', () => {
load(); figure().error(new ProgressEvent('error'));
expect(page.result().message).toContain('conectar');
page.requestFigure();
const pending = figure();
fixture.destroy();
expect(pending.cancelled).toBe(true);
});
it('controla errores de catálogo y puede recuperarse', () => {
http.expectOne('/tea/indicadores').flush('Error', { status: 500, statusText: 'Error' });
expect(page.catalogError()).toContain('error interno');
page.retryCatalog(); load(); figure().flush({ data: [], layout: {} });
});
});
@@ -1,119 +0,0 @@
import { Component, DestroyRef, inject, signal } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs';
import { FigureSelection, hasNoVisibleValues, Indicador, parsePeriodos, PlotlyFigure, Tema } from './indicadores.models';
import { IndicadoresService } from './indicadores.service';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
export function httpMessage(error: unknown, catalog = false): string {
if (!(error instanceof HttpErrorResponse)) return 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.';
if (error.status === 0) return 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.';
if (error.status === 400) return 'El servicio rechazó los parámetros. Revisa los periodos y la selección.';
if (error.status === 404) return catalog ? 'El catálogo no está disponible.' : 'La figura o los reportes no están disponibles para esta selección.';
if (error.status >= 500) return 'El servicio encontró un error interno. Intenta nuevamente más tarde.';
return 'No se pudo completar la solicitud. Intenta nuevamente.';
}
// Presentation only: contract semantics documented in G3 and G5C.
const CONTRACT_INTERPRETATIONS: Readonly<Record<string, readonly string[]>> = {
C1: [
'El punto representa la proporción observada.',
'La línea vertical representa el intervalo de confianza Wilson al 95 %.',
'Los intervalos amplios pueden deberse a denominadores pequeños.',
'Un porcentaje observado del 100 % no implica certeza poblacional.',
],
C2: [
'Las barras muestran la composición porcentual de cada grupo y periodo.',
'Las categorías corresponden a la distribución de cada grupo y periodo.',
'SIN_DATO, cuando aparece, es una categoría legítima de la representación.',
],
C3r: [
'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.',
'Los límites de dibujo no representan necesariamente extremos observados.',
'Plotly puede mostrar las etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.',
],
};
const UNKNOWN_INTERPRETATION = ['No hay una explicación específica disponible para este contrato. Consulta las notas de la figura; no se infiere su significado estadístico.'];
type FigureState = { status: 'idle' | 'loading' | 'ready' | 'error'; figure?: PlotlyFigure; message?: string };
@Component({
selector: 'app-indicadores-page',
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatProgressBarModule, PlotlyChart],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
export class IndicadoresPage {
private readonly service = inject(IndicadoresService);
private readonly destroyRef = inject(DestroyRef);
private readonly catalogRequests = new Subject<void>();
private readonly figureRequests = new Subject<FigureSelection | null>();
readonly catalog = signal<Indicador[]>([]);
readonly catalogLoading = signal(true);
readonly catalogError = signal('');
readonly result = signal<FigureState>({ status: 'idle' });
readonly hasNoVisibleValues = hasNoVisibleValues;
indicadorId = '';
figuraId = '';
periodMode: 'todos' | 'manual' = 'todos';
periodText = '';
periodError = '';
tema: Tema = 'claro';
get selected(): Indicador | undefined { return this.catalog().find(item => item.id === this.indicadorId); }
get interpretation(): readonly string[] {
const contract = this.selected?.contrato;
return contract && Object.hasOwn(CONTRACT_INTERPRETATIONS, contract)
? CONTRACT_INTERPRETATIONS[contract] : UNKNOWN_INTERPRETATION;
}
constructor() {
this.figureRequests.pipe(switchMap(selection => selection
? this.service.figura(selection).pipe(
map(figure => ({ status: 'ready', figure }) as FigureState),
catchError(error => of({ status: 'error', message: httpMessage(error) } as FigureState)),
startWith({ status: 'loading' } as FigureState))
: of({ status: 'idle' } as FigureState)), takeUntilDestroyed(this.destroyRef))
.subscribe(state => this.result.set(state));
this.catalogRequests.pipe(startWith(undefined), switchMap(() => {
this.catalogLoading.set(true);
this.catalogError.set('');
this.catalog.set([]);
this.indicadorId = this.figuraId = '';
this.figureRequests.next(null);
return this.service.catalogo().pipe(map(items => ({ items, error: '' })),
catchError(error => of({ items: [] as Indicador[], error: httpMessage(error, true) })));
}), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => {
this.catalogLoading.set(false);
this.catalog.set(items);
this.catalogError.set(error);
if (items.length) this.selectIndicador(items[0].id);
});
}
retryCatalog() { this.catalogRequests.next(); }
selectIndicador(id: string) {
this.indicadorId = id;
this.figuraId = this.selected?.figuras[0] ?? '';
this.requestFigure();
}
selectFigura(id: string) { this.figuraId = id; this.requestFigure(); }
changePeriodMode(mode: 'todos' | 'manual') { this.periodMode = mode; this.requestFigure(); }
changePeriodText(text: string) { this.periodText = text; this.requestFigure(); }
changeTema(tema: Tema) { this.tema = tema; this.requestFigure(); }
requestFigure() {
this.periodError = '';
const periodos = this.periodMode === 'manual' ? parsePeriodos(this.periodText) : undefined;
if (periodos === null) this.periodError = 'Introduce semestres AAAA-S1 o AAAA-S2 separados por comas.';
if (!this.selected || !this.selected.figuras.includes(this.figuraId) || periodos === null) {
this.figureRequests.next(null);
return;
}
this.figureRequests.next({ indicador: this.indicadorId, figura: this.figuraId, tema: this.tema, periodos });
}
}
@@ -1,23 +0,0 @@
import { hasNoVisibleValues, parsePeriodos } from './indicadores.models';
describe('Periodos y visibilidad conservadora', () => {
it('normaliza espacios y duplicados sin inventar periodos', () => {
expect(parsePeriodos('2025-S1, 2025-S2,2025-S1')).toEqual(['2025-S1', '2025-S2']);
expect(parsePeriodos('1900-S2')).toEqual(['1900-S2']);
});
it.each(['', '2025', '25-S1', '2025-S3', '2025-S1,', '2025-s1', '2025-S1 2025-S2'])('rechaza %s', value => {
expect(parsePeriodos(value)).toBeNull();
});
it('detecta trazos vacíos, nulos y cajas sin mediana', () => {
expect(hasNoVisibleValues({ data: [], layout: {} })).toBe(true);
expect(hasNoVisibleValues({ data: [{ type: 'scatter', y: [null] }, { type: 'bar', y: [] }, { type: 'box', median: [null] }], layout: {} })).toBe(true);
});
it('conserva cero, supresión y medianas válidas como valores visibles', () => {
expect(hasNoVisibleValues({ data: [{ y: [0] }], layout: {} })).toBe(false);
expect(hasNoVisibleValues({ data: [{ type: 'box', median: [10] }], layout: {} })).toBe(false);
});
it('no declara vacíos los formatos desconocidos o binarios', () => {
expect(hasNoVisibleValues({ data: [{ y: { bdata: 'AAAA', dtype: 'f8' } }], layout: {} })).toBe(false);
expect(hasNoVisibleValues({ data: [{ type: 'heatmap', z: [] }], layout: {} })).toBe(false);
});
});
@@ -1,36 +0,0 @@
export interface Indicador {
id: string;
titulo: string;
contrato: string;
figuras: string[];
}
// Keep the complete HTTP figure, including future attributes and interpretation notes.
export interface PlotlyFigure {
data: Record<string, unknown>[];
layout: Record<string, unknown>;
frames?: Record<string, unknown>[];
config?: Record<string, unknown>;
[key: string]: unknown;
}
export type Tema = 'claro' | 'oscuro';
export interface FigureSelection { indicador: string; figura: string; tema: Tema; periodos?: string[]; }
export function parsePeriodos(value: string): string[] | null {
const parts = value.split(',').map(part => part.trim());
return parts.length && parts.every(part => /^[0-9]{4}-S[12]$/.test(part))
? [...new Set(parts)] : null;
}
// Only assert emptiness for known TEA traces with ordinary arrays. Unknown/binary
// representations remain indeterminate; never infer counts or suppression causes.
export function hasNoVisibleValues(figure: PlotlyFigure): boolean {
return figure.data.every(trace => {
if (trace['visible'] === false || trace['visible'] === 'legendonly') return true;
const type = trace['type'] ?? 'scatter';
const values = type === 'box' ? trace['median'] ?? trace['y']
: type === 'scatter' || type === 'bar' ? trace['y'] : undefined;
if (!Array.isArray(values)) return false;
return !values.some(value => typeof value === 'number' && Number.isFinite(value));
});
}
@@ -1,53 +0,0 @@
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { IndicadoresService } from './indicadores.service';
describe('IndicadoresService HTTP', () => {
let service: IndicadoresService;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
service = TestBed.inject(IndicadoresService);
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it('consume un arreglo directo sin hardcodear catálogo', () => {
const data = [{ id: 'prueba', titulo: 'Título', contrato: 'C1', figuras: ['f1', 'f2'] }];
let actual: unknown;
service.catalogo().subscribe(value => actual = value);
http.expectOne('/tea/indicadores').flush(data);
expect(actual).toEqual(data);
});
it('acepta catálogo vacío y rechaza envelope inesperado', () => {
service.catalogo().subscribe(value => expect(value).toEqual([]));
http.expectOne('/tea/indicadores').flush([]);
let error: unknown;
service.catalogo().subscribe({ error: value => error = value });
http.expectOne('/tea/indicadores').flush({ items: [] });
expect(error).toBeInstanceOf(Error);
});
it('codifica segmentos y omite periodos en Todos', () => {
service.figura({ indicador: 'a/b ü', figura: 'f?#', tema: 'claro' }).subscribe();
const request = http.expectOne(req => req.url === '/tea/indicadores/a%2Fb%20%C3%BC/figuras/f%3F%23');
expect(request.request.method).toBe('GET');
expect(request.request.params.get('tema')).toBe('claro');
expect(request.request.params.has('periodos')).toBe(false);
request.flush({ data: [], layout: {} });
});
it('envía semestres y conserva atributos desconocidos, nulos y notas', () => {
const figure = { data: [{ y: [null, 0], customdata: [null] }], layout: { annotations: [{ text: 'Uso exclusivo de investigación' }] }, extension: { future: true }, frames: [] };
service.figura({ indicador: 'i', figura: 'f', tema: 'oscuro', periodos: ['2025-S1', '2025-S2'] })
.subscribe(value => expect(value).toEqual(figure));
const request = http.expectOne(req => req.url.endsWith('/i/figuras/f'));
expect(request.request.params.get('periodos')).toBe('2025-S1,2025-S2');
expect(request.request.params.get('tema')).toBe('oscuro');
request.flush(figure);
});
it('rechaza una figura estructuralmente inválida', () => {
let error: unknown;
service.figura({ indicador: 'i', figura: 'f', tema: 'claro' }).subscribe({ error: value => error = value });
http.expectOne(req => req.url.endsWith('/i/figuras/f')).flush({ data: null, layout: {} });
expect(error).toBeInstanceOf(Error);
});
});
@@ -1,33 +0,0 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { FigureSelection, Indicador, PlotlyFigure } from './indicadores.models';
function record(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
@Injectable({ providedIn: 'root' })
export class IndicadoresService {
private readonly http = inject(HttpClient);
catalogo() {
return this.http.get<unknown>('/tea/indicadores').pipe(map(value => {
if (!Array.isArray(value) || !value.every(item => record(item)
&& typeof item['id'] === 'string' && typeof item['titulo'] === 'string'
&& typeof item['contrato'] === 'string' && Array.isArray(item['figuras'])
&& item['figuras'].every((figure: unknown) => typeof figure === 'string'))) {
throw new Error('Respuesta de catálogo inválida');
}
return value as Indicador[];
}));
}
figura(selection: FigureSelection) {
let params = new HttpParams().set('tema', selection.tema);
if (selection.periodos?.length) params = params.set('periodos', selection.periodos.join(','));
const url = `/tea/indicadores/${encodeURIComponent(selection.indicador)}/figuras/${encodeURIComponent(selection.figura)}`;
return this.http.get<unknown>(url, { params }).pipe(map(value => {
if (!record(value) || !Array.isArray(value['data']) || !value['data'].every(record)
|| !record(value['layout'])) throw new Error('Respuesta de figura inválida');
return value as unknown as PlotlyFigure;
}));
}
}
@@ -1,41 +0,0 @@
import { TestBed } from '@angular/core/testing';
import { vi } from 'vitest';
import { PlotlyChart } from './plotly-chart';
import { PLOTLY_LOADER } from './plotly-runtime';
const mocks = { load: vi.fn(), react: vi.fn(), purge: vi.fn(), resize: vi.fn() };
describe('PlotlyChart lifecycle', () => {
beforeEach(() => {
vi.resetAllMocks();
mocks.react.mockResolvedValue(undefined);
mocks.resize.mockResolvedValue(undefined);
mocks.load.mockResolvedValue({ react: mocks.react, purge: mocks.purge, Plots: { resize: mocks.resize } });
TestBed.configureTestingModule({ imports: [PlotlyChart], providers: [{ provide: PLOTLY_LOADER, useValue: mocks.load }] });
});
it('monta el host, actualiza inputs y desconecta ResizeObserver', async () => {
const disconnect = vi.fn(); const observe = vi.fn();
vi.stubGlobal('ResizeObserver', class { observe = observe; disconnect = disconnect; });
const fixture = TestBed.createComponent(PlotlyChart);
fixture.componentRef.setInput('figure', { data: [], layout: {} });
fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve();
expect(observe).toHaveBeenCalledWith(fixture.nativeElement.querySelector('.plot'));
expect(mocks.react).toHaveBeenCalledTimes(1);
fixture.componentRef.setInput('figure', { data: [{ y: [1] }], layout: {} });
fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve();
expect(mocks.react).toHaveBeenCalledTimes(2);
fixture.destroy(); expect(disconnect).toHaveBeenCalled(); expect(mocks.purge).toHaveBeenCalled();
vi.unstubAllGlobals();
});
it('muestra error asíncrono y se recupera con reintento', async () => {
mocks.react.mockRejectedValueOnce(new Error('render failed'));
const fixture = TestBed.createComponent(PlotlyChart);
fixture.componentRef.setInput('figure', { data: [], layout: {} });
fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('No se pudo representar');
fixture.nativeElement.querySelector('button').click();
await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges();
expect(fixture.componentInstance.status()).toBe('ready'); fixture.destroy();
});
});
-61
View File
@@ -1,61 +0,0 @@
import { AfterViewInit, Component, inject, ElementRef, Input, OnChanges, OnDestroy, output, signal, ViewChild } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
import { PlotlyController } from './plotly-controller';
import { PLOTLY_LOADER } from './plotly-runtime';
@Component({
selector: 'app-plotly-chart',
imports: [MatButtonModule, MatProgressBarModule],
template: `
@if (status() === 'loading') { <mat-progress-bar mode="indeterminate" aria-label="Representando figura" /> }
@if (status() === 'error') {
<div role="alert"><p>No se pudo representar la figura. Puedes reintentar.</p>
<button mat-stroked-button (click)="retry()">Reintentar renderizado</button></div>
}
<div #host class="plot" role="img" aria-label="Figura del indicador seleccionado" [attr.aria-hidden]="status() !== 'ready'"></div>
@if (status() === 'ready' && notes.length) {
<section class="notes" aria-label="Notas completas de la figura">
<h2>Notas de la figura</h2>
@for (note of notes; track $index) { <p [innerHTML]="note"></p> }
</section>
}
`,
styles: `:host { display: block; min-width: 0; } .plot { width: 100%; min-height: 620px; visibility: hidden; } [role=alert] { padding: 1rem; } .notes { display: none; padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; } @media (max-width: 850px) { .notes { display: block; } }`,
})
export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy {
@Input({ required: true }) figure!: PlotlyFigure;
@ViewChild('host', { static: true }) host!: ElementRef<HTMLElement>;
readonly renderError = output<void>();
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
get notes(): string[] {
const annotations = this.figure?.layout['annotations'];
if (!Array.isArray(annotations)) return [];
return annotations.flatMap(annotation =>
annotation && typeof annotation.text === 'string' ? [annotation.text] : []);
}
private readonly loadPlotly = inject(PLOTLY_LOADER);
private controller?: PlotlyController;
private observer?: ResizeObserver;
private readonly windowResize = () => this.controller?.resize();
ngAfterViewInit() {
this.controller = new PlotlyController(this.host.nativeElement, this.loadPlotly, state => {
this.status.set(state);
if (state === 'error') this.renderError.emit();
});
if (typeof ResizeObserver !== 'undefined') {
this.observer = new ResizeObserver(this.windowResize);
this.observer.observe(this.host.nativeElement);
} else window.addEventListener('resize', this.windowResize);
this.controller.setFigure(this.figure);
}
ngOnChanges() { if (this.figure) this.controller?.setFigure(this.figure); }
retry() { this.controller?.setFigure(this.figure); }
ngOnDestroy() {
this.observer?.disconnect();
window.removeEventListener('resize', this.windowResize);
this.controller?.destroy();
}
}
@@ -1,178 +0,0 @@
import { vi } from 'vitest';
import { PlotlyController } from './plotly-controller';
import { PlotlyRuntime } from './plotly-runtime';
import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
function deferred() {
let resolve!: (value?: unknown) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<unknown>((yes, no) => { resolve = yes; reject = no; });
return { promise, resolve, reject };
}
async function settle() { for (let i = 0; i < 12; i++) await Promise.resolve(); }
const fig = (value: number): PlotlyFigure => ({ data: [{ type: 'scatter', y: [value, null] }], layout: { annotations: [{ text: 'No usar para decisiones clínicas' }] } });
describe('PlotlyController async', () => {
let host: HTMLElement;
let plotly: PlotlyRuntime;
let state: ReturnType<typeof vi.fn<(state: 'loading' | 'ready' | 'error') => void>>;
let controller: PlotlyController;
beforeEach(() => {
host = document.createElement('div');
plotly = { react: vi.fn().mockResolvedValue(undefined), purge: vi.fn(), Plots: { resize: vi.fn().mockResolvedValue(undefined) }, addFrames: vi.fn().mockResolvedValue(undefined), deleteFrames: vi.fn().mockResolvedValue(undefined) };
state = vi.fn();
controller = new PlotlyController(host, () => Promise.resolve(plotly), state);
});
it('conserva valores y anotaciones, aislando mutaciones de Plotly', async () => {
const figure = fig(0);
vi.mocked(plotly.react).mockImplementation(async (_host, data) => { data[0]['y'] = [123]; });
controller.setFigure(figure); await settle();
expect(figure.data[0]['y']).toEqual([0, null]);
expect(plotly.react).toHaveBeenCalledWith(host, expect.any(Array), figure.layout, expect.objectContaining({ displaylogo: false }));
expect(host.style.visibility).toBe('visible');
expect(state).toHaveBeenLastCalledWith('ready');
});
it('desactiva el envío externo sin alterar el JSON ni las opciones locales recibidas', async () => {
const figure: PlotlyFigure = {
...fig(1),
config: { showSendToCloud: true, displaylogo: true, scrollZoom: true, doubleClick: 'reset+autosize' },
frames: [{ name: 'uno', data: [{ y: [2, null] }] }],
};
const original = JSON.stringify(figure);
controller.setFigure(figure); await settle();
expect(plotly.react).toHaveBeenCalledWith(host, figure.data, figure.layout, {
responsive: false, displaylogo: false, showSendToCloud: false,
modeBarButtonsToRemove: ['sendChartToCloud'], scrollZoom: true, doubleClick: 'reset+autosize',
});
expect(plotly.addFrames).toHaveBeenCalledWith(host, figure.frames);
expect(JSON.stringify(figure)).toBe(original);
});
it('elige sólo la figura reciente si la importación sigue pendiente', async () => {
const load = deferred();
controller = new PlotlyController(host, () => load.promise as Promise<PlotlyRuntime>, state);
controller.setFigure(fig(1)); controller.setFigure(fig(2));
load.resolve(plotly); await settle();
expect(plotly.react).toHaveBeenCalledTimes(1);
expect(vi.mocked(plotly.react).mock.calls[0][1][0]['y']).toEqual([2, null]);
});
it('serializa react y oculta completados obsoletos', async () => {
const old = deferred(); const latest = deferred();
vi.mocked(plotly.react).mockReturnValueOnce(old.promise).mockReturnValueOnce(latest.promise);
controller.setFigure(fig(1)); await settle();
controller.setFigure(fig(2));
expect(plotly.react).toHaveBeenCalledTimes(1);
old.resolve(); await settle();
expect(plotly.react).toHaveBeenCalledTimes(2);
expect(host.style.visibility).toBe('hidden');
expect(state).not.toHaveBeenCalledWith('ready');
latest.resolve(); await settle();
expect(host.style.visibility).toBe('visible');
expect(state).toHaveBeenLastCalledWith('ready');
});
it('ignora rechazo antiguo y representa la siguiente figura', async () => {
const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise);
controller.setFigure(fig(1)); await settle(); controller.setFigure(fig(2));
pending.reject(new Error('old')); await settle();
expect(state).not.toHaveBeenCalledWith('error');
expect(state).toHaveBeenLastCalledWith('ready');
});
it('maneja error asíncrono y permite reintentar', async () => {
vi.mocked(plotly.react).mockRejectedValueOnce(new Error('failed'));
controller.setFigure(fig(1)); await settle();
expect(state).toHaveBeenLastCalledWith('error');
expect(host.style.visibility).toBe('hidden');
controller.setFigure(fig(1)); await settle();
expect(state).toHaveBeenLastCalledWith('ready');
});
it('maneja importación fallida y recupera el cargador', async () => {
const load = vi.fn().mockRejectedValueOnce(new Error()).mockResolvedValue(plotly);
controller = new PlotlyController(host, load, state);
controller.setFigure(fig(1)); await settle(); expect(state).toHaveBeenLastCalledWith('error');
controller.setFigure(fig(1)); await settle(); expect(state).toHaveBeenLastCalledWith('ready');
});
it('purga al destruir y nuevamente tras terminar react pendiente', async () => {
const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise);
controller.setFigure(fig(1)); await settle();
controller.destroy(); expect(plotly.purge).toHaveBeenCalledTimes(1);
pending.resolve(); await settle(); expect(plotly.purge).toHaveBeenCalledTimes(2);
expect(state).not.toHaveBeenCalledWith('ready');
controller.setFigure(fig(2)); controller.resize(); await settle();
expect(plotly.react).toHaveBeenCalledTimes(1);
expect(plotly.Plots.resize).not.toHaveBeenCalled();
});
it('no renderiza tras destruir durante la importación', async () => {
const pending = deferred(); controller = new PlotlyController(host, () => pending.promise as Promise<PlotlyRuntime>, state);
controller.setFigure(fig(1)); controller.destroy(); pending.resolve(plotly); await settle();
expect(plotly.react).not.toHaveBeenCalled(); expect(plotly.purge).toHaveBeenCalledWith(host);
});
it('serializa resize y el siguiente react', async () => {
controller.setFigure(fig(1)); await settle();
const resize = deferred(); vi.mocked(plotly.Plots.resize).mockReturnValueOnce(resize.promise);
controller.resize(); await settle(); controller.setFigure(fig(2));
expect(plotly.react).toHaveBeenCalledTimes(1);
resize.resolve(); await settle(); expect(plotly.react).toHaveBeenCalledTimes(2);
});
it('conserva frames y los retira al cambiar figura', async () => {
controller.setFigure({ ...fig(1), frames: [{ name: 'uno', data: [] }] }); await settle();
expect(plotly.addFrames).toHaveBeenCalledWith(host, [{ name: 'uno', data: [] }]);
controller.setFigure(fig(2)); await settle();
expect(plotly.deleteFrames).toHaveBeenCalledWith(host, [0]);
});
});
// Exercise the installed bundle in jsdom: no cloud action is clicked.
describe('PlotlyController con Plotly instalado', () => {
let runtime: PlotlyRuntime & {
version: string;
PlotSchema: { get(): { config: Record<string, { valType: string }> } };
};
beforeAll(async () => {
// jsdom has no canvas renderer; cartesian SVG only needs this import-time probe.
const canvas = vi.spyOn(HTMLCanvasElement.prototype, 'getContext')
.mockReturnValue({ measureText: () => ({ width: 0 }) } as unknown as CanvasRenderingContext2D);
try {
const module = await import('plotly.js-cartesian-dist-min');
runtime = (module.default ?? module) as typeof runtime;
} finally { canvas.mockRestore(); }
});
it('usa propiedades admitidas por el esquema de Plotly 4.1.2', () => {
expect(runtime.version).toBe('4.1.2');
const config = runtime.PlotSchema.get().config;
expect(config['showSendToCloud'].valType).toBe('boolean');
expect(config['displaylogo'].valType).toBe('boolean');
expect(config['modeBarButtonsToRemove'].valType).toBe('any');
});
it.each([
['C1', { type: 'scatter', x: [1, 2], y: [3, 4] }],
['C2', { type: 'bar', x: ['grupo'], y: [100] }],
['C3r', { type: 'box', x: ['grupo'], q1: [23.5], median: [45], q3: [55], lowerfence: [23.5], upperfence: [55] }],
])('genera la modebar %s sin envío externo y conserva zoom/pan/restauración', async (_contract, trace) => {
const host = document.createElement('div');
document.body.append(host);
const figure: PlotlyFigure = { data: [trace], layout: { width: 600, height: 400 } };
const original = JSON.stringify(figure);
let controller!: PlotlyController;
try {
await new Promise<void>((resolve, reject) => {
controller = new PlotlyController(host, () => Promise.resolve(runtime), state => {
if (state === 'ready') resolve();
if (state === 'error') reject(new Error('Plotly failed to render'));
});
controller.setFigure(figure);
});
const buttons = Array.from(host.querySelectorAll<HTMLElement>('.modebar-btn'));
const titles = buttons.map(button => button.getAttribute('data-title'));
expect(titles).not.toContain('Share chart...');
expect(titles).toEqual(expect.arrayContaining(['Zoom', 'Pan', 'Zoom in', 'Zoom out', 'Autoscale', 'Reset axes', 'Download plot as a PNG']));
expect(host.querySelector('.modebar a[href]')).toBeNull();
const rendered = host as unknown as HTMLElement & { _fullLayout: { dragmode: string } };
for (const [title, mode] of [['Pan', 'pan'], ['Zoom', 'zoom']]) {
buttons.find(button => button.getAttribute('data-title') === title)!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
await vi.waitFor(() => expect(rendered._fullLayout.dragmode).toBe(mode));
}
expect(JSON.stringify(figure)).toBe(original);
} finally {
controller?.destroy(); host.remove();
}
});
});
@@ -1,87 +0,0 @@
import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
import { PlotlyRuntime } from './plotly-runtime';
// One serialized queue owns the host. A completed stale operation cannot expose
// its graph or overwrite a newer react operation. Resize uses the same queue.
export class PlotlyController {
private desired?: PlotlyFigure;
private version = 0;
private rendered = -1;
private busy = false;
private destroyed = false;
private resizePending = false;
private plotly?: PlotlyRuntime;
private frameCount = 0;
constructor(private host: HTMLElement, private load: () => Promise<PlotlyRuntime>,
private state: (state: 'loading' | 'ready' | 'error') => void) {}
setFigure(figure: PlotlyFigure) {
if (this.destroyed) return;
this.desired = figure;
this.version++;
this.host.style.visibility = 'hidden';
this.state('loading');
void this.drain();
}
resize() {
if (this.destroyed || this.rendered < 0) return;
this.resizePending = true;
void this.drain();
}
destroy() {
this.destroyed = true;
this.host.style.visibility = 'hidden';
this.plotly?.purge(this.host);
}
private async drain() {
if (this.busy || this.destroyed) return;
this.busy = true;
try {
this.plotly ??= await this.load();
while (!this.destroyed && (this.rendered !== this.version || this.resizePending)) {
const version = this.version;
try {
if (this.rendered !== version && this.desired) {
// Plotly may mutate inputs; clone the complete JSON without changing values.
const figure = structuredClone(this.desired);
if (this.frameCount) await this.plotly.deleteFrames(this.host, Array.from({ length: this.frameCount }, (_, i) => i));
this.frameCount = 0;
if (this.destroyed) break;
await this.plotly.react(this.host, figure.data, figure.layout, {
...figure.config, responsive: false, displaylogo: false,
showSendToCloud: false,
modeBarButtonsToRemove: ['sendChartToCloud'],
});
if (this.destroyed) break;
if (version !== this.version) continue;
if (figure.frames?.length) {
await this.plotly.addFrames(this.host, figure.frames);
this.frameCount = figure.frames.length;
}
if (this.destroyed) break;
if (version !== this.version) continue;
this.rendered = version;
this.host.style.visibility = 'visible';
this.state('ready');
} else {
this.resizePending = false;
await this.plotly.Plots.resize(this.host);
}
} catch {
if (this.destroyed) break;
if (version !== this.version) continue;
this.rendered = version;
this.resizePending = false;
this.host.style.visibility = 'hidden';
this.state('error');
}
}
} catch {
if (!this.destroyed) this.state('error');
} finally {
this.busy = false;
// A pending react can recreate internal resources after the first purge.
if (this.destroyed) this.plotly?.purge(this.host);
}
}
}
@@ -1,23 +0,0 @@
import { vi } from 'vitest';
import { loadPlotly } from './plotly-runtime';
it('carga una sola instancia oficial con el esquema requerido por C1/C2/C3r', async () => {
// No chart rendering in jsdom. Schema inspection only needs browser globals.
const canvas = vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null);
try {
const first = loadPlotly();
expect(loadPlotly()).toBe(first);
const runtime = await first as unknown as { version: string; PlotSchema: { get(): any } };
expect(runtime.version).toBe('4.1.2');
const schema = runtime.PlotSchema.get();
expect(schema.traces.scatter).toBeDefined();
expect(schema.traces.bar).toBeDefined();
expect(schema.traces.box).toBeDefined();
expect(schema.traces.scatter.attributes.error_y).toBeDefined();
expect(schema.layout.layoutAttributes.xaxis.type.values).toContain('multicategory');
expect(schema.traces.scatter.layoutAttributes.scattermode.values).toContain('group');
expect(schema.traces.box.layoutAttributes.boxmode.values).toContain('group');
for (const key of ['q1', 'median', 'q3', 'lowerfence', 'upperfence']) expect(schema.traces.box.attributes[key]).toBeDefined();
for (const key of ['annotations', 'template', 'paper_bgcolor', 'plot_bgcolor']) expect(schema.layout.layoutAttributes[key]).toBeDefined();
} finally { canvas.mockRestore(); }
});
-20
View File
@@ -1,20 +0,0 @@
import { InjectionToken } from '@angular/core';
import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
// Narrow boundary for the official partial bundle, which ships without declarations.
export interface PlotlyRuntime {
react(host: HTMLElement, data: PlotlyFigure['data'], layout: PlotlyFigure['layout'], config: Record<string, unknown>): Promise<unknown>;
purge(host: HTMLElement): void;
Plots: { resize(host: HTMLElement): Promise<unknown> };
addFrames(host: HTMLElement, frames: Record<string, unknown>[]): Promise<unknown>;
deleteFrames(host: HTMLElement, indices: number[]): Promise<unknown>;
}
let runtime: Promise<PlotlyRuntime> | undefined;
export function loadPlotly(): Promise<PlotlyRuntime> {
return runtime ??= import('plotly.js-cartesian-dist-min')
.then(module => (module.default ?? module) as unknown as PlotlyRuntime)
.catch(error => { runtime = undefined; throw error; });
}
export const PLOTLY_LOADER = new InjectionToken<() => Promise<PlotlyRuntime>>('PLOTLY_LOADER', { providedIn: 'root', factory: () => loadPlotly });
-1
View File
@@ -1 +0,0 @@
declare module 'plotly.js-cartesian-dist-min';
+5 -2
View File
@@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="utf-8" />
<title>WebApp</title>
<title>Webapp</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
@@ -12,7 +12,10 @@
href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap"
rel="stylesheet"
/>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
<link
href="https://fonts.googleapis.com/icon?family=Material+Symbols+Outlined"
rel="stylesheet"
/>
</head>
<body>
<app-root></app-root>
+1 -2
View File
@@ -2,5 +2,4 @@ import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { App } from './app/app';
bootstrapApplication(App, appConfig)
.catch((err) => console.error(err));
bootstrapApplication(App, appConfig).catch((err) => console.error(err));
+2 -6
View File
@@ -5,10 +5,6 @@
"compilerOptions": {
"types": []
},
"include": [
"src/**/*.ts"
],
"exclude": [
"src/**/*.spec.ts"
]
"include": ["src/**/*.ts"],
"exclude": ["src/**/*.spec.ts"]
}
+2 -7
View File
@@ -3,12 +3,7 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"types": [
"vitest/globals"
]
"types": ["vitest/globals"]
},
"include": [
"src/**/*.d.ts",
"src/**/*.spec.ts"
]
"include": ["src/**/*.d.ts", "src/**/*.spec.ts"]
}