Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a66205b725 |
+1
-1
@@ -7,4 +7,4 @@ RUN npm install
|
||||
COPY . .
|
||||
|
||||
EXPOSE 4200
|
||||
CMD ["npx", "ng", "serve", "--host", "0.0.0.0", "--port", "4200", "--proxy-config", "proxy.docker.json"]
|
||||
CMD ["npx", "ng", "serve", "--host", "0.0.0.0", "--port", "4200"]
|
||||
|
||||
+3
-4
@@ -2,7 +2,8 @@
|
||||
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
|
||||
"version": 1,
|
||||
"cli": {
|
||||
"packageManager": "npm"
|
||||
"packageManager": "npm",
|
||||
"analytics": false
|
||||
},
|
||||
"newProjectRoot": "projects",
|
||||
"projects": {
|
||||
@@ -59,9 +60,7 @@
|
||||
},
|
||||
"serve": {
|
||||
"builder": "@angular/build:dev-server",
|
||||
"options": {
|
||||
"proxyConfig": "proxy.local.json"
|
||||
},
|
||||
"options": { "proxyConfig": "proxy.conf.json" },
|
||||
"configurations": {
|
||||
"production": {
|
||||
"buildTarget": "WebApp:build:production"
|
||||
|
||||
Generated
+7
@@ -16,6 +16,7 @@
|
||||
"@angular/material": "^22.1.7",
|
||||
"@angular/platform-browser": "^22.1.0",
|
||||
"@angular/router": "^22.1.0",
|
||||
"plotly.js-cartesian-dist-min": "4.1.2",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0"
|
||||
},
|
||||
@@ -6481,6 +6482,12 @@
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/plotly.js-cartesian-dist-min": {
|
||||
"version": "4.1.2",
|
||||
"resolved": "https://registry.npmjs.org/plotly.js-cartesian-dist-min/-/plotly.js-cartesian-dist-min-4.1.2.tgz",
|
||||
"integrity": "sha512-3UkyAT7/U8f3sOLavLnUjA6mqFmnqEe246GZhxT0J3TT9oZ0mh6SgwsL1yo/3/4xfmRSDFdGOxe+EsvT2XiE0g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/postcss": {
|
||||
"version": "8.5.28",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
"@angular/material": "^22.1.7",
|
||||
"@angular/platform-browser": "^22.1.0",
|
||||
"@angular/router": "^22.1.0",
|
||||
"plotly.js-cartesian-dist-min": "4.1.2",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"/tea/**": { "target": "http://127.0.0.1:5000", "secure": false },
|
||||
"/health": { "target": "http://127.0.0.1:5000", "secure": false }
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"/auth/**": {
|
||||
"target": "http://webapi:5000"
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"/auth/**": {
|
||||
"target": "http://127.0.0.1:5000"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 13 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 17 KiB |
@@ -1,12 +1,12 @@
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { routes } from './app.routes';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
provideBrowserGlobalErrorListeners(),
|
||||
provideHttpClient(),
|
||||
provideRouter(routes)
|
||||
provideRouter(routes),
|
||||
provideHttpClient()
|
||||
]
|
||||
};
|
||||
|
||||
+1
-7
@@ -1,13 +1,7 @@
|
||||
@if (auth.isAuthenticated()) {
|
||||
<mat-toolbar color="primary">
|
||||
<span>{{ title }}</span>
|
||||
<span class="spacer"></span>
|
||||
<span class="username">{{ auth.user()?.username }}</span>
|
||||
<button mat-button (click)="auth.logout()">Cerrar sesión</button>
|
||||
</mat-toolbar>
|
||||
}
|
||||
|
||||
<main>
|
||||
@if (auth.status() === 'checking') { <p role="status">Comprobando sesión…</p> }
|
||||
<div [hidden]="auth.status() === 'checking'"><router-outlet /></div>
|
||||
<router-outlet />
|
||||
</main>
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
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
-10
@@ -1,14 +1,5 @@
|
||||
import { Routes } from '@angular/router';
|
||||
import { authGuard, anonymousGuard, areaGuard } from './auth/auth.guard';
|
||||
import { AreaPlaceholder } from './auth/area-placeholder';
|
||||
import { Home } from './auth/home';
|
||||
import { Login } from './auth/login';
|
||||
|
||||
export const routes: Routes = [
|
||||
{ path: 'login', component: Login, canActivate: [anonymousGuard] },
|
||||
{ path: '', pathMatch: 'full', component: Home, canActivate: [authGuard] },
|
||||
{ path: 'cacu', component: AreaPlaceholder, data: { area: 'CACU' }, canActivate: [areaGuard('CACU')] },
|
||||
{ path: 'cama', component: AreaPlaceholder, data: { area: 'CAMA' }, canActivate: [areaGuard('CAMA')] },
|
||||
{ path: 'tea', component: AreaPlaceholder, data: { area: 'TEA' }, canActivate: [areaGuard('TEA')] },
|
||||
{ path: '**', redirectTo: '' },
|
||||
{ path: 'indicadores', loadComponent: () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage) },
|
||||
];
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
main {
|
||||
padding: 1.5rem;
|
||||
}
|
||||
.spacer { flex: 1; }
|
||||
.username { font-size: .875rem; margin-right: .5rem; overflow: hidden; text-overflow: ellipsis; }
|
||||
|
||||
@@ -1,23 +1,10 @@
|
||||
import { signal } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { vi } from 'vitest';
|
||||
import { App } from './app';
|
||||
import { AuthState } from './auth/auth.state';
|
||||
import { routes } from './app.routes';
|
||||
import { authGuard, anonymousGuard } from './auth/auth.guard';
|
||||
|
||||
describe('App', () => {
|
||||
const status = signal('anonymous');
|
||||
const user = signal({ id: 1, username: 'demo', roles: ['CAMA'] });
|
||||
const logout = vi.fn();
|
||||
beforeEach(async () => {
|
||||
status.set('anonymous'); logout.mockClear();
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [App],
|
||||
providers: [provideRouter([]), { provide: AuthState, useValue: {
|
||||
status, user, isAuthenticated: () => status() === 'authenticated', logout,
|
||||
} }],
|
||||
})
|
||||
.compileComponents();
|
||||
});
|
||||
@@ -29,28 +16,10 @@ describe('App', () => {
|
||||
});
|
||||
|
||||
it('should render the toolbar title', async () => {
|
||||
status.set('authenticated');
|
||||
const fixture = TestBed.createComponent(App);
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
const compiled = fixture.nativeElement as HTMLElement;
|
||||
expect(compiled.querySelector('mat-toolbar')?.textContent).toContain('ISSSTELEON');
|
||||
});
|
||||
it('hides shell for anonymous and checking', () => {
|
||||
const fixture = TestBed.createComponent(App); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('mat-toolbar')).toBeNull();
|
||||
status.set('checking'); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('mat-toolbar')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('router-outlet').parentElement.hidden).toBe(true);
|
||||
});
|
||||
it('invokes local logout from shell', () => {
|
||||
status.set('authenticated'); const fixture = TestBed.createComponent(App); fixture.detectChanges();
|
||||
fixture.nativeElement.querySelector('button').click(); expect(logout).toHaveBeenCalledOnce();
|
||||
});
|
||||
it('preserves login, protected home and wildcard alongside area routes', () => {
|
||||
expect(routes.map(route => route.path)).toEqual(['login', '', 'cacu', 'cama', 'tea', '**']);
|
||||
expect(routes[0].canActivate).toEqual([anonymousGuard]);
|
||||
expect(routes[1].canActivate).toEqual([authGuard]);
|
||||
expect(routes.at(-1)?.redirectTo).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
+2
-5
@@ -1,16 +1,13 @@
|
||||
import { Component, inject } from '@angular/core';
|
||||
import { Component } from '@angular/core';
|
||||
import { RouterOutlet } from '@angular/router';
|
||||
import { MatToolbarModule } from '@angular/material/toolbar';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { AuthState } from './auth/auth.state';
|
||||
|
||||
@Component({
|
||||
imports: [RouterOutlet, MatToolbarModule, MatButtonModule],
|
||||
imports: [RouterOutlet, MatToolbarModule],
|
||||
selector: 'app-root',
|
||||
styleUrl: './app.scss',
|
||||
templateUrl: './app.html',
|
||||
})
|
||||
export class App {
|
||||
protected readonly auth = inject(AuthState);
|
||||
protected readonly title = 'ISSSTELEON';
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import { Component, inject } from '@angular/core';
|
||||
import { ActivatedRoute, RouterLink } from '@angular/router';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { Area } from './auth.roles';
|
||||
|
||||
@Component({
|
||||
selector: 'app-area-placeholder',
|
||||
imports: [RouterLink, MatButtonModule],
|
||||
template: `<h1>Área {{ area }}</h1><a mat-button routerLink="/">Volver a áreas</a>`,
|
||||
})
|
||||
export class AreaPlaceholder {
|
||||
protected readonly area: Area = inject(ActivatedRoute).snapshot.data['area'];
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot, provideRouter } from '@angular/router';
|
||||
import { authGuard, anonymousGuard, areaGuard } from './auth.guard';
|
||||
import { Role } from './auth.models';
|
||||
import { Area } from './auth.roles';
|
||||
import { routes } from '../app.routes';
|
||||
import { AuthState } from './auth.state';
|
||||
|
||||
describe('Auth guards', () => {
|
||||
let http: HttpTestingController;
|
||||
const user = { id: 1, username: 'demo', roles: ['CAMA'] };
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([])] });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => { http.verify(); sessionStorage.clear(); });
|
||||
const run = (guard: typeof authGuard) => TestBed.runInInjectionContext(() =>
|
||||
guard({} as ActivatedRouteSnapshot, {} as RouterStateSnapshot));
|
||||
const url = (result: unknown) => TestBed.inject(Router).serializeUrl(result as ReturnType<Router['createUrlTree']>);
|
||||
it('anonymous redirects protected route to login', async () => {
|
||||
expect(url(await run(authGuard))).toBe('/login');
|
||||
});
|
||||
it('anonymous can open login', async () => { expect(await run(anonymousGuard)).toBe(true); });
|
||||
it('authenticated allows home and redirects login', async () => {
|
||||
const login = TestBed.inject(AuthState).login('demo', 'test-password');
|
||||
http.expectOne('/auth/login').flush({ token: 'test-token', expires_in: 28800, user }); await login;
|
||||
expect(await run(authGuard)).toBe(true); expect(url(await run(anonymousGuard))).toBe('/');
|
||||
});
|
||||
it('both guards wait on the same restore', async () => {
|
||||
sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token');
|
||||
let resolved = false;
|
||||
const home = Promise.resolve(run(authGuard)).then(result => { resolved = true; return result; });
|
||||
const login = run(anonymousGuard);
|
||||
await Promise.resolve(); expect(resolved).toBe(false);
|
||||
expect(TestBed.inject(AuthState).status()).toBe('checking');
|
||||
http.expectOne('/auth/me').flush({ user });
|
||||
expect(await home).toBe(true); expect(url(await login)).toBe('/');
|
||||
});
|
||||
it('rejected restore redirects home and allows login', async () => {
|
||||
sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token');
|
||||
const home = run(authGuard); const login = run(anonymousGuard);
|
||||
http.expectOne('/auth/me').flush({}, { status: 401, statusText: 'Unauthorized' });
|
||||
expect(url(await home)).toBe('/login'); expect(await login).toBe(true);
|
||||
});
|
||||
|
||||
it('anonymous is redirected to login for every area', async () => {
|
||||
for (const area of ['CACU', 'CAMA', 'TEA'] as const) {
|
||||
expect(url(await run(areaGuard(area)))).toBe('/login');
|
||||
}
|
||||
});
|
||||
const cases: [Role[], Area[]][] = [
|
||||
[['CAMA'], ['CAMA']], [['CACU', 'CAMA'], ['CACU', 'CAMA']],
|
||||
[['ADMIN'], ['CACU', 'CAMA', 'TEA']], [[], []],
|
||||
];
|
||||
for (const [roles, allowed] of cases) {
|
||||
it(`evaluates area guards and configured routes for ${JSON.stringify(roles)}`, async () => {
|
||||
const login = TestBed.inject(AuthState).login('demo', 'test-password');
|
||||
http.expectOne('/auth/login').flush({ token: 'test-token', expires_in: 28800, user: { ...user, roles } });
|
||||
await login;
|
||||
for (const area of ['CACU', 'CAMA', 'TEA'] as const) {
|
||||
const result = await run(areaGuard(area));
|
||||
expect(result === true ? true : url(result)).toBe(allowed.includes(area) ? true : '/');
|
||||
const route = routes.find(route => route.path === area.toLowerCase())!;
|
||||
expect(route.data?.['area']).toBe(area);
|
||||
expect(route.component).toBeDefined();
|
||||
expect(route.canActivate?.length).toBe(1);
|
||||
const routed = await run(route.canActivate![0] as typeof authGuard);
|
||||
expect(routed === true ? true : url(routed)).toBe(allowed.includes(area) ? true : '/');
|
||||
}
|
||||
http.expectNone('/auth/me');
|
||||
expect(TestBed.inject(AuthState).isAuthenticated()).toBe(true);
|
||||
});
|
||||
}
|
||||
it('waits for shared restore and uses server roles instead of cached roles', async () => {
|
||||
sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token');
|
||||
sessionStorage.setItem('ISSSTELEON.auth.user', JSON.stringify({ ...user, roles: ['ADMIN'] }));
|
||||
let resolved = false;
|
||||
const cama = Promise.resolve(run(areaGuard('CAMA'))).then(result => { resolved = true; return result; });
|
||||
const cacu = run(areaGuard('CACU')); const home = run(authGuard);
|
||||
await Promise.resolve(); expect(resolved).toBe(false);
|
||||
http.expectOne('/auth/me').flush({ user });
|
||||
expect(await cama).toBe(true); expect(url(await cacu)).toBe('/'); expect(await home).toBe(true);
|
||||
expect(await run(areaGuard('CAMA'))).toBe(true); http.expectNone('/auth/me');
|
||||
});
|
||||
it('rejected restore redirects pending area guards to login', async () => {
|
||||
sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token');
|
||||
const cama = run(areaGuard('CAMA')); const tea = run(areaGuard('TEA'));
|
||||
http.expectOne('/auth/me').flush({}, { status: 401, statusText: 'Unauthorized' });
|
||||
expect(url(await cama)).toBe('/login'); expect(url(await tea)).toBe('/login');
|
||||
});
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
import { AuthState } from './auth.state';
|
||||
import { Area, canAccessArea } from './auth.roles';
|
||||
|
||||
export function areaGuard(area: Area): CanActivateFn {
|
||||
return async () => {
|
||||
const auth = inject(AuthState);
|
||||
const router = inject(Router);
|
||||
await auth.restore();
|
||||
if (!auth.isAuthenticated()) return router.createUrlTree(['/login']);
|
||||
return canAccessArea(auth.user()?.roles ?? [], area) || router.createUrlTree(['/']);
|
||||
};
|
||||
}
|
||||
|
||||
export const authGuard: CanActivateFn = async () => {
|
||||
const auth = inject(AuthState);
|
||||
const router = inject(Router);
|
||||
await auth.restore();
|
||||
return auth.isAuthenticated() || router.createUrlTree(['/login']);
|
||||
};
|
||||
|
||||
export const anonymousGuard: CanActivateFn = async () => {
|
||||
const auth = inject(AuthState);
|
||||
const router = inject(Router);
|
||||
await auth.restore();
|
||||
return !auth.isAuthenticated() || router.createUrlTree(['/']);
|
||||
};
|
||||
@@ -1,17 +0,0 @@
|
||||
export type Role = 'ADMIN' | 'CACU' | 'CAMA' | 'TEA';
|
||||
|
||||
export interface AuthUser {
|
||||
id: number;
|
||||
username: string;
|
||||
roles: Role[];
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
token: string;
|
||||
expires_in: number;
|
||||
user: AuthUser;
|
||||
}
|
||||
|
||||
export interface MeResponse {
|
||||
user: AuthUser;
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import { Role } from './auth.models';
|
||||
import { Area, canAccessArea, getAccessibleAreas } from './auth.roles';
|
||||
|
||||
describe('Area access', () => {
|
||||
const cases: [Role[], Area[]][] = [
|
||||
[[], []],
|
||||
[['CACU'], ['CACU']],
|
||||
[['CAMA'], ['CAMA']],
|
||||
[['TEA'], ['TEA']],
|
||||
[['CACU', 'CAMA'], ['CACU', 'CAMA']],
|
||||
[['CACU', 'TEA'], ['CACU', 'TEA']],
|
||||
[['CAMA', 'TEA'], ['CAMA', 'TEA']],
|
||||
[['CACU', 'CAMA', 'TEA'], ['CACU', 'CAMA', 'TEA']],
|
||||
[['ADMIN'], ['CACU', 'CAMA', 'TEA']],
|
||||
[['ADMIN', 'CAMA'], ['CACU', 'CAMA', 'TEA']],
|
||||
];
|
||||
for (const [roles, allowed] of cases) {
|
||||
it(`evaluates all areas and stable list for ${JSON.stringify(roles)}`, () => {
|
||||
for (const area of ['CACU', 'CAMA', 'TEA'] as const) {
|
||||
expect(canAccessArea(roles, area)).toBe(allowed.includes(area));
|
||||
}
|
||||
expect(getAccessibleAreas(roles)).toEqual(allowed);
|
||||
});
|
||||
}
|
||||
it('keeps canonical order without modifying or duplicating input', () => {
|
||||
const roles: readonly Role[] = Object.freeze(['TEA', 'CAMA', 'CACU', 'CAMA']);
|
||||
expect(getAccessibleAreas(roles)).toEqual(['CACU', 'CAMA', 'TEA']);
|
||||
expect(roles).toEqual(['TEA', 'CAMA', 'CACU', 'CAMA']);
|
||||
});
|
||||
});
|
||||
@@ -1,12 +0,0 @@
|
||||
import { Role } from './auth.models';
|
||||
|
||||
export type Area = 'CACU' | 'CAMA' | 'TEA';
|
||||
|
||||
export function canAccessArea(roles: readonly Role[], area: Area): boolean {
|
||||
return roles.includes('ADMIN') || roles.includes(area);
|
||||
}
|
||||
|
||||
export function getAccessibleAreas(roles: readonly Role[]): Area[] {
|
||||
const areas: Area[] = ['CACU', 'CAMA', 'TEA'];
|
||||
return areas.filter(area => canAccessArea(roles, area));
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('AuthService', () => {
|
||||
let api: AuthService;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
api = TestBed.inject(AuthService);
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => http.verify());
|
||||
it('posts credentials using a relative URL without Bearer', () => {
|
||||
const response = { token: 'test-token', expires_in: 28800, user: { id: 1, username: 'demo', roles: [] } };
|
||||
api.login('demo', 'test-password').subscribe(value => expect(value).toEqual(response));
|
||||
const request = http.expectOne('/auth/login');
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual({ username: 'demo', password: 'test-password' });
|
||||
expect(request.request.headers.has('Authorization')).toBe(false);
|
||||
request.flush(response);
|
||||
});
|
||||
it('gets current identity with explicit Bearer', () => {
|
||||
const response = { user: { id: 1, username: 'demo', roles: ['CAMA'] } };
|
||||
api.me('test-token').subscribe(value => expect(value).toEqual(response));
|
||||
const request = http.expectOne('/auth/me');
|
||||
expect(request.request.method).toBe('GET');
|
||||
expect(request.request.headers.get('Authorization')).toBe('Bearer test-token');
|
||||
request.flush(response);
|
||||
});
|
||||
});
|
||||
@@ -1,18 +0,0 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { LoginResponse, MeResponse } from './auth.models';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AuthService {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
login(username: string, password: string) {
|
||||
return this.http.post<LoginResponse>('/auth/login', { username, password });
|
||||
}
|
||||
|
||||
me(token: string) {
|
||||
return this.http.get<MeResponse>('/auth/me', {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { Router, provideRouter } from '@angular/router';
|
||||
import { vi } from 'vitest';
|
||||
import { AuthState } from './auth.state';
|
||||
import { AuthStorage } from './auth.storage';
|
||||
|
||||
describe('AuthState', () => {
|
||||
const user = { id: 1, username: 'demo', roles: ['CAMA'] };
|
||||
let auth: AuthState;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([])] });
|
||||
auth = TestBed.inject(AuthState); http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => { http.verify(); sessionStorage.clear(); vi.restoreAllMocks(); });
|
||||
const seed = () => sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token');
|
||||
it('starts checking without trusting cache', () => {
|
||||
expect(auth.status()).toBe('checking'); expect(auth.user()).toBeNull(); expect(auth.isAuthenticated()).toBe(false);
|
||||
});
|
||||
it('restores without token without HTTP and clears cached identity', async () => {
|
||||
sessionStorage.setItem('ISSSTELEON.auth.user', JSON.stringify(user));
|
||||
await auth.restore(); expect(auth.status()).toBe('anonymous'); expect(auth.user()).toBeNull();
|
||||
http.expectNone('/auth/me'); expect(TestBed.inject(AuthStorage).readUser()).toBeNull();
|
||||
});
|
||||
it('shares concurrent restore and trusts only the current server identity', async () => {
|
||||
seed(); sessionStorage.setItem('ISSSTELEON.auth.user', JSON.stringify(user));
|
||||
const first = auth.restore(); const second = auth.restore(); expect(first).toBe(second);
|
||||
expect(auth.status()).toBe('checking'); expect(auth.user()).toBeNull();
|
||||
const current = { ...user, roles: ['TEA'] };
|
||||
http.expectOne('/auth/me').flush({ user: current }); await Promise.all([first, second]);
|
||||
expect(auth.isAuthenticated()).toBe(true); expect(auth.user()).toEqual(current);
|
||||
expect(TestBed.inject(AuthStorage).readUser()).toEqual(current);
|
||||
expect(TestBed.inject(AuthStorage).readToken()).toBe('test-token');
|
||||
await auth.restore(); http.expectNone('/auth/me');
|
||||
});
|
||||
for (const status of [401, 500, 0]) {
|
||||
it(`clears session on restore error ${status}`, async () => {
|
||||
seed(); const pending = auth.restore();
|
||||
const request = http.expectOne('/auth/me');
|
||||
if (status === 0) request.error(new ProgressEvent('error'));
|
||||
else request.flush({}, { status, statusText: 'Rejected' });
|
||||
await pending; expect(auth.status()).toBe('anonymous'); expect(auth.user()).toBeNull();
|
||||
expect(TestBed.inject(AuthStorage).readToken()).toBeNull();
|
||||
});
|
||||
}
|
||||
it('login saves identity and local logout clears it and navigates', async () => {
|
||||
const navigate = vi.spyOn(TestBed.inject(Router), 'navigateByUrl').mockResolvedValue(true);
|
||||
const pending = auth.login('demo', 'test-password');
|
||||
http.expectOne('/auth/login').flush({ token: 'test-token', expires_in: 28800, user }); await pending;
|
||||
expect(auth.isAuthenticated()).toBe(true); expect(auth.user()).toEqual(user);
|
||||
expect(TestBed.inject(AuthStorage).readToken()).toBe('test-token');
|
||||
expect(TestBed.inject(AuthStorage).readUser()).toEqual(user);
|
||||
auth.logout(); expect(auth.status()).toBe('anonymous'); expect(auth.user()).toBeNull();
|
||||
expect(TestBed.inject(AuthStorage).readToken()).toBeNull(); expect(navigate).toHaveBeenCalledWith('/login');
|
||||
await auth.restore(); http.expectNone('/auth/me');
|
||||
});
|
||||
it('failed login remains anonymous', async () => {
|
||||
const pending = auth.login('demo', 'test-password');
|
||||
const assertion = expect(pending).rejects.toMatchObject({ status: 401 });
|
||||
http.expectOne('/auth/login').flush({}, { status: 401, statusText: 'Unauthorized' });
|
||||
await assertion; expect(auth.status()).toBe('anonymous'); expect(auth.user()).toBeNull();
|
||||
});
|
||||
it('late restore cannot undo logout', async () => {
|
||||
vi.spyOn(TestBed.inject(Router), 'navigateByUrl').mockResolvedValue(true);
|
||||
seed(); const pending = auth.restore(); auth.logout();
|
||||
http.expectOne('/auth/me').flush({ user }); await pending;
|
||||
expect(auth.status()).toBe('anonymous'); expect(TestBed.inject(AuthStorage).readToken()).toBeNull();
|
||||
});
|
||||
it('late restore cannot overwrite a new login', async () => {
|
||||
seed(); const restoring = auth.restore(); const login = auth.login('demo', 'test-password');
|
||||
const current = { ...user, roles: ['ADMIN'] };
|
||||
http.expectOne('/auth/login').flush({ token: 'new-test-token', expires_in: 28800, user: current });
|
||||
await login; http.expectOne('/auth/me').flush({ user }); await restoring;
|
||||
expect(auth.user()).toEqual(current); expect(TestBed.inject(AuthStorage).readToken()).toBe('new-test-token');
|
||||
});
|
||||
});
|
||||
@@ -1,77 +0,0 @@
|
||||
import { computed, inject, Injectable, signal } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { AuthUser } from './auth.models';
|
||||
import { AuthService } from './auth.service';
|
||||
import { AuthStorage } from './auth.storage';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AuthState {
|
||||
private readonly api = inject(AuthService);
|
||||
private readonly storage = inject(AuthStorage);
|
||||
private readonly router = inject(Router);
|
||||
private readonly currentUser = signal<AuthUser | null>(null);
|
||||
private readonly token = signal<string | null>(null);
|
||||
private readonly currentStatus = signal<'checking' | 'authenticated' | 'anonymous'>('checking');
|
||||
readonly user = this.currentUser.asReadonly();
|
||||
readonly status = this.currentStatus.asReadonly();
|
||||
readonly isAuthenticated = computed(() => this.status() === 'authenticated');
|
||||
private restoration?: Promise<void>;
|
||||
private generation = 0;
|
||||
|
||||
restore(): Promise<void> {
|
||||
if (this.restoration) return this.restoration;
|
||||
if (this.status() !== 'checking') return Promise.resolve();
|
||||
const token = this.storage.readToken();
|
||||
if (!token) {
|
||||
this.clear();
|
||||
return Promise.resolve();
|
||||
}
|
||||
const generation = this.generation;
|
||||
const pending = this.validate(token, generation);
|
||||
this.restoration = pending;
|
||||
void pending.finally(() => {
|
||||
if (this.restoration === pending) this.restoration = undefined;
|
||||
});
|
||||
return pending;
|
||||
}
|
||||
|
||||
private async validate(token: string, generation: number): Promise<void> {
|
||||
try {
|
||||
const response = await firstValueFrom(this.api.me(token));
|
||||
if (generation !== this.generation) return;
|
||||
this.token.set(token);
|
||||
this.currentUser.set(response.user);
|
||||
this.storage.updateUser(response.user);
|
||||
this.currentStatus.set('authenticated');
|
||||
} catch {
|
||||
if (generation === this.generation) this.clear();
|
||||
}
|
||||
}
|
||||
|
||||
async login(username: string, password: string): Promise<void> {
|
||||
const generation = ++this.generation;
|
||||
this.restoration = undefined;
|
||||
this.clear();
|
||||
const response = await firstValueFrom(this.api.login(username, password));
|
||||
if (generation !== this.generation) return;
|
||||
this.token.set(response.token);
|
||||
this.currentUser.set(response.user);
|
||||
this.storage.save(response.token, response.user);
|
||||
this.currentStatus.set('authenticated');
|
||||
}
|
||||
|
||||
logout(): void {
|
||||
++this.generation;
|
||||
this.restoration = undefined;
|
||||
this.clear();
|
||||
void this.router.navigateByUrl('/login');
|
||||
}
|
||||
|
||||
private clear(): void {
|
||||
this.token.set(null);
|
||||
this.currentUser.set(null);
|
||||
this.storage.clear();
|
||||
this.currentStatus.set('anonymous');
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import { AuthStorage } from './auth.storage';
|
||||
import { vi } from 'vitest';
|
||||
|
||||
describe('AuthStorage', () => {
|
||||
const user = { id: 1, username: 'demo', roles: ['CAMA'] as const };
|
||||
let storage: AuthStorage;
|
||||
beforeEach(() => { sessionStorage.clear(); storage = new AuthStorage(); });
|
||||
afterEach(() => { vi.restoreAllMocks(); sessionStorage.clear(); });
|
||||
it('reads empty storage safely', () => {
|
||||
expect(storage.readToken()).toBeNull(); expect(storage.readUser()).toBeNull();
|
||||
});
|
||||
it('saves and clears the tab session', () => {
|
||||
storage.save('test-token', { ...user, roles: ['CAMA'] });
|
||||
expect(storage.readToken()).toBe('test-token'); expect(storage.readUser()).toEqual(user);
|
||||
storage.updateUser({ ...user, roles: ['ADMIN'] });
|
||||
expect(storage.readUser()?.roles).toEqual(['ADMIN']);
|
||||
storage.clear(); expect(storage.readToken()).toBeNull(); expect(storage.readUser()).toBeNull();
|
||||
});
|
||||
it('ignores malformed JSON and invalid cache shapes', () => {
|
||||
for (const value of ['{', '123', '{"id":1}', '{"id":1,"username":"demo","roles":["OTHER"]}']) {
|
||||
sessionStorage.setItem('ISSSTELEON.auth.user', value);
|
||||
expect(storage.readUser()).toBeNull();
|
||||
}
|
||||
});
|
||||
it('tolerates unavailable sessionStorage', () => {
|
||||
vi.spyOn(window, 'sessionStorage', 'get').mockImplementation(() => { throw new Error('disabled'); });
|
||||
expect(storage.readToken()).toBeNull(); expect(storage.readUser()).toBeNull();
|
||||
expect(() => storage.save('test-token', { ...user, roles: ['CAMA'] })).not.toThrow();
|
||||
expect(() => storage.updateUser({ ...user, roles: ['CAMA'] })).not.toThrow();
|
||||
expect(() => storage.clear()).not.toThrow();
|
||||
});
|
||||
it('tolerates read, write and removal failures', () => {
|
||||
vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new Error('read'); });
|
||||
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('write'); });
|
||||
vi.spyOn(Storage.prototype, 'removeItem').mockImplementation(() => { throw new Error('remove'); });
|
||||
expect(storage.readToken()).toBeNull(); expect(storage.readUser()).toBeNull();
|
||||
expect(() => storage.save('test-token', { ...user, roles: ['CAMA'] })).not.toThrow();
|
||||
expect(() => storage.clear()).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,41 +0,0 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { AuthUser } from './auth.models';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AuthStorage {
|
||||
private readonly tokenKey = 'ISSSTELEON.auth.token';
|
||||
private readonly userKey = 'ISSSTELEON.auth.user';
|
||||
|
||||
readToken(): string | null {
|
||||
try { return sessionStorage.getItem(this.tokenKey); } catch { return null; }
|
||||
}
|
||||
|
||||
readUser(): AuthUser | null {
|
||||
try {
|
||||
const value: unknown = JSON.parse(sessionStorage.getItem(this.userKey) ?? 'null');
|
||||
if (typeof value !== 'object' || value === null) return null;
|
||||
const user = value as AuthUser;
|
||||
return typeof user.id === 'number' && typeof user.username === 'string' &&
|
||||
Array.isArray(user.roles) && user.roles.every(role =>
|
||||
['ADMIN', 'CACU', 'CAMA', 'TEA'].includes(role)) ? user : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
save(token: string, user: AuthUser): void {
|
||||
try {
|
||||
sessionStorage.setItem(this.tokenKey, token);
|
||||
sessionStorage.setItem(this.userKey, JSON.stringify(user));
|
||||
} catch { this.clear(); }
|
||||
}
|
||||
|
||||
updateUser(user: AuthUser): void {
|
||||
try { sessionStorage.setItem(this.userKey, JSON.stringify(user)); } catch { this.clear(); }
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
// Attempt both removals even if one storage operation fails.
|
||||
for (const key of [this.tokenKey, this.userKey]) {
|
||||
try { sessionStorage.removeItem(key); } catch { /* Storage may be disabled. */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import { signal } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { AuthUser, Role } from './auth.models';
|
||||
import { AuthState } from './auth.state';
|
||||
import { Home } from './home';
|
||||
|
||||
describe('Home areas', () => {
|
||||
const user = signal<AuthUser>({ id: 1, username: 'demo', roles: [] });
|
||||
beforeEach(() => {
|
||||
user.set({ id: 1, username: 'demo', roles: [] });
|
||||
TestBed.configureTestingModule({ imports: [Home], providers: [
|
||||
provideRouter([]), { provide: AuthState, useValue: { user } },
|
||||
] });
|
||||
});
|
||||
const cases: [Role[], string[]][] = [
|
||||
[['CAMA'], ['CAMA']], [['CACU', 'CAMA'], ['CACU', 'CAMA']],
|
||||
[['ADMIN'], ['CACU', 'CAMA', 'TEA']], [[], []],
|
||||
];
|
||||
for (const [roles, areas] of cases) {
|
||||
it(`renders only authorized links for ${JSON.stringify(roles)}`, () => {
|
||||
user.set({ id: 1, username: 'demo', roles });
|
||||
const fixture = TestBed.createComponent(Home); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
const links = Array.from(root.querySelectorAll('a'));
|
||||
expect(links.map(link => link.textContent?.trim())).toEqual(areas);
|
||||
expect(links.map(link => link.getAttribute('href'))).toEqual(areas.map(area => '/' + area.toLowerCase()));
|
||||
expect(root.querySelector('[role="status"]')?.textContent ?? null)
|
||||
.toBe(areas.length ? null : 'No tienes áreas asignadas.');
|
||||
});
|
||||
}
|
||||
it('updates navigation from current AuthState roles', () => {
|
||||
user.set({ id: 1, username: 'demo', roles: ['ADMIN'] });
|
||||
const fixture = TestBed.createComponent(Home); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelectorAll('a').length).toBe(3);
|
||||
user.set({ id: 1, username: 'demo', roles: ['TEA'] }); fixture.detectChanges();
|
||||
expect(Array.from(fixture.nativeElement.querySelectorAll('a') as NodeListOf<HTMLAnchorElement>)
|
||||
.map(link => link.textContent?.trim())).toEqual(['TEA']);
|
||||
});
|
||||
});
|
||||
@@ -1,25 +0,0 @@
|
||||
import { Component, computed, inject } from '@angular/core';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { AuthState } from './auth.state';
|
||||
import { getAccessibleAreas } from './auth.roles';
|
||||
|
||||
@Component({
|
||||
selector: 'app-home',
|
||||
imports: [RouterLink, MatButtonModule],
|
||||
template: `
|
||||
<h1>Áreas disponibles</h1>
|
||||
<nav aria-label="Áreas disponibles">
|
||||
@for (area of areas(); track area) {
|
||||
<a mat-stroked-button [routerLink]="'/' + area.toLowerCase()">{{ area }}</a>
|
||||
} @empty {
|
||||
<p role="status">No tienes áreas asignadas.</p>
|
||||
}
|
||||
</nav>
|
||||
`,
|
||||
styles: `nav { display: flex; flex-wrap: wrap; gap: 1rem; }`,
|
||||
})
|
||||
export class Home {
|
||||
private readonly auth = inject(AuthState);
|
||||
protected readonly areas = computed(() => getAccessibleAreas(this.auth.user()?.roles ?? []));
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
<section class="login" aria-labelledby="login-title" lang="es">
|
||||
<h1 id="login-title">Inicio de sesión</h1>
|
||||
<form [formGroup]="form" (ngSubmit)="submit()" [attr.aria-busy]="loading()">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="login-field">
|
||||
<mat-label>Usuario</mat-label>
|
||||
<input matInput formControlName="username" autocomplete="username" maxlength="64"
|
||||
[errorStateMatcher]="usernameErrorMatcher"
|
||||
(focus)="usernameEditing.set(true)" (blur)="usernameEditing.set(false)" />
|
||||
@if (showUsernameError()) { <mat-error>Ingresa un usuario válido.</mat-error> }
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="login-field">
|
||||
<mat-label>Contraseña</mat-label>
|
||||
<input matInput [type]="passwordVisible() ? 'text' : 'password'" formControlName="password"
|
||||
autocomplete="current-password" maxlength="128" [errorStateMatcher]="passwordErrorMatcher"
|
||||
(focus)="passwordEditing.set(true)" (blur)="passwordEditing.set(false)" />
|
||||
<button mat-icon-button matSuffix type="button" class="password-toggle"
|
||||
(click)="$event.stopPropagation(); passwordVisible.set(!passwordVisible())"
|
||||
[attr.aria-label]="passwordVisible() ? 'Ocultar contraseña' : 'Mostrar contraseña'"
|
||||
[attr.aria-pressed]="passwordVisible()">
|
||||
<mat-icon aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" focusable="false" aria-hidden="true">
|
||||
<path d="M12 6c4.2 0 7.5 3.1 9 6-1.5 2.9-4.8 6-9 6s-7.5-3.1-9-6c1.5-2.9 4.8-6 9-6Z" />
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
@if (passwordVisible()) { <path d="m3 3 18 18" /> }
|
||||
</svg>
|
||||
</mat-icon>
|
||||
</button>
|
||||
@if (showPasswordError()) { <mat-error>Ingresa tu contraseña.</mat-error> }
|
||||
</mat-form-field>
|
||||
<button mat-flat-button class="login-action" type="submit" [disabled]="loading()">
|
||||
{{ loading() ? 'Iniciando sesión…' : 'Iniciar sesión' }}
|
||||
</button>
|
||||
<div class="login-feedback">
|
||||
@if (error()) { <p role="alert">{{ error() }}</p> }
|
||||
@if (loading()) { <p role="status">Comprobando credenciales…</p> }
|
||||
</div>
|
||||
</form>
|
||||
<img class="login-logo" src="branding/LogoISSSTELEON.png" alt="ISSSTELEON" width="1125" height="358" />
|
||||
</section>
|
||||
@@ -1,120 +0,0 @@
|
||||
@use '@angular/material' as mat;
|
||||
|
||||
:host {
|
||||
--login-page-bg: #f7f7f7;
|
||||
--login-surface: #ffffff;
|
||||
--login-text: #333333;
|
||||
--login-text-muted: #667085;
|
||||
--login-border: #cccccc;
|
||||
--login-focus: #00833c;
|
||||
--isssteleon-lime: #99ca3c;
|
||||
--isssteleon-green: #00833c;
|
||||
--login-icon-teal: #5f9ea0;
|
||||
--login-action-bg: #f8f9fa;
|
||||
--login-action-border: #e9ecef;
|
||||
|
||||
display: grid;
|
||||
box-sizing: border-box;
|
||||
min-height: 100dvh;
|
||||
margin: -1.5rem; // Compensate the existing main padding only while Login is mounted.
|
||||
padding: 2rem 24px;
|
||||
place-items: center;
|
||||
background: var(--login-page-bg);
|
||||
color: var(--login-text);
|
||||
font-family: Roboto, Arial, sans-serif;
|
||||
}
|
||||
|
||||
.login { width: min(100%, 26rem); min-width: 0; }
|
||||
|
||||
h1 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
margin: 0 0 2rem;
|
||||
font-size: 1.5rem;
|
||||
font-weight: 500;
|
||||
line-height: 1.3;
|
||||
white-space: nowrap;
|
||||
|
||||
&::before, &::after {
|
||||
content: '';
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
border-top: 1px solid var(--login-border);
|
||||
}
|
||||
}
|
||||
|
||||
form { display: flex; flex-direction: column; gap: .75rem; }
|
||||
|
||||
.login-field {
|
||||
width: 100%;
|
||||
position: relative;
|
||||
isolation: isolate;
|
||||
@include mat.form-field-overrides((
|
||||
outlined-container-shape: 5px,
|
||||
outlined-outline-color: var(--login-border),
|
||||
outlined-hover-outline-color: var(--login-text-muted),
|
||||
outlined-focus-outline-color: var(--login-focus),
|
||||
outlined-focus-label-text-color: var(--login-focus),
|
||||
outlined-label-text-color: var(--login-text-muted),
|
||||
outlined-input-text-color: var(--login-text),
|
||||
outlined-caret-color: var(--login-focus),
|
||||
container-text-size: 16px,
|
||||
));
|
||||
// Keep the validation subscript on the page background.
|
||||
&::before { content: ''; position: absolute; inset: 0 0 auto; height: 56px;
|
||||
background: var(--login-surface); border-radius: 5px; z-index: -1; }
|
||||
}
|
||||
|
||||
.password-toggle {
|
||||
color: var(--login-text-muted);
|
||||
margin-inline-end: 4px;
|
||||
min-width: 48px;
|
||||
min-height: 48px;
|
||||
svg { width: 24px; height: 24px; fill: none; stroke: currentColor; stroke-width: 1.8; }
|
||||
}
|
||||
|
||||
.login-action.mat-mdc-unelevated-button {
|
||||
@include mat.button-overrides((
|
||||
filled-container-color: var(--login-action-bg),
|
||||
filled-label-text-color: var(--login-text),
|
||||
filled-container-shape: 8px,
|
||||
filled-container-height: 50px,
|
||||
filled-label-text-size: 16px,
|
||||
filled-label-text-weight: 500,
|
||||
filled-state-layer-color: var(--login-focus),
|
||||
filled-disabled-container-color: #e9ecef,
|
||||
filled-disabled-label-text-color: #707780,
|
||||
));
|
||||
width: 100%;
|
||||
min-height: 50px;
|
||||
border: 1px solid var(--login-action-border);
|
||||
border-radius: 8px;
|
||||
background: var(--login-action-bg);
|
||||
color: var(--login-text);
|
||||
font: 500 16px Roboto, Arial, sans-serif;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 1px 2px #00000014;
|
||||
transition: transform 160ms cubic-bezier(.2, 0, 0, 1), background-color 160ms ease,
|
||||
border-color 160ms ease, box-shadow 160ms ease;
|
||||
&:hover:not(:disabled) {
|
||||
transform: translateY(-1px);
|
||||
background: #eef2ed;
|
||||
border-color: var(--login-focus);
|
||||
box-shadow: 0 3px 7px #0000001c;
|
||||
}
|
||||
&:active:not(:disabled) { transform: translateY(0) scale(.99); background: #e4ebdf; box-shadow: none; }
|
||||
&:disabled { transform: none; transition: none; background: #e9ecef; color: #707780; box-shadow: none; cursor: default; }
|
||||
}
|
||||
|
||||
button:focus-visible { outline: 2px solid var(--login-focus); outline-offset: 3px; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.login-action.mat-mdc-unelevated-button {
|
||||
transition: none;
|
||||
&:hover:not(:disabled), &:active:not(:disabled) { transform: none; }
|
||||
}
|
||||
}
|
||||
.login-feedback { min-height: 2.5rem; font-size: .875rem; line-height: 1.4; }
|
||||
[role='alert'] { color: var(--mat-sys-error); margin: 0; }
|
||||
[role='status'] { color: var(--login-text-muted); margin: 0; }
|
||||
.login-logo { display: block; width: min(100%, clamp(200px, 17vw, 240px)); height: auto; object-fit: contain; margin: 1.5rem auto 0; }
|
||||
@@ -1,139 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { Router, provideRouter } from '@angular/router';
|
||||
import { vi } from 'vitest';
|
||||
import { AuthState } from './auth.state';
|
||||
import { Login } from './login';
|
||||
|
||||
describe('Login', () => {
|
||||
let login: ReturnType<typeof vi.fn>;
|
||||
beforeEach(() => {
|
||||
login = vi.fn().mockResolvedValue(undefined);
|
||||
TestBed.configureTestingModule({ imports: [Login], providers: [provideRouter([]),
|
||||
{ provide: AuthState, useValue: { login, isAuthenticated: () => true } }] });
|
||||
vi.spyOn(TestBed.inject(Router), 'navigateByUrl').mockResolvedValue(true);
|
||||
});
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
const create = () => {
|
||||
const fixture = TestBed.createComponent(Login); fixture.detectChanges(); return fixture;
|
||||
};
|
||||
const fill = (component: Login) => component.form.setValue({ username: 'Demo', password: 'test-password' });
|
||||
const usernameInput = (fixture: ReturnType<typeof TestBed.createComponent<Login>>) =>
|
||||
fixture.nativeElement.querySelector('input[autocomplete="username"]') as HTMLInputElement;
|
||||
const hasUsernameError = (fixture: { nativeElement: HTMLElement }) =>
|
||||
!!fixture.nativeElement.querySelector('mat-error');
|
||||
it('renders required credentials and submit button', () => {
|
||||
const fixture = create(); const element: HTMLElement = fixture.nativeElement;
|
||||
expect(element.querySelector('input[autocomplete="username"]')).toBeTruthy();
|
||||
expect(element.querySelector('input[type="password"]')).toBeTruthy();
|
||||
expect(element.querySelector('button[type="submit"]')?.textContent).toContain('Iniciar sesión');
|
||||
expect(fixture.componentInstance.form.invalid).toBe(true);
|
||||
});
|
||||
it('rejects empty and invalid credentials', async () => {
|
||||
const component = create().componentInstance; await component.submit(); expect(login).not.toHaveBeenCalled();
|
||||
for (const username of ['ab', 'a'.repeat(65), 'demo@']) {
|
||||
component.form.setValue({ username, password: 'test-password' }); expect(component.form.invalid).toBe(true);
|
||||
}
|
||||
component.form.setValue({ username: 'demo', password: 'a'.repeat(129) }); expect(component.form.invalid).toBe(true);
|
||||
});
|
||||
it('shows the username error after blur, hides it while editing, and restores it on blur if still invalid', () => {
|
||||
const fixture = create(); const input = usernameInput(fixture); const control = fixture.componentInstance.form.controls.username;
|
||||
input.dispatchEvent(new Event('focus')); input.dispatchEvent(new Event('blur')); fixture.detectChanges();
|
||||
expect(control.invalid).toBe(true);
|
||||
expect(hasUsernameError(fixture)).toBe(true);
|
||||
expect(input.closest('mat-form-field')?.classList.contains('mat-form-field-invalid')).toBe(true);
|
||||
input.dispatchEvent(new Event('focus')); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.usernameEditing()).toBe(true);
|
||||
expect(hasUsernameError(fixture)).toBe(false);
|
||||
expect(input.closest('mat-form-field')?.classList.contains('mat-form-field-invalid')).toBe(false);
|
||||
input.dispatchEvent(new Event('input')); input.dispatchEvent(new Event('blur')); fixture.detectChanges();
|
||||
expect(hasUsernameError(fixture)).toBe(true);
|
||||
expect(input.closest('mat-form-field')?.classList.contains('mat-form-field-invalid')).toBe(true);
|
||||
});
|
||||
it('keeps the username error cleared after editing to a valid value', () => {
|
||||
const fixture = create(); const input = usernameInput(fixture); const control = fixture.componentInstance.form.controls.username;
|
||||
input.dispatchEvent(new Event('focus')); input.dispatchEvent(new Event('blur')); fixture.detectChanges();
|
||||
expect(hasUsernameError(fixture)).toBe(true);
|
||||
input.dispatchEvent(new Event('focus'));
|
||||
input.value = 'valid-user'; input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
input.dispatchEvent(new Event('blur')); fixture.detectChanges();
|
||||
expect(control.valid).toBe(true);
|
||||
expect(hasUsernameError(fixture)).toBe(false);
|
||||
});
|
||||
it('shows field errors on invalid submit and suppresses them once editing starts', async () => {
|
||||
const fixture = create(); const component = fixture.componentInstance;
|
||||
await component.submit(); fixture.detectChanges();
|
||||
expect(component.submitted()).toBe(true);
|
||||
expect(fixture.nativeElement.querySelectorAll('mat-error').length).toBe(2);
|
||||
const input = usernameInput(fixture); input.dispatchEvent(new Event('focus')); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelectorAll('mat-error').length).toBe(1);
|
||||
expect(component.form.controls.username.invalid).toBe(true);
|
||||
});
|
||||
it('uses dynamic subscripts for both fields', () => {
|
||||
const fixture = create();
|
||||
expect(fixture.nativeElement.querySelectorAll('mat-form-field[subscriptsizing="dynamic"]').length).toBe(2);
|
||||
});
|
||||
it('submits normalized credentials, clears password and navigates home', async () => {
|
||||
const component = create().componentInstance; fill(component); await component.submit();
|
||||
expect(login).toHaveBeenCalledWith('demo', 'test-password');
|
||||
expect(TestBed.inject(Router).navigateByUrl).toHaveBeenCalledWith('/');
|
||||
expect(component.form.controls.password.value).toBe(''); expect(component.loading()).toBe(false);
|
||||
});
|
||||
it('shows loading and prevents duplicate submissions', async () => {
|
||||
let resolve!: () => void;
|
||||
login.mockReturnValue(new Promise<void>(done => { resolve = done; }));
|
||||
const fixture = create(); const component = fixture.componentInstance; fill(component);
|
||||
const pending = component.submit(); fixture.detectChanges();
|
||||
expect(component.loading()).toBe(true);
|
||||
expect((fixture.nativeElement.querySelector('button[type="submit"]') as HTMLButtonElement).disabled).toBe(true);
|
||||
expect(fixture.nativeElement.querySelector('[role="status"]')).toBeTruthy();
|
||||
await component.submit(); expect(login).toHaveBeenCalledTimes(1); resolve(); await pending;
|
||||
});
|
||||
it('starts with the password hidden and an accessible unpressed toggle', () => {
|
||||
const fixture = create();
|
||||
const element: HTMLElement = fixture.nativeElement;
|
||||
const toggle = element.querySelector('.password-toggle') as HTMLButtonElement;
|
||||
expect(element.querySelector('input[autocomplete="current-password"]')?.getAttribute('type')).toBe('password');
|
||||
expect(toggle.type).toBe('button');
|
||||
expect(toggle.getAttribute('aria-label')).toBe('Mostrar contraseña');
|
||||
expect(toggle.getAttribute('aria-pressed')).toBe('false');
|
||||
});
|
||||
it('shows and hides the password with matching aria states without submitting', () => {
|
||||
const fixture = create(); fill(fixture.componentInstance);
|
||||
const element: HTMLElement = fixture.nativeElement;
|
||||
const toggle = element.querySelector('.password-toggle') as HTMLButtonElement;
|
||||
toggle.click(); fixture.detectChanges();
|
||||
expect(element.querySelector('input[autocomplete="current-password"]')?.getAttribute('type')).toBe('text');
|
||||
expect(toggle.getAttribute('aria-label')).toBe('Ocultar contraseña');
|
||||
expect(toggle.getAttribute('aria-pressed')).toBe('true');
|
||||
expect(login).not.toHaveBeenCalled();
|
||||
toggle.click(); fixture.detectChanges();
|
||||
expect(element.querySelector('input[autocomplete="current-password"]')?.getAttribute('type')).toBe('password');
|
||||
expect(toggle.getAttribute('aria-label')).toBe('Mostrar contraseña');
|
||||
expect(toggle.getAttribute('aria-pressed')).toBe('false');
|
||||
expect(login).not.toHaveBeenCalled();
|
||||
expect(fixture.componentInstance.form.controls.password.value).toBe('test-password');
|
||||
});
|
||||
it('submits the unchanged password while it is visible', async () => {
|
||||
const fixture = create(); fill(fixture.componentInstance);
|
||||
(fixture.nativeElement.querySelector('.password-toggle') as HTMLButtonElement).click();
|
||||
fixture.detectChanges();
|
||||
fixture.nativeElement.querySelector('form').dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
|
||||
await fixture.whenStable();
|
||||
expect(login).toHaveBeenCalledExactlyOnceWith('demo', 'test-password');
|
||||
expect(TestBed.inject(Router).navigateByUrl).toHaveBeenCalledWith('/');
|
||||
expect(fixture.componentInstance.form.controls.password.value).toBe('');
|
||||
});
|
||||
for (const status of [401, 500, 0, 404]) {
|
||||
it(`shows generic error for ${status}`, async () => {
|
||||
login.mockRejectedValue(new HttpErrorResponse({ status, error: 'PRIVATE TECHNICAL BODY' }));
|
||||
const fixture = create(); const component = fixture.componentInstance; fill(component); await component.submit();
|
||||
fixture.detectChanges();
|
||||
expect(component.error()).toBe(status === 401 ? 'Usuario o contraseña incorrectos.'
|
||||
: 'No fue posible iniciar sesión. Inténtalo de nuevo.');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('PRIVATE TECHNICAL BODY');
|
||||
expect(TestBed.inject(Router).navigateByUrl).not.toHaveBeenCalled();
|
||||
expect(component.loading()).toBe(false); expect(component.form.controls.password.value).toBe('');
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -1,73 +0,0 @@
|
||||
import { Component, inject, signal } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { FormBuilder, FormGroupDirective, NgForm, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||
import { ErrorStateMatcher } from '@angular/material/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { AuthState } from './auth.state';
|
||||
|
||||
class LoginFieldErrorStateMatcher implements ErrorStateMatcher {
|
||||
constructor(private readonly isEditing: () => boolean) {}
|
||||
|
||||
isErrorState(control: { invalid: boolean; touched: boolean } | null, form: FormGroupDirective | NgForm | null): boolean {
|
||||
return !!control?.invalid && (control.touched || !!form?.submitted) && !this.isEditing();
|
||||
}
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-login',
|
||||
imports: [ReactiveFormsModule, MatIconModule, MatFormFieldModule, MatInputModule, MatButtonModule],
|
||||
templateUrl: './login.html',
|
||||
styleUrl: './login.scss',
|
||||
})
|
||||
export class Login {
|
||||
private readonly auth = inject(AuthState);
|
||||
private readonly router = inject(Router);
|
||||
readonly loading = signal(false);
|
||||
readonly error = signal('');
|
||||
readonly passwordVisible = signal(false);
|
||||
readonly submitted = signal(false);
|
||||
readonly usernameEditing = signal(false);
|
||||
readonly passwordEditing = signal(false);
|
||||
readonly usernameErrorMatcher = new LoginFieldErrorStateMatcher(() => this.usernameEditing());
|
||||
readonly passwordErrorMatcher = new LoginFieldErrorStateMatcher(() => this.passwordEditing());
|
||||
readonly form = inject(FormBuilder).nonNullable.group({
|
||||
username: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(64),
|
||||
Validators.pattern(/^[a-zA-Z0-9._-]+$/)]],
|
||||
password: ['', [Validators.required, Validators.maxLength(128)]],
|
||||
});
|
||||
|
||||
showUsernameError(): boolean {
|
||||
return this.form.controls.username.invalid && (this.form.controls.username.touched || this.submitted())
|
||||
&& !this.usernameEditing();
|
||||
}
|
||||
|
||||
showPasswordError(): boolean {
|
||||
return this.form.controls.password.invalid && (this.form.controls.password.touched || this.submitted())
|
||||
&& !this.passwordEditing();
|
||||
}
|
||||
|
||||
async submit(): Promise<void> {
|
||||
if (this.loading()) return;
|
||||
this.submitted.set(true);
|
||||
if (this.form.invalid) { this.form.markAllAsTouched(); return; }
|
||||
this.loading.set(true);
|
||||
this.error.set('');
|
||||
const { username, password } = this.form.getRawValue();
|
||||
try {
|
||||
await this.auth.login(username.trim().toLowerCase(), password);
|
||||
this.form.controls.password.reset();
|
||||
if (this.auth.isAuthenticated()) await this.router.navigateByUrl('/');
|
||||
} catch (error) {
|
||||
this.form.controls.password.reset();
|
||||
this.error.set(error instanceof HttpErrorResponse && error.status === 401
|
||||
? 'Usuario o contraseña incorrectos.'
|
||||
: 'No fue posible iniciar sesión. Inténtalo de nuevo.');
|
||||
} finally {
|
||||
this.loading.set(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<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>
|
||||
@@ -0,0 +1,29 @@
|
||||
: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); }
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
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: {} });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
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));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
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;
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
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(); }
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
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 });
|
||||
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
declare module 'plotly.js-cartesian-dist-min';
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
<title>WebApp</title>
|
||||
<base href="/" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" type="image/png" href="branding/favicon-isssteleon.png" />
|
||||
<link rel="icon" type="image/x-icon" href="favicon.ico" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
|
||||
Reference in New Issue
Block a user