feat(frontend): affiche les prévisions de consommation sur le dashboard
This commit is contained in:
@@ -64,4 +64,13 @@ describe('mockApiInterceptor', () => {
|
||||
httpMock.expectNone(`${environment.apiUrl}/alerts`);
|
||||
expect((result as unknown[]).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('laisse toujours passer /predictions vers le réseau, même avec useMockFixtures activé', () => {
|
||||
environment.useMockFixtures = true;
|
||||
|
||||
http.get(`${environment.apiUrl}/predictions`).subscribe();
|
||||
|
||||
const req = httpMock.expectOne(`${environment.apiUrl}/predictions`);
|
||||
req.flush({ timestamp: '2026-09-18T09:00:00Z', sites: [] });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -26,5 +26,7 @@ export const mockApiInterceptor: HttpInterceptorFn = (req, next) => {
|
||||
if (req.url.endsWith(`${environment.apiUrl}/alerts`)) {
|
||||
return of(new HttpResponse({ status: 200, body: ALERTS_FIXTURE }));
|
||||
}
|
||||
// Volontairement jamais mocké, contrairement à `stats`/`alerts` : les prévisions sont servies
|
||||
// par l'API réelle dès maintenant (au même titre que `/auth/*`, déjà toujours réel).
|
||||
return next(req);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { PredictionSummary } from '../../shared/models/prediction.model';
|
||||
|
||||
export const PREDICTIONS_FIXTURE: PredictionSummary = {
|
||||
timestamp: '2026-09-18T09:00:00Z',
|
||||
sites: [
|
||||
{
|
||||
site_id: 'SITE001',
|
||||
site_name: 'Bureau Paris La Défense',
|
||||
prediction: {
|
||||
target_at: '2026-09-18T10:00:00Z',
|
||||
target_metric: 'consumption_kwh',
|
||||
period_minutes: 60,
|
||||
predicted_value: 89.2,
|
||||
status: 'available',
|
||||
failure_reason: null,
|
||||
model_reference: 'lightgbm-16b431449a50',
|
||||
created_at: '2026-09-18T09:00:00Z',
|
||||
},
|
||||
},
|
||||
{
|
||||
site_id: 'SITE002',
|
||||
site_name: 'Usine Lyon Vénissieux',
|
||||
prediction: {
|
||||
target_at: '2026-09-18T10:00:00Z',
|
||||
target_metric: 'consumption_kwh',
|
||||
period_minutes: 60,
|
||||
predicted_value: 561.4,
|
||||
status: 'available',
|
||||
failure_reason: null,
|
||||
model_reference: 'lightgbm-16b431449a50',
|
||||
created_at: '2026-09-18T09:00:00Z',
|
||||
},
|
||||
},
|
||||
{
|
||||
site_id: 'SITE003',
|
||||
site_name: 'Data Center Marseille',
|
||||
prediction: {
|
||||
target_at: '2026-09-18T10:00:00Z',
|
||||
target_metric: 'consumption_kwh',
|
||||
period_minutes: 60,
|
||||
predicted_value: null,
|
||||
status: 'insufficient_data',
|
||||
failure_reason:
|
||||
"Historique insuffisant : moins de 168h de consumption_kwh disponibles pour ce site.",
|
||||
model_reference: 'lightgbm-16b431449a50',
|
||||
created_at: '2026-09-18T09:00:00Z',
|
||||
},
|
||||
},
|
||||
{
|
||||
site_id: 'SITE004',
|
||||
site_name: 'Bureau Bordeaux',
|
||||
prediction: {
|
||||
target_at: '2026-09-18T10:00:00Z',
|
||||
target_metric: 'consumption_kwh',
|
||||
period_minutes: 60,
|
||||
predicted_value: 58.9,
|
||||
status: 'available',
|
||||
failure_reason: null,
|
||||
model_reference: 'lightgbm-16b431449a50',
|
||||
created_at: '2026-09-18T09:00:00Z',
|
||||
},
|
||||
},
|
||||
{
|
||||
site_id: 'SITE005',
|
||||
site_name: 'Usine Toulouse',
|
||||
prediction: {
|
||||
target_at: '2026-09-18T10:00:00Z',
|
||||
target_metric: 'consumption_kwh',
|
||||
period_minutes: 60,
|
||||
predicted_value: 402.7,
|
||||
status: 'available',
|
||||
failure_reason: null,
|
||||
model_reference: 'lightgbm-16b431449a50',
|
||||
created_at: '2026-09-18T09:00:00Z',
|
||||
},
|
||||
},
|
||||
{
|
||||
site_id: 'SITE006',
|
||||
site_name: 'Bureau Lille',
|
||||
prediction: {
|
||||
target_at: '2026-09-18T10:00:00Z',
|
||||
target_metric: 'consumption_kwh',
|
||||
period_minutes: 60,
|
||||
predicted_value: 91.3,
|
||||
status: 'available',
|
||||
failure_reason: null,
|
||||
model_reference: 'lightgbm-16b431449a50',
|
||||
created_at: '2026-09-18T09:00:00Z',
|
||||
},
|
||||
},
|
||||
{
|
||||
// Illustre le cas d'un site jamais scoré : `prediction` reste `null`, pas un statut inventé
|
||||
// (même contrat que `PredictionService.summary()` côté backend).
|
||||
site_id: 'SITE007',
|
||||
site_name: 'Data Center Nantes',
|
||||
prediction: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
|
||||
import { PredictionsService } from './predictions.service';
|
||||
import { environment } from '../../../environments/environment';
|
||||
|
||||
describe('PredictionsService', () => {
|
||||
let service: PredictionsService;
|
||||
let httpMock: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideHttpClient(), provideHttpClientTesting()],
|
||||
});
|
||||
service = TestBed.inject(PredictionsService);
|
||||
httpMock = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => httpMock.verify());
|
||||
|
||||
it('appelle le bon endpoint et retourne un résumé de prévisions', () => {
|
||||
let result: unknown;
|
||||
service.getPredictions().subscribe((r) => (result = r));
|
||||
|
||||
const req = httpMock.expectOne(`${environment.apiUrl}/predictions`);
|
||||
expect(req.request.method).toBe('GET');
|
||||
|
||||
req.flush({
|
||||
timestamp: '2026-09-18T09:00:00Z',
|
||||
sites: [{ site_id: 'SITE001', site_name: 'Test', prediction: null }],
|
||||
});
|
||||
|
||||
expect((result as { sites: unknown[] }).sites.length).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Service, inject } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { environment } from '../../../environments/environment';
|
||||
import { PredictionSummary } from '../../shared/models/prediction.model';
|
||||
|
||||
@Service()
|
||||
export class PredictionsService {
|
||||
private http = inject(HttpClient);
|
||||
|
||||
getPredictions() {
|
||||
return this.http.get<PredictionSummary>(`${environment.apiUrl}/predictions`);
|
||||
}
|
||||
}
|
||||
@@ -72,4 +72,33 @@
|
||||
</ul>
|
||||
</section>
|
||||
}
|
||||
|
||||
@if (predictions().length > 0) {
|
||||
<section class="predictions-section">
|
||||
<h2>Prévisions de consommation</h2>
|
||||
<ul class="predictions-list">
|
||||
@for (site of predictions(); track site.site_id) {
|
||||
<li class="prediction-item">
|
||||
<span class="prediction-item__site">{{ site.site_name }}</span>
|
||||
@if (site.prediction; as prediction) {
|
||||
@if (prediction.status === 'available') {
|
||||
<span class="prediction-item__value">
|
||||
{{ prediction.predicted_value | number: '1.0-1' }} kWh
|
||||
<span class="prediction-item__target"
|
||||
>à {{ prediction.target_at | date: 'HH:mm' }}</span
|
||||
>
|
||||
</span>
|
||||
} @else {
|
||||
<ev-badge [tone]="badgeToneForPredictionStatus(prediction.status)">{{
|
||||
prediction.status === 'insufficient_data' ? 'Historique insuffisant' : 'Erreur'
|
||||
}}</ev-badge>
|
||||
}
|
||||
} @else {
|
||||
<ev-badge tone="neutral">Pas encore de prévision</ev-badge>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -121,3 +121,40 @@ h2 {
|
||||
.alert-item__message {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.predictions-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.prediction-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
padding: 0.7rem 1rem;
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border-light);
|
||||
}
|
||||
|
||||
.prediction-item__site {
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.prediction-item__value {
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.prediction-item__target {
|
||||
margin-left: 0.35rem;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 400;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { of, throwError } from 'rxjs';
|
||||
import { Dashboard } from './dashboard';
|
||||
import { StatsService } from '../../core/services/stats.service';
|
||||
import { AlertsService } from '../../core/services/alerts.service';
|
||||
import { PredictionsService } from '../../core/services/predictions.service';
|
||||
import {AuthService} from '../../core/services/auth.service';
|
||||
import {Router, provideRouter} from '@angular/router';
|
||||
|
||||
@@ -17,18 +18,24 @@ vi.mock('chart.js', () => {
|
||||
return { Chart: ChartMock, registerables: [] };
|
||||
});
|
||||
|
||||
function predictionsMock(sites: unknown[] = []) {
|
||||
return { getPredictions: vi.fn().mockReturnValue(of({ timestamp: '2026-09-18T09:00:00Z', sites })) };
|
||||
}
|
||||
|
||||
describe('Dashboard', () => {
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it('charge les stats et les alertes au démarrage', async () => {
|
||||
it('charge les stats, les alertes et les prévisions au démarrage', async () => {
|
||||
const statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
||||
const alertsMock = { getAlerts: vi.fn().mockReturnValue(of([{ alert_id: 'A1' }])) };
|
||||
const predictions = predictionsMock([{ site_id: 'SITE001', site_name: 'Test', prediction: null }]);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [Dashboard],
|
||||
providers: [
|
||||
{ provide: StatsService, useValue: statsMock },
|
||||
{ provide: AlertsService, useValue: alertsMock },
|
||||
{ provide: PredictionsService, useValue: predictions },
|
||||
provideRouter([]),
|
||||
],
|
||||
});
|
||||
@@ -42,7 +49,9 @@ describe('Dashboard', () => {
|
||||
|
||||
expect(statsMock.getSummary).toHaveBeenCalled();
|
||||
expect(alertsMock.getAlerts).toHaveBeenCalled();
|
||||
expect(predictions.getPredictions).toHaveBeenCalled();
|
||||
expect(fixture.componentInstance.alerts().length).toBe(1);
|
||||
expect(fixture.componentInstance.predictions().length).toBe(1);
|
||||
expect(fixture.componentInstance.error()).toBeNull();
|
||||
});
|
||||
|
||||
@@ -61,6 +70,7 @@ describe('Dashboard', () => {
|
||||
providers: [
|
||||
{ provide: StatsService, useValue: statsMock },
|
||||
{ provide: AlertsService, useValue: alertsMock },
|
||||
{ provide: PredictionsService, useValue: predictionsMock() },
|
||||
provideRouter([]),
|
||||
],
|
||||
});
|
||||
@@ -88,6 +98,7 @@ describe('Dashboard', () => {
|
||||
providers: [
|
||||
{ provide: StatsService, useValue: statsMock },
|
||||
{ provide: AlertsService, useValue: alertsMock },
|
||||
{ provide: PredictionsService, useValue: predictionsMock() },
|
||||
provideRouter([]),
|
||||
],
|
||||
});
|
||||
@@ -98,6 +109,30 @@ describe('Dashboard', () => {
|
||||
expect(fixture.componentInstance.alerts().length).toBe(0);
|
||||
});
|
||||
|
||||
it("n'interrompt pas la page quand le chargement des prévisions échoue", () => {
|
||||
const statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
||||
const alertsMock = { getAlerts: vi.fn().mockReturnValue(of([])) };
|
||||
const predictions = {
|
||||
getPredictions: vi.fn().mockReturnValue(throwError(() => new Error('nope'))),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [Dashboard],
|
||||
providers: [
|
||||
{ provide: StatsService, useValue: statsMock },
|
||||
{ provide: AlertsService, useValue: alertsMock },
|
||||
{ provide: PredictionsService, useValue: predictions },
|
||||
provideRouter([]),
|
||||
],
|
||||
});
|
||||
|
||||
const fixture = TestBed.createComponent(Dashboard);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.componentInstance.predictions().length).toBe(0);
|
||||
expect(fixture.componentInstance.error()).not.toBeNull();
|
||||
});
|
||||
|
||||
it('appelle logout et redirige vers /login au clic sur le bouton de déconnexion', () => {
|
||||
const statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
||||
const alertsMock = { getAlerts: vi.fn().mockReturnValue(of([])) };
|
||||
@@ -108,6 +143,7 @@ describe('Dashboard', () => {
|
||||
providers: [
|
||||
{ provide: StatsService, useValue: statsMock },
|
||||
{ provide: AlertsService, useValue: alertsMock },
|
||||
{ provide: PredictionsService, useValue: predictionsMock() },
|
||||
{ provide: AuthService, useValue: authMock },
|
||||
provideRouter([]),
|
||||
],
|
||||
@@ -137,6 +173,7 @@ describe('Dashboard', () => {
|
||||
providers: [
|
||||
{ provide: StatsService, useValue: statsMock },
|
||||
{ provide: AlertsService, useValue: alertsMock },
|
||||
{ provide: PredictionsService, useValue: predictionsMock() },
|
||||
{ provide: AuthService, useValue: authMock },
|
||||
provideRouter([]),
|
||||
],
|
||||
@@ -164,6 +201,7 @@ describe('Dashboard', () => {
|
||||
providers: [
|
||||
{ provide: StatsService, useValue: statsMock },
|
||||
{ provide: AlertsService, useValue: alertsMock },
|
||||
{ provide: PredictionsService, useValue: predictionsMock() },
|
||||
provideRouter([]),
|
||||
],
|
||||
});
|
||||
@@ -179,4 +217,26 @@ describe('Dashboard', () => {
|
||||
dashboard.badgeToneForSeverity('critical'),
|
||||
);
|
||||
});
|
||||
|
||||
it('distingue le ton des statuts de prévision', () => {
|
||||
const statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
||||
const alertsMock = { getAlerts: vi.fn().mockReturnValue(of([])) };
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [Dashboard],
|
||||
providers: [
|
||||
{ provide: StatsService, useValue: statsMock },
|
||||
{ provide: AlertsService, useValue: alertsMock },
|
||||
{ provide: PredictionsService, useValue: predictionsMock() },
|
||||
provideRouter([]),
|
||||
],
|
||||
});
|
||||
|
||||
const fixture = TestBed.createComponent(Dashboard);
|
||||
const dashboard = fixture.componentInstance;
|
||||
|
||||
expect(dashboard.badgeToneForPredictionStatus('available')).toBe('success');
|
||||
expect(dashboard.badgeToneForPredictionStatus('insufficient_data')).toBe('warning');
|
||||
expect(dashboard.badgeToneForPredictionStatus('error')).toBe('danger');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import { Component, OnInit, inject, signal, DestroyRef } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { timer, switchMap, catchError, EMPTY, Observable } from 'rxjs';
|
||||
import { DecimalPipe } from '@angular/common';
|
||||
import { DecimalPipe, DatePipe } from '@angular/common';
|
||||
import { Router, RouterLink } from '@angular/router';
|
||||
import { StatsService } from '../../core/services/stats.service';
|
||||
import { ConsumptionGauge } from '../../shared/components/consumption-gauge/consumption-gauge';
|
||||
import { SiteLoadChart } from '../../shared/components/site-load-chart/site-load-chart';
|
||||
import { AlertsService } from '../../core/services/alerts.service';
|
||||
import { PredictionsService } from '../../core/services/predictions.service';
|
||||
import { AuthService } from '../../core/services/auth.service';
|
||||
import { StatsSummary } from '../../shared/models/stats.model';
|
||||
import { Alert, AlertSeverity } from '../../shared/models/alert.model';
|
||||
import { PredictionStatus, SitePredictionSummary } from '../../shared/models/prediction.model';
|
||||
import { Card } from '../../shared/components/ui/card/card';
|
||||
import { Alert as EvAlert } from '../../shared/components/ui/alert/alert';
|
||||
import { Badge, BadgeTone } from '../../shared/components/ui/badge/badge';
|
||||
@@ -27,11 +29,21 @@ const TON_PAR_SEVERITE: Record<AlertSeverity, BadgeTone> = {
|
||||
critical: 'critical',
|
||||
};
|
||||
|
||||
// `error` n'a pas de précédent dans les fixtures ou l'API à ce jour, mais figure dans le
|
||||
// domaine du schéma backend (`ck_prediction_status`) : mieux vaut une couleur définie que
|
||||
// tomber sur `undefined` si ce statut apparaît un jour.
|
||||
const TON_PAR_STATUT_PREDICTION: Record<PredictionStatus, BadgeTone> = {
|
||||
available: 'success',
|
||||
insufficient_data: 'warning',
|
||||
error: 'danger',
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-dashboard',
|
||||
standalone: true,
|
||||
imports: [
|
||||
DecimalPipe,
|
||||
DatePipe,
|
||||
RouterLink,
|
||||
ConsumptionGauge,
|
||||
SiteLoadChart,
|
||||
@@ -47,12 +59,14 @@ const TON_PAR_SEVERITE: Record<AlertSeverity, BadgeTone> = {
|
||||
export class Dashboard implements OnInit {
|
||||
private statsService = inject(StatsService);
|
||||
private alertsService = inject(AlertsService);
|
||||
private predictionsService = inject(PredictionsService);
|
||||
private auth = inject(AuthService);
|
||||
private router = inject(Router);
|
||||
private destroyRef = inject(DestroyRef);
|
||||
|
||||
stats = signal<StatsSummary | null>(null);
|
||||
alerts = signal<Alert[]>([]);
|
||||
predictions = signal<SitePredictionSummary[]>([]);
|
||||
error = signal<string | null>(null);
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -61,6 +75,13 @@ export class Dashboard implements OnInit {
|
||||
.pipe(catchError(() => this.reportUnavailable()))
|
||||
.subscribe((alerts) => this.alerts.set(alerts));
|
||||
|
||||
// Les prévisions viennent d'un scoring hors ligne, pas d'un calcul à la demande : un seul
|
||||
// chargement au démarrage suffit, pas besoin du rafraîchissement périodique de `stats`.
|
||||
this.predictionsService
|
||||
.getPredictions()
|
||||
.pipe(catchError(() => this.reportUnavailable()))
|
||||
.subscribe((summary) => this.predictions.set(summary.sites));
|
||||
|
||||
// Piège : le catchError porte sur l'observable interne. Sur le flux externe il
|
||||
// terminerait le timer, et le rafraîchissement ne repartirait jamais.
|
||||
timer(0, REFRESH_INTERVAL_MS)
|
||||
@@ -80,6 +101,10 @@ export class Dashboard implements OnInit {
|
||||
return TON_PAR_SEVERITE[severity];
|
||||
}
|
||||
|
||||
badgeToneForPredictionStatus(status: PredictionStatus): BadgeTone {
|
||||
return TON_PAR_STATUT_PREDICTION[status];
|
||||
}
|
||||
|
||||
onLogout(): void {
|
||||
this.auth.logout().subscribe({
|
||||
next: () => this.router.navigate(['/login']),
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
export type PredictionStatus = 'available' | 'insufficient_data' | 'error';
|
||||
export type PredictionTargetMetric = 'consumption_kwh' | 'consumption_kw';
|
||||
|
||||
export interface SitePrediction {
|
||||
target_at: string;
|
||||
target_metric: PredictionTargetMetric;
|
||||
period_minutes: number | null;
|
||||
predicted_value: number | null;
|
||||
status: PredictionStatus;
|
||||
failure_reason: string | null;
|
||||
model_reference: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface SitePredictionSummary {
|
||||
site_id: string;
|
||||
site_name: string;
|
||||
prediction: SitePrediction | null;
|
||||
}
|
||||
|
||||
export interface PredictionSummary {
|
||||
timestamp: string;
|
||||
sites: SitePredictionSummary[];
|
||||
}
|
||||
Reference in New Issue
Block a user