Compare commits
101
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
56c6b79a5a | ||
|
|
452cfdef85 | ||
|
|
96dd1f834c | ||
|
|
e66ef86729 | ||
|
|
0318ee6cc5 | ||
|
|
0ddfb1997d | ||
|
|
b96546cea3 | ||
|
|
c059f838bb | ||
|
|
a9e124a97d | ||
|
|
edd5e82d29 | ||
|
|
619024f547 | ||
|
|
460d6c1b3e | ||
|
|
eb4291b10a | ||
|
|
9a72bb3a8f | ||
|
|
bd1da05587 | ||
|
|
9376420868 | ||
|
|
d535959fbe | ||
|
|
33807e3038 | ||
|
|
c914d41f33 | ||
|
|
d3047f53e8 | ||
|
|
ec63798807 | ||
|
|
1e168ef03e | ||
|
|
ddf7e17788 | ||
|
|
56e8f95729 | ||
|
|
91d435748c | ||
|
|
0b41580310 | ||
|
|
e3d436ea53 | ||
|
|
c453700b13 | ||
|
|
f427f8a8f3 | ||
|
|
7be8a44e89 | ||
|
|
2095ad6bd3 | ||
|
|
fb06bf0062 | ||
|
|
e27142c7db | ||
|
|
77feabcbad | ||
|
|
18a4be6e38 | ||
|
|
feee6c3ffc | ||
|
|
173f91f26f | ||
|
|
1cd3688256 | ||
|
|
7eef960a30 | ||
|
|
db81290026 | ||
|
|
12fb8860d1 | ||
|
|
d9229e5a93 | ||
|
|
7c2936f2ef | ||
|
|
9d3e402ca4 | ||
|
|
e9376a98bf | ||
|
|
7db57f162c | ||
|
|
9ccc603d88 | ||
|
|
297d85a0ca | ||
|
|
af58172742 | ||
|
|
b433e01fa8 | ||
|
|
5eb74aa64a | ||
|
|
cc0a58ac4c | ||
|
|
2400b6f05e | ||
|
|
9e33c276d6 | ||
|
|
6cb9ac00cb | ||
|
|
c1f63889c1 | ||
|
|
5875e8c239 | ||
|
|
c8383014a8 | ||
|
|
3cf9194d4c | ||
|
|
8def1e23af | ||
|
|
e26948932e | ||
|
|
41acdb54b6 | ||
|
|
5d921a9b1e | ||
|
|
56c134beb0 | ||
|
|
8fb5ab9f65 | ||
|
|
e22feac2c4 | ||
|
|
5581cb1ef3 | ||
|
|
1d8c986386 | ||
|
|
85cb7c9eeb | ||
|
|
39b1d28ead | ||
|
|
5394257855 | ||
|
|
19cfac1cff | ||
|
|
1fce577a78 | ||
|
|
1afaee069f | ||
|
|
7bc9a09489 | ||
|
|
4ee2109628 | ||
|
|
ec1c05ad54 | ||
|
|
334ca5982b | ||
|
|
2465021d61 | ||
|
|
278299c2b1 | ||
|
|
4f69199734 | ||
|
|
1cca4f130c | ||
|
|
016f226fdb | ||
|
|
88f4f9a601 | ||
|
|
ed7311d4ef | ||
|
|
ff68a51424 | ||
|
|
11f9b1bcd5 | ||
|
|
41c18a3bb1 | ||
|
|
00ef725249 | ||
|
|
34f35f3ca0 | ||
|
|
f5cac1c2a8 | ||
|
|
8e07168a5e | ||
|
|
d167b64188 | ||
|
|
2ad7692f1c | ||
|
|
cd4fd962be | ||
|
|
517144f7e5 | ||
|
|
cc7ca2d359 | ||
|
|
bbafe7d119 | ||
|
|
9c78c6dc38 | ||
|
|
2f97e4d434 | ||
|
|
07ea8d21dc |
@@ -17,3 +17,9 @@ APP_LOG_LEVEL=INFO
|
|||||||
APP_SECRET_KEY=change_me
|
APP_SECRET_KEY=change_me
|
||||||
APP_CORS_ORIGINS=http://localhost:4200
|
APP_CORS_ORIGINS=http://localhost:4200
|
||||||
BACKEND_PORT=8000
|
BACKEND_PORT=8000
|
||||||
|
|
||||||
|
# API Mock EnerVision
|
||||||
|
APP_MOCK_API_BASE_URL=https://api-mock.charlieandre.fr
|
||||||
|
APP_MOCK_API_USERNAME=change_me
|
||||||
|
APP_MOCK_API_PASSWORD=change_me
|
||||||
|
APP_MOCK_API_TIMEOUT_SECONDS=10
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
# Frontend — npm
|
||||||
|
- package-ecosystem: "npm"
|
||||||
|
directory: "/apps/frontend"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
open-pull-requests-limit: 5
|
||||||
|
groups:
|
||||||
|
frontend-dependencies:
|
||||||
|
patterns:
|
||||||
|
- "*"
|
||||||
|
|
||||||
|
# Backend — uv (lit pyproject.toml / uv.lock)
|
||||||
|
- package-ecosystem: "uv"
|
||||||
|
directory: "/apps/backend"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
open-pull-requests-limit: 5
|
||||||
|
groups:
|
||||||
|
backend-dependencies:
|
||||||
|
patterns:
|
||||||
|
- "*"
|
||||||
|
|
||||||
|
# Les workflows GitHub Actions eux-mêmes ont aussi des dépendances à jour
|
||||||
|
- package-ecosystem: "github-actions"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
|
||||||
|
# Si un Dockerfile existe pour le backend
|
||||||
|
- package-ecosystem: "docker"
|
||||||
|
directory: "/apps/backend"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
|
||||||
|
- package-ecosystem: "docker"
|
||||||
|
directory: "/apps/frontend"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
@@ -56,3 +56,87 @@ jobs:
|
|||||||
# Le marqueur `integration` est exclu par défaut, donc aucune base n'est nécessaire ici.
|
# Le marqueur `integration` est exclu par défaut, donc aucune base n'est nécessaire ici.
|
||||||
- name: Tests et couverture
|
- name: Tests et couverture
|
||||||
run: uv run pytest --cov-fail-under=85
|
run: uv run pytest --cov-fail-under=85
|
||||||
|
|
||||||
|
# Piège : l'image est celle de docker-compose.yml, pas une image `postgres` nue. La première
|
||||||
|
# migration (`5353c0e4f094`) échoue volontairement si l'extension TimescaleDB manque, et un
|
||||||
|
# écart d'image entre la CI et le poste rendrait ce job vert sur une base qui n'est pas la nôtre.
|
||||||
|
integration:
|
||||||
|
name: Tests exigeant une base
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
services:
|
||||||
|
db:
|
||||||
|
image: timescale/timescaledb-ha:pg17
|
||||||
|
env:
|
||||||
|
POSTGRES_USER: enervision
|
||||||
|
POSTGRES_PASSWORD: change_me
|
||||||
|
POSTGRES_DB: enervision_test
|
||||||
|
ports:
|
||||||
|
- "5433:5432"
|
||||||
|
options: >-
|
||||||
|
--health-cmd "pg_isready -U enervision -d enervision_test"
|
||||||
|
--health-interval 10s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 12
|
||||||
|
--health-start-period 40s
|
||||||
|
|
||||||
|
env:
|
||||||
|
DATABASE_URL: postgresql+asyncpg://enervision:change_me@localhost:5433/enervision_test
|
||||||
|
APP_SECRET_KEY: secret-de-test-assez-long-pour-le-validateur
|
||||||
|
PGPASSWORD: change_me
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Récupère le dépôt
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Installe uv
|
||||||
|
uses: astral-sh/setup-uv@v5
|
||||||
|
with:
|
||||||
|
enable-cache: true
|
||||||
|
cache-dependency-glob: apps/backend/uv.lock
|
||||||
|
|
||||||
|
- name: Installe l'interpréteur déclaré par .python-version
|
||||||
|
run: uv python install
|
||||||
|
|
||||||
|
- name: Synchronise les dépendances sans dévier du verrou
|
||||||
|
run: uv sync --all-groups --frozen
|
||||||
|
|
||||||
|
# Sur le poste, c'est db/init/110-test-database.sql qui pose l'extension. Ce fichier n'est
|
||||||
|
# pas monté ici, et sans lui `alembic upgrade head` s'arrête sur la garde de la révision 1.
|
||||||
|
- name: Active TimescaleDB sur la base de test
|
||||||
|
run: psql -h localhost -p 5433 -U enervision -d enervision_test -c "CREATE EXTENSION IF NOT EXISTS timescaledb"
|
||||||
|
|
||||||
|
- name: Applique les migrations
|
||||||
|
run: uv run alembic upgrade head
|
||||||
|
|
||||||
|
# `-m` en ligne de commande écrase celui d'`addopts`. La couverture est désactivée : ce job
|
||||||
|
# ne joue qu'une partie de la suite, son taux n'aurait aucun sens face au seuil de 85 %.
|
||||||
|
- name: Tests d'intégration
|
||||||
|
run: uv run pytest -m integration --no-cov
|
||||||
|
|
||||||
|
security-audit:
|
||||||
|
name: Audit des dépendances
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Récupère le dépôt
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Installe uv
|
||||||
|
uses: astral-sh/setup-uv@v5
|
||||||
|
with:
|
||||||
|
enable-cache: true
|
||||||
|
cache-dependency-glob: apps/backend/uv.lock
|
||||||
|
|
||||||
|
# L'audit porte sur le verrou, pas sur l'environnement : sinon pip-audit auditerait
|
||||||
|
# aussi les paquets que son propre `--with` injecte, hors dépendances du projet.
|
||||||
|
- name: Audite les dépendances livrées
|
||||||
|
# Piège : sans `shell: bash`, un échec de `uv export` serait masqué par le pipe.
|
||||||
|
shell: bash
|
||||||
|
run: uv export --frozen --no-dev --no-emit-project --no-hashes | uvx pip-audit --requirement /dev/stdin --no-deps
|
||||||
|
|||||||
@@ -1,20 +1,6 @@
|
|||||||
name: Frontend
|
name: Frontend
|
||||||
# Pipeline à choix multiple
|
|
||||||
|
|
||||||
on:
|
on:
|
||||||
# workflow_dispatch -> lancement manuel des jobs
|
|
||||||
workflow_dispatch:
|
|
||||||
inputs:
|
|
||||||
job_choice:
|
|
||||||
required: true
|
|
||||||
description: "Choix du job"
|
|
||||||
type: choice
|
|
||||||
default: all
|
|
||||||
options:
|
|
||||||
- build
|
|
||||||
- sonarqube
|
|
||||||
- test
|
|
||||||
- all # lancer tous les jobs
|
|
||||||
push:
|
push:
|
||||||
paths:
|
paths:
|
||||||
- "apps/frontend/**"
|
- "apps/frontend/**"
|
||||||
@@ -23,8 +9,9 @@ on:
|
|||||||
paths:
|
paths:
|
||||||
- "apps/frontend/**"
|
- "apps/frontend/**"
|
||||||
- ".github/workflows/frontend.yml"
|
- ".github/workflows/frontend.yml"
|
||||||
# Ordre de lancement des jobs
|
|
||||||
# build -> test -> sonarqube -> deploy
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
@@ -42,6 +29,18 @@ jobs:
|
|||||||
- run: npm run build
|
- run: npm run build
|
||||||
working-directory: apps/frontend
|
working-directory: apps/frontend
|
||||||
|
|
||||||
|
security-audit:
|
||||||
|
name: Audit des dépendances
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
- uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
# Seuil high : une vulnérabilité moderate de devDependency ne doit pas bloquer une livraison.
|
||||||
|
- run: npm audit --audit-level=high --package-lock-only
|
||||||
|
working-directory: apps/frontend
|
||||||
|
|
||||||
test:
|
test:
|
||||||
needs: build
|
needs: build
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -52,26 +51,14 @@ jobs:
|
|||||||
node-version: 24
|
node-version: 24
|
||||||
cache: npm
|
cache: npm
|
||||||
cache-dependency-path: apps/frontend/package-lock.json
|
cache-dependency-path: apps/frontend/package-lock.json
|
||||||
- run: npm ci
|
- name : Installation des dépendances (Front)
|
||||||
|
run: npm ci
|
||||||
working-directory: apps/frontend
|
working-directory: apps/frontend
|
||||||
- run: npm test -- --watch=false
|
- name : Lancement des tests et génénration du rapport de couverture (Front)
|
||||||
|
run: npm test --watch=false --code-coverage --coverageReporters=lcov
|
||||||
working-directory: apps/frontend
|
working-directory: apps/frontend
|
||||||
|
- name: Upload coverage
|
||||||
sonarqube:
|
uses: actions/upload-artifact@v4
|
||||||
needs: [build, test]
|
|
||||||
name: SonarQube
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
|
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
|
name: frontend-coverage
|
||||||
- name: SonarQube Scan
|
path: apps/frontend/coverage/frontend/lcov.info
|
||||||
uses: SonarSource/sonarqube-scan-action@7006c4492b2e0ee0f816d36501671557c97f5995 # v8.1.0
|
|
||||||
env:
|
|
||||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
|
||||||
|
|
||||||
|
|
||||||
# deploy:
|
|
||||||
# runs-on: ubuntu-latest
|
|
||||||
# steps:
|
|
||||||
# - run: echo "DEPLOY job is running"
|
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
name: ML
|
||||||
|
|
||||||
|
# Piège : la version de Python vient de ml/.python-version, et doit rester en 3.14 (cf.
|
||||||
|
# .github/workflows/backend.yml, même contrainte).
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
paths:
|
||||||
|
- "ml/**"
|
||||||
|
- ".github/workflows/ml.yml"
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- "ml/**"
|
||||||
|
- ".github/workflows/ml.yml"
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ml-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
verification:
|
||||||
|
name: Lint, typage et tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: ml
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Récupère le dépôt
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Installe uv
|
||||||
|
uses: astral-sh/setup-uv@v5
|
||||||
|
with:
|
||||||
|
enable-cache: true
|
||||||
|
cache-dependency-glob: ml/uv.lock
|
||||||
|
|
||||||
|
- name: Installe l'interpréteur déclaré par .python-version
|
||||||
|
run: uv python install
|
||||||
|
|
||||||
|
- name: Synchronise les dépendances sans dévier du verrou
|
||||||
|
run: uv sync --all-groups --frozen
|
||||||
|
|
||||||
|
- name: Vérifie le formatage
|
||||||
|
run: uv run ruff format --check .
|
||||||
|
|
||||||
|
- name: Analyse statique
|
||||||
|
run: uv run ruff check --output-format=github .
|
||||||
|
|
||||||
|
- name: Typage
|
||||||
|
run: uv run mypy enervision_ml tests
|
||||||
|
|
||||||
|
# Aucun test ne touche PostgreSQL ni MLflow distant : tout tourne sur donnees
|
||||||
|
# synthetiques ou un magasin SQLite local jetable (cf. ml/tests/test_train.py).
|
||||||
|
- name: Tests
|
||||||
|
run: uv run pytest
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
name: SonarQube
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
paths:
|
||||||
|
- "apps/frontend/**"
|
||||||
|
- "apps/backend/**"
|
||||||
|
- ".github/workflows/sonarqube.yml"
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- "apps/frontend/**"
|
||||||
|
- "apps/backend/**"
|
||||||
|
- ".github/workflows/sonarqube.yml"
|
||||||
|
|
||||||
|
|
||||||
|
# Build l'ensemble du projet, puis lance les tests
|
||||||
|
# Génère les rapports de couverture, puis lance l'analyse SonarQube
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-front:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
- uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
cache: npm
|
||||||
|
cache-dependency-path: apps/frontend/package-lock.json
|
||||||
|
|
||||||
|
- run: npm ci
|
||||||
|
working-directory: apps/frontend
|
||||||
|
- run: npm run build
|
||||||
|
working-directory: apps/frontend
|
||||||
|
|
||||||
|
test-front:
|
||||||
|
needs: build-front
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
- uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
cache: npm
|
||||||
|
cache-dependency-path: apps/frontend/package-lock.json
|
||||||
|
|
||||||
|
- name : Installation des dépendances (Front)
|
||||||
|
run: npm ci
|
||||||
|
working-directory: apps/frontend
|
||||||
|
|
||||||
|
- name : Lancement des tests et génénration du rapport de couverture (Front)
|
||||||
|
run: npm test --watch=false --code-coverage --coverageReporters=lcov
|
||||||
|
working-directory: apps/frontend
|
||||||
|
|
||||||
|
- name: Upload coverage
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: frontend-coverage
|
||||||
|
path: apps/frontend/coverage/frontend/lcov.info
|
||||||
|
|
||||||
|
build-back:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
- name: Installe uv
|
||||||
|
uses: astral-sh/setup-uv@v5
|
||||||
|
with:
|
||||||
|
enable-cache: true
|
||||||
|
cache-dependency-glob: apps/backend/uv.lock
|
||||||
|
- name: Installe l'interpréteur déclaré par .python-version
|
||||||
|
run: uv python install
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
- name: Synchronise les dépendances sans dévier du verrou
|
||||||
|
run: uv sync --all-groups --frozen
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
- name: Vérifie le formatage
|
||||||
|
run: uv run ruff format --check .
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
- name: Analyse statique
|
||||||
|
run: uv run ruff check --output-format=github .
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
- name: Typage
|
||||||
|
run: uv run mypy app
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
|
||||||
|
test-back:
|
||||||
|
needs: build-back
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
- name: Installe uv
|
||||||
|
uses: astral-sh/setup-uv@v5
|
||||||
|
with:
|
||||||
|
enable-cache: true
|
||||||
|
cache-dependency-glob: apps/backend/uv.lock
|
||||||
|
|
||||||
|
- name : Lancement des tests et génénration du rapport de couverture (Back)
|
||||||
|
run: uv run pytest --cov-fail-under=85 --cov-report=xml
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
- name: Upload coverage
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: backend-coverage
|
||||||
|
path: apps/backend/coverage.xml
|
||||||
|
|
||||||
|
sonarqube:
|
||||||
|
needs: [build-front, build-back, test-front, test-back]
|
||||||
|
name: SonarQube
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- name: Téléchargement du rapport de couverture (Front)
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: frontend-coverage
|
||||||
|
path: apps/frontend/coverage/frontend
|
||||||
|
- name: Téléchargement du rapport de couverture (Back)
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: backend-coverage
|
||||||
|
path: apps/backend
|
||||||
|
- name: SonarQube Scan
|
||||||
|
uses: SonarSource/sonarqube-scan-action@v8
|
||||||
|
env:
|
||||||
|
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||||
@@ -58,6 +58,14 @@ data/raw/*
|
|||||||
monitoring/grafana/data/
|
monitoring/grafana/data/
|
||||||
monitoring/prometheus/data/
|
monitoring/prometheus/data/
|
||||||
|
|
||||||
|
# ML : jeu de donnees, modeles entraines et suivi MLflow local, tous generes/volumineux
|
||||||
|
ml/data/
|
||||||
|
ml/models/*
|
||||||
|
!ml/models/.gitkeep
|
||||||
|
ml/mlruns/
|
||||||
|
ml/mlartifacts/
|
||||||
|
ml/mlflow.db
|
||||||
|
|
||||||
# IDE et OS
|
# IDE et OS
|
||||||
.idea/
|
.idea/
|
||||||
.vscode/
|
.vscode/
|
||||||
|
|||||||
@@ -1,15 +1,17 @@
|
|||||||
BACKEND := apps/backend
|
BACKEND := apps/backend
|
||||||
FRONTEND := apps/frontend
|
FRONTEND := apps/frontend
|
||||||
|
ML := ml
|
||||||
|
|
||||||
.DEFAULT_GOAL := help
|
.DEFAULT_GOAL := help
|
||||||
.PHONY: help install install-backend install-frontend dev dev-backend dev-frontend \
|
.PHONY: help install install-backend install-frontend install-ml dev dev-backend dev-frontend \
|
||||||
lint format typecheck test test-cov test-integration check \
|
lint format typecheck test test-cov test-integration check \
|
||||||
openapi docker-build db-up db-down db-reset db-logs db-psql migrate bootstrap-admin
|
openapi docker-build db-up db-down db-reset db-logs db-psql migrate bootstrap-admin \
|
||||||
|
ml-lint ml-typecheck ml-test ml-check ml-train ml-score
|
||||||
|
|
||||||
help: ## Liste les cibles disponibles
|
help: ## Liste les cibles disponibles
|
||||||
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-16s\033[0m %s\n", $$1, $$2}'
|
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-16s\033[0m %s\n", $$1, $$2}'
|
||||||
|
|
||||||
install: install-backend install-frontend ## Installe les dépendances backend et frontend
|
install: install-backend install-frontend install-ml ## Installe les dépendances backend, frontend et ML
|
||||||
|
|
||||||
install-backend: ## Installe les dépendances du backend
|
install-backend: ## Installe les dépendances du backend
|
||||||
cd $(BACKEND) && uv sync --all-groups
|
cd $(BACKEND) && uv sync --all-groups
|
||||||
@@ -17,6 +19,9 @@ install-backend: ## Installe les dépendances du backend
|
|||||||
install-frontend: ## Installe les dépendances du frontend
|
install-frontend: ## Installe les dépendances du frontend
|
||||||
cd $(FRONTEND) && npm ci
|
cd $(FRONTEND) && npm ci
|
||||||
|
|
||||||
|
install-ml: ## Installe les dépendances du pipeline ML
|
||||||
|
cd $(ML) && uv sync --all-groups
|
||||||
|
|
||||||
dev: ## Lance toute la stack (backend + frontend) en rechargement à chaud
|
dev: ## Lance toute la stack (backend + frontend) en rechargement à chaud
|
||||||
@trap 'kill 0' EXIT INT TERM; \
|
@trap 'kill 0' EXIT INT TERM; \
|
||||||
$(MAKE) --no-print-directory dev-backend & \
|
$(MAKE) --no-print-directory dev-backend & \
|
||||||
@@ -55,6 +60,23 @@ check: lint typecheck test ## Chaîne de vérification complète
|
|||||||
openapi: ## Régénère apps/backend/openapi.json depuis les routes déclarées
|
openapi: ## Régénère apps/backend/openapi.json depuis les routes déclarées
|
||||||
cd $(BACKEND) && uv run python -m app.cli export-openapi
|
cd $(BACKEND) && uv run python -m app.cli export-openapi
|
||||||
|
|
||||||
|
ml-lint: ## Analyse statique du pipeline ML
|
||||||
|
cd $(ML) && uv run ruff check .
|
||||||
|
|
||||||
|
ml-typecheck: ## Vérifie le typage du pipeline ML
|
||||||
|
cd $(ML) && uv run mypy enervision_ml tests
|
||||||
|
|
||||||
|
ml-test: ## Exécute les tests du pipeline ML (donnees synthetiques, sans base ni serveur MLflow)
|
||||||
|
cd $(ML) && uv run pytest
|
||||||
|
|
||||||
|
ml-check: ml-lint ml-typecheck ml-test ## Chaîne de vérification complète du pipeline ML
|
||||||
|
|
||||||
|
ml-train: ## Entraine le modele LightGBM. CSV=chemin optionnel, sinon lit ML_DATABASE_URL
|
||||||
|
cd $(ML) && uv run python -m enervision_ml.train $(if $(CSV),--csv $(CSV),)
|
||||||
|
|
||||||
|
ml-score: ## Score le prochain pas horaire et l'ecrit dans `prediction`. CSV=chemin optionnel
|
||||||
|
cd $(ML) && uv run python -m enervision_ml.score $(if $(CSV),--csv $(CSV),)
|
||||||
|
|
||||||
docker-build: ## Construit l'image du backend
|
docker-build: ## Construit l'image du backend
|
||||||
docker build -t enervision-backend:local $(BACKEND)
|
docker build -t enervision-backend:local $(BACKEND)
|
||||||
|
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ Ce que la documentation apporte à chacun : [docs/architecture/00-vue-ensemble.m
|
|||||||
| Infra | Terraform (k3s single-node) | `infra/terraform` | Initialise |
|
| Infra | Terraform (k3s single-node) | `infra/terraform` | Initialise |
|
||||||
| CI/CD | GitHub Actions | `.github/workflows` | Backend en place |
|
| CI/CD | GitHub Actions | `.github/workflows` | Backend en place |
|
||||||
| Monitoring | Prometheus, Grafana, Alertmanager | `monitoring` | A initialiser |
|
| Monitoring | Prometheus, Grafana, Alertmanager | `monitoring` | A initialiser |
|
||||||
|
| ML | LightGBM, MLflow | `ml` | Entrainement initialise |
|
||||||
|
|
||||||
Le backend, la base et l'infrastructure (Terraform/k3s) sont initialises a ce stade. Le frontend
|
Le backend, la base et l'infrastructure (Terraform/k3s) sont initialises a ce stade. Le frontend
|
||||||
sert un tableau de bord sur `/dashboard`, dont les données proviennent de fixtures : les endpoints
|
sert un tableau de bord sur `/dashboard`, dont les données proviennent de fixtures : les endpoints
|
||||||
@@ -53,6 +54,7 @@ L'etat detaille de chaque brique et les vues d'architecture sont dans
|
|||||||
├── infra/terraform/
|
├── infra/terraform/
|
||||||
│ ├── modules/ Modules reutilisables
|
│ ├── modules/ Modules reutilisables
|
||||||
│ └── environments/ Racines Terraform, une par environnement
|
│ └── environments/ Racines Terraform, une par environnement
|
||||||
|
├── ml/ Pipeline d'entrainement LightGBM, suivi MLflow
|
||||||
├── monitoring/
|
├── monitoring/
|
||||||
│ ├── prometheus/ Collecte et regles d'alerte
|
│ ├── prometheus/ Collecte et regles d'alerte
|
||||||
│ ├── grafana/ Provisioning et dashboards
|
│ ├── grafana/ Provisioning et dashboards
|
||||||
|
|||||||
@@ -18,3 +18,7 @@ APP_SMTP_HOST=localhost
|
|||||||
APP_SMTP_PORT=1025
|
APP_SMTP_PORT=1025
|
||||||
APP_SMTP_USE_TLS=false
|
APP_SMTP_USE_TLS=false
|
||||||
APP_SMTP_FROM_ADDRESS=no-reply@enervision.fr
|
APP_SMTP_FROM_ADDRESS=no-reply@enervision.fr
|
||||||
|
APP_MOCK_API_BASE_URL=https://api-mock.charlieandre.fr
|
||||||
|
APP_MOCK_API_USERNAME=change_me
|
||||||
|
APP_MOCK_API_PASSWORD=change_me
|
||||||
|
APP_MOCK_API_TIMEOUT_SECONDS=10
|
||||||
|
|||||||
+21
-3
@@ -123,6 +123,11 @@ async def test_repository_reads_back_what_it_wrote(session: AsyncSession) -> Non
|
|||||||
defaut, ce qui garde `make check` jouable sans Docker. Tout autre marqueur doit etre
|
defaut, ce qui garde `make check` jouable sans Docker. Tout autre marqueur doit etre
|
||||||
declare dans `pyproject.toml` : `--strict-markers` refuse les marqueurs inconnus.
|
declare dans `pyproject.toml` : `--strict-markers` refuse les marqueurs inconnus.
|
||||||
|
|
||||||
|
Ces tests ne sont pas pour autant facultatifs : le job `integration` de
|
||||||
|
`.github/workflows/backend.yml` monte un service TimescaleDB, applique les migrations et
|
||||||
|
les joue a chaque poussee. Un test `integration` casse donc la CI comme un autre. En local,
|
||||||
|
`make db-up` puis `make test-integration`.
|
||||||
|
|
||||||
## Couverture
|
## Couverture
|
||||||
|
|
||||||
Les branches sont mesurees, pas seulement les lignes. Le seuil de 85 % ne s'applique
|
Les branches sont mesurees, pas seulement les lignes. Le seuil de 85 % ne s'applique
|
||||||
@@ -142,14 +147,27 @@ uv run pytest tests/api/test_health.py # un seul fichier
|
|||||||
uv run pytest -k readiness # par motif de nom
|
uv run pytest -k readiness # par motif de nom
|
||||||
```
|
```
|
||||||
|
|
||||||
## Trois fichiers à connaître avant de toucher à l'authentification
|
## Quatre fichiers à connaître avant de toucher à l'authentification
|
||||||
|
|
||||||
|
`tests/api/acces.py` porte la classification des routes du contrat, en quatre ensembles :
|
||||||
|
`ROUTES_PUBLIQUES`, `ROUTE_COOKIE`, `ROUTES_SANS_ROLE` et la table `ROLE_MINIMUM`. Ce n'est pas
|
||||||
|
un fichier de test, c'est la référence que les trois autres confrontent au comportement observé.
|
||||||
|
**Toute route ajoutée doit y être classée** : `test_every_declared_route_is_classified` échoue
|
||||||
|
sinon, et échoue aussi sur une entrée qui ne correspond plus à aucune route.
|
||||||
|
|
||||||
`tests/api/test_route_protection.py` interroge réellement chaque route sans identifiant et
|
`tests/api/test_route_protection.py` interroge réellement chaque route sans identifiant et
|
||||||
échoue si l'une d'elles répond autre chose qu'un 401 ou un 403. Il n'inspecte pas l'arbre de
|
échoue si l'une d'elles répond autre chose qu'un 401 ou un 403. Il n'inspecte pas l'arbre de
|
||||||
dépendances : celui-ci n'est accessible que par l'API privée de FastAPI, et surtout une route
|
dépendances : celui-ci n'est accessible que par l'API privée de FastAPI, et surtout une route
|
||||||
peut porter la bonne dépendance tout en répondant quand même. **Rendre une route publique impose
|
peut porter la bonne dépendance tout en répondant quand même. **Rendre une route publique impose
|
||||||
donc de modifier la liste `ROUTES_PUBLIQUES` de ce fichier**, ce qui apparaît en clair dans la
|
donc de modifier `ROUTES_PUBLIQUES` dans `acces.py`**, ce qui apparaît en clair dans la diff
|
||||||
diff d'une pull request.
|
d'une pull request.
|
||||||
|
|
||||||
|
`tests/api/test_matrice_acces.py` croise chaque route gardée avec chacun des trois rôles, dans
|
||||||
|
les deux sens : un rôle insuffisant reçoit un 403 `Droits insuffisants`, un rôle suffisant ne le
|
||||||
|
reçoit jamais. Le second sens est ce qui rend visible une garde posée trop haut, par exemple
|
||||||
|
`AdminDep` sur une route de lecture. La même matrice est rejouée sous `integration` avec de vrais
|
||||||
|
jetons, donc en traversant le décodage du JWT et la relecture du compte en base, que
|
||||||
|
`dependency_overrides` court-circuite.
|
||||||
|
|
||||||
`tests/services/test_auth.py` donne au faux hacheur un **compteur d'appels**. C'est ce qui rend
|
`tests/services/test_auth.py` donne au faux hacheur un **compteur d'appels**. C'est ce qui rend
|
||||||
possibles les deux assertions qui prouvent la conception, et qu'aucune autre forme de test
|
possibles les deux assertions qui prouvent la conception, et qu'aucune autre forme de test
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ from app.repositories.audit_log import AuditLogRepository
|
|||||||
from app.repositories.login_attempt import LoginAttemptRepository
|
from app.repositories.login_attempt import LoginAttemptRepository
|
||||||
from app.repositories.password_reset_attempt import PasswordResetAttemptRepository
|
from app.repositories.password_reset_attempt import PasswordResetAttemptRepository
|
||||||
from app.repositories.password_reset_token import PasswordResetTokenRepository
|
from app.repositories.password_reset_token import PasswordResetTokenRepository
|
||||||
|
from app.repositories.prediction import PredictionRepository
|
||||||
from app.repositories.reading import ReadingRepository
|
from app.repositories.reading import ReadingRepository
|
||||||
from app.repositories.recommendation import RecommendationRepository
|
from app.repositories.recommendation import RecommendationRepository
|
||||||
from app.repositories.refresh_token import RefreshTokenRepository
|
from app.repositories.refresh_token import RefreshTokenRepository
|
||||||
@@ -34,6 +35,7 @@ from app.repositories.site import SiteRepository
|
|||||||
from app.repositories.user import UserRepository
|
from app.repositories.user import UserRepository
|
||||||
from app.services.alert import AlertService
|
from app.services.alert import AlertService
|
||||||
from app.services.auth import AuthService, LoginPolicy, PasswordResetPolicy
|
from app.services.auth import AuthService, LoginPolicy, PasswordResetPolicy
|
||||||
|
from app.services.prediction import PredictionService
|
||||||
from app.services.reading import ReadingService
|
from app.services.reading import ReadingService
|
||||||
from app.services.recommendation import RecommendationService
|
from app.services.recommendation import RecommendationService
|
||||||
from app.services.sensor import SensorService
|
from app.services.sensor import SensorService
|
||||||
@@ -171,14 +173,19 @@ UserServiceDep = Annotated[UserService, Depends(get_user_service)]
|
|||||||
|
|
||||||
|
|
||||||
def get_site_service(session: SessionDep) -> SiteService:
|
def get_site_service(session: SessionDep) -> SiteService:
|
||||||
return SiteService(sites=SiteRepository(session))
|
return SiteService(sites=SiteRepository(session), readings=ReadingRepository(session))
|
||||||
|
|
||||||
|
|
||||||
SiteServiceDep = Annotated[SiteService, Depends(get_site_service)]
|
SiteServiceDep = Annotated[SiteService, Depends(get_site_service)]
|
||||||
|
|
||||||
|
|
||||||
def get_alert_service(session: SessionDep) -> AlertService:
|
def get_alert_service(session: SessionDep) -> AlertService:
|
||||||
return AlertService(alerts=AlertRepository(session))
|
return AlertService(
|
||||||
|
alerts=AlertRepository(session),
|
||||||
|
readings=ReadingRepository(session),
|
||||||
|
predictions=PredictionRepository(session),
|
||||||
|
sites=SiteRepository(session),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
AlertServiceDep = Annotated[AlertService, Depends(get_alert_service)]
|
AlertServiceDep = Annotated[AlertService, Depends(get_alert_service)]
|
||||||
@@ -212,6 +219,15 @@ def get_sensor_service(session: SessionDep) -> SensorService:
|
|||||||
SensorServiceDep = Annotated[SensorService, Depends(get_sensor_service)]
|
SensorServiceDep = Annotated[SensorService, Depends(get_sensor_service)]
|
||||||
|
|
||||||
|
|
||||||
|
def get_prediction_service(session: SessionDep) -> PredictionService:
|
||||||
|
return PredictionService(
|
||||||
|
sites=SiteRepository(session), predictions=PredictionRepository(session)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
PredictionServiceDep = Annotated[PredictionService, Depends(get_prediction_service)]
|
||||||
|
|
||||||
|
|
||||||
async def get_current_principal(
|
async def get_current_principal(
|
||||||
credentials: CredentialsDep,
|
credentials: CredentialsDep,
|
||||||
session: SessionDep,
|
session: SessionDep,
|
||||||
|
|||||||
@@ -83,6 +83,13 @@ TAGS: Final[list[dict[str, Any]]] = [
|
|||||||
"name": "sensors",
|
"name": "sensors",
|
||||||
"description": "État de santé des capteurs par site. Réservé au rôle `admin`.",
|
"description": "État de santé des capteurs par site. Réservé au rôle `admin`.",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"name": "predictions",
|
||||||
|
"description": (
|
||||||
|
"Dernière prévision de consommation par site, calculée hors ligne par le pipeline "
|
||||||
|
"de scoring (`ml/`) et simplement lue ici. Accessible à partir du rôle `lecteur`."
|
||||||
|
),
|
||||||
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
cookie_de_rafraichissement = APIKeyCookie(
|
cookie_de_rafraichissement = APIKeyCookie(
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.api.deps import LecteurDep, PredictionServiceDep
|
||||||
|
from app.schemas.prediction import PredictionSummaryResponse
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"",
|
||||||
|
response_model=PredictionSummaryResponse,
|
||||||
|
summary="Dernière prédiction de consommation par site",
|
||||||
|
)
|
||||||
|
async def get_predictions(
|
||||||
|
_: LecteurDep, service: PredictionServiceDep
|
||||||
|
) -> PredictionSummaryResponse:
|
||||||
|
resume = await service.summary()
|
||||||
|
return PredictionSummaryResponse.model_validate(resume)
|
||||||
@@ -3,7 +3,7 @@ from fastapi import APIRouter, HTTPException, status
|
|||||||
from app.api.deps import LecteurDep, SiteServiceDep
|
from app.api.deps import LecteurDep, SiteServiceDep
|
||||||
from app.api.openapi import REPONSE_VALIDATION, Reponses
|
from app.api.openapi import REPONSE_VALIDATION, Reponses
|
||||||
from app.schemas.errors import ErrorResponse
|
from app.schemas.errors import ErrorResponse
|
||||||
from app.schemas.site import SiteResponse
|
from app.schemas.site import SiteCurrentResponse, SiteResponse
|
||||||
from app.services.site import SiteNotFoundError
|
from app.services.site import SiteNotFoundError
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
@@ -34,3 +34,19 @@ async def get_site(site_id: str, _: LecteurDep, service: SiteServiceDep) -> Site
|
|||||||
status_code=status.HTTP_404_NOT_FOUND, detail="Site introuvable"
|
status_code=status.HTTP_404_NOT_FOUND, detail="Site introuvable"
|
||||||
) from erreur
|
) from erreur
|
||||||
return SiteResponse.model_validate(site)
|
return SiteResponse.model_validate(site)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/{site_id}/current",
|
||||||
|
response_model=SiteCurrentResponse,
|
||||||
|
summary="Dernière mesure d'un site",
|
||||||
|
responses=REPONSES_INTROUVABLE,
|
||||||
|
)
|
||||||
|
async def get_current(site_id: str, _: LecteurDep, service: SiteServiceDep) -> SiteCurrentResponse:
|
||||||
|
try:
|
||||||
|
actuel = await service.current(site_id)
|
||||||
|
except SiteNotFoundError as erreur:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND, detail="Site introuvable"
|
||||||
|
) from erreur
|
||||||
|
return SiteCurrentResponse.model_validate(actuel)
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ from app.api.v1.endpoints import (
|
|||||||
alerts,
|
alerts,
|
||||||
auth,
|
auth,
|
||||||
health,
|
health,
|
||||||
|
predictions,
|
||||||
readings,
|
readings,
|
||||||
recommendations,
|
recommendations,
|
||||||
sensors,
|
sensors,
|
||||||
@@ -34,3 +35,6 @@ api_router.include_router(
|
|||||||
api_router.include_router(
|
api_router.include_router(
|
||||||
sensors.router, prefix="/sensors", tags=["sensors"], responses=REPONSES_ADMIN
|
sensors.router, prefix="/sensors", tags=["sensors"], responses=REPONSES_ADMIN
|
||||||
)
|
)
|
||||||
|
api_router.include_router(
|
||||||
|
predictions.router, prefix="/predictions", tags=["predictions"], responses=REPONSES_LECTEUR
|
||||||
|
)
|
||||||
|
|||||||
@@ -34,6 +34,11 @@ class Settings(BaseSettings):
|
|||||||
database_pool_size: int = 5
|
database_pool_size: int = 5
|
||||||
database_max_overflow: int = 10
|
database_max_overflow: int = 10
|
||||||
|
|
||||||
|
mock_api_base_url: str = "https://api-mock.charlieandre.fr"
|
||||||
|
mock_api_username: str | None = None
|
||||||
|
mock_api_password: SecretStr | None = None
|
||||||
|
mock_api_timeout_seconds: float = Field(default=10.0, gt=0)
|
||||||
|
|
||||||
jwt_issuer: str = "enervision-api"
|
jwt_issuer: str = "enervision-api"
|
||||||
jwt_audience: str = "enervision-web"
|
jwt_audience: str = "enervision-web"
|
||||||
access_token_ttl_seconds: int = Field(default=900, ge=60, le=3600)
|
access_token_ttl_seconds: int = Field(default=900, ge=60, le=3600)
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
# Détection d'alertes internes EnerVision (issue #104) : script lancé à la main pour l'instant,
|
||||||
|
# comme `enervision_ml.score` côté ML, sans automatisation Airflow pour l'ordonnancer.
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import asyncio
|
||||||
|
import sys
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
|
||||||
|
from app.core.config import get_settings
|
||||||
|
from app.db.session import get_session_factory
|
||||||
|
from app.repositories.alert import AlertRepository
|
||||||
|
from app.repositories.prediction import PredictionRepository
|
||||||
|
from app.repositories.reading import ReadingRepository
|
||||||
|
from app.repositories.site import SiteRepository
|
||||||
|
from app.services.alert import AlertService
|
||||||
|
|
||||||
|
|
||||||
|
async def run_detection(*, now: datetime | None = None, site_id: str | None = None) -> int:
|
||||||
|
"""Exécute les cinq règles de détection et enregistre les nouvelles alertes. Rend le nombre de
|
||||||
|
lignes effectivement insérées (les doublons de `source_alert_id` sont silencieusement
|
||||||
|
ignorés)."""
|
||||||
|
async with get_session_factory()() as session:
|
||||||
|
service = AlertService(
|
||||||
|
alerts=AlertRepository(session),
|
||||||
|
readings=ReadingRepository(session),
|
||||||
|
predictions=PredictionRepository(session),
|
||||||
|
sites=SiteRepository(session),
|
||||||
|
)
|
||||||
|
nouvelles = await service.detect(now=now, site_id=site_id)
|
||||||
|
await session.commit()
|
||||||
|
return len(nouvelles)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_instant(valeur: str) -> datetime:
|
||||||
|
instant = datetime.fromisoformat(valeur)
|
||||||
|
return instant if instant.tzinfo is not None else instant.replace(tzinfo=UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
prog="python -m app.detection.internal_alerts",
|
||||||
|
description="Détection d'alertes internes EnerVision",
|
||||||
|
)
|
||||||
|
parser.add_argument("--site-id", default=None, help="Limite la détection à un seul site.")
|
||||||
|
parser.add_argument(
|
||||||
|
"--now",
|
||||||
|
type=_parse_instant,
|
||||||
|
default=None,
|
||||||
|
help=(
|
||||||
|
"Instant de référence (ISO 8601, UTC si le fuseau est omis). Défaut : l'heure courante."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return parser.parse_args(argv)
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str] | None = None) -> int:
|
||||||
|
args = parse_args(argv)
|
||||||
|
# Échoue tôt si `APP_SECRET_KEY`/`DATABASE_URL` manquent, avant toute requête à la base.
|
||||||
|
get_settings()
|
||||||
|
nombre = asyncio.run(run_detection(now=args.now, site_id=args.site_id))
|
||||||
|
print(f"{nombre} nouvelle(s) alerte(s) enregistrée(s).")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__": # pragma: no cover
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,315 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from sqlalchemy import text
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
|
||||||
|
|
||||||
|
from app.core.config import get_settings
|
||||||
|
|
||||||
|
SOURCE_HISTORY = "api_history"
|
||||||
|
|
||||||
|
|
||||||
|
def create_mock_api_client() -> httpx.AsyncClient:
|
||||||
|
settings = get_settings()
|
||||||
|
|
||||||
|
if settings.mock_api_username is None or settings.mock_api_password is None:
|
||||||
|
raise ValueError("Les identifiants de l'API Mock ne sont pas configurés.")
|
||||||
|
|
||||||
|
return httpx.AsyncClient(
|
||||||
|
base_url=settings.mock_api_base_url.rstrip("/"),
|
||||||
|
auth=(
|
||||||
|
settings.mock_api_username,
|
||||||
|
settings.mock_api_password.get_secret_value(),
|
||||||
|
),
|
||||||
|
timeout=settings.mock_api_timeout_seconds,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def fetch_sites(
|
||||||
|
client: httpx.AsyncClient,
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
response = await client.get("/api/v1/sites")
|
||||||
|
|
||||||
|
response.raise_for_status()
|
||||||
|
|
||||||
|
payload = response.json()
|
||||||
|
|
||||||
|
if not isinstance(payload, list):
|
||||||
|
raise ValueError("La réponse /api/v1/sites doit être une liste.")
|
||||||
|
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
async def upsert_sites(
|
||||||
|
connection: AsyncConnection,
|
||||||
|
sites: list[dict[str, Any]],
|
||||||
|
) -> None:
|
||||||
|
if not sites:
|
||||||
|
return
|
||||||
|
|
||||||
|
await connection.execute(
|
||||||
|
text(
|
||||||
|
"""
|
||||||
|
INSERT INTO site (
|
||||||
|
site_id,
|
||||||
|
site_type,
|
||||||
|
site_name,
|
||||||
|
location,
|
||||||
|
capacity_kw,
|
||||||
|
status
|
||||||
|
)
|
||||||
|
VALUES (
|
||||||
|
:site_id,
|
||||||
|
:site_type,
|
||||||
|
:site_name,
|
||||||
|
:location,
|
||||||
|
:capacity_kw,
|
||||||
|
:status
|
||||||
|
)
|
||||||
|
ON CONFLICT (site_id)
|
||||||
|
DO UPDATE SET
|
||||||
|
site_type = EXCLUDED.site_type,
|
||||||
|
site_name = EXCLUDED.site_name,
|
||||||
|
location = EXCLUDED.location,
|
||||||
|
capacity_kw = EXCLUDED.capacity_kw,
|
||||||
|
status = EXCLUDED.status
|
||||||
|
"""
|
||||||
|
),
|
||||||
|
sites,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def fetch_readings(
|
||||||
|
client: httpx.AsyncClient,
|
||||||
|
site_id: str,
|
||||||
|
start_time: datetime,
|
||||||
|
end_time: datetime,
|
||||||
|
limit: int = 1000,
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
response = await client.get(
|
||||||
|
"/api/v1/readings",
|
||||||
|
params={
|
||||||
|
"site_id": site_id,
|
||||||
|
"start_time": start_time.isoformat(),
|
||||||
|
"end_time": end_time.isoformat(),
|
||||||
|
"limit": limit,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
response.raise_for_status()
|
||||||
|
|
||||||
|
payload = response.json()
|
||||||
|
|
||||||
|
if not isinstance(payload, list):
|
||||||
|
raise ValueError("La réponse /api/v1/readings doit être une liste.")
|
||||||
|
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def build_reading_row(
|
||||||
|
reading: dict[str, Any],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
timestamp = datetime.fromisoformat(reading["timestamp"].replace("Z", "+00:00"))
|
||||||
|
return {
|
||||||
|
"site_id": reading["site_id"],
|
||||||
|
"timestamp": timestamp,
|
||||||
|
"source": SOURCE_HISTORY,
|
||||||
|
"dataset_id": None,
|
||||||
|
"consumption_kw": reading.get("consumption_kw"),
|
||||||
|
"consumption_kwh": reading.get("consumption_kwh"),
|
||||||
|
"consumption_euros": None,
|
||||||
|
"voltage_v": reading.get("voltage_v"),
|
||||||
|
"current_a": reading.get("current_a"),
|
||||||
|
"power_factor": reading.get("power_factor"),
|
||||||
|
"temperature_celsius": reading.get("temperature_celsius"),
|
||||||
|
"humidity_percent": reading.get("humidity_percent"),
|
||||||
|
"solar_irradiance_wm2": None,
|
||||||
|
"is_working_hours": None,
|
||||||
|
"data_quality": reading.get("data_quality"),
|
||||||
|
"null_reasons": reading.get("null_reasons"),
|
||||||
|
"imputed_values": None,
|
||||||
|
"imputation_method": None,
|
||||||
|
"raw_data": json.dumps(
|
||||||
|
reading,
|
||||||
|
ensure_ascii=False,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
READING_INSERT = text(
|
||||||
|
"""
|
||||||
|
INSERT INTO reading (
|
||||||
|
site_id,
|
||||||
|
timestamp,
|
||||||
|
source,
|
||||||
|
dataset_id,
|
||||||
|
consumption_kw,
|
||||||
|
consumption_kwh,
|
||||||
|
consumption_euros,
|
||||||
|
voltage_v,
|
||||||
|
current_a,
|
||||||
|
power_factor,
|
||||||
|
temperature_celsius,
|
||||||
|
humidity_percent,
|
||||||
|
solar_irradiance_wm2,
|
||||||
|
is_working_hours,
|
||||||
|
data_quality,
|
||||||
|
null_reasons,
|
||||||
|
imputed_values,
|
||||||
|
imputation_method,
|
||||||
|
raw_data
|
||||||
|
)
|
||||||
|
VALUES (
|
||||||
|
:site_id,
|
||||||
|
:timestamp,
|
||||||
|
:source,
|
||||||
|
:dataset_id,
|
||||||
|
:consumption_kw,
|
||||||
|
:consumption_kwh,
|
||||||
|
:consumption_euros,
|
||||||
|
:voltage_v,
|
||||||
|
:current_a,
|
||||||
|
:power_factor,
|
||||||
|
:temperature_celsius,
|
||||||
|
:humidity_percent,
|
||||||
|
:solar_irradiance_wm2,
|
||||||
|
:is_working_hours,
|
||||||
|
:data_quality,
|
||||||
|
:null_reasons,
|
||||||
|
CAST(:imputed_values AS jsonb),
|
||||||
|
:imputation_method,
|
||||||
|
CAST(:raw_data AS jsonb)
|
||||||
|
)
|
||||||
|
ON CONFLICT DO NOTHING
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def build_reading_batch(
|
||||||
|
readings: list[dict[str, Any]],
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
return [build_reading_row(reading) for reading in readings]
|
||||||
|
|
||||||
|
|
||||||
|
async def import_mock_api_history(
|
||||||
|
start_time: datetime,
|
||||||
|
end_time: datetime,
|
||||||
|
limit: int,
|
||||||
|
dry_run: bool,
|
||||||
|
) -> None:
|
||||||
|
settings = get_settings()
|
||||||
|
|
||||||
|
async with create_mock_api_client() as client:
|
||||||
|
sites = await fetch_sites(client)
|
||||||
|
|
||||||
|
print(f"Sites récupérés : {len(sites)}")
|
||||||
|
|
||||||
|
all_readings: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
for site in sites:
|
||||||
|
site_id = site["site_id"]
|
||||||
|
|
||||||
|
readings = await fetch_readings(
|
||||||
|
client=client,
|
||||||
|
site_id=site_id,
|
||||||
|
start_time=start_time,
|
||||||
|
end_time=end_time,
|
||||||
|
limit=limit,
|
||||||
|
)
|
||||||
|
|
||||||
|
print(f"{site_id}: {len(readings)} lectures")
|
||||||
|
|
||||||
|
all_readings.extend(readings)
|
||||||
|
|
||||||
|
print(f"Lectures récupérées : {len(all_readings)}")
|
||||||
|
|
||||||
|
if dry_run:
|
||||||
|
print("Dry-run terminé : aucune donnée écrite.")
|
||||||
|
return
|
||||||
|
|
||||||
|
engine = create_async_engine(
|
||||||
|
str(settings.database_url),
|
||||||
|
pool_pre_ping=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
async with engine.begin() as connection:
|
||||||
|
await upsert_sites(
|
||||||
|
connection,
|
||||||
|
sites,
|
||||||
|
)
|
||||||
|
|
||||||
|
rows = build_reading_batch(all_readings)
|
||||||
|
|
||||||
|
if rows:
|
||||||
|
await connection.execute(
|
||||||
|
READING_INSERT,
|
||||||
|
rows,
|
||||||
|
)
|
||||||
|
|
||||||
|
finally:
|
||||||
|
await engine.dispose()
|
||||||
|
|
||||||
|
print("Import API Mock terminé.")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_datetime(value: str) -> datetime:
|
||||||
|
return datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args() -> argparse.Namespace:
|
||||||
|
parser = argparse.ArgumentParser(description=("Import historique depuis l'API Mock EnerVision"))
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"--start-time",
|
||||||
|
required=True,
|
||||||
|
type=parse_datetime,
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"--end-time",
|
||||||
|
required=True,
|
||||||
|
type=parse_datetime,
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"--limit",
|
||||||
|
type=int,
|
||||||
|
default=1000,
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"--dry-run",
|
||||||
|
action="store_true",
|
||||||
|
)
|
||||||
|
|
||||||
|
return parser.parse_args()
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
args = parse_args()
|
||||||
|
|
||||||
|
if args.limit < 1 or args.limit > 1000:
|
||||||
|
raise ValueError("--limit doit être compris entre 1 et 1000.")
|
||||||
|
|
||||||
|
if args.start_time >= args.end_time:
|
||||||
|
raise ValueError("--start-time doit être antérieur à --end-time.")
|
||||||
|
|
||||||
|
asyncio.run(
|
||||||
|
import_mock_api_history(
|
||||||
|
start_time=args.start_time,
|
||||||
|
end_time=args.end_time,
|
||||||
|
limit=args.limit,
|
||||||
|
dry_run=args.dry_run,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -1,9 +1,14 @@
|
|||||||
from collections.abc import AsyncIterator
|
from collections.abc import AsyncIterator
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from fastapi import Depends, FastAPI
|
from fastapi import Depends, FastAPI
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html
|
||||||
|
from fastapi.staticfiles import StaticFiles
|
||||||
from prometheus_fastapi_instrumentator import Instrumentator
|
from prometheus_fastapi_instrumentator import Instrumentator
|
||||||
|
from starlette.requests import Request
|
||||||
|
from starlette.responses import HTMLResponse
|
||||||
|
|
||||||
from app.api.errors import register_error_handlers
|
from app.api.errors import register_error_handlers
|
||||||
from app.api.middleware import SecurityHeadersMiddleware
|
from app.api.middleware import SecurityHeadersMiddleware
|
||||||
@@ -18,6 +23,8 @@ logger = get_logger(__name__)
|
|||||||
|
|
||||||
METHODES_AUTORISEES = ["GET", "POST", "PATCH", "PUT", "DELETE", "OPTIONS"]
|
METHODES_AUTORISEES = ["GET", "POST", "PATCH", "PUT", "DELETE", "OPTIONS"]
|
||||||
EN_TETES_AUTORISES = ["Authorization", "Content-Type"]
|
EN_TETES_AUTORISES = ["Authorization", "Content-Type"]
|
||||||
|
STATIC_DIR = Path(__file__).parent / "static"
|
||||||
|
LOGO_URL = "/static/logo-icon.png"
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
@@ -43,11 +50,41 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
|||||||
openapi_tags=TAGS,
|
openapi_tags=TAGS,
|
||||||
debug=resolved.debug,
|
debug=resolved.debug,
|
||||||
lifespan=lifespan,
|
lifespan=lifespan,
|
||||||
docs_url="/docs" if documentee else None,
|
docs_url=None,
|
||||||
redoc_url="/redoc" if documentee else None,
|
redoc_url=None,
|
||||||
openapi_url="/openapi.json" if documentee else None,
|
openapi_url="/openapi.json" if documentee else None,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if documentee:
|
||||||
|
application.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
|
||||||
|
|
||||||
|
# ReDoc supporte nativement `info.x-logo` (extension Redocly) pour afficher un logo
|
||||||
|
# en en-tête ; Swagger UI n'a pas d'equivalent, il ne reprend que le favicon.
|
||||||
|
openapi_original = application.openapi
|
||||||
|
|
||||||
|
def openapi_avec_logo() -> dict[str, object]:
|
||||||
|
schema = openapi_original()
|
||||||
|
schema["info"]["x-logo"] = {"url": LOGO_URL, "altText": "EnerVision"}
|
||||||
|
return schema
|
||||||
|
|
||||||
|
application.openapi = openapi_avec_logo # type: ignore[method-assign]
|
||||||
|
|
||||||
|
@application.get("/docs", include_in_schema=False)
|
||||||
|
async def docs_swagger(_: Request) -> HTMLResponse:
|
||||||
|
return get_swagger_ui_html(
|
||||||
|
openapi_url="/openapi.json",
|
||||||
|
title=f"{application.title} · Swagger UI",
|
||||||
|
swagger_favicon_url=LOGO_URL,
|
||||||
|
)
|
||||||
|
|
||||||
|
@application.get("/redoc", include_in_schema=False)
|
||||||
|
async def docs_redoc(_: Request) -> HTMLResponse:
|
||||||
|
return get_redoc_html(
|
||||||
|
openapi_url="/openapi.json",
|
||||||
|
title=f"{application.title} · ReDoc",
|
||||||
|
redoc_favicon_url=LOGO_URL,
|
||||||
|
)
|
||||||
|
|
||||||
application.add_middleware(SecurityHeadersMiddleware)
|
application.add_middleware(SecurityHeadersMiddleware)
|
||||||
|
|
||||||
if resolved.allowed_origins:
|
if resolved.allowed_origins:
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from collections.abc import Sequence
|
from collections.abc import Sequence
|
||||||
|
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.dialects.postgresql import insert
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from app.models.energy import Alert
|
from app.models.energy import Alert
|
||||||
@@ -19,3 +20,36 @@ class AlertRepository:
|
|||||||
if severity is not None:
|
if severity is not None:
|
||||||
requete = requete.where(Alert.severity == severity)
|
requete = requete.where(Alert.severity == severity)
|
||||||
return (await self._session.scalars(requete)).all()
|
return (await self._session.scalars(requete)).all()
|
||||||
|
|
||||||
|
async def create_many(self, alerts: Sequence[Alert]) -> Sequence[Alert]:
|
||||||
|
# `ON CONFLICT DO NOTHING` sur `uq_alert_source_reference` : rejouer la détection sur une
|
||||||
|
# fenêtre qui recouvre une exécution précédente ne doit pas dupliquer une alerte déjà
|
||||||
|
# enregistrée. `RETURNING` ne renvoie donc que les lignes effectivement insérées.
|
||||||
|
if not alerts:
|
||||||
|
return []
|
||||||
|
valeurs = [
|
||||||
|
{
|
||||||
|
"source_alert_id": alerte.source_alert_id,
|
||||||
|
"site_id": alerte.site_id,
|
||||||
|
"source": alerte.source,
|
||||||
|
"timestamp": alerte.timestamp,
|
||||||
|
"type": alerte.type,
|
||||||
|
"severity": alerte.severity,
|
||||||
|
"message": alerte.message,
|
||||||
|
"value": alerte.value,
|
||||||
|
"threshold": alerte.threshold,
|
||||||
|
"metric": alerte.metric,
|
||||||
|
"prediction_id": alerte.prediction_id,
|
||||||
|
"raw_data": alerte.raw_data,
|
||||||
|
}
|
||||||
|
for alerte in alerts
|
||||||
|
]
|
||||||
|
requete = (
|
||||||
|
insert(Alert)
|
||||||
|
.values(valeurs)
|
||||||
|
.on_conflict_do_nothing(constraint="uq_alert_source_reference")
|
||||||
|
.returning(Alert)
|
||||||
|
)
|
||||||
|
resultat = await self._session.execute(requete)
|
||||||
|
await self._session.flush()
|
||||||
|
return resultat.scalars().all()
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
from collections.abc import Sequence
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.models.energy import Prediction
|
||||||
|
|
||||||
|
|
||||||
|
class PredictionRepository:
|
||||||
|
def __init__(self, session: AsyncSession) -> None:
|
||||||
|
self._session = session
|
||||||
|
|
||||||
|
async def list_since(
|
||||||
|
self, *, since: datetime, site_id: str | None = None
|
||||||
|
) -> Sequence[Prediction]:
|
||||||
|
# Restreint à `available` : une prévision `insufficient_data`/`error` n'a pas de
|
||||||
|
# `predicted_value` à comparer à une lecture réelle (détection d'anomalie).
|
||||||
|
# Piège : `prediction` n'a pas d'unicité sur `(site_id, target_at)` (cf.
|
||||||
|
# `enervision_ml.score`, qui insère toujours une nouvelle ligne plutôt que d'écraser la
|
||||||
|
# précédente). `prediction_id` en dernier départage donc les égalités de `target_at` par
|
||||||
|
# ordre croissant : `_detect_anomaly` construit un dict qui garde le dernier rencontré,
|
||||||
|
# c'est-à-dire le run le plus récent plutôt qu'une ligne choisie au hasard par le plan
|
||||||
|
# d'exécution.
|
||||||
|
requete = (
|
||||||
|
select(Prediction)
|
||||||
|
.where(Prediction.target_at >= since, Prediction.status == "available")
|
||||||
|
.order_by(Prediction.site_id, Prediction.target_at, Prediction.prediction_id)
|
||||||
|
)
|
||||||
|
if site_id is not None:
|
||||||
|
requete = requete.where(Prediction.site_id == site_id)
|
||||||
|
return (await self._session.scalars(requete)).all()
|
||||||
|
|
||||||
|
async def latest_by_site(self) -> Sequence[Prediction]:
|
||||||
|
# `.distinct(site_id)` compile en `DISTINCT ON (site_id)` sous PostgreSQL : une seule
|
||||||
|
# ligne par site, la plus récente grâce à l'ordre composite qui suit. Même mécanisme que
|
||||||
|
# `ReadingRepository.latest_by_site`. Trié sur `target_at` (couvert par
|
||||||
|
# `ix_prediction_site_target`) plutôt que `created_at` : c'est la prévision la plus
|
||||||
|
# récente qui compte pour un tableau de bord, pas forcément le dernier run de scoring.
|
||||||
|
requete = (
|
||||||
|
select(Prediction)
|
||||||
|
.distinct(Prediction.site_id)
|
||||||
|
.order_by(
|
||||||
|
Prediction.site_id,
|
||||||
|
Prediction.target_at.desc(),
|
||||||
|
Prediction.prediction_id.desc(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return (await self._session.scalars(requete)).all()
|
||||||
@@ -13,14 +13,42 @@ class ReadingRepository:
|
|||||||
|
|
||||||
async def latest_by_site(self) -> Sequence[Reading]:
|
async def latest_by_site(self) -> Sequence[Reading]:
|
||||||
# `.distinct(site_id)` compile en `DISTINCT ON (site_id)` sous PostgreSQL : une seule
|
# `.distinct(site_id)` compile en `DISTINCT ON (site_id)` sous PostgreSQL : une seule
|
||||||
# ligne par site, la plus récente grâce à l'ordre composite qui suit.
|
# ligne par site, la plus récente grâce à l'ordre composite qui suit. `reading_id` départage
|
||||||
|
# les égalités de timestamp, que `uq_reading_source` autorise à `source` différente.
|
||||||
requete = (
|
requete = (
|
||||||
select(Reading)
|
select(Reading)
|
||||||
.distinct(Reading.site_id)
|
.distinct(Reading.site_id)
|
||||||
.order_by(Reading.site_id, Reading.timestamp.desc())
|
.order_by(Reading.site_id, Reading.timestamp.desc(), Reading.reading_id.desc())
|
||||||
)
|
)
|
||||||
return (await self._session.execute(requete)).scalars().all()
|
return (await self._session.execute(requete)).scalars().all()
|
||||||
|
|
||||||
|
async def latest_for_site(self, site_id: str) -> Reading | None:
|
||||||
|
# Piège : `uq_reading_source` autorise deux lignes au même `site_id`+`timestamp` quand la
|
||||||
|
# `source` diffère. Sans `reading_id` en départage, le `LIMIT 1` renverrait au hasard.
|
||||||
|
requete = (
|
||||||
|
select(Reading)
|
||||||
|
.where(Reading.site_id == site_id)
|
||||||
|
.order_by(Reading.timestamp.desc(), Reading.reading_id.desc())
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
lecture: Reading | None = await self._session.scalar(requete)
|
||||||
|
return lecture
|
||||||
|
|
||||||
|
async def list_since(self, *, since: datetime, site_id: str | None = None) -> Sequence[Reading]:
|
||||||
|
# Trié par site puis par heure croissante : la détection d'alertes (spike) a besoin de
|
||||||
|
# comparer chaque lecture à celle qui la précède immédiatement pour le même site.
|
||||||
|
# `reading_id` en dernier départage : `uq_reading_source` autorise deux lignes au même
|
||||||
|
# `site_id`+`timestamp` quand la `source` diffère (même piège que `latest_for_site`), sans
|
||||||
|
# quoi l'ordre entre elles ne serait pas garanti d'un appel à l'autre.
|
||||||
|
requete = (
|
||||||
|
select(Reading)
|
||||||
|
.where(Reading.timestamp >= since)
|
||||||
|
.order_by(Reading.site_id, Reading.timestamp, Reading.reading_id)
|
||||||
|
)
|
||||||
|
if site_id is not None:
|
||||||
|
requete = requete.where(Reading.site_id == site_id)
|
||||||
|
return (await self._session.scalars(requete)).all()
|
||||||
|
|
||||||
async def list_history(
|
async def list_history(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from enum import StrEnum
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class PredictionTargetMetric(StrEnum):
|
||||||
|
CONSUMPTION_KWH = "consumption_kwh"
|
||||||
|
CONSUMPTION_KW = "consumption_kw"
|
||||||
|
|
||||||
|
|
||||||
|
class PredictionStatus(StrEnum):
|
||||||
|
AVAILABLE = "available"
|
||||||
|
INSUFFICIENT_DATA = "insufficient_data"
|
||||||
|
ERROR = "error"
|
||||||
|
|
||||||
|
|
||||||
|
class SitePredictionResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
target_at: datetime
|
||||||
|
target_metric: PredictionTargetMetric
|
||||||
|
period_minutes: int | None
|
||||||
|
predicted_value: float | None
|
||||||
|
status: PredictionStatus
|
||||||
|
failure_reason: str | None
|
||||||
|
model_reference: str
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class SitePredictionSummaryResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
site_id: str
|
||||||
|
site_name: str
|
||||||
|
prediction: SitePredictionResponse | None
|
||||||
|
|
||||||
|
|
||||||
|
class PredictionSummaryResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
timestamp: datetime
|
||||||
|
sites: list[SitePredictionSummaryResponse]
|
||||||
@@ -1,3 +1,6 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict
|
from pydantic import BaseModel, ConfigDict
|
||||||
|
|
||||||
|
|
||||||
@@ -10,3 +13,20 @@ class SiteResponse(BaseModel):
|
|||||||
location: str | None
|
location: str | None
|
||||||
capacity_kw: float | None
|
capacity_kw: float | None
|
||||||
status: str | None
|
status: str | None
|
||||||
|
|
||||||
|
|
||||||
|
class SiteCurrentResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
timestamp: datetime | None
|
||||||
|
site_id: str
|
||||||
|
site_type: str
|
||||||
|
consumption_kw: float | None
|
||||||
|
consumption_kwh: float | None
|
||||||
|
voltage_v: float | None
|
||||||
|
current_a: float | None
|
||||||
|
power_factor: float | None
|
||||||
|
temperature_celsius: float | None
|
||||||
|
humidity_percent: float | None
|
||||||
|
null_reasons: list[str]
|
||||||
|
data_quality: Literal["good", "partial", "degraded", "critical"]
|
||||||
|
|||||||
@@ -1,14 +1,323 @@
|
|||||||
from collections.abc import Sequence
|
from collections.abc import Sequence
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
from app.models.energy import Alert
|
from app.models.energy import Alert, Prediction, Reading, Site
|
||||||
from app.repositories.alert import AlertRepository
|
from app.repositories.alert import AlertRepository
|
||||||
|
from app.repositories.prediction import PredictionRepository
|
||||||
|
from app.repositories.reading import ReadingRepository
|
||||||
|
from app.repositories.site import SiteRepository
|
||||||
|
|
||||||
|
# Fenêtre de lectures/prédictions analysée à chaque exécution : assez large pour couvrir une paire
|
||||||
|
# de lectures consécutives (spike) et une coupure prolongée (outage), sans réanalyser tout
|
||||||
|
# l'historique à chaque lancement manuel du script de détection.
|
||||||
|
LOOKBACK = timedelta(hours=48)
|
||||||
|
|
||||||
|
# Cadence nominale d'une lecture : le CSV historique comme l'API Mock livrent un pas horaire.
|
||||||
|
EXPECTED_INTERVAL = timedelta(hours=1)
|
||||||
|
# Au-delà de trois pas manqués, on parle de coupure plutôt que d'un simple retard d'ingestion.
|
||||||
|
OUTAGE_THRESHOLD = EXPECTED_INTERVAL * 3
|
||||||
|
|
||||||
|
# +/-50% entre deux lectures consécutives du même site.
|
||||||
|
SPIKE_RELATIVE_THRESHOLD = 0.5
|
||||||
|
# 30% d'écart entre la consommation réelle et la prévision du même site/instant.
|
||||||
|
ANOMALY_RELATIVE_THRESHOLD = 0.3
|
||||||
|
# Une prévision quasi nulle rend l'écart relatif ininterprétable ; on l'ignore plutôt.
|
||||||
|
ANOMALY_MINIMUM_PREDICTED_VALUE = 1e-6
|
||||||
|
|
||||||
|
THRESHOLD_METRIC = "consumption_kw"
|
||||||
|
ANOMALY_METRIC = "consumption_kwh"
|
||||||
|
# `data_quality` -> sévérité du capteur défaillant. `good` est volontairement absent : il ne
|
||||||
|
# déclenche jamais d'alerte.
|
||||||
|
QUALITE_VERS_SEVERITE: dict[str, str] = {
|
||||||
|
"partial": "low",
|
||||||
|
"degraded": "medium",
|
||||||
|
"critical": "critical",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
class AlertService:
|
class AlertService:
|
||||||
def __init__(self, *, alerts: AlertRepository) -> None:
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
alerts: AlertRepository,
|
||||||
|
readings: ReadingRepository,
|
||||||
|
predictions: PredictionRepository,
|
||||||
|
sites: SiteRepository,
|
||||||
|
) -> None:
|
||||||
self._alerts = alerts
|
self._alerts = alerts
|
||||||
|
self._readings = readings
|
||||||
|
self._predictions = predictions
|
||||||
|
self._sites = sites
|
||||||
|
|
||||||
async def list_all(
|
async def list_all(
|
||||||
self, *, site_id: str | None = None, severity: str | None = None
|
self, *, site_id: str | None = None, severity: str | None = None
|
||||||
) -> Sequence[Alert]:
|
) -> Sequence[Alert]:
|
||||||
return await self._alerts.list_all(site_id=site_id, severity=severity)
|
return await self._alerts.list_all(site_id=site_id, severity=severity)
|
||||||
|
|
||||||
|
async def detect(
|
||||||
|
self, *, now: datetime | None = None, site_id: str | None = None
|
||||||
|
) -> Sequence[Alert]:
|
||||||
|
"""Compare les lectures/prévisions récentes aux cinq règles internes et enregistre les
|
||||||
|
alertes déclenchées (`source='enervision'`). Idempotent grâce à `source_alert_id` :
|
||||||
|
rejouer sur une fenêtre déjà analysée ne recrée pas les mêmes lignes."""
|
||||||
|
instant = now or datetime.now(UTC)
|
||||||
|
depuis = instant - LOOKBACK
|
||||||
|
|
||||||
|
sites = await self._sites.list_all()
|
||||||
|
if site_id is not None:
|
||||||
|
sites = [site for site in sites if site.site_id == site_id]
|
||||||
|
sites_par_id = {site.site_id: site for site in sites}
|
||||||
|
if not sites_par_id:
|
||||||
|
return []
|
||||||
|
|
||||||
|
lectures = [
|
||||||
|
lecture
|
||||||
|
for lecture in await self._readings.list_since(since=depuis, site_id=site_id)
|
||||||
|
if lecture.site_id in sites_par_id
|
||||||
|
]
|
||||||
|
predictions = [
|
||||||
|
prediction
|
||||||
|
for prediction in await self._predictions.list_since(since=depuis, site_id=site_id)
|
||||||
|
if prediction.site_id in sites_par_id
|
||||||
|
]
|
||||||
|
dernieres_lectures = {
|
||||||
|
lecture.site_id: lecture
|
||||||
|
for lecture in await self._readings.latest_by_site()
|
||||||
|
if lecture.site_id in sites_par_id
|
||||||
|
}
|
||||||
|
|
||||||
|
candidates = [
|
||||||
|
*_detect_threshold(lectures, sites_par_id),
|
||||||
|
*_detect_spike(lectures),
|
||||||
|
*_detect_anomaly(lectures, predictions),
|
||||||
|
*_detect_outage(sites, dernieres_lectures, instant),
|
||||||
|
*_detect_sensor(lectures),
|
||||||
|
]
|
||||||
|
if not candidates:
|
||||||
|
return []
|
||||||
|
return await self._alerts.create_many(candidates)
|
||||||
|
|
||||||
|
|
||||||
|
def _severity_from_ratio(ratio: float) -> str:
|
||||||
|
if ratio >= 2.0:
|
||||||
|
return "critical"
|
||||||
|
if ratio >= 1.5:
|
||||||
|
return "high"
|
||||||
|
if ratio >= 1.2:
|
||||||
|
return "medium"
|
||||||
|
return "low"
|
||||||
|
|
||||||
|
|
||||||
|
def _detect_threshold(lectures: Sequence[Reading], sites_par_id: dict[str, Site]) -> list[Alert]:
|
||||||
|
# Seuil fixe = la capacité déclarée du site : dépasser `capacity_kw` est un dépassement
|
||||||
|
# matériel, pas une simple variation, et évite un seuil arbitraire non fourni par le domaine.
|
||||||
|
alertes = []
|
||||||
|
for lecture in lectures:
|
||||||
|
site = sites_par_id[lecture.site_id]
|
||||||
|
valeur = lecture.consumption_kw
|
||||||
|
if site.capacity_kw is None or site.capacity_kw <= 0 or valeur is None:
|
||||||
|
continue
|
||||||
|
if valeur <= site.capacity_kw:
|
||||||
|
continue
|
||||||
|
alertes.append(
|
||||||
|
Alert(
|
||||||
|
source_alert_id=f"threshold:{THRESHOLD_METRIC}:{lecture.timestamp.isoformat()}",
|
||||||
|
site_id=lecture.site_id,
|
||||||
|
source="enervision",
|
||||||
|
timestamp=lecture.timestamp,
|
||||||
|
type="threshold",
|
||||||
|
severity=_severity_from_ratio(valeur / site.capacity_kw),
|
||||||
|
message=(
|
||||||
|
f"Puissance appelée {valeur:.1f} kW au-dessus de la capacité du site "
|
||||||
|
f"({site.capacity_kw:.1f} kW)"
|
||||||
|
),
|
||||||
|
value=valeur,
|
||||||
|
threshold=site.capacity_kw,
|
||||||
|
metric=THRESHOLD_METRIC,
|
||||||
|
prediction_id=None,
|
||||||
|
raw_data={},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return alertes
|
||||||
|
|
||||||
|
|
||||||
|
def _detect_spike(lectures: Sequence[Reading]) -> list[Alert]:
|
||||||
|
# `lectures` est triée par site, heure puis `reading_id` (cf. `ReadingRepository.list_since`) :
|
||||||
|
# deux lignes consécutives du même site sont donc deux mesures consécutives dans le temps,
|
||||||
|
# sauf lorsqu'elles partagent le même horodatage (deux `source` différentes pour le même
|
||||||
|
# instant, permises par `uq_reading_source`) : ce n'est alors pas une variation réelle, on
|
||||||
|
# l'ignore plutôt que de générer une fausse alerte figée par son `source_alert_id`.
|
||||||
|
alertes = []
|
||||||
|
precedente: Reading | None = None
|
||||||
|
for lecture in lectures:
|
||||||
|
if (
|
||||||
|
precedente is None
|
||||||
|
or precedente.site_id != lecture.site_id
|
||||||
|
or precedente.timestamp == lecture.timestamp
|
||||||
|
):
|
||||||
|
precedente = lecture
|
||||||
|
continue
|
||||||
|
avant, apres = precedente.consumption_kw, lecture.consumption_kw
|
||||||
|
precedente = lecture
|
||||||
|
if avant is None or apres is None:
|
||||||
|
continue
|
||||||
|
if avant == 0:
|
||||||
|
# Une variation relative n'a pas de sens depuis zéro, mais un redémarrage direct à
|
||||||
|
# une consommation positive reste le signal le plus alarmant du lot : `critical`
|
||||||
|
# plutôt qu'un ratio indéfini.
|
||||||
|
if apres > 0:
|
||||||
|
alertes.append(_spike_alert(lecture, avant, apres, severity="critical"))
|
||||||
|
continue
|
||||||
|
variation = abs(apres - avant) / abs(avant)
|
||||||
|
if variation < SPIKE_RELATIVE_THRESHOLD:
|
||||||
|
continue
|
||||||
|
alertes.append(
|
||||||
|
_spike_alert(
|
||||||
|
lecture,
|
||||||
|
avant,
|
||||||
|
apres,
|
||||||
|
severity=_severity_from_ratio(variation / SPIKE_RELATIVE_THRESHOLD),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return alertes
|
||||||
|
|
||||||
|
|
||||||
|
def _spike_alert(lecture: Reading, avant: float, apres: float, *, severity: str) -> Alert:
|
||||||
|
return Alert(
|
||||||
|
source_alert_id=f"spike:{THRESHOLD_METRIC}:{lecture.timestamp.isoformat()}",
|
||||||
|
site_id=lecture.site_id,
|
||||||
|
source="enervision",
|
||||||
|
timestamp=lecture.timestamp,
|
||||||
|
type="spike",
|
||||||
|
severity=severity,
|
||||||
|
message=(
|
||||||
|
f"Variation brutale entre deux lectures consécutives ({avant:.1f} kW -> {apres:.1f} kW)"
|
||||||
|
),
|
||||||
|
value=apres,
|
||||||
|
threshold=avant,
|
||||||
|
metric=THRESHOLD_METRIC,
|
||||||
|
prediction_id=None,
|
||||||
|
raw_data={},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _detect_anomaly(lectures: Sequence[Reading], predictions: Sequence[Prediction]) -> list[Alert]:
|
||||||
|
# Alignement strict (site_id, target_at == timestamp) : `enervision_ml.score` produit une
|
||||||
|
# cible à l'heure pile suivant la dernière lecture, sur la même grille horaire que `reading`.
|
||||||
|
predictions_par_cle = {
|
||||||
|
(prediction.site_id, prediction.target_at): prediction
|
||||||
|
for prediction in predictions
|
||||||
|
if prediction.target_metric == ANOMALY_METRIC
|
||||||
|
}
|
||||||
|
alertes = []
|
||||||
|
for lecture in lectures:
|
||||||
|
prediction = predictions_par_cle.get((lecture.site_id, lecture.timestamp))
|
||||||
|
reel = lecture.consumption_kwh
|
||||||
|
if prediction is None or reel is None or prediction.predicted_value is None:
|
||||||
|
continue
|
||||||
|
predite = prediction.predicted_value
|
||||||
|
if abs(predite) < ANOMALY_MINIMUM_PREDICTED_VALUE:
|
||||||
|
continue
|
||||||
|
ecart = abs(reel - predite) / abs(predite)
|
||||||
|
if ecart < ANOMALY_RELATIVE_THRESHOLD:
|
||||||
|
continue
|
||||||
|
alertes.append(
|
||||||
|
Alert(
|
||||||
|
source_alert_id=f"anomaly:{ANOMALY_METRIC}:{lecture.timestamp.isoformat()}",
|
||||||
|
site_id=lecture.site_id,
|
||||||
|
source="enervision",
|
||||||
|
timestamp=lecture.timestamp,
|
||||||
|
type="anomaly",
|
||||||
|
severity=_severity_from_ratio(ecart / ANOMALY_RELATIVE_THRESHOLD),
|
||||||
|
message=(
|
||||||
|
f"Écart de {ecart * 100:.0f}% entre la consommation mesurée ({reel:.1f} kWh) "
|
||||||
|
f"et la prévision ({predite:.1f} kWh)"
|
||||||
|
),
|
||||||
|
value=reel,
|
||||||
|
threshold=predite,
|
||||||
|
metric=ANOMALY_METRIC,
|
||||||
|
prediction_id=prediction.prediction_id,
|
||||||
|
raw_data={},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return alertes
|
||||||
|
|
||||||
|
|
||||||
|
def _detect_outage(
|
||||||
|
sites: Sequence[Site], dernieres_lectures: dict[str, Reading], now: datetime
|
||||||
|
) -> list[Alert]:
|
||||||
|
alertes = []
|
||||||
|
for site in sites:
|
||||||
|
derniere = dernieres_lectures.get(site.site_id)
|
||||||
|
if derniere is None:
|
||||||
|
alertes.append(
|
||||||
|
_outage_alert(
|
||||||
|
site.site_id,
|
||||||
|
now,
|
||||||
|
reference=None,
|
||||||
|
message="Aucune lecture n'a jamais été reçue pour ce site",
|
||||||
|
severity="critical",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
absence = now - derniere.timestamp
|
||||||
|
if absence < OUTAGE_THRESHOLD:
|
||||||
|
continue
|
||||||
|
alertes.append(
|
||||||
|
_outage_alert(
|
||||||
|
site.site_id,
|
||||||
|
now,
|
||||||
|
reference=derniere.timestamp,
|
||||||
|
message=(
|
||||||
|
f"Aucune lecture depuis {absence} (dernière lecture : "
|
||||||
|
f"{derniere.timestamp.isoformat()})"
|
||||||
|
),
|
||||||
|
severity=_severity_from_ratio(absence / OUTAGE_THRESHOLD),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return alertes
|
||||||
|
|
||||||
|
|
||||||
|
def _outage_alert(
|
||||||
|
site_id: str, now: datetime, *, reference: datetime | None, message: str, severity: str
|
||||||
|
) -> Alert:
|
||||||
|
return Alert(
|
||||||
|
source_alert_id=f"outage:{reference.isoformat() if reference is not None else 'jamais'}",
|
||||||
|
site_id=site_id,
|
||||||
|
source="enervision",
|
||||||
|
timestamp=now,
|
||||||
|
type="outage",
|
||||||
|
severity=severity,
|
||||||
|
message=message,
|
||||||
|
value=None,
|
||||||
|
threshold=None,
|
||||||
|
metric=None,
|
||||||
|
prediction_id=None,
|
||||||
|
raw_data={},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _detect_sensor(lectures: Sequence[Reading]) -> list[Alert]:
|
||||||
|
alertes = []
|
||||||
|
for lecture in lectures:
|
||||||
|
severite = QUALITE_VERS_SEVERITE.get(lecture.data_quality or "")
|
||||||
|
if severite is None:
|
||||||
|
continue
|
||||||
|
raisons = ", ".join(lecture.null_reasons or []) or "raison non précisée"
|
||||||
|
alertes.append(
|
||||||
|
Alert(
|
||||||
|
source_alert_id=f"sensor:{lecture.timestamp.isoformat()}",
|
||||||
|
site_id=lecture.site_id,
|
||||||
|
source="enervision",
|
||||||
|
timestamp=lecture.timestamp,
|
||||||
|
type="sensor",
|
||||||
|
severity=severite,
|
||||||
|
message=f"Qualité de mesure {lecture.data_quality} ({raisons})",
|
||||||
|
value=None,
|
||||||
|
threshold=None,
|
||||||
|
metric=None,
|
||||||
|
prediction_id=None,
|
||||||
|
raw_data={},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return alertes
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Contrainte : `ck_reading_quality` accepte NULL et quatre valeurs seulement, alors que le contrat
|
||||||
|
# frontend n'a aucune valeur pour l'absence de qualité. `qualite_ou_critique()` replie donc sur
|
||||||
|
# `critical`, la seule des quatre qui n'induise pas une confiance qu'on n'a pas. `QUALITES_CONNUES`
|
||||||
|
# reste exposé pour les appelants qui doivent distinguer un `critical` stocké d'un repli.
|
||||||
|
|
||||||
|
from typing import Literal, get_args
|
||||||
|
|
||||||
|
DataQuality = Literal["good", "partial", "degraded", "critical"]
|
||||||
|
|
||||||
|
QUALITES_CONNUES: frozenset[str] = frozenset(get_args(DataQuality))
|
||||||
|
|
||||||
|
_PAR_VALEUR: dict[str, DataQuality] = {valeur: valeur for valeur in get_args(DataQuality)}
|
||||||
|
|
||||||
|
|
||||||
|
def qualite_ou_critique(valeur: str | None) -> DataQuality:
|
||||||
|
if valeur is None:
|
||||||
|
return "critical"
|
||||||
|
return _PAR_VALEUR.get(valeur, "critical")
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
|
||||||
|
from app.models.energy import Prediction, Site
|
||||||
|
from app.repositories.prediction import PredictionRepository
|
||||||
|
from app.repositories.site import SiteRepository
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class SitePrediction:
|
||||||
|
target_at: datetime
|
||||||
|
target_metric: str
|
||||||
|
period_minutes: int | None
|
||||||
|
predicted_value: float | None
|
||||||
|
status: str
|
||||||
|
failure_reason: str | None
|
||||||
|
model_reference: str
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class SitePredictionSummary:
|
||||||
|
site_id: str
|
||||||
|
site_name: str
|
||||||
|
prediction: SitePrediction | None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class PredictionSummary:
|
||||||
|
timestamp: datetime
|
||||||
|
sites: list[SitePredictionSummary]
|
||||||
|
|
||||||
|
|
||||||
|
class PredictionService:
|
||||||
|
def __init__(self, sites: SiteRepository, predictions: PredictionRepository) -> None:
|
||||||
|
self._sites = sites
|
||||||
|
self._predictions = predictions
|
||||||
|
|
||||||
|
async def summary(self) -> PredictionSummary:
|
||||||
|
sites = await self._sites.list_all()
|
||||||
|
dernieres = {p.site_id: p for p in await self._predictions.latest_by_site()}
|
||||||
|
|
||||||
|
return PredictionSummary(
|
||||||
|
timestamp=datetime.now(UTC),
|
||||||
|
sites=[_resume_site(site, dernieres.get(site.site_id)) for site in sites],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _resume_site(site: Site, derniere: Prediction | None) -> SitePredictionSummary:
|
||||||
|
# Piège : l'absence de ligne signifie « jamais scoré », pas une valeur pseudo-statut, qui
|
||||||
|
# n'existe pas dans la contrainte de la table. `prediction` reste `None` plutôt que de
|
||||||
|
# fabriquer un statut absent du domaine `available`/`insufficient_data`/`error`.
|
||||||
|
prediction = None
|
||||||
|
if derniere is not None:
|
||||||
|
prediction = SitePrediction(
|
||||||
|
target_at=derniere.target_at,
|
||||||
|
target_metric=derniere.target_metric,
|
||||||
|
period_minutes=derniere.period_minutes,
|
||||||
|
predicted_value=derniere.predicted_value,
|
||||||
|
status=derniere.status,
|
||||||
|
failure_reason=derniere.failure_reason,
|
||||||
|
model_reference=derniere.model_reference,
|
||||||
|
created_at=derniere.created_at,
|
||||||
|
)
|
||||||
|
|
||||||
|
return SitePredictionSummary(
|
||||||
|
site_id=site.site_id, site_name=site.site_name, prediction=prediction
|
||||||
|
)
|
||||||
@@ -5,12 +5,11 @@ from typing import Literal
|
|||||||
from app.models.energy import Reading, Site
|
from app.models.energy import Reading, Site
|
||||||
from app.repositories.reading import ReadingRepository
|
from app.repositories.reading import ReadingRepository
|
||||||
from app.repositories.site import SiteRepository
|
from app.repositories.site import SiteRepository
|
||||||
|
from app.services.data_quality import qualite_ou_critique
|
||||||
|
|
||||||
CapteurStatus = Literal["ok", "failing"]
|
CapteurStatus = Literal["ok", "failing"]
|
||||||
OverallStatus = Literal["ok", "degraded", "critical"]
|
OverallStatus = Literal["ok", "degraded", "critical"]
|
||||||
|
|
||||||
QUALITES_CONNUES: frozenset[str] = frozenset({"good", "partial", "degraded", "critical"})
|
|
||||||
|
|
||||||
RAISON_VERS_CAPTEUR: dict[str, str] = {
|
RAISON_VERS_CAPTEUR: dict[str, str] = {
|
||||||
"consumption_sensor_failure": "consumption",
|
"consumption_sensor_failure": "consumption",
|
||||||
"electrical_sensor_failure": "electrical",
|
"electrical_sensor_failure": "electrical",
|
||||||
@@ -80,7 +79,7 @@ def _sante_site(site: Site, derniere: Reading | None) -> SanteSite:
|
|||||||
overall="critical",
|
overall="critical",
|
||||||
)
|
)
|
||||||
|
|
||||||
qualite = derniere.data_quality if derniere.data_quality in QUALITES_CONNUES else "critical"
|
qualite = qualite_ou_critique(derniere.data_quality)
|
||||||
overall = _overall_depuis_qualite(qualite)
|
overall = _overall_depuis_qualite(qualite)
|
||||||
|
|
||||||
if overall == "critical":
|
if overall == "critical":
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
from collections.abc import Sequence
|
from collections.abc import Sequence
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
from app.models.energy import Site
|
from app.models.energy import Site
|
||||||
|
from app.repositories.reading import ReadingRepository
|
||||||
from app.repositories.site import SiteRepository
|
from app.repositories.site import SiteRepository
|
||||||
|
from app.services.data_quality import DataQuality, qualite_ou_critique
|
||||||
|
|
||||||
|
|
||||||
class SiteError(Exception):
|
class SiteError(Exception):
|
||||||
@@ -12,9 +16,26 @@ class SiteNotFoundError(SiteError):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class SiteCurrentReading:
|
||||||
|
timestamp: datetime | None
|
||||||
|
site_id: str
|
||||||
|
site_type: str
|
||||||
|
consumption_kw: float | None
|
||||||
|
consumption_kwh: float | None
|
||||||
|
voltage_v: float | None
|
||||||
|
current_a: float | None
|
||||||
|
power_factor: float | None
|
||||||
|
temperature_celsius: float | None
|
||||||
|
humidity_percent: float | None
|
||||||
|
null_reasons: list[str]
|
||||||
|
data_quality: DataQuality
|
||||||
|
|
||||||
|
|
||||||
class SiteService:
|
class SiteService:
|
||||||
def __init__(self, *, sites: SiteRepository) -> None:
|
def __init__(self, *, sites: SiteRepository, readings: ReadingRepository) -> None:
|
||||||
self._sites = sites
|
self._sites = sites
|
||||||
|
self._readings = readings
|
||||||
|
|
||||||
async def list_all(self) -> Sequence[Site]:
|
async def list_all(self) -> Sequence[Site]:
|
||||||
return await self._sites.list_all()
|
return await self._sites.list_all()
|
||||||
@@ -24,3 +45,38 @@ class SiteService:
|
|||||||
if site is None:
|
if site is None:
|
||||||
raise SiteNotFoundError(site_id)
|
raise SiteNotFoundError(site_id)
|
||||||
return site
|
return site
|
||||||
|
|
||||||
|
async def current(self, site_id: str) -> SiteCurrentReading:
|
||||||
|
site = await self.get_by_id(site_id)
|
||||||
|
derniere = await self._readings.latest_for_site(site_id)
|
||||||
|
|
||||||
|
if derniere is None:
|
||||||
|
return SiteCurrentReading(
|
||||||
|
timestamp=None,
|
||||||
|
site_id=site.site_id,
|
||||||
|
site_type=site.site_type,
|
||||||
|
consumption_kw=None,
|
||||||
|
consumption_kwh=None,
|
||||||
|
voltage_v=None,
|
||||||
|
current_a=None,
|
||||||
|
power_factor=None,
|
||||||
|
temperature_celsius=None,
|
||||||
|
humidity_percent=None,
|
||||||
|
null_reasons=[],
|
||||||
|
data_quality="critical",
|
||||||
|
)
|
||||||
|
|
||||||
|
return SiteCurrentReading(
|
||||||
|
timestamp=derniere.timestamp,
|
||||||
|
site_id=site.site_id,
|
||||||
|
site_type=site.site_type,
|
||||||
|
consumption_kw=derniere.consumption_kw,
|
||||||
|
consumption_kwh=derniere.consumption_kwh,
|
||||||
|
voltage_v=derniere.voltage_v,
|
||||||
|
current_a=derniere.current_a,
|
||||||
|
power_factor=derniere.power_factor,
|
||||||
|
temperature_celsius=derniere.temperature_celsius,
|
||||||
|
humidity_percent=derniere.humidity_percent,
|
||||||
|
null_reasons=derniere.null_reasons or [],
|
||||||
|
data_quality=qualite_ou_critique(derniere.data_quality),
|
||||||
|
)
|
||||||
|
|||||||
@@ -1,14 +1,10 @@
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime
|
||||||
from typing import Literal
|
|
||||||
|
|
||||||
from app.models.energy import Reading, Site
|
from app.models.energy import Reading, Site
|
||||||
from app.repositories.reading import ReadingRepository
|
from app.repositories.reading import ReadingRepository
|
||||||
from app.repositories.site import SiteRepository
|
from app.repositories.site import SiteRepository
|
||||||
|
from app.services.data_quality import QUALITES_CONNUES, DataQuality, qualite_ou_critique
|
||||||
DataQuality = Literal["good", "partial", "degraded", "critical"]
|
|
||||||
|
|
||||||
QUALITES_CONNUES: frozenset[str] = frozenset({"good", "partial", "degraded", "critical"})
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
@dataclass(frozen=True, slots=True)
|
||||||
@@ -58,13 +54,10 @@ class StatsService:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def _resume_site(site: Site, derniere: Reading | None) -> SiteConsumption:
|
def _resume_site(site: Site, derniere: Reading | None) -> SiteConsumption:
|
||||||
capacite = site.capacity_kw or 0
|
capacite = site.capacity_kw or 0
|
||||||
# Piège : `data_quality` est nul dès qu'un site n'a jamais reçu de lecture, ou que le
|
|
||||||
# producteur n'a pas su la qualifier. Le contrat frontend n'a pas de valeur pour ce cas,
|
|
||||||
# `critical` est la seule des quatre qui n'induit pas une confiance qu'on n'a pas.
|
|
||||||
qualite: DataQuality = "critical"
|
qualite: DataQuality = "critical"
|
||||||
consommation = None
|
consommation = None
|
||||||
if derniere is not None and derniere.data_quality in QUALITES_CONNUES:
|
if derniere is not None and derniere.data_quality in QUALITES_CONNUES:
|
||||||
qualite = derniere.data_quality # type: ignore[assignment]
|
qualite = qualite_ou_critique(derniere.data_quality)
|
||||||
consommation = derniere.consumption_kw
|
consommation = derniere.consumption_kw
|
||||||
|
|
||||||
charge = (
|
charge = (
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
File diff suppressed because it is too large
Load Diff
+423
-1
@@ -4,7 +4,11 @@
|
|||||||
"title": "EnerVision API",
|
"title": "EnerVision API",
|
||||||
"summary": "Collecte, analyse et restitution de séries temporelles énergétiques.",
|
"summary": "Collecte, analyse et restitution de séries temporelles énergétiques.",
|
||||||
"description": "\nToutes les routes sont préfixées par `/api/v1`.\n\n**Authentification.** Le jeton d'accès se présente dans l'en-tête `Authorization: Bearer ...`.\nLe jeton de rafraîchissement est un cookie `HttpOnly` que le code client ne voit jamais : il\nsuffit d'émettre les requêtes avec les identifiants de session. `POST /auth/refresh` rend un\nnouveau jeton d'accès et fait tourner le cookie.\n\n**Rôles.** `lecteur`, puis `operateur`, puis `admin`. Chaque rôle couvre les droits du\nprécédent.\n\n**Erreurs.** Le corps porte toujours une clé `detail`. Un `403` dont le `detail` vaut\n`password_change_required` n'est pas un refus de droits : il exige le changement du mot de passe\nprovisoire avant toute autre action.\n\nLe parcours de session complet est décrit dans\n`docs/architecture/31-contrat-authentification.md`.\n",
|
"description": "\nToutes les routes sont préfixées par `/api/v1`.\n\n**Authentification.** Le jeton d'accès se présente dans l'en-tête `Authorization: Bearer ...`.\nLe jeton de rafraîchissement est un cookie `HttpOnly` que le code client ne voit jamais : il\nsuffit d'émettre les requêtes avec les identifiants de session. `POST /auth/refresh` rend un\nnouveau jeton d'accès et fait tourner le cookie.\n\n**Rôles.** `lecteur`, puis `operateur`, puis `admin`. Chaque rôle couvre les droits du\nprécédent.\n\n**Erreurs.** Le corps porte toujours une clé `detail`. Un `403` dont le `detail` vaut\n`password_change_required` n'est pas un refus de droits : il exige le changement du mot de passe\nprovisoire avant toute autre action.\n\nLe parcours de session complet est décrit dans\n`docs/architecture/31-contrat-authentification.md`.\n",
|
||||||
"version": "0.1.0"
|
"version": "0.1.0",
|
||||||
|
"x-logo": {
|
||||||
|
"url": "/static/logo-icon.png",
|
||||||
|
"altText": "EnerVision"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"paths": {
|
"paths": {
|
||||||
"/api/v1/health/live": {
|
"/api/v1/health/live": {
|
||||||
@@ -1111,6 +1115,93 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"/api/v1/sites/{site_id}/current": {
|
||||||
|
"get": {
|
||||||
|
"tags": [
|
||||||
|
"sites"
|
||||||
|
],
|
||||||
|
"summary": "Dernière mesure d'un site",
|
||||||
|
"operationId": "get_current_api_v1_sites__site_id__current_get",
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"Jeton d'accès": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"name": "site_id",
|
||||||
|
"in": "path",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "Site Id"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "Successful Response",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/SiteCurrentResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas renvoyée au client.",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/InternalErrorResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"401": {
|
||||||
|
"description": "Jeton absent, illisible, périmé, ou rendu caduc par un changement de rôle ou une désactivation. L'en-tête `WWW-Authenticate` porte la cause dans `error=`.",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/ErrorResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"403": {
|
||||||
|
"description": "Mot de passe provisoire à changer (`detail` vaut `password_change_required`).",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/ErrorResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"422": {
|
||||||
|
"description": "Corps invalide. Le détail nomme le champ fautif et le type d'erreur, jamais la valeur envoyée.",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/ValidationErrorResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"404": {
|
||||||
|
"description": "Aucun site ne porte cet identifiant.",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/ErrorResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"/api/v1/alerts": {
|
"/api/v1/alerts": {
|
||||||
"get": {
|
"get": {
|
||||||
"tags": [
|
"tags": [
|
||||||
@@ -1628,6 +1719,62 @@
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"/api/v1/predictions": {
|
||||||
|
"get": {
|
||||||
|
"tags": [
|
||||||
|
"predictions"
|
||||||
|
],
|
||||||
|
"summary": "Dernière prédiction de consommation par site",
|
||||||
|
"operationId": "get_predictions_api_v1_predictions_get",
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "Successful Response",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/PredictionSummaryResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas renvoyée au client.",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/InternalErrorResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"401": {
|
||||||
|
"description": "Jeton absent, illisible, périmé, ou rendu caduc par un changement de rôle ou une désactivation. L'en-tête `WWW-Authenticate` porte la cause dans `error=`.",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/ErrorResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"403": {
|
||||||
|
"description": "Mot de passe provisoire à changer (`detail` vaut `password_change_required`).",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/ErrorResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"Jeton d'accès": []
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"components": {
|
"components": {
|
||||||
@@ -1881,6 +2028,45 @@
|
|||||||
],
|
],
|
||||||
"title": "PasswordChangeRequest"
|
"title": "PasswordChangeRequest"
|
||||||
},
|
},
|
||||||
|
"PredictionStatus": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": [
|
||||||
|
"available",
|
||||||
|
"insufficient_data",
|
||||||
|
"error"
|
||||||
|
],
|
||||||
|
"title": "PredictionStatus"
|
||||||
|
},
|
||||||
|
"PredictionSummaryResponse": {
|
||||||
|
"properties": {
|
||||||
|
"timestamp": {
|
||||||
|
"type": "string",
|
||||||
|
"format": "date-time",
|
||||||
|
"title": "Timestamp"
|
||||||
|
},
|
||||||
|
"sites": {
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/components/schemas/SitePredictionSummaryResponse"
|
||||||
|
},
|
||||||
|
"type": "array",
|
||||||
|
"title": "Sites"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"timestamp",
|
||||||
|
"sites"
|
||||||
|
],
|
||||||
|
"title": "PredictionSummaryResponse"
|
||||||
|
},
|
||||||
|
"PredictionTargetMetric": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": [
|
||||||
|
"consumption_kwh",
|
||||||
|
"consumption_kw"
|
||||||
|
],
|
||||||
|
"title": "PredictionTargetMetric"
|
||||||
|
},
|
||||||
"PrincipalResponse": {
|
"PrincipalResponse": {
|
||||||
"properties": {
|
"properties": {
|
||||||
"id": {
|
"id": {
|
||||||
@@ -2293,6 +2479,238 @@
|
|||||||
],
|
],
|
||||||
"title": "SensorStatusResponse"
|
"title": "SensorStatusResponse"
|
||||||
},
|
},
|
||||||
|
"SiteCurrentResponse": {
|
||||||
|
"properties": {
|
||||||
|
"timestamp": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "string",
|
||||||
|
"format": "date-time"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Timestamp"
|
||||||
|
},
|
||||||
|
"site_id": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "Site Id"
|
||||||
|
},
|
||||||
|
"site_type": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "Site Type"
|
||||||
|
},
|
||||||
|
"consumption_kw": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Consumption Kw"
|
||||||
|
},
|
||||||
|
"consumption_kwh": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Consumption Kwh"
|
||||||
|
},
|
||||||
|
"voltage_v": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Voltage V"
|
||||||
|
},
|
||||||
|
"current_a": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Current A"
|
||||||
|
},
|
||||||
|
"power_factor": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Power Factor"
|
||||||
|
},
|
||||||
|
"temperature_celsius": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Temperature Celsius"
|
||||||
|
},
|
||||||
|
"humidity_percent": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Humidity Percent"
|
||||||
|
},
|
||||||
|
"null_reasons": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": "array",
|
||||||
|
"title": "Null Reasons"
|
||||||
|
},
|
||||||
|
"data_quality": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": [
|
||||||
|
"good",
|
||||||
|
"partial",
|
||||||
|
"degraded",
|
||||||
|
"critical"
|
||||||
|
],
|
||||||
|
"title": "Data Quality"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"timestamp",
|
||||||
|
"site_id",
|
||||||
|
"site_type",
|
||||||
|
"consumption_kw",
|
||||||
|
"consumption_kwh",
|
||||||
|
"voltage_v",
|
||||||
|
"current_a",
|
||||||
|
"power_factor",
|
||||||
|
"temperature_celsius",
|
||||||
|
"humidity_percent",
|
||||||
|
"null_reasons",
|
||||||
|
"data_quality"
|
||||||
|
],
|
||||||
|
"title": "SiteCurrentResponse"
|
||||||
|
},
|
||||||
|
"SitePredictionResponse": {
|
||||||
|
"properties": {
|
||||||
|
"target_at": {
|
||||||
|
"type": "string",
|
||||||
|
"format": "date-time",
|
||||||
|
"title": "Target At"
|
||||||
|
},
|
||||||
|
"target_metric": {
|
||||||
|
"$ref": "#/components/schemas/PredictionTargetMetric"
|
||||||
|
},
|
||||||
|
"period_minutes": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Period Minutes"
|
||||||
|
},
|
||||||
|
"predicted_value": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Predicted Value"
|
||||||
|
},
|
||||||
|
"status": {
|
||||||
|
"$ref": "#/components/schemas/PredictionStatus"
|
||||||
|
},
|
||||||
|
"failure_reason": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Failure Reason"
|
||||||
|
},
|
||||||
|
"model_reference": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "Model Reference"
|
||||||
|
},
|
||||||
|
"created_at": {
|
||||||
|
"type": "string",
|
||||||
|
"format": "date-time",
|
||||||
|
"title": "Created At"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"target_at",
|
||||||
|
"target_metric",
|
||||||
|
"period_minutes",
|
||||||
|
"predicted_value",
|
||||||
|
"status",
|
||||||
|
"failure_reason",
|
||||||
|
"model_reference",
|
||||||
|
"created_at"
|
||||||
|
],
|
||||||
|
"title": "SitePredictionResponse"
|
||||||
|
},
|
||||||
|
"SitePredictionSummaryResponse": {
|
||||||
|
"properties": {
|
||||||
|
"site_id": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "Site Id"
|
||||||
|
},
|
||||||
|
"site_name": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "Site Name"
|
||||||
|
},
|
||||||
|
"prediction": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/components/schemas/SitePredictionResponse"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"site_id",
|
||||||
|
"site_name",
|
||||||
|
"prediction"
|
||||||
|
],
|
||||||
|
"title": "SitePredictionSummaryResponse"
|
||||||
|
},
|
||||||
"SiteResponse": {
|
"SiteResponse": {
|
||||||
"properties": {
|
"properties": {
|
||||||
"site_id": {
|
"site_id": {
|
||||||
@@ -2748,6 +3166,10 @@
|
|||||||
{
|
{
|
||||||
"name": "sensors",
|
"name": "sensors",
|
||||||
"description": "État de santé des capteurs par site. Réservé au rôle `admin`."
|
"description": "État de santé des capteurs par site. Réservé au rôle `admin`."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "predictions",
|
||||||
|
"description": "Dernière prévision de consommation par site, calculée hors ligne par le pipeline de scoring (`ml/`) et simplement lue ici. Accessible à partir du rôle `lecteur`."
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ dependencies = [
|
|||||||
"argon2-cffi>=23.1",
|
"argon2-cffi>=23.1",
|
||||||
"anyio>=4.0",
|
"anyio>=4.0",
|
||||||
"aiosmtplib>=5.1.3",
|
"aiosmtplib>=5.1.3",
|
||||||
|
"httpx>=0.28.1",
|
||||||
"pandas>=3.0.5",
|
"pandas>=3.0.5",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -27,7 +28,6 @@ dev = [
|
|||||||
"pytest>=9.1.1",
|
"pytest>=9.1.1",
|
||||||
"pytest-asyncio>=1.4.0",
|
"pytest-asyncio>=1.4.0",
|
||||||
"pytest-cov>=7.1.0",
|
"pytest-cov>=7.1.0",
|
||||||
"httpx>=0.28.1",
|
|
||||||
"pandas-stubs>=3.0.5.260914",
|
"pandas-stubs>=3.0.5.260914",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
# Pourquoi : classification unique des routes du contrat, lue par test_route_protection.py,
|
||||||
|
# test_openapi.py et test_matrice_acces.py. Trois listes séparées dérivaient auparavant chacune
|
||||||
|
# de leur côté, et deux entrées de ROUTES_A_ROLE ne correspondaient plus à aucune route sans que
|
||||||
|
# rien ne le signale.
|
||||||
|
# Piège : les trois ensembles doivent rester disjoints et couvrir tout le schéma. C'est
|
||||||
|
# `test_every_declared_route_is_classified` qui le vérifie, pas la relecture.
|
||||||
|
|
||||||
|
from typing import Final
|
||||||
|
|
||||||
|
from app.core.roles import Role
|
||||||
|
|
||||||
|
Route = tuple[str, str]
|
||||||
|
|
||||||
|
ROUTES_PUBLIQUES: Final[frozenset[Route]] = frozenset(
|
||||||
|
{
|
||||||
|
("GET", "/api/v1/health/live"),
|
||||||
|
("GET", "/api/v1/health/ready"),
|
||||||
|
("POST", "/api/v1/auth/login"),
|
||||||
|
# Sans cookie, la déconnexion ne fait rien et répond 204 : elle est idempotente.
|
||||||
|
("POST", "/api/v1/auth/logout"),
|
||||||
|
("POST", "/api/v1/auth/forgot-password"),
|
||||||
|
# Protégée par le jeton dans le corps de la requête, pas par un `Principal` : aucune
|
||||||
|
# authentification préalable ne s'applique, c'est la validité du jeton qui tranche.
|
||||||
|
("POST", "/api/v1/auth/reset-password"),
|
||||||
|
# Même raison : lecture seule, protégée par le jeton passé en paramètre, pas par un
|
||||||
|
# `Principal`. Le jeton est un secret de 256 bits, non brute-forçable.
|
||||||
|
("GET", "/api/v1/auth/reset-password/validate"),
|
||||||
|
("GET", "/metrics"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
# Le cookie opaque porte seul l'autorisation : sans lui la route rend 401, mais aucun `Principal`
|
||||||
|
# n'est construit et `require_role` n'entre jamais en jeu.
|
||||||
|
ROUTE_COOKIE: Final[frozenset[Route]] = frozenset({("POST", "/api/v1/auth/refresh")})
|
||||||
|
|
||||||
|
# Authentifiées par `CurrentPrincipalDep` nu, donc hors de `require_role` et, avec lui, hors du
|
||||||
|
# refus `password_change_required`. Volontaire pour `/auth/password`, qui est la sortie de l'état
|
||||||
|
# provisoire ; subi pour `/auth/logout-all`, cf. test_matrice_acces.py.
|
||||||
|
ROUTES_SANS_ROLE: Final[frozenset[Route]] = frozenset(
|
||||||
|
{
|
||||||
|
("GET", "/api/v1/auth/me"),
|
||||||
|
("POST", "/api/v1/auth/password"),
|
||||||
|
("POST", "/api/v1/auth/logout-all"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
ROLE_MINIMUM: Final[dict[Route, Role]] = {
|
||||||
|
("GET", "/api/v1/sites"): Role.LECTEUR,
|
||||||
|
("GET", "/api/v1/sites/{site_id}"): Role.LECTEUR,
|
||||||
|
("GET", "/api/v1/sites/{site_id}/current"): Role.LECTEUR,
|
||||||
|
("GET", "/api/v1/alerts"): Role.LECTEUR,
|
||||||
|
("GET", "/api/v1/recommendations"): Role.LECTEUR,
|
||||||
|
("GET", "/api/v1/recommendations/{recommendation_id}"): Role.LECTEUR,
|
||||||
|
("GET", "/api/v1/stats/summary"): Role.LECTEUR,
|
||||||
|
("GET", "/api/v1/readings"): Role.LECTEUR,
|
||||||
|
("GET", "/api/v1/predictions"): Role.LECTEUR,
|
||||||
|
("GET", "/api/v1/sensors/status"): Role.ADMIN,
|
||||||
|
("GET", "/api/v1/users"): Role.ADMIN,
|
||||||
|
("POST", "/api/v1/users"): Role.ADMIN,
|
||||||
|
("PATCH", "/api/v1/users/{user_id}"): Role.ADMIN,
|
||||||
|
("POST", "/api/v1/users/{user_id}/password-reset"): Role.ADMIN,
|
||||||
|
}
|
||||||
|
|
||||||
|
# Piège : `{recommendation_id}` est typé `int` et `{user_id}` est un UUID. Une substitution
|
||||||
|
# uniforme par une chaîne quelconque rendrait 422 avant d'atteindre la garde de rôle, et le test
|
||||||
|
# passerait en prouvant autre chose que ce qu'il annonce.
|
||||||
|
SUBSTITUTIONS: Final[dict[str, str]] = {
|
||||||
|
"{user_id}": "00000000-0000-0000-0000-000000000000",
|
||||||
|
"{site_id}": "site-absent-du-jeu-de-donnees",
|
||||||
|
"{recommendation_id}": "999999999",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def chemin_concret(chemin: str) -> str:
|
||||||
|
for gabarit, valeur in SUBSTITUTIONS.items():
|
||||||
|
chemin = chemin.replace(gabarit, valeur)
|
||||||
|
return chemin
|
||||||
|
|
||||||
|
|
||||||
|
def routes_du_schema(schema: dict[str, object]) -> list[Route]:
|
||||||
|
chemins: dict[str, dict[str, object]] = schema["paths"] # type: ignore[assignment]
|
||||||
|
return [
|
||||||
|
(methode.upper(), chemin)
|
||||||
|
for chemin, operations in chemins.items()
|
||||||
|
for methode in operations
|
||||||
|
if methode.upper() in {"GET", "POST", "PATCH", "PUT", "DELETE"}
|
||||||
|
]
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
# Pourquoi : la matrice rôle x route sur les routes réelles. `test_authorization.py` la joue déjà,
|
||||||
|
# mais contre une route jetable montée par une fixture, ce qui ne dit rien du niveau effectivement
|
||||||
|
# posé sur `/sites` ou `/users`. `ROLE_MINIMUM` (tests/api/acces.py) est la référence, et ce
|
||||||
|
# fichier est ce qui la confronte au comportement observé.
|
||||||
|
# Piège : l'assertion porte sur le refus de la garde, pas sur un 200. Un rôle suffisant peut
|
||||||
|
# légitimement recevoir 404 ou 422 selon les données ; ce qui compte est qu'il ne reçoive pas le
|
||||||
|
# 403 `Droits insuffisants`. Sans cette nuance, le test dépendrait du contenu de la base.
|
||||||
|
# Les tests `integration` en fin de fichier rejouent la même matrice avec de vrais jetons, donc en
|
||||||
|
# traversant le décodage du JWT et la relecture du compte, ce que l'override court-circuite.
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from collections.abc import AsyncIterator, Callable, Iterator
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from httpx import AsyncClient, Response
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
from app.api.deps import get_current_principal
|
||||||
|
from app.core.hashing import build_hasher
|
||||||
|
from app.core.principal import Principal
|
||||||
|
from app.core.roles import AccountKind, Role, has_at_least
|
||||||
|
from app.db.session import get_session, get_session_factory
|
||||||
|
from app.repositories.user import UserRepository
|
||||||
|
from tests.api.acces import ROLE_MINIMUM, chemin_concret
|
||||||
|
|
||||||
|
ROLES = [Role.LECTEUR, Role.OPERATEUR, Role.ADMIN]
|
||||||
|
IDS_DE_ROLE = ["lecteur", "operateur", "admin"]
|
||||||
|
REFUS_DE_DROITS = "Droits insuffisants"
|
||||||
|
REFUS_DE_MOT_DE_PASSE = "password_change_required"
|
||||||
|
MOT_DE_PASSE = "un-mot-de-passe-de-recette"
|
||||||
|
|
||||||
|
|
||||||
|
# `FakeSession` de tests/factories.py rend un unique objet pour les trois formes d'appel, ce qui
|
||||||
|
# suffit à un test d'endpoint ciblé mais pas à balayer 13 routes qui interrogent chacune la base
|
||||||
|
# à sa façon. Ce double rend un résultat vide quelle que soit la forme demandée, pour que la
|
||||||
|
# réponse observée vienne de la garde de rôle et jamais d'un double mal ajusté.
|
||||||
|
class ResultatVide:
|
||||||
|
def scalars(self) -> ResultatVide:
|
||||||
|
return self
|
||||||
|
|
||||||
|
def all(self) -> list[object]:
|
||||||
|
return []
|
||||||
|
|
||||||
|
def first(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def one_or_none(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def scalar_one_or_none(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def mappings(self) -> ResultatVide:
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __iter__(self) -> Iterator[object]:
|
||||||
|
return iter(())
|
||||||
|
|
||||||
|
|
||||||
|
class SessionMuette:
|
||||||
|
async def scalar(self, *_: object, **__: object) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def execute(self, *_: object, **__: object) -> ResultatVide:
|
||||||
|
return ResultatVide()
|
||||||
|
|
||||||
|
async def scalars(self, *_: object, **__: object) -> ResultatVide:
|
||||||
|
return ResultatVide()
|
||||||
|
|
||||||
|
async def get(self, *_: object, **__: object) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def flush(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def commit(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def rollback(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def add(self, *_: object, **__: object) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def base_muette(app: FastAPI) -> None:
|
||||||
|
async def override() -> AsyncIterator[SessionMuette]:
|
||||||
|
yield SessionMuette()
|
||||||
|
|
||||||
|
app.dependency_overrides[get_session] = override
|
||||||
|
|
||||||
|
|
||||||
|
def principal(role: Role, *, must_change_password: bool = False) -> Principal:
|
||||||
|
return Principal(
|
||||||
|
id=uuid.uuid4(),
|
||||||
|
email=f"matrice-{role.value}@enervision.fr",
|
||||||
|
role=role,
|
||||||
|
kind=AccountKind.HUMAIN,
|
||||||
|
must_change_password=must_change_password,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def connecte(app: FastAPI) -> Iterator[Callable[[Principal], None]]:
|
||||||
|
def installe(acteur: Principal) -> None:
|
||||||
|
app.dependency_overrides[get_current_principal] = lambda: acteur
|
||||||
|
|
||||||
|
yield installe
|
||||||
|
app.dependency_overrides.pop(get_current_principal, None)
|
||||||
|
|
||||||
|
|
||||||
|
async def appelle(client: AsyncClient, methode: str, chemin: str, **kwargs: object) -> Response:
|
||||||
|
return await client.request(methode, chemin_concret(chemin), json={}, **kwargs) # type: ignore[arg-type]
|
||||||
|
|
||||||
|
|
||||||
|
def motif_du_refus(response: Response) -> str | None:
|
||||||
|
if response.status_code != 403:
|
||||||
|
return None
|
||||||
|
detail = response.json().get("detail")
|
||||||
|
return detail if isinstance(detail, str) else None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("role", ROLES, ids=IDS_DE_ROLE)
|
||||||
|
async def test_a_role_below_the_minimum_is_refused_on_every_guarded_route(
|
||||||
|
connecte: Callable[[Principal], None],
|
||||||
|
client: AsyncClient,
|
||||||
|
base_muette: None,
|
||||||
|
role: Role,
|
||||||
|
) -> None:
|
||||||
|
connecte(principal(role))
|
||||||
|
laissees_passer: list[tuple[str, str, int]] = []
|
||||||
|
|
||||||
|
for (methode, chemin), minimum in ROLE_MINIMUM.items():
|
||||||
|
if has_at_least(role, minimum):
|
||||||
|
continue
|
||||||
|
response = await appelle(client, methode, chemin)
|
||||||
|
if motif_du_refus(response) != REFUS_DE_DROITS:
|
||||||
|
laissees_passer.append((methode, chemin, response.status_code))
|
||||||
|
|
||||||
|
assert laissees_passer == []
|
||||||
|
|
||||||
|
|
||||||
|
# Le pendant du test précédent : sans lui, une garde posée trop haut, par exemple `AdminDep` sur
|
||||||
|
# `/sites`, ne ferait échouer aucun test du dépôt.
|
||||||
|
@pytest.mark.parametrize("role", ROLES, ids=IDS_DE_ROLE)
|
||||||
|
async def test_a_role_at_or_above_the_minimum_is_never_refused_by_the_guard(
|
||||||
|
connecte: Callable[[Principal], None],
|
||||||
|
client: AsyncClient,
|
||||||
|
base_muette: None,
|
||||||
|
role: Role,
|
||||||
|
) -> None:
|
||||||
|
connecte(principal(role))
|
||||||
|
refusees: list[tuple[str, str]] = []
|
||||||
|
|
||||||
|
for (methode, chemin), minimum in ROLE_MINIMUM.items():
|
||||||
|
if not has_at_least(role, minimum):
|
||||||
|
continue
|
||||||
|
response = await appelle(client, methode, chemin)
|
||||||
|
if motif_du_refus(response) == REFUS_DE_DROITS:
|
||||||
|
refusees.append((methode, chemin))
|
||||||
|
|
||||||
|
assert refusees == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_a_pending_password_change_is_refused_on_every_guarded_route(
|
||||||
|
connecte: Callable[[Principal], None],
|
||||||
|
client: AsyncClient,
|
||||||
|
base_muette: None,
|
||||||
|
) -> None:
|
||||||
|
connecte(principal(Role.ADMIN, must_change_password=True))
|
||||||
|
laissees_passer: list[tuple[str, str, int]] = []
|
||||||
|
|
||||||
|
for methode, chemin in ROLE_MINIMUM:
|
||||||
|
response = await appelle(client, methode, chemin)
|
||||||
|
if motif_du_refus(response) != REFUS_DE_MOT_DE_PASSE:
|
||||||
|
laissees_passer.append((methode, chemin, response.status_code))
|
||||||
|
|
||||||
|
assert laissees_passer == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
async def comptes_par_role() -> AsyncIterator[dict[Role, str]]:
|
||||||
|
marque = uuid.uuid4().hex[:12]
|
||||||
|
hacheur = build_hasher(time_cost=1, memory_cost_kib=8192, parallelism=1, max_concurrency=2)
|
||||||
|
empreinte = await hacheur.hash(MOT_DE_PASSE)
|
||||||
|
adresses = {role: f"matrice-{marque}-{role.value}@enervision.fr" for role in ROLES}
|
||||||
|
|
||||||
|
async with get_session_factory()() as session:
|
||||||
|
depot = UserRepository(session)
|
||||||
|
for role, email in adresses.items():
|
||||||
|
await depot.create(email=email, password_hash=empreinte, role=role)
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
yield adresses
|
||||||
|
|
||||||
|
async with get_session_factory()() as session:
|
||||||
|
await session.execute(
|
||||||
|
text("delete from app_user where email like :motif"), {"motif": f"matrice-{marque}-%"}
|
||||||
|
)
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
async def authentifie(client: AsyncClient, email: str) -> dict[str, str]:
|
||||||
|
reponse = await client.post(
|
||||||
|
"/api/v1/auth/login", json={"email": email, "password": MOT_DE_PASSE}
|
||||||
|
)
|
||||||
|
assert reponse.status_code == 200, reponse.text
|
||||||
|
return {"Authorization": f"Bearer {reponse.json()['access_token']}"}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.integration
|
||||||
|
@pytest.mark.parametrize("role", ROLES, ids=IDS_DE_ROLE)
|
||||||
|
async def test_a_real_token_reaches_exactly_the_routes_of_its_rank(
|
||||||
|
comptes_par_role: dict[Role, str], client: AsyncClient, role: Role
|
||||||
|
) -> None:
|
||||||
|
entetes = await authentifie(client, comptes_par_role[role])
|
||||||
|
ecarts: list[tuple[str, str, int, str]] = []
|
||||||
|
|
||||||
|
for (methode, chemin), minimum in ROLE_MINIMUM.items():
|
||||||
|
response = await appelle(client, methode, chemin, headers=entetes)
|
||||||
|
refuse = motif_du_refus(response) == REFUS_DE_DROITS
|
||||||
|
if refuse is has_at_least(role, minimum):
|
||||||
|
ecarts.append((methode, chemin, response.status_code, response.text[:120]))
|
||||||
|
|
||||||
|
assert ecarts == []
|
||||||
|
|
||||||
|
|
||||||
|
# Contrainte : `operateur` n'ouvre aujourd'hui aucune route de plus que `lecteur`, faute d'écriture
|
||||||
|
# métier dans l'API. Figer l'égalité rend la régression visible le jour où une route d'opérateur
|
||||||
|
# arrive sans que `ROLE_MINIMUM` soit mis à jour.
|
||||||
|
@pytest.mark.integration
|
||||||
|
async def test_the_operator_rank_opens_nothing_more_than_the_reader_rank(
|
||||||
|
comptes_par_role: dict[Role, str], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
lecteur = await authentifie(client, comptes_par_role[Role.LECTEUR])
|
||||||
|
operateur = await authentifie(client, comptes_par_role[Role.OPERATEUR])
|
||||||
|
divergences: list[tuple[str, str]] = []
|
||||||
|
|
||||||
|
for methode, chemin in ROLE_MINIMUM:
|
||||||
|
cote_lecteur = await appelle(client, methode, chemin, headers=lecteur)
|
||||||
|
cote_operateur = await appelle(client, methode, chemin, headers=operateur)
|
||||||
|
if cote_lecteur.status_code != cote_operateur.status_code:
|
||||||
|
divergences.append((methode, chemin))
|
||||||
|
|
||||||
|
assert divergences == []
|
||||||
|
|
||||||
|
|
||||||
|
# Piège : `/auth/logout-all` prend un `CurrentPrincipalDep` nu, donc elle échappe au gate
|
||||||
|
# `must_change_password` que seul `require_role` applique. Comportement figé ici, pas corrigé.
|
||||||
|
@pytest.mark.integration
|
||||||
|
async def test_a_temporary_password_blocks_the_business_routes_but_not_logout_all(
|
||||||
|
client: AsyncClient,
|
||||||
|
) -> None:
|
||||||
|
marque = uuid.uuid4().hex[:12]
|
||||||
|
email = f"matrice-{marque}-provisoire@enervision.fr"
|
||||||
|
hacheur = build_hasher(time_cost=1, memory_cost_kib=8192, parallelism=1, max_concurrency=2)
|
||||||
|
empreinte = await hacheur.hash(MOT_DE_PASSE)
|
||||||
|
|
||||||
|
async with get_session_factory()() as session:
|
||||||
|
await UserRepository(session).create(
|
||||||
|
email=email, password_hash=empreinte, role=Role.ADMIN, must_change_password=True
|
||||||
|
)
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
try:
|
||||||
|
entetes = await authentifie(client, email)
|
||||||
|
sites = await client.get("/api/v1/sites", headers=entetes)
|
||||||
|
identite = await client.get("/api/v1/auth/me", headers=entetes)
|
||||||
|
fermeture = await client.post("/api/v1/auth/logout-all", headers=entetes)
|
||||||
|
|
||||||
|
assert motif_du_refus(sites) == REFUS_DE_MOT_DE_PASSE
|
||||||
|
assert identite.status_code == 200
|
||||||
|
assert fermeture.status_code == 204
|
||||||
|
finally:
|
||||||
|
async with get_session_factory()() as session:
|
||||||
|
await session.execute(text("delete from app_user where email = :e"), {"e": email})
|
||||||
|
await session.commit()
|
||||||
@@ -8,6 +8,7 @@ from typing import Any
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from app import cli
|
from app import cli
|
||||||
|
from tests.api.acces import ROLE_MINIMUM
|
||||||
|
|
||||||
METHODES = {"get", "post", "patch", "put", "delete"}
|
METHODES = {"get", "post", "patch", "put", "delete"}
|
||||||
|
|
||||||
@@ -24,20 +25,11 @@ ORIGINE_VERIFIEE = {
|
|||||||
|
|
||||||
# Toute route derrière `require_role` (LecteurDep, OperateurDep, AdminDep) peut rendre 403 pour
|
# Toute route derrière `require_role` (LecteurDep, OperateurDep, AdminDep) peut rendre 403 pour
|
||||||
# `password_change_required`, pas seulement les routes `admin`.
|
# `password_change_required`, pas seulement les routes `admin`.
|
||||||
ROUTES_A_ROLE = {
|
# Piège : cette liste était recopiée ici, et deux de ses entrées portaient `{id}` là où le contrat
|
||||||
("GET", "/api/v1/users"),
|
# expose `{user_id}`. Elles ne correspondaient donc à aucune opération, et le test ci-dessous
|
||||||
("POST", "/api/v1/users"),
|
# passait au vert sans rien vérifier sur ces deux routes. Elle est maintenant dérivée, et
|
||||||
("PATCH", "/api/v1/users/{id}"),
|
# `test_every_declared_route_is_classified` interdit l'entrée morte.
|
||||||
("POST", "/api/v1/users/{id}/password-reset"),
|
ROUTES_A_ROLE = frozenset(ROLE_MINIMUM)
|
||||||
("GET", "/api/v1/sites"),
|
|
||||||
("GET", "/api/v1/sites/{site_id}"),
|
|
||||||
("GET", "/api/v1/alerts"),
|
|
||||||
("GET", "/api/v1/recommendations"),
|
|
||||||
("GET", "/api/v1/recommendations/{recommendation_id}"),
|
|
||||||
("GET", "/api/v1/stats/summary"),
|
|
||||||
("GET", "/api/v1/readings"),
|
|
||||||
("GET", "/api/v1/sensors/status"),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
@pytest.fixture(scope="module")
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
from collections.abc import Callable, Iterator
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from httpx import AsyncClient
|
||||||
|
|
||||||
|
from app.api.deps import get_current_principal, get_prediction_service
|
||||||
|
from app.core.principal import Principal
|
||||||
|
from app.core.roles import AccountKind, Role
|
||||||
|
from app.services.prediction import PredictionSummary, SitePrediction, SitePredictionSummary
|
||||||
|
|
||||||
|
TARGET_AT = datetime(2026, 9, 16, 13, 0, tzinfo=UTC)
|
||||||
|
CREATED_AT = datetime(2026, 9, 16, 12, 0, tzinfo=UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def lecteur() -> Principal:
|
||||||
|
# Le garde-fou de rôle (`lecteur` minimum) est déjà couvert par l'ensemble `ROUTES_A_ROLE`
|
||||||
|
# de `tests/api/test_openapi.py` : pas besoin ici d'un paramètre de rôle jamais appelé avec
|
||||||
|
# autre chose que sa valeur par défaut.
|
||||||
|
return Principal(
|
||||||
|
id=uuid4(),
|
||||||
|
email="lecteur@enervision.fr",
|
||||||
|
role=Role.LECTEUR,
|
||||||
|
kind=AccountKind.HUMAIN,
|
||||||
|
must_change_password=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FauxService:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.resume = PredictionSummary(
|
||||||
|
timestamp=datetime.now(UTC),
|
||||||
|
sites=[
|
||||||
|
SitePredictionSummary(
|
||||||
|
site_id="SITE001",
|
||||||
|
site_name="Bureau Paris La Défense",
|
||||||
|
prediction=SitePrediction(
|
||||||
|
target_at=TARGET_AT,
|
||||||
|
target_metric="consumption_kwh",
|
||||||
|
period_minutes=60,
|
||||||
|
predicted_value=812.5,
|
||||||
|
status="available",
|
||||||
|
failure_reason=None,
|
||||||
|
model_reference="lightgbm-abc123",
|
||||||
|
created_at=CREATED_AT,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
SitePredictionSummary(site_id="SITE002", site_name="Usine Lyon", prediction=None),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
async def summary(self) -> PredictionSummary:
|
||||||
|
return self.resume
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def servi(app: FastAPI) -> Iterator[Callable[[], FauxService]]:
|
||||||
|
def installe() -> FauxService:
|
||||||
|
service = FauxService()
|
||||||
|
app.dependency_overrides[get_prediction_service] = lambda: service
|
||||||
|
app.dependency_overrides[get_current_principal] = lambda: lecteur()
|
||||||
|
return service
|
||||||
|
|
||||||
|
yield installe
|
||||||
|
app.dependency_overrides.pop(get_prediction_service, None)
|
||||||
|
app.dependency_overrides.pop(get_current_principal, None)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_get_predictions_returns_the_service_result(
|
||||||
|
servi: Callable[[], FauxService], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
servi()
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/predictions")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
corps = response.json()
|
||||||
|
premier, second = corps["sites"]
|
||||||
|
assert premier["site_id"] == "SITE001"
|
||||||
|
assert premier["prediction"]["predicted_value"] == 812.5
|
||||||
|
assert premier["prediction"]["status"] == "available"
|
||||||
|
assert second["site_id"] == "SITE002"
|
||||||
|
assert second["prediction"] is None
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# Ce test est le garde-fou de l'autorisation : rendre une route publique oblige à modifier
|
# Ce test est le garde-fou de l'autorisation : rendre une route publique oblige à modifier
|
||||||
# `ROUTES_PUBLIQUES` ci-dessous, ce qui apparaît en clair dans la diff d'une pull request et
|
# `ROUTES_PUBLIQUES` dans `tests/api/acces.py`, ce qui apparaît en clair dans la diff d'une pull
|
||||||
# demande une justification au relecteur.
|
# request et demande une justification au relecteur.
|
||||||
# Pourquoi : il interroge réellement chaque route sans jeton au lieu d'inspecter l'arbre de
|
# Pourquoi : il interroge réellement chaque route sans jeton au lieu d'inspecter l'arbre de
|
||||||
# dépendances. L'arbre n'est accessible que par l'API privée de FastAPI, et surtout une route
|
# dépendances. L'arbre n'est accessible que par l'API privée de FastAPI, et surtout une route
|
||||||
# peut porter la bonne dépendance tout en répondant quand même.
|
# peut porter la bonne dépendance tout en répondant quand même.
|
||||||
@@ -11,58 +11,64 @@ import pytest
|
|||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from httpx import AsyncClient
|
from httpx import AsyncClient
|
||||||
|
|
||||||
ROUTES_PUBLIQUES = frozenset(
|
from tests.api.acces import (
|
||||||
{
|
ROLE_MINIMUM,
|
||||||
("GET", "/api/v1/health/live"),
|
ROUTE_COOKIE,
|
||||||
("GET", "/api/v1/health/ready"),
|
ROUTES_PUBLIQUES,
|
||||||
("POST", "/api/v1/auth/login"),
|
ROUTES_SANS_ROLE,
|
||||||
# Sans cookie, la déconnexion ne fait rien et répond 204 : elle est idempotente.
|
Route,
|
||||||
("POST", "/api/v1/auth/logout"),
|
chemin_concret,
|
||||||
("POST", "/api/v1/auth/forgot-password"),
|
routes_du_schema,
|
||||||
# Protégée par le jeton dans le corps de la requête, pas par un `Principal` : aucune
|
|
||||||
# authentification préalable ne s'applique, c'est la validité du jeton qui tranche.
|
|
||||||
("POST", "/api/v1/auth/reset-password"),
|
|
||||||
# Même raison : lecture seule, protégée par le jeton passé en paramètre, pas par un
|
|
||||||
# `Principal`. Le jeton est un secret de 256 bits, non brute-forçable.
|
|
||||||
("GET", "/api/v1/auth/reset-password/validate"),
|
|
||||||
("GET", "/metrics"),
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
VALEURS_DE_SUBSTITUTION = "00000000-0000-0000-0000-000000000000"
|
|
||||||
STATUTS_DE_REFUS = {401, 403}
|
STATUTS_DE_REFUS = {401, 403}
|
||||||
|
HORS_SCHEMA = {("GET", "/metrics")}
|
||||||
|
|
||||||
|
|
||||||
def routes_declarees(app: FastAPI) -> list[tuple[str, str]]:
|
def routes_declarees(app: FastAPI) -> list[Route]:
|
||||||
schema: dict[str, Any] = app.openapi()
|
schema: dict[str, Any] = app.openapi()
|
||||||
return [
|
return routes_du_schema(schema)
|
||||||
(methode.upper(), chemin)
|
|
||||||
for chemin, operations in schema["paths"].items()
|
|
||||||
for methode in operations
|
|
||||||
if methode.upper() in {"GET", "POST", "PATCH", "PUT", "DELETE"}
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def routes_protegees(app: FastAPI) -> list[tuple[str, str]]:
|
def routes_protegees(app: FastAPI) -> list[Route]:
|
||||||
return [route for route in routes_declarees(app) if route not in ROUTES_PUBLIQUES]
|
return [route for route in routes_declarees(app) if route not in ROUTES_PUBLIQUES]
|
||||||
|
|
||||||
|
|
||||||
def test_the_public_allow_list_has_no_stale_entry(app: FastAPI) -> None:
|
def test_the_public_allow_list_has_no_stale_entry(app: FastAPI) -> None:
|
||||||
declarees = set(routes_declarees(app)) | {("GET", "/metrics")}
|
declarees = set(routes_declarees(app)) | HORS_SCHEMA
|
||||||
|
|
||||||
inconnues = ROUTES_PUBLIQUES - declarees
|
inconnues = ROUTES_PUBLIQUES - declarees
|
||||||
|
|
||||||
assert inconnues == set()
|
assert inconnues == set()
|
||||||
|
|
||||||
|
|
||||||
|
# Sans lui, une route ajoutée sans être classée n'est vue par aucun test de rôle : elle hérite
|
||||||
|
# du seul contrôle anonyme, et une garde posée au mauvais niveau passe inaperçue.
|
||||||
|
def test_every_declared_route_is_classified(app: FastAPI) -> None:
|
||||||
|
classees = ROUTES_PUBLIQUES | ROUTE_COOKIE | ROUTES_SANS_ROLE | set(ROLE_MINIMUM)
|
||||||
|
|
||||||
|
non_classees = set(routes_declarees(app)) - classees
|
||||||
|
fantomes = classees - set(routes_declarees(app)) - HORS_SCHEMA
|
||||||
|
|
||||||
|
assert non_classees == set(), "classer la route dans tests/api/acces.py"
|
||||||
|
assert fantomes == set(), "entrée morte : la route n'existe plus sous ce chemin"
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_four_classes_of_routes_stay_disjoint() -> None:
|
||||||
|
classes = [ROUTES_PUBLIQUES, ROUTE_COOKIE, ROUTES_SANS_ROLE, frozenset(ROLE_MINIMUM)]
|
||||||
|
|
||||||
|
for rang, classe in enumerate(classes):
|
||||||
|
for autre in classes[rang + 1 :]:
|
||||||
|
assert classe & autre == frozenset()
|
||||||
|
|
||||||
|
|
||||||
async def test_every_route_rejects_an_anonymous_caller_unless_explicitly_public(
|
async def test_every_route_rejects_an_anonymous_caller_unless_explicitly_public(
|
||||||
app: FastAPI, client: AsyncClient
|
app: FastAPI, client: AsyncClient
|
||||||
) -> None:
|
) -> None:
|
||||||
ouvertes: list[tuple[str, str, int]] = []
|
ouvertes: list[tuple[str, str, int]] = []
|
||||||
|
|
||||||
for methode, chemin in routes_protegees(app):
|
for methode, chemin in routes_protegees(app):
|
||||||
concret = chemin.replace("{user_id}", VALEURS_DE_SUBSTITUTION)
|
response = await client.request(methode, chemin_concret(chemin), json={})
|
||||||
response = await client.request(methode, concret, json={})
|
|
||||||
if response.status_code not in STATUTS_DE_REFUS:
|
if response.status_code not in STATUTS_DE_REFUS:
|
||||||
ouvertes.append((methode, chemin, response.status_code))
|
ouvertes.append((methode, chemin, response.status_code))
|
||||||
|
|
||||||
@@ -81,3 +87,19 @@ async def test_the_declared_routes_are_actually_reachable(app: FastAPI) -> None:
|
|||||||
)
|
)
|
||||||
def test_the_health_probes_stay_public(app: FastAPI, chemin: str) -> None:
|
def test_the_health_probes_stay_public(app: FastAPI, chemin: str) -> None:
|
||||||
assert ("GET", chemin) in ROUTES_PUBLIQUES
|
assert ("GET", chemin) in ROUTES_PUBLIQUES
|
||||||
|
|
||||||
|
|
||||||
|
# Piège : ni les routes `include_in_schema=False` (/docs, /redoc) ni un `Mount` Starlette
|
||||||
|
# (/static) n'apparaissent dans `app.openapi()["paths"]`. `routes_declarees()` ne les voit
|
||||||
|
# donc jamais, et elles échapperaient silencieusement au garde-fou ci-dessus.
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"chemin",
|
||||||
|
["/docs", "/redoc", "/static/logo-icon.png"],
|
||||||
|
ids=["swagger_ui", "redoc", "logo_statique"],
|
||||||
|
)
|
||||||
|
async def test_the_documentation_routes_are_public_by_design(
|
||||||
|
app: FastAPI, client: AsyncClient, chemin: str
|
||||||
|
) -> None:
|
||||||
|
response = await client.get(chemin)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
from collections.abc import Callable, Iterator
|
from collections.abc import Callable, Iterator
|
||||||
|
from datetime import UTC, datetime
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@@ -9,7 +10,9 @@ from app.api.deps import get_current_principal, get_site_service
|
|||||||
from app.core.principal import Principal
|
from app.core.principal import Principal
|
||||||
from app.core.roles import AccountKind, Role
|
from app.core.roles import AccountKind, Role
|
||||||
from app.models.energy import Site
|
from app.models.energy import Site
|
||||||
from app.services.site import SiteNotFoundError
|
from app.services.site import SiteCurrentReading, SiteNotFoundError
|
||||||
|
|
||||||
|
TIMESTAMP = datetime(2026, 9, 16, 12, 0, tzinfo=UTC)
|
||||||
|
|
||||||
|
|
||||||
def principal(role: Role = Role.LECTEUR) -> Principal:
|
def principal(role: Role = Role.LECTEUR) -> Principal:
|
||||||
@@ -33,10 +36,28 @@ def site(site_id: str = "site-1") -> Site:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def lecture_actuelle(site_id: str = "site-1") -> SiteCurrentReading:
|
||||||
|
return SiteCurrentReading(
|
||||||
|
timestamp=TIMESTAMP,
|
||||||
|
site_id=site_id,
|
||||||
|
site_type="industriel",
|
||||||
|
consumption_kw=87.34,
|
||||||
|
consumption_kwh=87.34,
|
||||||
|
voltage_v=401.2,
|
||||||
|
current_a=132.5,
|
||||||
|
power_factor=0.923,
|
||||||
|
temperature_celsius=22.1,
|
||||||
|
humidity_percent=58.4,
|
||||||
|
null_reasons=[],
|
||||||
|
data_quality="good",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class FauxService:
|
class FauxService:
|
||||||
def __init__(self, erreur: Exception | None = None) -> None:
|
def __init__(self, erreur: Exception | None = None) -> None:
|
||||||
self._erreur = erreur
|
self._erreur = erreur
|
||||||
self.site = site()
|
self.site = site()
|
||||||
|
self.actuel = lecture_actuelle()
|
||||||
|
|
||||||
async def list_all(self) -> list[Site]:
|
async def list_all(self) -> list[Site]:
|
||||||
return [self.site]
|
return [self.site]
|
||||||
@@ -46,6 +67,11 @@ class FauxService:
|
|||||||
raise self._erreur
|
raise self._erreur
|
||||||
return self.site
|
return self.site
|
||||||
|
|
||||||
|
async def current(self, site_id: str) -> SiteCurrentReading:
|
||||||
|
if self._erreur is not None:
|
||||||
|
raise self._erreur
|
||||||
|
return self.actuel
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def lecteur_connecte(app: FastAPI) -> Iterator[None]:
|
def lecteur_connecte(app: FastAPI) -> Iterator[None]:
|
||||||
@@ -109,6 +135,30 @@ async def test_get_site_returns_404_for_an_unknown_site(
|
|||||||
assert response.status_code == 404
|
assert response.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
async def test_get_current_returns_the_latest_reading(
|
||||||
|
servi: Callable[..., FauxService], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
servi()
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/sites/site-1/current")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
corps = response.json()
|
||||||
|
assert corps["site_id"] == "site-1"
|
||||||
|
assert corps["data_quality"] == "good"
|
||||||
|
assert corps["consumption_kw"] == 87.34
|
||||||
|
|
||||||
|
|
||||||
|
async def test_get_current_returns_404_for_an_unknown_site(
|
||||||
|
servi: Callable[..., FauxService], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
servi(SiteNotFoundError("site-inconnu"))
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/sites/site-inconnu/current")
|
||||||
|
|
||||||
|
assert response.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
async def test_list_sites_reaches_the_repository_through_the_session(
|
async def test_list_sites_reaches_the_repository_through_the_session(
|
||||||
lecteur_connecte: None, fake_session: Callable[..., None], client: AsyncClient
|
lecteur_connecte: None, fake_session: Callable[..., None], client: AsyncClient
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|||||||
@@ -0,0 +1,622 @@
|
|||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from datetime import datetime
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from typing import Any
|
||||||
|
from unittest.mock import AsyncMock, MagicMock
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
from httpx import AsyncClient, MockTransport, Request, Response
|
||||||
|
from sqlalchemy import text
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
import app.etl.mock_api_import as mock_api_import
|
||||||
|
from app.etl.mock_api_import import (
|
||||||
|
READING_INSERT,
|
||||||
|
SOURCE_HISTORY,
|
||||||
|
build_reading_batch,
|
||||||
|
build_reading_row,
|
||||||
|
fetch_readings,
|
||||||
|
fetch_sites,
|
||||||
|
upsert_sites,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def make_site() -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"site_id": "SITE001",
|
||||||
|
"site_type": "office",
|
||||||
|
"site_name": "Bureau Paris La Défense",
|
||||||
|
"location": "Paris, France",
|
||||||
|
"capacity_kw": 200,
|
||||||
|
"status": "active",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def make_reading() -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"timestamp": "2024-06-15T12:00:00Z",
|
||||||
|
"site_id": "SITE001",
|
||||||
|
"site_type": "office",
|
||||||
|
"consumption_kw": 87.34,
|
||||||
|
"consumption_kwh": 87.34,
|
||||||
|
"voltage_v": 401.2,
|
||||||
|
"current_a": 132.5,
|
||||||
|
"power_factor": 0.923,
|
||||||
|
"temperature_celsius": 22.1,
|
||||||
|
"humidity_percent": 58.4,
|
||||||
|
"null_reasons": [],
|
||||||
|
"data_quality": "good",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_fetch_sites_returns_sites() -> None:
|
||||||
|
def handler(request: Request) -> Response:
|
||||||
|
assert request.url.path == "/api/v1/sites"
|
||||||
|
|
||||||
|
return Response(
|
||||||
|
status_code=200,
|
||||||
|
json=[make_site()],
|
||||||
|
)
|
||||||
|
|
||||||
|
transport = MockTransport(handler)
|
||||||
|
|
||||||
|
async with AsyncClient(
|
||||||
|
transport=transport,
|
||||||
|
base_url="https://mock.test",
|
||||||
|
) as client:
|
||||||
|
sites = await fetch_sites(client)
|
||||||
|
|
||||||
|
assert len(sites) == 1
|
||||||
|
assert sites[0]["site_id"] == "SITE001"
|
||||||
|
assert sites[0]["site_type"] == "office"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_fetch_readings_sends_expected_query_parameters() -> None:
|
||||||
|
captured_params: dict[str, str] = {}
|
||||||
|
|
||||||
|
def handler(request: Request) -> Response:
|
||||||
|
nonlocal captured_params
|
||||||
|
|
||||||
|
captured_params = dict(request.url.params)
|
||||||
|
|
||||||
|
return Response(
|
||||||
|
status_code=200,
|
||||||
|
json=[make_reading()],
|
||||||
|
)
|
||||||
|
|
||||||
|
transport = MockTransport(handler)
|
||||||
|
|
||||||
|
start_time = datetime.fromisoformat("2024-06-15T12:00:00")
|
||||||
|
end_time = datetime.fromisoformat("2024-06-15T13:00:00")
|
||||||
|
|
||||||
|
async with AsyncClient(
|
||||||
|
transport=transport,
|
||||||
|
base_url="https://mock.test",
|
||||||
|
) as client:
|
||||||
|
readings = await fetch_readings(
|
||||||
|
client=client,
|
||||||
|
site_id="SITE001",
|
||||||
|
start_time=start_time,
|
||||||
|
end_time=end_time,
|
||||||
|
limit=60,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert len(readings) == 1
|
||||||
|
assert captured_params["site_id"] == "SITE001"
|
||||||
|
assert captured_params["start_time"] == "2024-06-15T12:00:00"
|
||||||
|
assert captured_params["end_time"] == "2024-06-15T13:00:00"
|
||||||
|
assert captured_params["limit"] == "60"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_fetch_readings_rejects_non_list_response() -> None:
|
||||||
|
def handler(request: Request) -> Response:
|
||||||
|
return Response(
|
||||||
|
status_code=200,
|
||||||
|
json={"unexpected": "payload"},
|
||||||
|
)
|
||||||
|
|
||||||
|
transport = MockTransport(handler)
|
||||||
|
|
||||||
|
async with AsyncClient(
|
||||||
|
transport=transport,
|
||||||
|
base_url="https://mock.test",
|
||||||
|
) as client:
|
||||||
|
with pytest.raises(
|
||||||
|
ValueError,
|
||||||
|
match="La réponse /api/v1/readings doit être une liste",
|
||||||
|
):
|
||||||
|
await fetch_readings(
|
||||||
|
client=client,
|
||||||
|
site_id="SITE001",
|
||||||
|
start_time=datetime.fromisoformat("2024-06-15T12:00:00"),
|
||||||
|
end_time=datetime.fromisoformat("2024-06-15T13:00:00"),
|
||||||
|
limit=60,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_fetch_readings_raises_on_http_error() -> None:
|
||||||
|
def handler(request: Request) -> Response:
|
||||||
|
return Response(
|
||||||
|
status_code=404,
|
||||||
|
json={"detail": "Site non trouvé"},
|
||||||
|
)
|
||||||
|
|
||||||
|
transport = MockTransport(handler)
|
||||||
|
|
||||||
|
async with AsyncClient(
|
||||||
|
transport=transport,
|
||||||
|
base_url="https://mock.test",
|
||||||
|
) as client:
|
||||||
|
with pytest.raises(httpx.HTTPStatusError):
|
||||||
|
await fetch_readings(
|
||||||
|
client=client,
|
||||||
|
site_id="SITE999",
|
||||||
|
start_time=datetime.fromisoformat("2024-06-15T12:00:00"),
|
||||||
|
end_time=datetime.fromisoformat("2024-06-15T13:00:00"),
|
||||||
|
limit=60,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_reading_row_respects_database_contract() -> None:
|
||||||
|
reading = make_reading()
|
||||||
|
|
||||||
|
row = build_reading_row(reading)
|
||||||
|
|
||||||
|
assert row["site_id"] == "SITE001"
|
||||||
|
assert row["source"] == SOURCE_HISTORY
|
||||||
|
assert row["source"] == "api_history"
|
||||||
|
assert row["dataset_id"] is None
|
||||||
|
|
||||||
|
assert row["timestamp"] == datetime.fromisoformat("2024-06-15T12:00:00+00:00")
|
||||||
|
|
||||||
|
assert row["consumption_kw"] == 87.34
|
||||||
|
assert row["consumption_kwh"] == 87.34
|
||||||
|
assert row["data_quality"] == "good"
|
||||||
|
assert row["null_reasons"] == []
|
||||||
|
|
||||||
|
assert row["imputed_values"] is None
|
||||||
|
assert row["imputation_method"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_reading_row_keeps_null_values_and_quality() -> None:
|
||||||
|
reading = make_reading()
|
||||||
|
|
||||||
|
reading["consumption_kw"] = None
|
||||||
|
reading["consumption_kwh"] = None
|
||||||
|
reading["voltage_v"] = None
|
||||||
|
reading["current_a"] = None
|
||||||
|
reading["power_factor"] = None
|
||||||
|
reading["data_quality"] = "degraded"
|
||||||
|
reading["null_reasons"] = [
|
||||||
|
"consumption_sensor_failure",
|
||||||
|
"electrical_sensor_failure",
|
||||||
|
]
|
||||||
|
|
||||||
|
row = build_reading_row(reading)
|
||||||
|
|
||||||
|
assert row["consumption_kw"] is None
|
||||||
|
assert row["consumption_kwh"] is None
|
||||||
|
assert row["voltage_v"] is None
|
||||||
|
assert row["current_a"] is None
|
||||||
|
assert row["power_factor"] is None
|
||||||
|
|
||||||
|
assert row["data_quality"] == "degraded"
|
||||||
|
assert row["null_reasons"] == [
|
||||||
|
"consumption_sensor_failure",
|
||||||
|
"electrical_sensor_failure",
|
||||||
|
]
|
||||||
|
|
||||||
|
assert row["imputed_values"] is None
|
||||||
|
assert row["imputation_method"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_reading_row_keeps_raw_source_data() -> None:
|
||||||
|
reading = make_reading()
|
||||||
|
|
||||||
|
row = build_reading_row(reading)
|
||||||
|
|
||||||
|
raw_data = json.loads(row["raw_data"])
|
||||||
|
|
||||||
|
assert raw_data == reading
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_reading_batch_transforms_all_readings() -> None:
|
||||||
|
first = make_reading()
|
||||||
|
|
||||||
|
second = make_reading()
|
||||||
|
second["timestamp"] = "2024-06-15T12:01:00Z"
|
||||||
|
second["consumption_kw"] = 90.5
|
||||||
|
|
||||||
|
rows = build_reading_batch([first, second])
|
||||||
|
|
||||||
|
assert len(rows) == 2
|
||||||
|
|
||||||
|
assert rows[0]["site_id"] == "SITE001"
|
||||||
|
assert rows[0]["consumption_kw"] == 87.34
|
||||||
|
|
||||||
|
assert rows[1]["site_id"] == "SITE001"
|
||||||
|
assert rows[1]["consumption_kw"] == 90.5
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_mock_api_client_requires_credentials(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
settings = SimpleNamespace(
|
||||||
|
mock_api_username=None,
|
||||||
|
mock_api_password=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
mock_api_import,
|
||||||
|
"get_settings",
|
||||||
|
lambda: settings,
|
||||||
|
)
|
||||||
|
|
||||||
|
with pytest.raises(
|
||||||
|
ValueError,
|
||||||
|
match="Les identifiants de l'API Mock ne sont pas configurés",
|
||||||
|
):
|
||||||
|
mock_api_import.create_mock_api_client()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_create_mock_api_client_uses_configuration(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
password = MagicMock()
|
||||||
|
password.get_secret_value.return_value = "test-password"
|
||||||
|
|
||||||
|
settings = SimpleNamespace(
|
||||||
|
mock_api_base_url="https://mock.test/",
|
||||||
|
mock_api_username="test-user",
|
||||||
|
mock_api_password=password,
|
||||||
|
mock_api_timeout_seconds=10.0,
|
||||||
|
)
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
mock_api_import,
|
||||||
|
"get_settings",
|
||||||
|
lambda: settings,
|
||||||
|
)
|
||||||
|
|
||||||
|
client = mock_api_import.create_mock_api_client()
|
||||||
|
|
||||||
|
try:
|
||||||
|
assert str(client.base_url) == "https://mock.test"
|
||||||
|
assert client.timeout.connect == 10.0
|
||||||
|
finally:
|
||||||
|
await client.aclose()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_upsert_sites_with_empty_list_does_nothing() -> None:
|
||||||
|
connection = AsyncMock()
|
||||||
|
|
||||||
|
await upsert_sites(
|
||||||
|
connection,
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
|
||||||
|
connection.execute.assert_not_awaited()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_import_mock_api_history_dry_run_does_not_write(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
def handler(request: Request) -> Response:
|
||||||
|
if request.url.path == "/api/v1/sites":
|
||||||
|
return Response(
|
||||||
|
status_code=200,
|
||||||
|
json=[make_site()],
|
||||||
|
)
|
||||||
|
|
||||||
|
if request.url.path == "/api/v1/readings":
|
||||||
|
return Response(
|
||||||
|
status_code=200,
|
||||||
|
json=[make_reading()],
|
||||||
|
)
|
||||||
|
|
||||||
|
return Response(status_code=404)
|
||||||
|
|
||||||
|
transport = MockTransport(handler)
|
||||||
|
|
||||||
|
client = AsyncClient(
|
||||||
|
transport=transport,
|
||||||
|
base_url="https://mock.test",
|
||||||
|
)
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
mock_api_import,
|
||||||
|
"create_mock_api_client",
|
||||||
|
lambda: client,
|
||||||
|
)
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
mock_api_import,
|
||||||
|
"get_settings",
|
||||||
|
lambda: SimpleNamespace(
|
||||||
|
database_url="postgresql+asyncpg://unused",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
create_engine_mock = MagicMock()
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
mock_api_import,
|
||||||
|
"create_async_engine",
|
||||||
|
create_engine_mock,
|
||||||
|
)
|
||||||
|
|
||||||
|
await mock_api_import.import_mock_api_history(
|
||||||
|
start_time=datetime.fromisoformat("2024-06-15T12:00:00"),
|
||||||
|
end_time=datetime.fromisoformat("2024-06-15T13:00:00"),
|
||||||
|
limit=60,
|
||||||
|
dry_run=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
create_engine_mock.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_import_mock_api_history_loads_data(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
def handler(request: Request) -> Response:
|
||||||
|
if request.url.path == "/api/v1/sites":
|
||||||
|
return Response(
|
||||||
|
status_code=200,
|
||||||
|
json=[make_site()],
|
||||||
|
)
|
||||||
|
|
||||||
|
if request.url.path == "/api/v1/readings":
|
||||||
|
return Response(
|
||||||
|
status_code=200,
|
||||||
|
json=[make_reading()],
|
||||||
|
)
|
||||||
|
|
||||||
|
return Response(status_code=404)
|
||||||
|
|
||||||
|
transport = MockTransport(handler)
|
||||||
|
|
||||||
|
client = AsyncClient(
|
||||||
|
transport=transport,
|
||||||
|
base_url="https://mock.test",
|
||||||
|
)
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
mock_api_import,
|
||||||
|
"create_mock_api_client",
|
||||||
|
lambda: client,
|
||||||
|
)
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
mock_api_import,
|
||||||
|
"get_settings",
|
||||||
|
lambda: SimpleNamespace(
|
||||||
|
database_url="postgresql+asyncpg://test:test@localhost/test",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
connection = AsyncMock()
|
||||||
|
|
||||||
|
transaction_context = MagicMock()
|
||||||
|
transaction_context.__aenter__ = AsyncMock(
|
||||||
|
return_value=connection,
|
||||||
|
)
|
||||||
|
transaction_context.__aexit__ = AsyncMock(
|
||||||
|
return_value=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
engine = MagicMock()
|
||||||
|
engine.begin.return_value = transaction_context
|
||||||
|
engine.dispose = AsyncMock()
|
||||||
|
|
||||||
|
create_engine_mock = MagicMock(
|
||||||
|
return_value=engine,
|
||||||
|
)
|
||||||
|
|
||||||
|
upsert_sites_mock = AsyncMock()
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
mock_api_import,
|
||||||
|
"create_async_engine",
|
||||||
|
create_engine_mock,
|
||||||
|
)
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
mock_api_import,
|
||||||
|
"upsert_sites",
|
||||||
|
upsert_sites_mock,
|
||||||
|
)
|
||||||
|
|
||||||
|
await mock_api_import.import_mock_api_history(
|
||||||
|
start_time=datetime.fromisoformat("2024-06-15T12:00:00"),
|
||||||
|
end_time=datetime.fromisoformat("2024-06-15T13:00:00"),
|
||||||
|
limit=60,
|
||||||
|
dry_run=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
create_engine_mock.assert_called_once_with(
|
||||||
|
"postgresql+asyncpg://test:test@localhost/test",
|
||||||
|
pool_pre_ping=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
upsert_sites_mock.assert_awaited_once_with(
|
||||||
|
connection,
|
||||||
|
[make_site()],
|
||||||
|
)
|
||||||
|
|
||||||
|
connection.execute.assert_awaited_once()
|
||||||
|
engine.dispose.assert_awaited_once()
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_datetime_accepts_z_suffix() -> None:
|
||||||
|
result = mock_api_import.parse_datetime(
|
||||||
|
"2024-06-15T12:00:00Z",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result == datetime.fromisoformat(
|
||||||
|
"2024-06-15T12:00:00+00:00",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_args_reads_cli_parameters(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
monkeypatch.setattr(
|
||||||
|
sys,
|
||||||
|
"argv",
|
||||||
|
[
|
||||||
|
"mock_api_import",
|
||||||
|
"--start-time",
|
||||||
|
"2024-06-15T12:00:00Z",
|
||||||
|
"--end-time",
|
||||||
|
"2024-06-15T13:00:00Z",
|
||||||
|
"--limit",
|
||||||
|
"60",
|
||||||
|
"--dry-run",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
args = mock_api_import.parse_args()
|
||||||
|
|
||||||
|
assert args.start_time == datetime.fromisoformat(
|
||||||
|
"2024-06-15T12:00:00+00:00",
|
||||||
|
)
|
||||||
|
assert args.end_time == datetime.fromisoformat(
|
||||||
|
"2024-06-15T13:00:00+00:00",
|
||||||
|
)
|
||||||
|
assert args.limit == 60
|
||||||
|
assert args.dry_run is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_main_rejects_limit_out_of_bounds(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
monkeypatch.setattr(
|
||||||
|
sys,
|
||||||
|
"argv",
|
||||||
|
[
|
||||||
|
"mock_api_import",
|
||||||
|
"--start-time",
|
||||||
|
"2024-06-15T12:00:00Z",
|
||||||
|
"--end-time",
|
||||||
|
"2024-06-15T13:00:00Z",
|
||||||
|
"--limit",
|
||||||
|
"0",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
with pytest.raises(
|
||||||
|
ValueError,
|
||||||
|
match="--limit doit être compris entre 1 et 1000",
|
||||||
|
):
|
||||||
|
mock_api_import.main()
|
||||||
|
|
||||||
|
|
||||||
|
def test_main_rejects_invalid_period(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
monkeypatch.setattr(
|
||||||
|
sys,
|
||||||
|
"argv",
|
||||||
|
[
|
||||||
|
"mock_api_import",
|
||||||
|
"--start-time",
|
||||||
|
"2024-06-15T14:00:00Z",
|
||||||
|
"--end-time",
|
||||||
|
"2024-06-15T13:00:00Z",
|
||||||
|
"--limit",
|
||||||
|
"60",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
with pytest.raises(
|
||||||
|
ValueError,
|
||||||
|
match="--start-time doit être antérieur à --end-time",
|
||||||
|
):
|
||||||
|
mock_api_import.main()
|
||||||
|
|
||||||
|
|
||||||
|
def test_main_runs_import(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
start_time = datetime.fromisoformat(
|
||||||
|
"2024-06-15T12:00:00+00:00",
|
||||||
|
)
|
||||||
|
end_time = datetime.fromisoformat(
|
||||||
|
"2024-06-15T13:00:00+00:00",
|
||||||
|
)
|
||||||
|
|
||||||
|
import_mock = AsyncMock()
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
mock_api_import,
|
||||||
|
"parse_args",
|
||||||
|
lambda: SimpleNamespace(
|
||||||
|
start_time=start_time,
|
||||||
|
end_time=end_time,
|
||||||
|
limit=60,
|
||||||
|
dry_run=True,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
mock_api_import,
|
||||||
|
"import_mock_api_history",
|
||||||
|
import_mock,
|
||||||
|
)
|
||||||
|
|
||||||
|
mock_api_import.main()
|
||||||
|
|
||||||
|
import_mock.assert_awaited_once_with(
|
||||||
|
start_time=start_time,
|
||||||
|
end_time=end_time,
|
||||||
|
limit=60,
|
||||||
|
dry_run=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.integration
|
||||||
|
async def test_reading_insert_is_idempotent(
|
||||||
|
session: AsyncSession,
|
||||||
|
) -> None:
|
||||||
|
reading = make_reading()
|
||||||
|
row = build_reading_row(reading)
|
||||||
|
|
||||||
|
connection = await session.connection()
|
||||||
|
|
||||||
|
await upsert_sites(
|
||||||
|
connection,
|
||||||
|
[make_site()],
|
||||||
|
)
|
||||||
|
|
||||||
|
await session.execute(
|
||||||
|
READING_INSERT,
|
||||||
|
[row],
|
||||||
|
)
|
||||||
|
|
||||||
|
await session.execute(
|
||||||
|
READING_INSERT,
|
||||||
|
[row],
|
||||||
|
)
|
||||||
|
|
||||||
|
result = await session.execute(
|
||||||
|
text(
|
||||||
|
"""
|
||||||
|
SELECT COUNT(*)
|
||||||
|
FROM reading
|
||||||
|
WHERE site_id = :site_id
|
||||||
|
AND timestamp = :timestamp
|
||||||
|
AND source = :source
|
||||||
|
"""
|
||||||
|
),
|
||||||
|
{
|
||||||
|
"site_id": row["site_id"],
|
||||||
|
"timestamp": row["timestamp"],
|
||||||
|
"source": row["source"],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.scalar_one() == 1
|
||||||
|
|
||||||
|
await session.rollback()
|
||||||
@@ -89,3 +89,60 @@ async def test_list_all_returns_an_empty_list_when_there_is_nothing(
|
|||||||
alertes = await depot.list_all(site_id=identifiant_site())
|
alertes = await depot.list_all(site_id=identifiant_site())
|
||||||
|
|
||||||
assert list(alertes) == []
|
assert list(alertes) == []
|
||||||
|
|
||||||
|
|
||||||
|
def _alerte_a_inserer(*, site_id: str, source_alert_id: str) -> Alert:
|
||||||
|
return Alert(
|
||||||
|
source_alert_id=source_alert_id,
|
||||||
|
site_id=site_id,
|
||||||
|
source="enervision",
|
||||||
|
timestamp=datetime(2026, 9, 16, tzinfo=UTC),
|
||||||
|
type="threshold",
|
||||||
|
severity="high",
|
||||||
|
message="Dépassement du seuil configuré",
|
||||||
|
value=812.5,
|
||||||
|
threshold=720.0,
|
||||||
|
metric="consumption_kw",
|
||||||
|
prediction_id=None,
|
||||||
|
raw_data={},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_create_many_inserts_every_alert(session: AsyncSession) -> None:
|
||||||
|
site = await creer_site(session)
|
||||||
|
depot = AlertRepository(session)
|
||||||
|
|
||||||
|
creees = await depot.create_many(
|
||||||
|
[
|
||||||
|
_alerte_a_inserer(site_id=site.site_id, source_alert_id="threshold:a"),
|
||||||
|
_alerte_a_inserer(site_id=site.site_id, source_alert_id="threshold:b"),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
identifiants = [a.alert_id for a in creees]
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert len(identifiants) == 2
|
||||||
|
assert all(identifiant is not None for identifiant in identifiants)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_create_many_skips_a_duplicate_source_alert_id(session: AsyncSession) -> None:
|
||||||
|
site = await creer_site(session)
|
||||||
|
depot = AlertRepository(session)
|
||||||
|
await depot.create_many(
|
||||||
|
[_alerte_a_inserer(site_id=site.site_id, source_alert_id="threshold:rejouee")]
|
||||||
|
)
|
||||||
|
|
||||||
|
rejouees = await depot.create_many(
|
||||||
|
[_alerte_a_inserer(site_id=site.site_id, source_alert_id="threshold:rejouee")]
|
||||||
|
)
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert rejouees == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_create_many_does_nothing_for_an_empty_list(session: AsyncSession) -> None:
|
||||||
|
depot = AlertRepository(session)
|
||||||
|
|
||||||
|
creees = await depot.create_many([])
|
||||||
|
|
||||||
|
assert creees == []
|
||||||
|
|||||||
@@ -0,0 +1,171 @@
|
|||||||
|
from datetime import UTC, datetime
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.models.energy import Prediction
|
||||||
|
from app.repositories.prediction import PredictionRepository
|
||||||
|
from tests.repositories.test_site import creer as creer_site
|
||||||
|
from tests.repositories.test_site import identifiant as identifiant_site
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.integration
|
||||||
|
|
||||||
|
|
||||||
|
async def creer_prediction(
|
||||||
|
session: AsyncSession, *, site_id: str, **overrides: object
|
||||||
|
) -> Prediction:
|
||||||
|
prediction = Prediction(
|
||||||
|
site_id=site_id,
|
||||||
|
target_at=overrides.get("target_at", datetime(2026, 9, 16, tzinfo=UTC)),
|
||||||
|
target_metric=overrides.get("target_metric", "consumption_kwh"),
|
||||||
|
period_minutes=overrides.get("period_minutes", 60),
|
||||||
|
predicted_value=overrides.get("predicted_value", 42.0),
|
||||||
|
model_reference=overrides.get("model_reference", "lightgbm-test"),
|
||||||
|
status=overrides.get("status", "available"),
|
||||||
|
failure_reason=overrides.get("failure_reason"),
|
||||||
|
)
|
||||||
|
session.add(prediction)
|
||||||
|
await session.flush()
|
||||||
|
return prediction
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_since_excludes_predictions_before_the_cutoff(session: AsyncSession) -> None:
|
||||||
|
site = await creer_site(session)
|
||||||
|
depot = PredictionRepository(session)
|
||||||
|
dedans = await creer_prediction(
|
||||||
|
session, site_id=site.site_id, target_at=datetime(2026, 9, 16, tzinfo=UTC)
|
||||||
|
)
|
||||||
|
await creer_prediction(
|
||||||
|
session, site_id=site.site_id, target_at=datetime(2026, 9, 1, tzinfo=UTC)
|
||||||
|
)
|
||||||
|
|
||||||
|
resultats = await depot.list_since(
|
||||||
|
since=datetime(2026, 9, 10, tzinfo=UTC), site_id=site.site_id
|
||||||
|
)
|
||||||
|
identifiants = [p.prediction_id for p in resultats]
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert identifiants == [dedans.prediction_id]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_since_excludes_predictions_that_are_not_available(
|
||||||
|
session: AsyncSession,
|
||||||
|
) -> None:
|
||||||
|
site = await creer_site(session)
|
||||||
|
depot = PredictionRepository(session)
|
||||||
|
await creer_prediction(
|
||||||
|
session,
|
||||||
|
site_id=site.site_id,
|
||||||
|
target_at=datetime(2026, 9, 16, tzinfo=UTC),
|
||||||
|
status="insufficient_data",
|
||||||
|
predicted_value=None,
|
||||||
|
failure_reason="pas assez d'historique",
|
||||||
|
)
|
||||||
|
|
||||||
|
resultats = await depot.list_since(since=datetime(2026, 9, 1, tzinfo=UTC), site_id=site.site_id)
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert list(resultats) == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_since_breaks_a_target_at_tie_by_ascending_prediction_id(
|
||||||
|
session: AsyncSession,
|
||||||
|
) -> None:
|
||||||
|
# `prediction` n'a pas d'unicité sur `(site_id, target_at)` : deux runs de scoring sans
|
||||||
|
# nouvelle lecture entre-temps produisent deux lignes `available` à la même cible. Sans ce
|
||||||
|
# départage, `_detect_anomaly` retiendrait une ligne au hasard plutôt que le run le plus
|
||||||
|
# récent.
|
||||||
|
site = await creer_site(session)
|
||||||
|
depot = PredictionRepository(session)
|
||||||
|
cible = datetime(2026, 9, 16, tzinfo=UTC)
|
||||||
|
premier_run = await creer_prediction(
|
||||||
|
session, site_id=site.site_id, target_at=cible, predicted_value=10.0
|
||||||
|
)
|
||||||
|
second_run = await creer_prediction(
|
||||||
|
session, site_id=site.site_id, target_at=cible, predicted_value=20.0
|
||||||
|
)
|
||||||
|
|
||||||
|
resultats = await depot.list_since(since=datetime(2026, 9, 1, tzinfo=UTC), site_id=site.site_id)
|
||||||
|
identifiants = [p.prediction_id for p in resultats]
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert identifiants == [premier_run.prediction_id, second_run.prediction_id]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_since_filters_by_site_id(session: AsyncSession) -> None:
|
||||||
|
premier = await creer_site(session)
|
||||||
|
second = await creer_site(session)
|
||||||
|
depot = PredictionRepository(session)
|
||||||
|
voulue = await creer_prediction(session, site_id=premier.site_id)
|
||||||
|
await creer_prediction(session, site_id=second.site_id)
|
||||||
|
|
||||||
|
resultats = await depot.list_since(
|
||||||
|
since=datetime(2026, 8, 1, tzinfo=UTC), site_id=premier.site_id
|
||||||
|
)
|
||||||
|
identifiants = [p.prediction_id for p in resultats]
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert identifiants == [voulue.prediction_id]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_latest_by_site_keeps_only_the_most_recent_target(session: AsyncSession) -> None:
|
||||||
|
site = await creer_site(session)
|
||||||
|
depot = PredictionRepository(session)
|
||||||
|
ancienne = await creer_prediction(
|
||||||
|
session, site_id=site.site_id, target_at=datetime(2026, 9, 1, tzinfo=UTC)
|
||||||
|
)
|
||||||
|
recente = await creer_prediction(
|
||||||
|
session, site_id=site.site_id, target_at=datetime(2026, 9, 15, tzinfo=UTC)
|
||||||
|
)
|
||||||
|
|
||||||
|
resultats = await depot.latest_by_site()
|
||||||
|
identifiants = [
|
||||||
|
p.prediction_id
|
||||||
|
for p in resultats
|
||||||
|
if p.prediction_id in (ancienne.prediction_id, recente.prediction_id)
|
||||||
|
]
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert identifiants == [recente.prediction_id]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_latest_by_site_returns_one_row_per_site(session: AsyncSession) -> None:
|
||||||
|
premier = await creer_site(session)
|
||||||
|
second = await creer_site(session)
|
||||||
|
depot = PredictionRepository(session)
|
||||||
|
voulue_premier = await creer_prediction(session, site_id=premier.site_id)
|
||||||
|
voulue_second = await creer_prediction(session, site_id=second.site_id)
|
||||||
|
|
||||||
|
resultats = await depot.latest_by_site()
|
||||||
|
identifiants = {p.site_id for p in resultats if p.site_id in (premier.site_id, second.site_id)}
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert identifiants == {voulue_premier.site_id, voulue_second.site_id}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_latest_by_site_keeps_an_insufficient_data_prediction(session: AsyncSession) -> None:
|
||||||
|
site = await creer_site(session)
|
||||||
|
depot = PredictionRepository(session)
|
||||||
|
voulue = await creer_prediction(
|
||||||
|
session,
|
||||||
|
site_id=site.site_id,
|
||||||
|
status="insufficient_data",
|
||||||
|
predicted_value=None,
|
||||||
|
failure_reason="pas assez d'historique",
|
||||||
|
)
|
||||||
|
|
||||||
|
resultats = await depot.latest_by_site()
|
||||||
|
identifiants = [p.prediction_id for p in resultats if p.site_id == site.site_id]
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert identifiants == [voulue.prediction_id]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_latest_by_site_returns_an_empty_list_when_there_is_nothing(
|
||||||
|
session: AsyncSession,
|
||||||
|
) -> None:
|
||||||
|
depot = PredictionRepository(session)
|
||||||
|
|
||||||
|
resultats = [p for p in await depot.latest_by_site() if p.site_id == identifiant_site()]
|
||||||
|
|
||||||
|
assert resultats == []
|
||||||
@@ -88,6 +88,146 @@ async def test_latest_by_site_returns_one_row_per_site(session: AsyncSession) ->
|
|||||||
assert identifiants == {premier, second}
|
assert identifiants == {premier, second}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_latest_by_site_breaks_a_timestamp_tie_on_the_last_written_reading(
|
||||||
|
session: AsyncSession,
|
||||||
|
) -> None:
|
||||||
|
site = await creer_site(session)
|
||||||
|
depot = ReadingRepository(session)
|
||||||
|
horodatage = datetime(2026, 9, 15, tzinfo=UTC)
|
||||||
|
await creer_lecture(
|
||||||
|
session, site_id=site.site_id, timestamp=horodatage, source="api_history", consumption_kw=10
|
||||||
|
)
|
||||||
|
derniere = await creer_lecture(
|
||||||
|
session, site_id=site.site_id, timestamp=horodatage, source="api_current", consumption_kw=42
|
||||||
|
)
|
||||||
|
|
||||||
|
resultats = await depot.latest_by_site()
|
||||||
|
retenues = [r.reading_id for r in resultats if r.site_id == site.site_id]
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert retenues == [derniere.reading_id]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_latest_for_site_returns_the_most_recent_reading(session: AsyncSession) -> None:
|
||||||
|
site = await creer_site(session)
|
||||||
|
depot = ReadingRepository(session)
|
||||||
|
await creer_lecture(session, site_id=site.site_id, timestamp=datetime(2026, 9, 1, tzinfo=UTC))
|
||||||
|
recente = await creer_lecture(
|
||||||
|
session, site_id=site.site_id, timestamp=datetime(2026, 9, 15, tzinfo=UTC)
|
||||||
|
)
|
||||||
|
|
||||||
|
trouvee = await depot.latest_for_site(site.site_id)
|
||||||
|
reading_id = trouvee.reading_id if trouvee else None
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert reading_id == recente.reading_id
|
||||||
|
|
||||||
|
|
||||||
|
async def test_latest_for_site_breaks_a_timestamp_tie_on_the_last_written_reading(
|
||||||
|
session: AsyncSession,
|
||||||
|
) -> None:
|
||||||
|
site = await creer_site(session)
|
||||||
|
depot = ReadingRepository(session)
|
||||||
|
horodatage = datetime(2026, 9, 15, tzinfo=UTC)
|
||||||
|
await creer_lecture(session, site_id=site.site_id, timestamp=horodatage, source="api_history")
|
||||||
|
derniere = await creer_lecture(
|
||||||
|
session, site_id=site.site_id, timestamp=horodatage, source="api_current"
|
||||||
|
)
|
||||||
|
|
||||||
|
trouvee = await depot.latest_for_site(site.site_id)
|
||||||
|
reading_id = trouvee.reading_id if trouvee else None
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert reading_id == derniere.reading_id
|
||||||
|
|
||||||
|
|
||||||
|
async def test_latest_for_site_ignores_the_readings_of_the_other_sites(
|
||||||
|
session: AsyncSession,
|
||||||
|
) -> None:
|
||||||
|
sans_lecture = await creer_site(session)
|
||||||
|
autre = await creer_site(session)
|
||||||
|
depot = ReadingRepository(session)
|
||||||
|
await creer_lecture(session, site_id=autre.site_id)
|
||||||
|
|
||||||
|
trouvee = await depot.latest_for_site(sans_lecture.site_id)
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert trouvee is None
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_since_orders_by_site_then_by_time_ascending(session: AsyncSession) -> None:
|
||||||
|
site = await creer_site(session)
|
||||||
|
depot = ReadingRepository(session)
|
||||||
|
plus_recente = await creer_lecture(
|
||||||
|
session, site_id=site.site_id, timestamp=datetime(2026, 9, 16, tzinfo=UTC)
|
||||||
|
)
|
||||||
|
plus_ancienne = await creer_lecture(
|
||||||
|
session, site_id=site.site_id, timestamp=datetime(2026, 9, 15, tzinfo=UTC)
|
||||||
|
)
|
||||||
|
|
||||||
|
resultats = await depot.list_since(since=datetime(2026, 9, 1, tzinfo=UTC), site_id=site.site_id)
|
||||||
|
identifiants = [r.reading_id for r in resultats]
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert identifiants == [plus_ancienne.reading_id, plus_recente.reading_id]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_since_excludes_readings_before_the_cutoff(session: AsyncSession) -> None:
|
||||||
|
site = await creer_site(session)
|
||||||
|
depot = ReadingRepository(session)
|
||||||
|
dedans = await creer_lecture(
|
||||||
|
session, site_id=site.site_id, timestamp=datetime(2026, 9, 16, tzinfo=UTC)
|
||||||
|
)
|
||||||
|
await creer_lecture(session, site_id=site.site_id, timestamp=datetime(2026, 9, 1, tzinfo=UTC))
|
||||||
|
|
||||||
|
resultats = await depot.list_since(
|
||||||
|
since=datetime(2026, 9, 10, tzinfo=UTC), site_id=site.site_id
|
||||||
|
)
|
||||||
|
identifiants = [r.reading_id for r in resultats]
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert identifiants == [dedans.reading_id]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_since_breaks_a_timestamp_tie_by_ascending_reading_id(
|
||||||
|
session: AsyncSession,
|
||||||
|
) -> None:
|
||||||
|
# `uq_reading_source` autorise deux lignes au même `site_id`+`timestamp` quand la `source`
|
||||||
|
# diffère (même piège que `latest_for_site`). Sans ce départage, `_detect_spike` traiterait
|
||||||
|
# cette paire comme une variation réelle selon un ordre non garanti par le plan d'exécution.
|
||||||
|
site = await creer_site(session)
|
||||||
|
depot = ReadingRepository(session)
|
||||||
|
horodatage = datetime(2026, 9, 16, tzinfo=UTC)
|
||||||
|
premiere = await creer_lecture(
|
||||||
|
session, site_id=site.site_id, timestamp=horodatage, source="api_history", consumption_kw=10
|
||||||
|
)
|
||||||
|
seconde = await creer_lecture(
|
||||||
|
session, site_id=site.site_id, timestamp=horodatage, source="api_current", consumption_kw=42
|
||||||
|
)
|
||||||
|
|
||||||
|
resultats = await depot.list_since(since=datetime(2026, 9, 1, tzinfo=UTC), site_id=site.site_id)
|
||||||
|
identifiants = [r.reading_id for r in resultats]
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert identifiants == [premiere.reading_id, seconde.reading_id]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_since_filters_by_site_id(session: AsyncSession) -> None:
|
||||||
|
premier = await creer_site(session)
|
||||||
|
second = await creer_site(session)
|
||||||
|
depot = ReadingRepository(session)
|
||||||
|
voulue = await creer_lecture(session, site_id=premier.site_id)
|
||||||
|
await creer_lecture(session, site_id=second.site_id)
|
||||||
|
|
||||||
|
resultats = await depot.list_since(
|
||||||
|
since=datetime(2026, 8, 1, tzinfo=UTC), site_id=premier.site_id
|
||||||
|
)
|
||||||
|
identifiants = [r.reading_id for r in resultats]
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert identifiants == [voulue.reading_id]
|
||||||
|
|
||||||
|
|
||||||
async def test_list_history_orders_the_readings_by_timestamp_descending(
|
async def test_list_history_orders_the_readings_by_timestamp_descending(
|
||||||
session: AsyncSession,
|
session: AsyncSession,
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
from datetime import UTC, datetime
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
from app.models.energy import Alert
|
from app.models.energy import Alert
|
||||||
from app.services.alert import AlertService
|
from app.services.alert import OUTAGE_THRESHOLD, AlertService, _severity_from_ratio
|
||||||
|
|
||||||
|
NOW = datetime(2026, 9, 16, 12, 0, tzinfo=UTC)
|
||||||
|
|
||||||
|
|
||||||
def alert(
|
def alert(
|
||||||
@@ -26,10 +29,36 @@ def alert(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class FauxSite:
|
||||||
|
site_id: str
|
||||||
|
capacity_kw: float | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class FauxLecture:
|
||||||
|
site_id: str
|
||||||
|
timestamp: datetime
|
||||||
|
consumption_kw: float | None = None
|
||||||
|
consumption_kwh: float | None = None
|
||||||
|
data_quality: str | None = None
|
||||||
|
null_reasons: list[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class FauxPrediction:
|
||||||
|
site_id: str
|
||||||
|
target_at: datetime
|
||||||
|
predicted_value: float | None
|
||||||
|
target_metric: str = "consumption_kwh"
|
||||||
|
prediction_id: int = 1
|
||||||
|
|
||||||
|
|
||||||
class FakeRepository:
|
class FakeRepository:
|
||||||
def __init__(self, alerts: list[Alert]) -> None:
|
def __init__(self, alerts: list[Alert]) -> None:
|
||||||
self._alerts = alerts
|
self._alerts = alerts
|
||||||
self.appels: list[tuple[str | None, str | None]] = []
|
self.appels: list[tuple[str | None, str | None]] = []
|
||||||
|
self.crees: list[Alert] = []
|
||||||
|
|
||||||
async def list_all(
|
async def list_all(
|
||||||
self, *, site_id: str | None = None, severity: str | None = None
|
self, *, site_id: str | None = None, severity: str | None = None
|
||||||
@@ -37,19 +66,392 @@ class FakeRepository:
|
|||||||
self.appels.append((site_id, severity))
|
self.appels.append((site_id, severity))
|
||||||
return self._alerts
|
return self._alerts
|
||||||
|
|
||||||
|
async def create_many(self, alerts: list[Alert]) -> list[Alert]:
|
||||||
|
self.crees = list(alerts)
|
||||||
|
return self.crees
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class FauxDepotLectures:
|
||||||
|
depuis: list[FauxLecture] = field(default_factory=list)
|
||||||
|
dernieres: list[FauxLecture] = field(default_factory=list)
|
||||||
|
|
||||||
|
async def list_since(self, *, since: datetime, site_id: str | None = None) -> list[FauxLecture]:
|
||||||
|
return [lecture for lecture in self.depuis if site_id is None or lecture.site_id == site_id]
|
||||||
|
|
||||||
|
async def latest_by_site(self) -> list[FauxLecture]:
|
||||||
|
return self.dernieres
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class FauxDepotPredictions:
|
||||||
|
predictions: list[FauxPrediction] = field(default_factory=list)
|
||||||
|
|
||||||
|
async def list_since(
|
||||||
|
self, *, since: datetime, site_id: str | None = None
|
||||||
|
) -> list[FauxPrediction]:
|
||||||
|
return [p for p in self.predictions if site_id is None or p.site_id == site_id]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class FauxDepotSites:
|
||||||
|
sites: list[FauxSite]
|
||||||
|
|
||||||
|
async def list_all(self) -> list[FauxSite]:
|
||||||
|
return self.sites
|
||||||
|
|
||||||
|
|
||||||
|
def service(
|
||||||
|
*,
|
||||||
|
sites: list[FauxSite],
|
||||||
|
lectures: list[FauxLecture] | None = None,
|
||||||
|
dernieres: list[FauxLecture] | None = None,
|
||||||
|
predictions: list[FauxPrediction] | None = None,
|
||||||
|
alerts: FakeRepository | None = None,
|
||||||
|
) -> tuple[AlertService, FakeRepository]:
|
||||||
|
depot_alertes = alerts or FakeRepository([])
|
||||||
|
dernieres_lectures = dernieres if dernieres is not None else (lectures or [])
|
||||||
|
return (
|
||||||
|
AlertService(
|
||||||
|
alerts=depot_alertes, # type: ignore[arg-type]
|
||||||
|
readings=FauxDepotLectures(depuis=lectures or [], dernieres=dernieres_lectures), # type: ignore[arg-type]
|
||||||
|
predictions=FauxDepotPredictions(predictions or []), # type: ignore[arg-type]
|
||||||
|
sites=FauxDepotSites(sites), # type: ignore[arg-type]
|
||||||
|
),
|
||||||
|
depot_alertes,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
async def test_list_all_returns_the_repository_alerts() -> None:
|
async def test_list_all_returns_the_repository_alerts() -> None:
|
||||||
service = AlertService(alerts=FakeRepository([alert(1), alert(2)]))
|
svc, _ = service(sites=[], alerts=FakeRepository([alert(1), alert(2)]))
|
||||||
|
|
||||||
alertes = await service.list_all()
|
alertes = await svc.list_all()
|
||||||
|
|
||||||
assert [a.alert_id for a in alertes] == [1, 2]
|
assert [a.alert_id for a in alertes] == [1, 2]
|
||||||
|
|
||||||
|
|
||||||
async def test_list_all_relays_the_filters_to_the_repository() -> None:
|
async def test_list_all_relays_the_filters_to_the_repository() -> None:
|
||||||
depot = FakeRepository([])
|
depot = FakeRepository([])
|
||||||
service = AlertService(alerts=depot)
|
svc, _ = service(sites=[], alerts=depot)
|
||||||
|
|
||||||
await service.list_all(site_id="site-1", severity="critical")
|
await svc.list_all(site_id="site-1", severity="critical")
|
||||||
|
|
||||||
assert depot.appels == [("site-1", "critical")]
|
assert depot.appels == [("site-1", "critical")]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_raises_a_threshold_alert_above_site_capacity() -> None:
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A", capacity_kw=100.0)],
|
||||||
|
lectures=[FauxLecture("A", NOW, consumption_kw=150.0)],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
(candidate,) = depot.crees
|
||||||
|
assert candidate.type == "threshold"
|
||||||
|
assert candidate.severity == "high"
|
||||||
|
assert candidate.value == 150.0
|
||||||
|
assert candidate.threshold == 100.0
|
||||||
|
assert candidate.metric == "consumption_kw"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_ignores_a_reading_within_capacity() -> None:
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A", capacity_kw=100.0)],
|
||||||
|
lectures=[FauxLecture("A", NOW, consumption_kw=80.0)],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
assert depot.crees == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_ignores_threshold_when_the_site_has_no_declared_capacity() -> None:
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A", capacity_kw=None)],
|
||||||
|
lectures=[FauxLecture("A", NOW, consumption_kw=9999.0)],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
assert depot.crees == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_raises_a_spike_alert_on_a_brutal_consecutive_variation() -> None:
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A")],
|
||||||
|
lectures=[
|
||||||
|
FauxLecture("A", NOW - timedelta(hours=1), consumption_kw=100.0),
|
||||||
|
FauxLecture("A", NOW, consumption_kw=160.0),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
(candidate,) = [a for a in depot.crees if a.type == "spike"]
|
||||||
|
assert candidate.value == 160.0
|
||||||
|
assert candidate.threshold == 100.0
|
||||||
|
assert candidate.timestamp == NOW
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_ignores_a_moderate_consecutive_variation() -> None:
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A")],
|
||||||
|
lectures=[
|
||||||
|
FauxLecture("A", NOW - timedelta(hours=1), consumption_kw=100.0),
|
||||||
|
FauxLecture("A", NOW, consumption_kw=110.0),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
assert [a for a in depot.crees if a.type == "spike"] == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_never_compares_consecutive_readings_across_two_sites() -> None:
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A"), FauxSite("B")],
|
||||||
|
lectures=[
|
||||||
|
FauxLecture("A", NOW - timedelta(hours=1), consumption_kw=10.0),
|
||||||
|
FauxLecture("B", NOW, consumption_kw=1000.0),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
assert [a for a in depot.crees if a.type == "spike"] == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_raises_an_anomaly_alert_far_from_the_matching_prediction() -> None:
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A")],
|
||||||
|
lectures=[FauxLecture("A", NOW, consumption_kwh=100.0)],
|
||||||
|
predictions=[FauxPrediction("A", target_at=NOW, predicted_value=70.0)],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
(candidate,) = [a for a in depot.crees if a.type == "anomaly"]
|
||||||
|
assert candidate.value == 100.0
|
||||||
|
assert candidate.threshold == 70.0
|
||||||
|
assert candidate.metric == "consumption_kwh"
|
||||||
|
assert candidate.prediction_id == 1
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_ignores_a_reading_close_to_its_prediction() -> None:
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A")],
|
||||||
|
lectures=[FauxLecture("A", NOW, consumption_kwh=100.0)],
|
||||||
|
predictions=[FauxPrediction("A", target_at=NOW, predicted_value=95.0)],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
assert [a for a in depot.crees if a.type == "anomaly"] == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_ignores_a_prediction_whose_target_at_does_not_match_the_reading() -> None:
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A")],
|
||||||
|
lectures=[FauxLecture("A", NOW, consumption_kwh=100.0)],
|
||||||
|
predictions=[FauxPrediction("A", target_at=NOW - timedelta(hours=1), predicted_value=1.0)],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
assert [a for a in depot.crees if a.type == "anomaly"] == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_keeps_the_most_recent_run_when_two_predictions_share_the_same_target() -> (
|
||||||
|
None
|
||||||
|
):
|
||||||
|
# `PredictionRepository.list_since` départage les égalités de `target_at` par `prediction_id`
|
||||||
|
# croissant : le repository fait donc déjà passer le run le plus récent en dernier dans la
|
||||||
|
# liste, et c'est ce dernier que le dict de `_detect_anomaly` doit retenir.
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A")],
|
||||||
|
lectures=[FauxLecture("A", NOW, consumption_kwh=100.0)],
|
||||||
|
predictions=[
|
||||||
|
FauxPrediction("A", target_at=NOW, predicted_value=100.0, prediction_id=1),
|
||||||
|
FauxPrediction("A", target_at=NOW, predicted_value=70.0, prediction_id=2),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
(candidate,) = [a for a in depot.crees if a.type == "anomaly"]
|
||||||
|
assert candidate.threshold == 70.0
|
||||||
|
assert candidate.prediction_id == 2
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_raises_an_outage_alert_past_the_threshold() -> None:
|
||||||
|
derniere = NOW - OUTAGE_THRESHOLD - timedelta(minutes=1)
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A")],
|
||||||
|
lectures=[],
|
||||||
|
dernieres=[FauxLecture("A", derniere)],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
(candidate,) = [a for a in depot.crees if a.type == "outage"]
|
||||||
|
assert candidate.severity in {"low", "medium", "high", "critical"}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_ignores_a_site_still_within_the_outage_threshold() -> None:
|
||||||
|
derniere = NOW - OUTAGE_THRESHOLD + timedelta(minutes=1)
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A")],
|
||||||
|
lectures=[],
|
||||||
|
dernieres=[FauxLecture("A", derniere)],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
assert [a for a in depot.crees if a.type == "outage"] == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_raises_a_critical_outage_alert_for_a_site_never_read() -> None:
|
||||||
|
svc, depot = service(sites=[FauxSite("A")], lectures=[], dernieres=[])
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
(candidate,) = [a for a in depot.crees if a.type == "outage"]
|
||||||
|
assert candidate.severity == "critical"
|
||||||
|
assert candidate.source_alert_id == "outage:jamais"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_raises_a_sensor_alert_on_a_degraded_reading() -> None:
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A")],
|
||||||
|
lectures=[FauxLecture("A", NOW, data_quality="critical", null_reasons=["missing:x"])],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
(candidate,) = [a for a in depot.crees if a.type == "sensor"]
|
||||||
|
assert candidate.severity == "critical"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_ignores_a_good_quality_reading_for_the_sensor_rule() -> None:
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A")],
|
||||||
|
lectures=[FauxLecture("A", NOW, data_quality="good")],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
assert [a for a in depot.crees if a.type == "sensor"] == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_scopes_to_a_single_site_when_asked() -> None:
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A", capacity_kw=100.0), FauxSite("B", capacity_kw=100.0)],
|
||||||
|
lectures=[
|
||||||
|
FauxLecture("A", NOW, consumption_kw=150.0),
|
||||||
|
FauxLecture("B", NOW, consumption_kw=150.0),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW, site_id="A")
|
||||||
|
|
||||||
|
assert {a.site_id for a in depot.crees} == {"A"}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_returns_early_when_there_is_no_site() -> None:
|
||||||
|
svc, depot = service(sites=[])
|
||||||
|
|
||||||
|
resultat = await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
assert resultat == []
|
||||||
|
assert depot.crees == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_ignores_a_spike_pair_with_a_missing_measurement() -> None:
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A")],
|
||||||
|
lectures=[
|
||||||
|
FauxLecture("A", NOW - timedelta(hours=1), consumption_kw=None),
|
||||||
|
FauxLecture("A", NOW, consumption_kw=160.0),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
assert [a for a in depot.crees if a.type == "spike"] == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_ignores_a_reading_still_at_zero_after_a_previous_zero() -> None:
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A")],
|
||||||
|
lectures=[
|
||||||
|
FauxLecture("A", NOW - timedelta(hours=1), consumption_kw=0.0),
|
||||||
|
FauxLecture("A", NOW, consumption_kw=0.0),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
assert [a for a in depot.crees if a.type == "spike"] == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_raises_a_critical_spike_when_a_site_restarts_from_zero() -> None:
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A")],
|
||||||
|
lectures=[
|
||||||
|
FauxLecture("A", NOW - timedelta(hours=1), consumption_kw=0.0),
|
||||||
|
FauxLecture("A", NOW, consumption_kw=50.0),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
(candidate,) = [a for a in depot.crees if a.type == "spike"]
|
||||||
|
assert candidate.severity == "critical"
|
||||||
|
assert candidate.value == 50.0
|
||||||
|
assert candidate.threshold == 0.0
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_ignores_a_spike_pair_sharing_the_same_timestamp() -> None:
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A")],
|
||||||
|
lectures=[
|
||||||
|
FauxLecture("A", NOW, consumption_kw=100.0),
|
||||||
|
FauxLecture("A", NOW, consumption_kw=160.0),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
assert [a for a in depot.crees if a.type == "spike"] == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_ignores_an_anomaly_when_the_prediction_is_near_zero() -> None:
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A")],
|
||||||
|
lectures=[FauxLecture("A", NOW, consumption_kwh=5.0)],
|
||||||
|
predictions=[FauxPrediction("A", target_at=NOW, predicted_value=0.0)],
|
||||||
|
)
|
||||||
|
|
||||||
|
await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
assert [a for a in depot.crees if a.type == "anomaly"] == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_severity_from_ratio_covers_every_band() -> None:
|
||||||
|
assert _severity_from_ratio(1.0) == "low"
|
||||||
|
assert _severity_from_ratio(1.2) == "medium"
|
||||||
|
assert _severity_from_ratio(1.5) == "high"
|
||||||
|
assert _severity_from_ratio(2.0) == "critical"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_detect_does_not_call_create_many_when_nothing_triggers() -> None:
|
||||||
|
svc, depot = service(
|
||||||
|
sites=[FauxSite("A", capacity_kw=100.0)],
|
||||||
|
lectures=[FauxLecture("A", NOW, consumption_kw=10.0, data_quality="good")],
|
||||||
|
)
|
||||||
|
|
||||||
|
resultat = await svc.detect(now=NOW)
|
||||||
|
|
||||||
|
assert resultat == []
|
||||||
|
assert depot.crees == []
|
||||||
|
|||||||
@@ -0,0 +1,121 @@
|
|||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
|
||||||
|
from app.services.prediction import PredictionService
|
||||||
|
|
||||||
|
TARGET_AT = datetime(2026, 9, 16, 13, 0, tzinfo=UTC)
|
||||||
|
CREATED_AT = datetime(2026, 9, 16, 12, 0, tzinfo=UTC)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class FauxSite:
|
||||||
|
site_id: str
|
||||||
|
site_name: str
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class FauxPrediction:
|
||||||
|
site_id: str
|
||||||
|
target_at: datetime
|
||||||
|
target_metric: str
|
||||||
|
period_minutes: int | None
|
||||||
|
predicted_value: float | None
|
||||||
|
status: str
|
||||||
|
failure_reason: str | None
|
||||||
|
model_reference: str
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class FauxDepotSites:
|
||||||
|
def __init__(self, sites: list[FauxSite]) -> None:
|
||||||
|
self._sites = sites
|
||||||
|
|
||||||
|
async def list_all(self) -> list[FauxSite]:
|
||||||
|
return self._sites
|
||||||
|
|
||||||
|
|
||||||
|
class FauxDepotPredictions:
|
||||||
|
def __init__(self, predictions: list[FauxPrediction]) -> None:
|
||||||
|
self._predictions = predictions
|
||||||
|
|
||||||
|
async def latest_by_site(self) -> list[FauxPrediction]:
|
||||||
|
return self._predictions
|
||||||
|
|
||||||
|
|
||||||
|
def prediction_disponible(site_id: str = "A") -> FauxPrediction:
|
||||||
|
return FauxPrediction(
|
||||||
|
site_id=site_id,
|
||||||
|
target_at=TARGET_AT,
|
||||||
|
target_metric="consumption_kwh",
|
||||||
|
period_minutes=60,
|
||||||
|
predicted_value=812.5,
|
||||||
|
status="available",
|
||||||
|
failure_reason=None,
|
||||||
|
model_reference="lightgbm-abc123",
|
||||||
|
created_at=CREATED_AT,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_summary_attaches_the_latest_prediction_to_its_site() -> None:
|
||||||
|
service = PredictionService(
|
||||||
|
sites=FauxDepotSites([FauxSite("A", "Site A")]), # type: ignore[arg-type]
|
||||||
|
predictions=FauxDepotPredictions([prediction_disponible("A")]), # type: ignore[arg-type]
|
||||||
|
)
|
||||||
|
|
||||||
|
resume = await service.summary()
|
||||||
|
|
||||||
|
site = resume.sites[0]
|
||||||
|
assert site.site_id == "A"
|
||||||
|
assert site.prediction is not None
|
||||||
|
assert site.prediction.predicted_value == 812.5
|
||||||
|
assert site.prediction.status == "available"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_summary_leaves_prediction_none_for_a_site_never_scored() -> None:
|
||||||
|
service = PredictionService(
|
||||||
|
sites=FauxDepotSites([FauxSite("A", "Site A")]), # type: ignore[arg-type]
|
||||||
|
predictions=FauxDepotPredictions([]), # type: ignore[arg-type]
|
||||||
|
)
|
||||||
|
|
||||||
|
resume = await service.summary()
|
||||||
|
|
||||||
|
assert resume.sites[0].prediction is None
|
||||||
|
|
||||||
|
|
||||||
|
async def test_summary_carries_an_insufficient_data_prediction_without_a_value() -> None:
|
||||||
|
insuffisante = FauxPrediction(
|
||||||
|
site_id="A",
|
||||||
|
target_at=TARGET_AT,
|
||||||
|
target_metric="consumption_kwh",
|
||||||
|
period_minutes=60,
|
||||||
|
predicted_value=None,
|
||||||
|
status="insufficient_data",
|
||||||
|
failure_reason="pas assez d'historique",
|
||||||
|
model_reference="lightgbm-abc123",
|
||||||
|
created_at=CREATED_AT,
|
||||||
|
)
|
||||||
|
service = PredictionService(
|
||||||
|
sites=FauxDepotSites([FauxSite("A", "Site A")]), # type: ignore[arg-type]
|
||||||
|
predictions=FauxDepotPredictions([insuffisante]), # type: ignore[arg-type]
|
||||||
|
)
|
||||||
|
|
||||||
|
resume = await service.summary()
|
||||||
|
|
||||||
|
site = resume.sites[0]
|
||||||
|
assert site.prediction is not None
|
||||||
|
assert site.prediction.status == "insufficient_data"
|
||||||
|
assert site.prediction.predicted_value is None
|
||||||
|
assert site.prediction.failure_reason == "pas assez d'historique"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_summary_covers_every_site_even_with_a_single_prediction_in_the_repository() -> None:
|
||||||
|
service = PredictionService(
|
||||||
|
sites=FauxDepotSites([FauxSite("A", "Site A"), FauxSite("B", "Site B")]), # type: ignore[arg-type]
|
||||||
|
predictions=FauxDepotPredictions([prediction_disponible("A")]), # type: ignore[arg-type]
|
||||||
|
)
|
||||||
|
|
||||||
|
resume = await service.summary()
|
||||||
|
|
||||||
|
par_site = {site.site_id: site for site in resume.sites}
|
||||||
|
assert par_site["A"].prediction is not None
|
||||||
|
assert par_site["B"].prediction is None
|
||||||
@@ -1,8 +1,13 @@
|
|||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from app.models.energy import Site
|
from app.models.energy import Site
|
||||||
from app.services.site import SiteNotFoundError, SiteService
|
from app.services.site import SiteNotFoundError, SiteService
|
||||||
|
|
||||||
|
TIMESTAMP = datetime(2026, 9, 16, 12, 0, tzinfo=UTC)
|
||||||
|
|
||||||
|
|
||||||
def site(site_id: str = "site-1") -> Site:
|
def site(site_id: str = "site-1") -> Site:
|
||||||
return Site(
|
return Site(
|
||||||
@@ -15,6 +20,21 @@ def site(site_id: str = "site-1") -> Site:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class FauxLecture:
|
||||||
|
site_id: str
|
||||||
|
timestamp: datetime = TIMESTAMP
|
||||||
|
consumption_kw: float | None = 87.34
|
||||||
|
consumption_kwh: float | None = 87.34
|
||||||
|
voltage_v: float | None = 401.2
|
||||||
|
current_a: float | None = 132.5
|
||||||
|
power_factor: float | None = 0.923
|
||||||
|
temperature_celsius: float | None = 22.1
|
||||||
|
humidity_percent: float | None = 58.4
|
||||||
|
null_reasons: list[str] | None = field(default_factory=list)
|
||||||
|
data_quality: str | None = "good"
|
||||||
|
|
||||||
|
|
||||||
class FakeRepository:
|
class FakeRepository:
|
||||||
def __init__(self, sites: list[Site]) -> None:
|
def __init__(self, sites: list[Site]) -> None:
|
||||||
self._sites = sites
|
self._sites = sites
|
||||||
@@ -26,24 +46,77 @@ class FakeRepository:
|
|||||||
return next((s for s in self._sites if s.site_id == site_id), None)
|
return next((s for s in self._sites if s.site_id == site_id), None)
|
||||||
|
|
||||||
|
|
||||||
async def test_list_all_returns_the_repository_sites() -> None:
|
class FauxDepotLectures:
|
||||||
service = SiteService(sites=FakeRepository([site("a"), site("b")]))
|
def __init__(self, lectures: dict[str, FauxLecture]) -> None:
|
||||||
|
self._lectures = lectures
|
||||||
|
|
||||||
sites = await service.list_all()
|
async def latest_for_site(self, site_id: str) -> FauxLecture | None:
|
||||||
|
return self._lectures.get(site_id)
|
||||||
|
|
||||||
|
|
||||||
|
def service(sites: list[Site], lectures: dict[str, FauxLecture] | None = None) -> SiteService:
|
||||||
|
return SiteService(
|
||||||
|
sites=FakeRepository(sites), # type: ignore[arg-type]
|
||||||
|
readings=FauxDepotLectures(lectures or {}), # type: ignore[arg-type]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_all_returns_the_repository_sites() -> None:
|
||||||
|
svc = service([site("a"), site("b")])
|
||||||
|
|
||||||
|
sites = await svc.list_all()
|
||||||
|
|
||||||
assert [s.site_id for s in sites] == ["a", "b"]
|
assert [s.site_id for s in sites] == ["a", "b"]
|
||||||
|
|
||||||
|
|
||||||
async def test_get_by_id_returns_the_matching_site() -> None:
|
async def test_get_by_id_returns_the_matching_site() -> None:
|
||||||
service = SiteService(sites=FakeRepository([site("a")]))
|
svc = service([site("a")])
|
||||||
|
|
||||||
trouve = await service.get_by_id("a")
|
trouve = await svc.get_by_id("a")
|
||||||
|
|
||||||
assert trouve.site_id == "a"
|
assert trouve.site_id == "a"
|
||||||
|
|
||||||
|
|
||||||
async def test_get_by_id_raises_when_the_site_is_unknown() -> None:
|
async def test_get_by_id_raises_when_the_site_is_unknown() -> None:
|
||||||
service = SiteService(sites=FakeRepository([]))
|
svc = service([])
|
||||||
|
|
||||||
with pytest.raises(SiteNotFoundError):
|
with pytest.raises(SiteNotFoundError):
|
||||||
await service.get_by_id("inconnu")
|
await svc.get_by_id("inconnu")
|
||||||
|
|
||||||
|
|
||||||
|
async def test_current_raises_when_the_site_is_unknown() -> None:
|
||||||
|
svc = service([])
|
||||||
|
|
||||||
|
with pytest.raises(SiteNotFoundError):
|
||||||
|
await svc.current("inconnu")
|
||||||
|
|
||||||
|
|
||||||
|
async def test_current_returns_every_field_as_null_when_the_site_has_no_reading() -> None:
|
||||||
|
svc = service([site("a")])
|
||||||
|
|
||||||
|
actuel = await svc.current("a")
|
||||||
|
|
||||||
|
assert actuel.timestamp is None
|
||||||
|
assert actuel.consumption_kw is None
|
||||||
|
assert actuel.data_quality == "critical"
|
||||||
|
assert actuel.null_reasons == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_current_copies_every_field_from_the_latest_reading() -> None:
|
||||||
|
svc = service([site("a")], {"a": FauxLecture(site_id="a")})
|
||||||
|
|
||||||
|
actuel = await svc.current("a")
|
||||||
|
|
||||||
|
assert actuel.timestamp == TIMESTAMP
|
||||||
|
assert actuel.site_type == "industriel"
|
||||||
|
assert actuel.consumption_kw == 87.34
|
||||||
|
assert actuel.voltage_v == 401.2
|
||||||
|
assert actuel.data_quality == "good"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_current_treats_an_unknown_data_quality_as_critical() -> None:
|
||||||
|
svc = service([site("a")], {"a": FauxLecture(site_id="a", data_quality=None)})
|
||||||
|
|
||||||
|
actuel = await svc.current("a")
|
||||||
|
|
||||||
|
assert actuel.data_quality == "critical"
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
from datetime import UTC, datetime
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlalchemy import text
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.db.session import get_session_factory
|
||||||
|
from app.detection import internal_alerts
|
||||||
|
from app.repositories.alert import AlertRepository
|
||||||
|
from tests.repositories.test_reading import creer_lecture
|
||||||
|
from tests.repositories.test_site import creer as creer_site
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_args_defaults_to_no_site_and_no_instant() -> None:
|
||||||
|
arguments = internal_alerts.parse_args([])
|
||||||
|
|
||||||
|
assert arguments.site_id is None
|
||||||
|
assert arguments.now is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_args_reads_the_site_id() -> None:
|
||||||
|
arguments = internal_alerts.parse_args(["--site-id", "site-1"])
|
||||||
|
|
||||||
|
assert arguments.site_id == "site-1"
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_args_parses_the_instant_option() -> None:
|
||||||
|
arguments = internal_alerts.parse_args(["--now", "2026-09-16T12:00:00+00:00"])
|
||||||
|
|
||||||
|
assert arguments.now == datetime(2026, 9, 16, 12, tzinfo=UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_instant_treats_a_naive_datetime_as_utc() -> None:
|
||||||
|
assert internal_alerts._parse_instant("2026-09-16T12:00:00") == datetime(
|
||||||
|
2026, 9, 16, 12, tzinfo=UTC
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_main_prints_how_many_alerts_were_recorded(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||||
|
) -> None:
|
||||||
|
async def fausse_execution(*, now: datetime | None, site_id: str | None) -> int:
|
||||||
|
return 3
|
||||||
|
|
||||||
|
monkeypatch.setattr(internal_alerts, "run_detection", fausse_execution)
|
||||||
|
|
||||||
|
code = internal_alerts.main([])
|
||||||
|
|
||||||
|
assert code == 0
|
||||||
|
assert "3 nouvelle" in capsys.readouterr().out
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.integration
|
||||||
|
async def test_run_detection_writes_a_threshold_alert_end_to_end(session: AsyncSession) -> None:
|
||||||
|
# `run_detection` ouvre sa propre session et commite : `session.rollback()` seul ne défait
|
||||||
|
# rien ici (contrairement au reste de la suite), d'où le nettoyage explicite ci-dessous, sur
|
||||||
|
# le modèle de `tests/api/test_matrice_acces.py`.
|
||||||
|
site = await creer_site(session, capacity_kw=100.0)
|
||||||
|
site_id = site.site_id
|
||||||
|
instant = datetime(2026, 9, 16, 12, tzinfo=UTC)
|
||||||
|
await creer_lecture(session, site_id=site_id, timestamp=instant, consumption_kw=150.0)
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
try:
|
||||||
|
nombre = await internal_alerts.run_detection(now=instant, site_id=site_id)
|
||||||
|
|
||||||
|
alertes = await AlertRepository(session).list_all(site_id=site_id)
|
||||||
|
types = [a.type for a in alertes]
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert nombre == 1
|
||||||
|
assert types == ["threshold"]
|
||||||
|
finally:
|
||||||
|
# `site.site_id` n'est plus sûr après `session.rollback()` : le rollback expire tous les
|
||||||
|
# objets de la session (indépendamment d'`expire_on_commit`), et y accéder ici relance une
|
||||||
|
# requête hors contexte async. D'où `site_id`, capturé avant.
|
||||||
|
async with get_session_factory()() as nettoyage:
|
||||||
|
await nettoyage.execute(
|
||||||
|
text("delete from alert where site_id = :site_id"), {"site_id": site_id}
|
||||||
|
)
|
||||||
|
await nettoyage.execute(
|
||||||
|
text("delete from reading where site_id = :site_id"), {"site_id": site_id}
|
||||||
|
)
|
||||||
|
await nettoyage.execute(
|
||||||
|
text("delete from site where site_id = :site_id"), {"site_id": site_id}
|
||||||
|
)
|
||||||
|
await nettoyage.commit()
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# Piège : le logo est committé indépendamment à deux endroits (`app/static/`, servi par
|
||||||
|
# `/docs`/`/redoc`, et `apps/frontend/public/`, servi au front) faute d'étape de build partagée.
|
||||||
|
# Sans ce test, une mise à jour d'un seul des deux fichiers dérive silencieusement : rien en CI
|
||||||
|
# ne le détecte.
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
BACKEND_LOGO = Path(__file__).parent.parent / "app" / "static" / "logo-icon.png"
|
||||||
|
FRONTEND_LOGO = Path(__file__).parent.parent.parent / "frontend" / "public" / "logo-icon.png"
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_backend_logo_stays_in_sync_with_the_frontend_one() -> None:
|
||||||
|
assert BACKEND_LOGO.read_bytes() == FRONTEND_LOGO.read_bytes()
|
||||||
Generated
+2
-2
@@ -326,6 +326,7 @@ dependencies = [
|
|||||||
{ name = "argon2-cffi" },
|
{ name = "argon2-cffi" },
|
||||||
{ name = "asyncpg" },
|
{ name = "asyncpg" },
|
||||||
{ name = "fastapi" },
|
{ name = "fastapi" },
|
||||||
|
{ name = "httpx" },
|
||||||
{ name = "pandas" },
|
{ name = "pandas" },
|
||||||
{ name = "prometheus-fastapi-instrumentator" },
|
{ name = "prometheus-fastapi-instrumentator" },
|
||||||
{ name = "pydantic", extra = ["email"] },
|
{ name = "pydantic", extra = ["email"] },
|
||||||
@@ -338,7 +339,6 @@ dependencies = [
|
|||||||
|
|
||||||
[package.dev-dependencies]
|
[package.dev-dependencies]
|
||||||
dev = [
|
dev = [
|
||||||
{ name = "httpx" },
|
|
||||||
{ name = "mypy" },
|
{ name = "mypy" },
|
||||||
{ name = "pandas-stubs" },
|
{ name = "pandas-stubs" },
|
||||||
{ name = "pytest" },
|
{ name = "pytest" },
|
||||||
@@ -355,6 +355,7 @@ requires-dist = [
|
|||||||
{ name = "argon2-cffi", specifier = ">=23.1" },
|
{ name = "argon2-cffi", specifier = ">=23.1" },
|
||||||
{ name = "asyncpg", specifier = ">=0.31.0" },
|
{ name = "asyncpg", specifier = ">=0.31.0" },
|
||||||
{ name = "fastapi", specifier = ">=0.141.1" },
|
{ name = "fastapi", specifier = ">=0.141.1" },
|
||||||
|
{ name = "httpx", specifier = ">=0.28.1" },
|
||||||
{ name = "pandas", specifier = ">=3.0.5" },
|
{ name = "pandas", specifier = ">=3.0.5" },
|
||||||
{ name = "prometheus-fastapi-instrumentator", specifier = ">=8.1.0" },
|
{ name = "prometheus-fastapi-instrumentator", specifier = ">=8.1.0" },
|
||||||
{ name = "pydantic", extras = ["email"], specifier = ">=2.13.5" },
|
{ name = "pydantic", extras = ["email"], specifier = ">=2.13.5" },
|
||||||
@@ -367,7 +368,6 @@ requires-dist = [
|
|||||||
|
|
||||||
[package.metadata.requires-dev]
|
[package.metadata.requires-dev]
|
||||||
dev = [
|
dev = [
|
||||||
{ name = "httpx", specifier = ">=0.28.1" },
|
|
||||||
{ name = "mypy", specifier = ">=2.3.1" },
|
{ name = "mypy", specifier = ">=2.3.1" },
|
||||||
{ name = "pandas-stubs", specifier = ">=3.0.5.260914" },
|
{ name = "pandas-stubs", specifier = ">=3.0.5.260914" },
|
||||||
{ name = "pytest", specifier = ">=9.1.1" },
|
{ name = "pytest", specifier = ">=9.1.1" },
|
||||||
|
|||||||
@@ -76,6 +76,13 @@ Points à vérifier après toute regénération :
|
|||||||
côté backend. Le `docker-compose.yml` n'a aucun service frontend.
|
côté backend. Le `docker-compose.yml` n'a aucun service frontend.
|
||||||
4. Ajouter le `Dockerfile` multi-stage (build Angular puis service statique nginx).
|
4. Ajouter le `Dockerfile` multi-stage (build Angular puis service statique nginx).
|
||||||
|
|
||||||
|
## Design système
|
||||||
|
|
||||||
|
Tokens (couleurs, typo, espacements) et composants partagés (`ev-button`, `ev-card`,
|
||||||
|
`ev-alert`, `ev-badge`) sont documentés dans
|
||||||
|
[`docs/architecture/32-design-systeme-frontend.md`](../../docs/architecture/32-design-systeme-frontend.md).
|
||||||
|
Toute nouvelle page doit les réutiliser plutôt que définir ses propres valeurs.
|
||||||
|
|
||||||
## Additional Resources
|
## Additional Resources
|
||||||
|
|
||||||
For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.
|
For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.
|
||||||
|
|||||||
@@ -86,15 +86,6 @@
|
|||||||
"text-summary",
|
"text-summary",
|
||||||
"lcov",
|
"lcov",
|
||||||
"html"
|
"html"
|
||||||
],
|
|
||||||
"reporters": [
|
|
||||||
"default",
|
|
||||||
[
|
|
||||||
"junit",
|
|
||||||
{
|
|
||||||
"outputFile": "test-results/junit.xml"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 57 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
@@ -0,0 +1,18 @@
|
|||||||
|
sonar.projectKey=ProjetPiscine_EnerVision
|
||||||
|
sonar.organization=groupe3-ener-vision
|
||||||
|
sonar.sourceEncoding=UTF-8
|
||||||
|
|
||||||
|
# Dossier contenant le code source
|
||||||
|
sonar.sources=apps/frontend/src,apps/backend/app
|
||||||
|
sonar.tests=apps/backend/tests
|
||||||
|
|
||||||
|
# Liste des fichiers et dossiers à exclure de l'analyse
|
||||||
|
# Liste des fichiers et dossiers à exclure de l'analyse
|
||||||
|
sonar.exclusions=**/node_modules/**,**/dist/**,**/*.spec.js,**/*.test.js,github,db,ml,docker-compose.yml,**/**/Dockerfile,**/**/proxy.conf.json,**/**/package.json,**/**/angular.json
|
||||||
|
|
||||||
|
# Chemin vers le rapport de couverture de code
|
||||||
|
# Fichier généré par Vitest
|
||||||
|
# Chemin vers le rapport de couverture de code
|
||||||
|
# Fichier généré par Vitest
|
||||||
|
sonar.javascript.lcov.reportPaths=apps/frontend/coverage/frontend/lcov.info
|
||||||
|
sonar.python.coverage.reportPaths=apps/backend/cov.info
|
||||||
@@ -12,4 +12,15 @@ export const routes: Routes = [
|
|||||||
canActivate: [authGuard],
|
canActivate: [authGuard],
|
||||||
loadComponent: () => import('./features/dashboard/dashboard').then(m => m.Dashboard),
|
loadComponent: () => import('./features/dashboard/dashboard').then(m => m.Dashboard),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'sites',
|
||||||
|
canActivate: [authGuard],
|
||||||
|
loadComponent: () => import('./features/sites/site-list/site-list').then(m => m.SiteList),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'sites/:siteId',
|
||||||
|
canActivate: [authGuard],
|
||||||
|
loadComponent: () =>
|
||||||
|
import('./features/sites/site-detail/site-detail').then((m) => m.SiteDetail),
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -64,4 +64,13 @@ describe('mockApiInterceptor', () => {
|
|||||||
httpMock.expectNone(`${environment.apiUrl}/alerts`);
|
httpMock.expectNone(`${environment.apiUrl}/alerts`);
|
||||||
expect((result as unknown[]).length).toBeGreaterThan(0);
|
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`)) {
|
if (req.url.endsWith(`${environment.apiUrl}/alerts`)) {
|
||||||
return of(new HttpResponse({ status: 200, body: ALERTS_FIXTURE }));
|
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);
|
return next(req);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -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`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
|
||||||
|
import { ReadingsService } from './readings.service';
|
||||||
|
import { environment } from '../../../environments/environment';
|
||||||
|
|
||||||
|
describe('ReadingsService', () => {
|
||||||
|
let service: ReadingsService;
|
||||||
|
let httpMock: HttpTestingController;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [provideHttpClient(), provideHttpClientTesting()],
|
||||||
|
});
|
||||||
|
service = TestBed.inject(ReadingsService);
|
||||||
|
httpMock = TestBed.inject(HttpTestingController);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => httpMock.verify());
|
||||||
|
|
||||||
|
it("demande l'historique du site avec la fenêtre temporelle donnée", () => {
|
||||||
|
let result: unknown;
|
||||||
|
service
|
||||||
|
.getHistory('SITE001', '2026-09-16T00:00:00Z', '2026-09-17T00:00:00Z')
|
||||||
|
.subscribe((r) => (result = r));
|
||||||
|
|
||||||
|
const req = httpMock.expectOne(
|
||||||
|
(r) => r.url === `${environment.apiUrl}/readings` && r.method === 'GET',
|
||||||
|
);
|
||||||
|
expect(req.request.params.get('site_id')).toBe('SITE001');
|
||||||
|
expect(req.request.params.get('start')).toBe('2026-09-16T00:00:00Z');
|
||||||
|
expect(req.request.params.get('end')).toBe('2026-09-17T00:00:00Z');
|
||||||
|
|
||||||
|
req.flush([{ reading_id: 1, site_id: 'SITE001', consumption_kw: 12.5 }]);
|
||||||
|
|
||||||
|
expect((result as unknown[]).length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ne pose pas de paramètres start/end quand ils sont omis', () => {
|
||||||
|
service.getHistory('SITE001').subscribe();
|
||||||
|
|
||||||
|
const req = httpMock.expectOne(
|
||||||
|
(r) => r.url === `${environment.apiUrl}/readings` && r.method === 'GET',
|
||||||
|
);
|
||||||
|
expect(req.request.params.has('start')).toBe(false);
|
||||||
|
expect(req.request.params.has('end')).toBe(false);
|
||||||
|
|
||||||
|
req.flush([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { Service, inject } from '@angular/core';
|
||||||
|
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||||
|
import { environment } from '../../../environments/environment';
|
||||||
|
import { Reading } from '../../shared/models/reading.model';
|
||||||
|
|
||||||
|
@Service()
|
||||||
|
export class ReadingsService {
|
||||||
|
private http = inject(HttpClient);
|
||||||
|
|
||||||
|
getHistory(siteId: string, start?: string, end?: string) {
|
||||||
|
let params = new HttpParams().set('site_id', siteId);
|
||||||
|
if (start) {
|
||||||
|
params = params.set('start', start);
|
||||||
|
}
|
||||||
|
if (end) {
|
||||||
|
params = params.set('end', end);
|
||||||
|
}
|
||||||
|
return this.http.get<Reading[]>(`${environment.apiUrl}/readings`, { params });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
|
||||||
|
import { SitesService } from './sites.service';
|
||||||
|
import { environment } from '../../../environments/environment';
|
||||||
|
|
||||||
|
describe('SitesService', () => {
|
||||||
|
let service: SitesService;
|
||||||
|
let httpMock: HttpTestingController;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [provideHttpClient(), provideHttpClientTesting()],
|
||||||
|
});
|
||||||
|
service = TestBed.inject(SitesService);
|
||||||
|
httpMock = TestBed.inject(HttpTestingController);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => httpMock.verify());
|
||||||
|
|
||||||
|
it('appelle le bon endpoint et retourne la liste des sites', () => {
|
||||||
|
let result: unknown;
|
||||||
|
service.getSites().subscribe((r) => (result = r));
|
||||||
|
|
||||||
|
const req = httpMock.expectOne(`${environment.apiUrl}/sites`);
|
||||||
|
expect(req.request.method).toBe('GET');
|
||||||
|
|
||||||
|
req.flush([
|
||||||
|
{
|
||||||
|
site_id: 'SITE001',
|
||||||
|
site_name: 'Site 1',
|
||||||
|
site_type: 'industriel',
|
||||||
|
location: 'Nantes',
|
||||||
|
capacity_kw: 500,
|
||||||
|
status: 'actif',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect((result as { site_id: string }[])[0].site_id).toBe('SITE001');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('appelle le bon endpoint et retourne un site', () => {
|
||||||
|
let result: unknown;
|
||||||
|
service.getSite('SITE001').subscribe((r) => (result = r));
|
||||||
|
|
||||||
|
const req = httpMock.expectOne(`${environment.apiUrl}/sites/SITE001`);
|
||||||
|
expect(req.request.method).toBe('GET');
|
||||||
|
|
||||||
|
req.flush({
|
||||||
|
site_id: 'SITE001',
|
||||||
|
site_name: 'Site 1',
|
||||||
|
site_type: 'industriel',
|
||||||
|
location: 'Nantes',
|
||||||
|
capacity_kw: 500,
|
||||||
|
status: 'actif',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect((result as { site_id: string }).site_id).toBe('SITE001');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('appelle le bon endpoint et retourne la mesure courante du site', () => {
|
||||||
|
let result: unknown;
|
||||||
|
service.getCurrent('SITE001').subscribe((r) => (result = r));
|
||||||
|
|
||||||
|
const req = httpMock.expectOne(`${environment.apiUrl}/sites/SITE001/current`);
|
||||||
|
expect(req.request.method).toBe('GET');
|
||||||
|
|
||||||
|
req.flush({
|
||||||
|
timestamp: '2026-09-17T10:00:00Z',
|
||||||
|
site_id: 'SITE001',
|
||||||
|
site_type: 'industriel',
|
||||||
|
consumption_kw: 120,
|
||||||
|
consumption_kwh: null,
|
||||||
|
voltage_v: null,
|
||||||
|
current_a: null,
|
||||||
|
power_factor: null,
|
||||||
|
temperature_celsius: 22,
|
||||||
|
humidity_percent: 55,
|
||||||
|
null_reasons: ['electrical_sensor_failure'],
|
||||||
|
data_quality: 'partial',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect((result as { null_reasons: string[] }).null_reasons).toEqual([
|
||||||
|
'electrical_sensor_failure',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { Service, inject } from '@angular/core';
|
||||||
|
import { HttpClient } from '@angular/common/http';
|
||||||
|
import { environment } from '../../../environments/environment';
|
||||||
|
import { Site } from '../../shared/models/site.model';
|
||||||
|
import { SiteCurrent } from '../../shared/models/site-current.model';
|
||||||
|
|
||||||
|
@Service()
|
||||||
|
export class SitesService {
|
||||||
|
private http = inject(HttpClient);
|
||||||
|
|
||||||
|
getSites() {
|
||||||
|
return this.http.get<Site[]>(`${environment.apiUrl}/sites`);
|
||||||
|
}
|
||||||
|
|
||||||
|
getSite(siteId: string) {
|
||||||
|
return this.http.get<Site>(`${environment.apiUrl}/sites/${siteId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
getCurrent(siteId: string) {
|
||||||
|
return this.http.get<SiteCurrent>(`${environment.apiUrl}/sites/${siteId}/current`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,31 +1,38 @@
|
|||||||
<div class="auth-page">
|
<div class="auth-page">
|
||||||
<form class="auth-card" [formGroup]="form" (ngSubmit)="onSubmit()">
|
<form class="auth-card-wrapper" [formGroup]="form" (ngSubmit)="onSubmit()">
|
||||||
|
<ev-card>
|
||||||
|
<ev-brand class="auth-brand" />
|
||||||
<h1>Nouveau mot de passe</h1>
|
<h1>Nouveau mot de passe</h1>
|
||||||
<p class="auth-subtitle">Votre mot de passe est provisoire, vous devez le modifier avant de continuer</p>
|
<p class="auth-subtitle">
|
||||||
|
Votre mot de passe est provisoire, vous devez le modifier avant de continuer
|
||||||
|
</p>
|
||||||
|
|
||||||
<label for="current_password">Mot de passe actuel</label>
|
<label class="form-label" for="current_password">Mot de passe actuel</label>
|
||||||
<input
|
<input
|
||||||
id="current_password"
|
id="current_password"
|
||||||
|
class="form-input"
|
||||||
type="password"
|
type="password"
|
||||||
formControlName="current_password"
|
formControlName="current_password"
|
||||||
autocomplete="current-password"
|
autocomplete="current-password"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<label for="new_password">Nouveau mot de passe</label>
|
<label class="form-label" for="new_password">Nouveau mot de passe</label>
|
||||||
<input
|
<input
|
||||||
id="new_password"
|
id="new_password"
|
||||||
|
class="form-input"
|
||||||
type="password"
|
type="password"
|
||||||
formControlName="new_password"
|
formControlName="new_password"
|
||||||
autocomplete="new-password"
|
autocomplete="new-password"
|
||||||
/>
|
/>
|
||||||
<span class="auth-hint">{{ passwordHint }}</span>
|
<span class="form-hint">{{ passwordHint }}</span>
|
||||||
|
|
||||||
@if (errorMessage()) {
|
@if (errorMessage()) {
|
||||||
<p class="auth-error">{{ errorMessage() }}</p>
|
<ev-alert severity="danger">{{ errorMessage() }}</ev-alert>
|
||||||
}
|
}
|
||||||
|
|
||||||
<button type="submit" [disabled]="form.invalid || isLoading()">
|
<ev-button type="submit" [disabled]="form.invalid || isLoading()">
|
||||||
{{ isLoading() ? 'Modification...' : 'Valider' }}
|
{{ isLoading() ? 'Modification...' : 'Valider' }}
|
||||||
</button>
|
</ev-button>
|
||||||
|
</ev-card>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,88 +0,0 @@
|
|||||||
:host {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
min-height: 100vh;
|
|
||||||
background: #f3f4f6;
|
|
||||||
font-family: 'Segoe UI', system-ui, sans-serif;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-card {
|
|
||||||
background: #ffffff;
|
|
||||||
border: 1px solid #e5e7eb;
|
|
||||||
border-radius: 12px;
|
|
||||||
padding: 2.5rem;
|
|
||||||
width: 100%;
|
|
||||||
max-width: 360px;
|
|
||||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
|
|
||||||
h1 {
|
|
||||||
margin: 0;
|
|
||||||
font-size: 1.5rem;
|
|
||||||
font-weight: 700;
|
|
||||||
color: #1f2937;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-subtitle {
|
|
||||||
margin: 0.25rem 0 1.5rem;
|
|
||||||
color: #6b7280;
|
|
||||||
font-size: 0.9rem;
|
|
||||||
line-height: 1.4;
|
|
||||||
}
|
|
||||||
|
|
||||||
label {
|
|
||||||
font-size: 0.85rem;
|
|
||||||
font-weight: 600;
|
|
||||||
color: #374151;
|
|
||||||
margin-bottom: 0.35rem;
|
|
||||||
margin-top: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
input {
|
|
||||||
padding: 0.6rem 0.75rem;
|
|
||||||
border: 1px solid #d1d5db;
|
|
||||||
border-radius: 8px;
|
|
||||||
font-size: 0.95rem;
|
|
||||||
|
|
||||||
&:focus {
|
|
||||||
outline: none;
|
|
||||||
border-color: #3b82f6;
|
|
||||||
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
button {
|
|
||||||
margin-top: 1.5rem;
|
|
||||||
padding: 0.7rem;
|
|
||||||
background: #3b82f6;
|
|
||||||
color: #fff;
|
|
||||||
border: none;
|
|
||||||
border-radius: 8px;
|
|
||||||
font-size: 0.95rem;
|
|
||||||
font-weight: 600;
|
|
||||||
cursor: pointer;
|
|
||||||
|
|
||||||
&:disabled {
|
|
||||||
background: #9ca3af;
|
|
||||||
cursor: not-allowed;
|
|
||||||
}
|
|
||||||
|
|
||||||
&:not(:disabled):hover {
|
|
||||||
background: #2563eb;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-hint {
|
|
||||||
font-size: 0.75rem;
|
|
||||||
color: #9ca3af;
|
|
||||||
margin-top: 0.25rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-error {
|
|
||||||
margin: 0.75rem 0 0;
|
|
||||||
color: #dc2626;
|
|
||||||
font-size: 0.85rem;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ describe('ChangePassword', () => {
|
|||||||
fixture.detectChanges(); // rend le bloc @if (errorMessage())
|
fixture.detectChanges(); // rend le bloc @if (errorMessage())
|
||||||
|
|
||||||
expect(component.errorMessage()).toContain('incorrect');
|
expect(component.errorMessage()).toContain('incorrect');
|
||||||
const errorEl = fixture.nativeElement.querySelector('.auth-error');
|
const errorEl = fixture.nativeElement.querySelector('.ev-alert');
|
||||||
expect(errorEl?.textContent).toContain('incorrect');
|
expect(errorEl?.textContent).toContain('incorrect');
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -73,7 +73,7 @@ describe('ChangePassword', () => {
|
|||||||
|
|
||||||
const button = fixture.nativeElement.querySelector('button[type="submit"]');
|
const button = fixture.nativeElement.querySelector('button[type="submit"]');
|
||||||
expect(button.disabled).toBe(true);
|
expect(button.disabled).toBe(true);
|
||||||
expect(fixture.nativeElement.querySelector('.auth-error')).toBeNull();
|
expect(fixture.nativeElement.querySelector('.ev-alert')).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('déclenche onSubmit via la soumission réelle du formulaire (ngSubmit)', () => {
|
it('déclenche onSubmit via la soumission réelle du formulaire (ngSubmit)', () => {
|
||||||
|
|||||||
@@ -2,12 +2,16 @@ import { Component, inject, signal } from '@angular/core';
|
|||||||
import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';
|
import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';
|
||||||
import { Router } from '@angular/router';
|
import { Router } from '@angular/router';
|
||||||
import { AuthService } from '../../../core/services/auth.service';
|
import { AuthService } from '../../../core/services/auth.service';
|
||||||
|
import { Button } from '../../../shared/components/ui/button/button';
|
||||||
|
import { Card } from '../../../shared/components/ui/card/card';
|
||||||
|
import { Alert } from '../../../shared/components/ui/alert/alert';
|
||||||
|
import { Brand } from '../../../shared/components/ui/brand/brand';
|
||||||
import { passwordValidators, PASSWORD_HINT } from '../../../shared/validators/password.validator';
|
import { passwordValidators, PASSWORD_HINT } from '../../../shared/validators/password.validator';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-change-password',
|
selector: 'app-change-password',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [ReactiveFormsModule],
|
imports: [ReactiveFormsModule, Button, Card, Alert, Brand],
|
||||||
templateUrl: './change-password.html',
|
templateUrl: './change-password.html',
|
||||||
styleUrl: './change-password.scss',
|
styleUrl: './change-password.scss',
|
||||||
})
|
})
|
||||||
@@ -36,7 +40,9 @@ export class ChangePassword {
|
|||||||
},
|
},
|
||||||
error: () => {
|
error: () => {
|
||||||
this.isLoading.set(false);
|
this.isLoading.set(false);
|
||||||
this.errorMessage.set(`Mot de passe actuel incorrect, ou nouveau mot de passe invalide (${this.passwordHint}).`);
|
this.errorMessage.set(
|
||||||
|
`Mot de passe actuel incorrect, ou nouveau mot de passe invalide (${this.passwordHint}).`,
|
||||||
|
);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,38 +1,43 @@
|
|||||||
<div class="auth-page">
|
<div class="auth-page">
|
||||||
<form class="auth-card" [formGroup]="form" (ngSubmit)="onSubmit()">
|
<form class="auth-card-wrapper" [formGroup]="form" (ngSubmit)="onSubmit()">
|
||||||
|
<ev-card>
|
||||||
|
<ev-brand class="auth-brand" />
|
||||||
<h1>Connexion</h1>
|
<h1>Connexion</h1>
|
||||||
<p class="auth-subtitle">Accédez à votre espace EnerVision</p>
|
<p class="auth-subtitle">Accédez à votre espace EnerVision</p>
|
||||||
|
|
||||||
<label for="email">Email</label>
|
<label class="form-label" for="email">Email</label>
|
||||||
<input
|
<input
|
||||||
id="email"
|
id="email"
|
||||||
|
class="form-input"
|
||||||
type="email"
|
type="email"
|
||||||
formControlName="email"
|
formControlName="email"
|
||||||
autocomplete="username"
|
autocomplete="username"
|
||||||
placeholder="vous@enervision.fr"
|
placeholder="vous@enervision.fr"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<label for="password">Mot de passe</label>
|
<label class="form-label" for="password">Mot de passe</label>
|
||||||
<input
|
<input
|
||||||
id="password"
|
id="password"
|
||||||
|
class="form-input"
|
||||||
type="password"
|
type="password"
|
||||||
formControlName="password"
|
formControlName="password"
|
||||||
autocomplete="current-password"
|
autocomplete="current-password"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@if (errorMessage()) {
|
@if (errorMessage()) {
|
||||||
<p class="auth-error">
|
<ev-alert severity="danger">
|
||||||
{{ errorMessage() }}
|
{{ errorMessage() }}
|
||||||
@if (retryAfterSeconds(); as seconds) {
|
@if (retryAfterSeconds(); as seconds) {
|
||||||
(réessayez dans {{ seconds }}s)
|
(réessayez dans {{ seconds }}s)
|
||||||
}
|
}
|
||||||
</p>
|
</ev-alert>
|
||||||
}
|
}
|
||||||
|
|
||||||
<button type="submit" [disabled]="form.invalid || isLoading()">
|
<ev-button type="submit" [disabled]="form.invalid || isLoading()">
|
||||||
{{ isLoading() ? 'Connexion...' : 'Se connecter' }}
|
{{ isLoading() ? 'Connexion...' : 'Se connecter' }}
|
||||||
</button>
|
</ev-button>
|
||||||
|
|
||||||
<p class="auth-link"><a routerLink="/forgot-password">Mot de passe oublié ?</a></p>
|
<p class="auth-link"><a routerLink="/forgot-password">Mot de passe oublié ?</a></p>
|
||||||
|
</ev-card>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,85 +1,3 @@
|
|||||||
:host {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
min-height: 100vh;
|
|
||||||
background: #f3f4f6;
|
|
||||||
font-family: 'Segoe UI', system-ui, sans-serif;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-card {
|
|
||||||
background: #ffffff;
|
|
||||||
border: 1px solid #e5e7eb;
|
|
||||||
border-radius: 12px;
|
|
||||||
padding: 2.5rem;
|
|
||||||
width: 100%;
|
|
||||||
max-width: 360px;
|
|
||||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
|
|
||||||
h1 {
|
|
||||||
margin: 0;
|
|
||||||
font-size: 1.5rem;
|
|
||||||
font-weight: 700;
|
|
||||||
color: #1f2937;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-subtitle {
|
|
||||||
margin: 0.25rem 0 1.5rem;
|
|
||||||
color: #6b7280;
|
|
||||||
font-size: 0.9rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
label {
|
|
||||||
font-size: 0.85rem;
|
|
||||||
font-weight: 600;
|
|
||||||
color: #374151;
|
|
||||||
margin-bottom: 0.35rem;
|
|
||||||
margin-top: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
input {
|
|
||||||
padding: 0.6rem 0.75rem;
|
|
||||||
border: 1px solid #d1d5db;
|
|
||||||
border-radius: 8px;
|
|
||||||
font-size: 0.95rem;
|
|
||||||
|
|
||||||
&:focus {
|
|
||||||
outline: none;
|
|
||||||
border-color: #3b82f6;
|
|
||||||
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
button {
|
|
||||||
margin-top: 1.5rem;
|
|
||||||
padding: 0.7rem;
|
|
||||||
background: #3b82f6;
|
|
||||||
color: #fff;
|
|
||||||
border: none;
|
|
||||||
border-radius: 8px;
|
|
||||||
font-size: 0.95rem;
|
|
||||||
font-weight: 600;
|
|
||||||
cursor: pointer;
|
|
||||||
|
|
||||||
&:disabled {
|
|
||||||
background: #9ca3af;
|
|
||||||
cursor: not-allowed;
|
|
||||||
}
|
|
||||||
|
|
||||||
&:not(:disabled):hover {
|
|
||||||
background: #2563eb;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-error {
|
|
||||||
margin: 0.75rem 0 0;
|
|
||||||
color: #dc2626;
|
|
||||||
font-size: 0.85rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-link {
|
.auth-link {
|
||||||
margin-top: 1rem;
|
margin-top: 1rem;
|
||||||
font-size: 0.85rem;
|
font-size: 0.85rem;
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ describe('Login', () => {
|
|||||||
fixture.detectChanges(); // rend le bloc @if (errorMessage()) du template
|
fixture.detectChanges(); // rend le bloc @if (errorMessage()) du template
|
||||||
|
|
||||||
expect(component.errorMessage()).toBe('Email ou mot de passe incorrect.');
|
expect(component.errorMessage()).toBe('Email ou mot de passe incorrect.');
|
||||||
const errorEl = fixture.nativeElement.querySelector('.auth-error');
|
const errorEl = fixture.nativeElement.querySelector('.ev-alert');
|
||||||
expect(errorEl?.textContent).toContain('Email ou mot de passe incorrect.');
|
expect(errorEl?.textContent).toContain('Email ou mot de passe incorrect.');
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -96,7 +96,7 @@ describe('Login', () => {
|
|||||||
fixture.detectChanges(); // rend aussi le sous-bloc @if (retryAfterSeconds(); as seconds)
|
fixture.detectChanges(); // rend aussi le sous-bloc @if (retryAfterSeconds(); as seconds)
|
||||||
|
|
||||||
expect(component.retryAfterSeconds()).toBe(30);
|
expect(component.retryAfterSeconds()).toBe(30);
|
||||||
const errorEl = fixture.nativeElement.querySelector('.auth-error');
|
const errorEl = fixture.nativeElement.querySelector('.ev-alert');
|
||||||
expect(errorEl?.textContent).toContain('30s');
|
expect(errorEl?.textContent).toContain('30s');
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -114,7 +114,7 @@ describe('Login', () => {
|
|||||||
|
|
||||||
const button = fixture.nativeElement.querySelector('button[type="submit"]');
|
const button = fixture.nativeElement.querySelector('button[type="submit"]');
|
||||||
expect(button.disabled).toBe(true);
|
expect(button.disabled).toBe(true);
|
||||||
expect(fixture.nativeElement.querySelector('.auth-error')).toBeNull();
|
expect(fixture.nativeElement.querySelector('.ev-alert')).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('déclenche onSubmit via la soumission réelle du formulaire (ngSubmit)', () => {
|
it('déclenche onSubmit via la soumission réelle du formulaire (ngSubmit)', () => {
|
||||||
|
|||||||
@@ -3,12 +3,19 @@ import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';
|
|||||||
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
||||||
import { HttpErrorResponse } from '@angular/common/http';
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
import { AuthService } from '../../../core/services/auth.service';
|
import { AuthService } from '../../../core/services/auth.service';
|
||||||
import { MESSAGE_LIEN_RESET_INVALIDE, MOTIF_LIEN_RESET_INVALIDE } from '../../../shared/models/auth-redirect-reason';
|
import { Button } from '../../../shared/components/ui/button/button';
|
||||||
|
import { Card } from '../../../shared/components/ui/card/card';
|
||||||
|
import { Alert } from '../../../shared/components/ui/alert/alert';
|
||||||
|
import { Brand } from '../../../shared/components/ui/brand/brand';
|
||||||
|
import {
|
||||||
|
MESSAGE_LIEN_RESET_INVALIDE,
|
||||||
|
MOTIF_LIEN_RESET_INVALIDE,
|
||||||
|
} from '../../../shared/models/auth-redirect-reason';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-login',
|
selector: 'app-login',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [ReactiveFormsModule, RouterLink],
|
imports: [ReactiveFormsModule, RouterLink, Button, Card, Alert, Brand],
|
||||||
templateUrl: './login.html',
|
templateUrl: './login.html',
|
||||||
styleUrl: './login.scss',
|
styleUrl: './login.scss',
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,19 +1,39 @@
|
|||||||
<div class="dashboard">
|
<div class="dashboard">
|
||||||
<header class="dashboard__header">
|
<header class="dashboard__header">
|
||||||
|
<div class="dashboard__brand">
|
||||||
|
<a routerLink="/dashboard" class="ev-brand-link">
|
||||||
|
<ev-brand class="dashboard__logo" />
|
||||||
|
</a>
|
||||||
<div>
|
<div>
|
||||||
<h1>Vue d'ensemble</h1>
|
<h1>Vue d'ensemble</h1>
|
||||||
<p class="dashboard__subtitle">Consommation instantanée du parc</p>
|
<p class="dashboard__subtitle">Consommation instantanée du parc</p>
|
||||||
</div>
|
</div>
|
||||||
<button type="button" class="logout-button" (click)="onLogout()">Déconnexion</button>
|
</div>
|
||||||
|
<div class="dashboard__actions">
|
||||||
|
<a routerLink="/sites" class="ev-link">Voir les sites</a>
|
||||||
|
<ev-button
|
||||||
|
class="logout-button"
|
||||||
|
variant="secondary"
|
||||||
|
[fullWidth]="false"
|
||||||
|
(click)="onLogout()"
|
||||||
|
>Déconnexion</ev-button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
@if (error(); as message) {
|
@if (statsError(); as message) {
|
||||||
<p class="banner-error" role="alert">{{ message }}</p>
|
<ev-alert severity="danger" class="banner-error">{{ message }}</ev-alert>
|
||||||
|
}
|
||||||
|
@if (alertsError(); as message) {
|
||||||
|
<ev-alert severity="danger" class="banner-error">{{ message }}</ev-alert>
|
||||||
|
}
|
||||||
|
@if (predictionsError(); as message) {
|
||||||
|
<ev-alert severity="danger" class="banner-error">{{ message }}</ev-alert>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (stats(); as s) {
|
@if (stats(); as s) {
|
||||||
<section class="overview">
|
<section class="overview">
|
||||||
<div class="card card--gauge">
|
<ev-card class="card card--gauge">
|
||||||
<span class="card__label">Consommation vs capacité</span>
|
<span class="card__label">Consommation vs capacité</span>
|
||||||
<app-consumption-gauge
|
<app-consumption-gauge
|
||||||
[consumption]="s.total_consumption_kw"
|
[consumption]="s.total_consumption_kw"
|
||||||
@@ -23,20 +43,20 @@
|
|||||||
>{{ s.total_consumption_kw | number: '1.0-1' }} /
|
>{{ s.total_consumption_kw | number: '1.0-1' }} /
|
||||||
{{ s.total_capacity_kw | number }} kW</span
|
{{ s.total_capacity_kw | number }} kW</span
|
||||||
>
|
>
|
||||||
</div>
|
</ev-card>
|
||||||
|
|
||||||
<div class="card">
|
<ev-card class="card">
|
||||||
<span class="card__label">Charge moyenne du parc</span>
|
<span class="card__label">Charge moyenne du parc</span>
|
||||||
<span class="card__value">{{ s.average_load_percent }} %</span>
|
<span class="card__value">{{ s.average_load_percent }} %</span>
|
||||||
<div class="progress-bar">
|
<div class="progress-bar">
|
||||||
<div class="progress-bar__fill" [style.width.%]="s.average_load_percent"></div>
|
<div class="progress-bar__fill" [style.width.%]="s.average_load_percent"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</ev-card>
|
||||||
|
|
||||||
<div class="card">
|
<ev-card class="card">
|
||||||
<span class="card__label">Sites suivis</span>
|
<span class="card__label">Sites suivis</span>
|
||||||
<span class="card__value">{{ s.total_sites }}</span>
|
<span class="card__value">{{ s.total_sites }}</span>
|
||||||
</div>
|
</ev-card>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="chart-section">
|
<section class="chart-section">
|
||||||
@@ -50,12 +70,41 @@
|
|||||||
<h2>Alertes actives</h2>
|
<h2>Alertes actives</h2>
|
||||||
<ul class="alerts-list">
|
<ul class="alerts-list">
|
||||||
@for (alert of alerts(); track alert.alert_id) {
|
@for (alert of alerts(); track alert.alert_id) {
|
||||||
<li class="alert-item" [class]="'alert-item--' + alert.severity">
|
<li class="alert-item">
|
||||||
<span class="alert-item__badge">{{ alert.severity }}</span>
|
<ev-badge [tone]="badgeToneForSeverity(alert.severity)">{{ alert.severity }}</ev-badge>
|
||||||
<span class="alert-item__message">{{ alert.message }}</span>
|
<span class="alert-item__message">{{ alert.message }}</span>
|
||||||
</li>
|
</li>
|
||||||
}
|
}
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</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: "dd/MM 'à' 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>
|
</div>
|
||||||
|
|||||||
@@ -1,23 +1,22 @@
|
|||||||
:host {
|
:host {
|
||||||
--color-good: #2e7d32;
|
|
||||||
--color-partial: #f9a825;
|
|
||||||
--color-degraded: #ef6c00;
|
|
||||||
--color-critical: #c62828;
|
|
||||||
--color-bg-card: #ffffff;
|
|
||||||
--color-border: #e5e7eb;
|
|
||||||
--color-text-muted: #6b7280;
|
|
||||||
--radius: 10px;
|
|
||||||
|
|
||||||
display: block;
|
display: block;
|
||||||
font-family: 'Segoe UI', system-ui, sans-serif;
|
color: var(--color-text);
|
||||||
color: #1f2937;
|
padding: 2.5rem 2rem;
|
||||||
padding: 2rem;
|
|
||||||
max-width: 1100px;
|
max-width: 1100px;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
.dashboard__header {
|
.dashboard__header {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: space-between;
|
||||||
margin-bottom: 2rem;
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dashboard__brand {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.85rem;
|
||||||
|
|
||||||
h1 {
|
h1 {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
@@ -26,11 +25,21 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.dashboard__logo {
|
||||||
|
font-size: 1.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
.dashboard__subtitle {
|
.dashboard__subtitle {
|
||||||
margin: 0.25rem 0 0;
|
margin: 0.25rem 0 0;
|
||||||
color: var(--color-text-muted);
|
color: var(--color-text-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.dashboard__actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
h2 {
|
h2 {
|
||||||
font-size: 1.1rem;
|
font-size: 1.1rem;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
@@ -38,13 +47,8 @@ h2 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.banner-error {
|
.banner-error {
|
||||||
|
display: block;
|
||||||
margin: 0 0 1.5rem;
|
margin: 0 0 1.5rem;
|
||||||
padding: 0.75rem 1rem;
|
|
||||||
border: 1px solid var(--color-critical);
|
|
||||||
border-left-width: 4px;
|
|
||||||
border-radius: var(--radius);
|
|
||||||
background: #fdecea;
|
|
||||||
color: var(--color-critical);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.overview {
|
.overview {
|
||||||
@@ -55,14 +59,8 @@ h2 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.card {
|
.card {
|
||||||
background: var(--color-bg-card);
|
|
||||||
border: 1px solid var(--color-border);
|
|
||||||
border-radius: var(--radius);
|
|
||||||
padding: 1.25rem;
|
padding: 1.25rem;
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 0.35rem;
|
gap: 0.35rem;
|
||||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.card--gauge {
|
.card--gauge {
|
||||||
@@ -84,16 +82,16 @@ h2 {
|
|||||||
|
|
||||||
.progress-bar {
|
.progress-bar {
|
||||||
height: 6px;
|
height: 6px;
|
||||||
background: #e5e7eb;
|
background: var(--color-border-light);
|
||||||
border-radius: 999px;
|
border-radius: var(--radius-pill);
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
margin-top: 0.25rem;
|
margin-top: 0.25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.progress-bar__fill {
|
.progress-bar__fill {
|
||||||
height: 100%;
|
height: 100%;
|
||||||
background: #3b82f6;
|
background: var(--color-primary);
|
||||||
border-radius: 999px;
|
border-radius: var(--radius-pill);
|
||||||
transition: width 0.3s ease;
|
transition: width 0.3s ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,59 +113,48 @@ h2 {
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 0.75rem;
|
gap: 0.75rem;
|
||||||
padding: 0.7rem 1rem;
|
padding: 0.7rem 1rem;
|
||||||
border-radius: var(--radius);
|
border-radius: var(--radius-md);
|
||||||
background: #fef2f2;
|
background: var(--color-danger-bg);
|
||||||
border: 1px solid #fecaca;
|
border: 1px solid var(--color-danger-border);
|
||||||
}
|
|
||||||
|
|
||||||
.alert-item__badge {
|
|
||||||
font-size: 0.7rem;
|
|
||||||
font-weight: 700;
|
|
||||||
text-transform: uppercase;
|
|
||||||
padding: 0.2rem 0.55rem;
|
|
||||||
border-radius: 999px;
|
|
||||||
color: #fff;
|
|
||||||
background: var(--color-critical);
|
|
||||||
flex-shrink: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.alert-item--high .alert-item__badge {
|
|
||||||
background: var(--color-degraded);
|
|
||||||
}
|
|
||||||
.alert-item--medium .alert-item__badge {
|
|
||||||
background: var(--color-partial);
|
|
||||||
}
|
|
||||||
.alert-item--low .alert-item__badge {
|
|
||||||
background: var(--color-good);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.alert-item__message {
|
.alert-item__message {
|
||||||
font-size: 0.9rem;
|
font-size: 0.9rem;
|
||||||
}
|
}
|
||||||
.dashboard__header {
|
|
||||||
display: flex;
|
|
||||||
align-items: flex-start;
|
|
||||||
justify-content: space-between;
|
|
||||||
margin-bottom: 2rem;
|
|
||||||
|
|
||||||
h1 {
|
.predictions-list {
|
||||||
|
list-style: none;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
font-size: 1.75rem;
|
padding: 0;
|
||||||
font-weight: 700;
|
display: flex;
|
||||||
}
|
flex-direction: column;
|
||||||
|
gap: 0.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.logout-button {
|
.prediction-item {
|
||||||
padding: 0.5rem 1rem;
|
display: flex;
|
||||||
background: #ffffff;
|
align-items: center;
|
||||||
border: 1px solid #d1d5db;
|
justify-content: space-between;
|
||||||
border-radius: 8px;
|
gap: 0.75rem;
|
||||||
font-size: 0.85rem;
|
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;
|
font-weight: 600;
|
||||||
color: #374151;
|
}
|
||||||
cursor: pointer;
|
|
||||||
|
|
||||||
&:hover {
|
.prediction-item__value {
|
||||||
background: #f3f4f6;
|
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,8 +4,9 @@ import { of, throwError } from 'rxjs';
|
|||||||
import { Dashboard } from './dashboard';
|
import { Dashboard } from './dashboard';
|
||||||
import { StatsService } from '../../core/services/stats.service';
|
import { StatsService } from '../../core/services/stats.service';
|
||||||
import { AlertsService } from '../../core/services/alerts.service';
|
import { AlertsService } from '../../core/services/alerts.service';
|
||||||
|
import { PredictionsService } from '../../core/services/predictions.service';
|
||||||
import {AuthService} from '../../core/services/auth.service';
|
import {AuthService} from '../../core/services/auth.service';
|
||||||
import {Router} from '@angular/router';
|
import {Router, provideRouter} from '@angular/router';
|
||||||
|
|
||||||
vi.mock('chart.js', () => {
|
vi.mock('chart.js', () => {
|
||||||
class ChartMock {
|
class ChartMock {
|
||||||
@@ -17,18 +18,25 @@ vi.mock('chart.js', () => {
|
|||||||
return { Chart: ChartMock, registerables: [] };
|
return { Chart: ChartMock, registerables: [] };
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function predictionsMock(sites: unknown[] = []) {
|
||||||
|
return { getPredictions: vi.fn().mockReturnValue(of({ timestamp: '2026-09-18T09:00:00Z', sites })) };
|
||||||
|
}
|
||||||
|
|
||||||
describe('Dashboard', () => {
|
describe('Dashboard', () => {
|
||||||
afterEach(() => vi.useRealTimers());
|
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 statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
||||||
const alertsMock = { getAlerts: vi.fn().mockReturnValue(of([{ alert_id: 'A1' }])) };
|
const alertsMock = { getAlerts: vi.fn().mockReturnValue(of([{ alert_id: 'A1' }])) };
|
||||||
|
const predictions = predictionsMock([{ site_id: 'SITE001', site_name: 'Test', prediction: null }]);
|
||||||
|
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
imports: [Dashboard],
|
imports: [Dashboard],
|
||||||
providers: [
|
providers: [
|
||||||
{ provide: StatsService, useValue: statsMock },
|
{ provide: StatsService, useValue: statsMock },
|
||||||
{ provide: AlertsService, useValue: alertsMock },
|
{ provide: AlertsService, useValue: alertsMock },
|
||||||
|
{ provide: PredictionsService, useValue: predictions },
|
||||||
|
provideRouter([]),
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -41,8 +49,12 @@ describe('Dashboard', () => {
|
|||||||
|
|
||||||
expect(statsMock.getSummary).toHaveBeenCalled();
|
expect(statsMock.getSummary).toHaveBeenCalled();
|
||||||
expect(alertsMock.getAlerts).toHaveBeenCalled();
|
expect(alertsMock.getAlerts).toHaveBeenCalled();
|
||||||
|
expect(predictions.getPredictions).toHaveBeenCalled();
|
||||||
expect(fixture.componentInstance.alerts().length).toBe(1);
|
expect(fixture.componentInstance.alerts().length).toBe(1);
|
||||||
expect(fixture.componentInstance.error()).toBeNull();
|
expect(fixture.componentInstance.predictions().length).toBe(1);
|
||||||
|
expect(fixture.componentInstance.statsError()).toBeNull();
|
||||||
|
expect(fixture.componentInstance.alertsError()).toBeNull();
|
||||||
|
expect(fixture.componentInstance.predictionsError()).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("signale l'indisponibilité puis repart au rafraîchissement suivant", () => {
|
it("signale l'indisponibilité puis repart au rafraîchissement suivant", () => {
|
||||||
@@ -60,6 +72,8 @@ describe('Dashboard', () => {
|
|||||||
providers: [
|
providers: [
|
||||||
{ provide: StatsService, useValue: statsMock },
|
{ provide: StatsService, useValue: statsMock },
|
||||||
{ provide: AlertsService, useValue: alertsMock },
|
{ provide: AlertsService, useValue: alertsMock },
|
||||||
|
{ provide: PredictionsService, useValue: predictionsMock() },
|
||||||
|
provideRouter([]),
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -68,13 +82,13 @@ describe('Dashboard', () => {
|
|||||||
|
|
||||||
vi.advanceTimersByTime(1);
|
vi.advanceTimersByTime(1);
|
||||||
expect(statsMock.getSummary).toHaveBeenCalledTimes(1);
|
expect(statsMock.getSummary).toHaveBeenCalledTimes(1);
|
||||||
expect(fixture.componentInstance.error()).not.toBeNull();
|
expect(fixture.componentInstance.statsError()).not.toBeNull();
|
||||||
expect(fixture.componentInstance.stats()).toBeNull();
|
expect(fixture.componentInstance.stats()).toBeNull();
|
||||||
|
|
||||||
vi.advanceTimersByTime(10000);
|
vi.advanceTimersByTime(10000);
|
||||||
expect(statsMock.getSummary).toHaveBeenCalledTimes(2);
|
expect(statsMock.getSummary).toHaveBeenCalledTimes(2);
|
||||||
expect(fixture.componentInstance.stats()).not.toBeNull();
|
expect(fixture.componentInstance.stats()).not.toBeNull();
|
||||||
expect(fixture.componentInstance.error()).toBeNull();
|
expect(fixture.componentInstance.statsError()).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("n'interrompt pas la page quand le chargement des alertes échoue", () => {
|
it("n'interrompt pas la page quand le chargement des alertes échoue", () => {
|
||||||
@@ -86,6 +100,8 @@ describe('Dashboard', () => {
|
|||||||
providers: [
|
providers: [
|
||||||
{ provide: StatsService, useValue: statsMock },
|
{ provide: StatsService, useValue: statsMock },
|
||||||
{ provide: AlertsService, useValue: alertsMock },
|
{ provide: AlertsService, useValue: alertsMock },
|
||||||
|
{ provide: PredictionsService, useValue: predictionsMock() },
|
||||||
|
provideRouter([]),
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -93,32 +109,91 @@ describe('Dashboard', () => {
|
|||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
expect(fixture.componentInstance.alerts().length).toBe(0);
|
expect(fixture.componentInstance.alerts().length).toBe(0);
|
||||||
|
expect(fixture.componentInstance.alertsError()).not.toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('appelle logout et redirige vers /login au clic sur le bouton de déconnexion', () => {
|
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 statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
||||||
const alertsMock = { getAlerts: vi.fn().mockReturnValue(of([])) };
|
const alertsMock = { getAlerts: vi.fn().mockReturnValue(of([])) };
|
||||||
const authMock = { logout: vi.fn().mockReturnValue(of(undefined)), clearSession: vi.fn() };
|
const predictions = {
|
||||||
const routerMock = { navigate: vi.fn() };
|
getPredictions: vi.fn().mockReturnValue(throwError(() => new Error('nope'))),
|
||||||
|
};
|
||||||
|
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
imports: [Dashboard],
|
imports: [Dashboard],
|
||||||
providers: [
|
providers: [
|
||||||
{ provide: StatsService, useValue: statsMock },
|
{ provide: StatsService, useValue: statsMock },
|
||||||
{ provide: AlertsService, useValue: alertsMock },
|
{ provide: AlertsService, useValue: alertsMock },
|
||||||
{ provide: AuthService, useValue: authMock },
|
{ provide: PredictionsService, useValue: predictions },
|
||||||
{ provide: Router, useValue: routerMock },
|
provideRouter([]),
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(Dashboard);
|
const fixture = TestBed.createComponent(Dashboard);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.predictions().length).toBe(0);
|
||||||
|
expect(fixture.componentInstance.predictionsError()).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("un rafraîchissement de stats n'efface pas une erreur de prévisions en attente", () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
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.predictionsError()).not.toBeNull();
|
||||||
|
|
||||||
|
// Plusieurs cycles de `timer(0, 10_000)` (stats) plus tard, l'erreur des prévisions doit
|
||||||
|
// toujours être visible : rien ne vient la rafraîchir tant que la section n'est pas rechargée.
|
||||||
|
vi.advanceTimersByTime(30000);
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.predictionsError()).not.toBeNull();
|
||||||
|
expect(fixture.componentInstance.statsError()).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([])) };
|
||||||
|
const authMock = { logout: vi.fn().mockReturnValue(of(undefined)), clearSession: vi.fn() };
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [Dashboard],
|
||||||
|
providers: [
|
||||||
|
{ provide: StatsService, useValue: statsMock },
|
||||||
|
{ provide: AlertsService, useValue: alertsMock },
|
||||||
|
{ provide: PredictionsService, useValue: predictionsMock() },
|
||||||
|
{ provide: AuthService, useValue: authMock },
|
||||||
|
provideRouter([]),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(Dashboard);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const router = TestBed.inject(Router);
|
||||||
|
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||||
|
|
||||||
const button = fixture.nativeElement.querySelector('.logout-button');
|
const button = fixture.nativeElement.querySelector('.logout-button');
|
||||||
button.click();
|
button.click();
|
||||||
|
|
||||||
expect(authMock.logout).toHaveBeenCalled();
|
expect(authMock.logout).toHaveBeenCalled();
|
||||||
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
|
expect(navigateSpy).toHaveBeenCalledWith(['/login']);
|
||||||
});
|
});
|
||||||
it('déconnecte localement et redirige vers /login même si logout échoue côté réseau', () => {
|
it('déconnecte localement et redirige vers /login même si logout échoue côté réseau', () => {
|
||||||
const statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
const statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
||||||
@@ -127,25 +202,75 @@ describe('Dashboard', () => {
|
|||||||
logout: vi.fn().mockReturnValue(throwError(() => new Error('réseau indisponible'))),
|
logout: vi.fn().mockReturnValue(throwError(() => new Error('réseau indisponible'))),
|
||||||
clearSession: vi.fn(),
|
clearSession: vi.fn(),
|
||||||
};
|
};
|
||||||
const routerMock = { navigate: vi.fn() };
|
|
||||||
|
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
imports: [Dashboard],
|
imports: [Dashboard],
|
||||||
providers: [
|
providers: [
|
||||||
{ provide: StatsService, useValue: statsMock },
|
{ provide: StatsService, useValue: statsMock },
|
||||||
{ provide: AlertsService, useValue: alertsMock },
|
{ provide: AlertsService, useValue: alertsMock },
|
||||||
|
{ provide: PredictionsService, useValue: predictionsMock() },
|
||||||
{ provide: AuthService, useValue: authMock },
|
{ provide: AuthService, useValue: authMock },
|
||||||
{ provide: Router, useValue: routerMock },
|
provideRouter([]),
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(Dashboard);
|
const fixture = TestBed.createComponent(Dashboard);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const router = TestBed.inject(Router);
|
||||||
|
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||||
|
|
||||||
const button = fixture.nativeElement.querySelector('.logout-button');
|
const button = fixture.nativeElement.querySelector('.logout-button');
|
||||||
button.click();
|
button.click();
|
||||||
|
|
||||||
expect(authMock.clearSession).toHaveBeenCalled();
|
expect(authMock.clearSession).toHaveBeenCalled();
|
||||||
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
|
expect(navigateSpy).toHaveBeenCalledWith(['/login']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('distingue le ton des sévérités high et critical', () => {
|
||||||
|
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.badgeToneForSeverity('low')).toBe('success');
|
||||||
|
expect(dashboard.badgeToneForSeverity('medium')).toBe('warning');
|
||||||
|
expect(dashboard.badgeToneForSeverity('high')).toBe('danger');
|
||||||
|
expect(dashboard.badgeToneForSeverity('critical')).toBe('critical');
|
||||||
|
expect(dashboard.badgeToneForSeverity('high')).not.toBe(
|
||||||
|
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,59 +1,122 @@
|
|||||||
import { Component, OnInit, inject, signal, DestroyRef } from '@angular/core';
|
import { Component, OnInit, inject, signal, DestroyRef, WritableSignal } from '@angular/core';
|
||||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
import { timer, switchMap, catchError, EMPTY, Observable } from 'rxjs';
|
import { timer, switchMap, catchError, EMPTY, Observable } from 'rxjs';
|
||||||
import { DecimalPipe } from '@angular/common';
|
import { DecimalPipe, DatePipe } from '@angular/common';
|
||||||
import { Router } from '@angular/router';
|
import { Router, RouterLink } from '@angular/router';
|
||||||
import { StatsService } from '../../core/services/stats.service';
|
import { StatsService } from '../../core/services/stats.service';
|
||||||
import { ConsumptionGauge } from '../../shared/components/consumption-gauge/consumption-gauge';
|
import { ConsumptionGauge } from '../../shared/components/consumption-gauge/consumption-gauge';
|
||||||
import { SiteLoadChart } from '../../shared/components/site-load-chart/site-load-chart';
|
import { SiteLoadChart } from '../../shared/components/site-load-chart/site-load-chart';
|
||||||
import { AlertsService } from '../../core/services/alerts.service';
|
import { AlertsService } from '../../core/services/alerts.service';
|
||||||
|
import { PredictionsService } from '../../core/services/predictions.service';
|
||||||
import { AuthService } from '../../core/services/auth.service';
|
import { AuthService } from '../../core/services/auth.service';
|
||||||
import { StatsSummary } from '../../shared/models/stats.model';
|
import { StatsSummary } from '../../shared/models/stats.model';
|
||||||
import { Alert } from '../../shared/models/alert.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';
|
||||||
|
import { Brand } from '../../shared/components/ui/brand/brand';
|
||||||
|
import { Button } from '../../shared/components/ui/button/button';
|
||||||
|
|
||||||
const REFRESH_INTERVAL_MS = 10000;
|
const REFRESH_INTERVAL_MS = 10000;
|
||||||
const UNAVAILABLE_MESSAGE =
|
const UNAVAILABLE_MESSAGE =
|
||||||
'Données indisponibles, les valeurs affichées datent du dernier relevé.';
|
'Données indisponibles, les valeurs affichées datent du dernier relevé.';
|
||||||
|
|
||||||
|
const TON_PAR_SEVERITE: Record<AlertSeverity, BadgeTone> = {
|
||||||
|
low: 'success',
|
||||||
|
medium: 'warning',
|
||||||
|
high: 'danger',
|
||||||
|
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({
|
@Component({
|
||||||
selector: 'app-dashboard',
|
selector: 'app-dashboard',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [DecimalPipe, ConsumptionGauge, SiteLoadChart],
|
imports: [
|
||||||
|
DecimalPipe,
|
||||||
|
DatePipe,
|
||||||
|
RouterLink,
|
||||||
|
ConsumptionGauge,
|
||||||
|
SiteLoadChart,
|
||||||
|
Card,
|
||||||
|
EvAlert,
|
||||||
|
Badge,
|
||||||
|
Brand,
|
||||||
|
Button,
|
||||||
|
],
|
||||||
templateUrl: './dashboard.html',
|
templateUrl: './dashboard.html',
|
||||||
styleUrl: './dashboard.scss',
|
styleUrl: './dashboard.scss',
|
||||||
})
|
})
|
||||||
export class Dashboard implements OnInit {
|
export class Dashboard implements OnInit {
|
||||||
private statsService = inject(StatsService);
|
private statsService = inject(StatsService);
|
||||||
private alertsService = inject(AlertsService);
|
private alertsService = inject(AlertsService);
|
||||||
|
private predictionsService = inject(PredictionsService);
|
||||||
private auth = inject(AuthService);
|
private auth = inject(AuthService);
|
||||||
private router = inject(Router);
|
private router = inject(Router);
|
||||||
private destroyRef = inject(DestroyRef);
|
private destroyRef = inject(DestroyRef);
|
||||||
|
|
||||||
stats = signal<StatsSummary | null>(null);
|
stats = signal<StatsSummary | null>(null);
|
||||||
alerts = signal<Alert[]>([]);
|
alerts = signal<Alert[]>([]);
|
||||||
error = signal<string | null>(null);
|
predictions = signal<SitePredictionSummary[]>([]);
|
||||||
|
|
||||||
|
// Un signal par flux, pas un seul `error` partagé : sinon le tick suivant de `timer` (stats)
|
||||||
|
// efface silencieusement un message d'échec des prévisions ou des alertes après 10s au plus,
|
||||||
|
// sans retry ni indication pour l'utilisateur que la section correspondante est restée vide.
|
||||||
|
statsError = signal<string | null>(null);
|
||||||
|
alertsError = signal<string | null>(null);
|
||||||
|
predictionsError = signal<string | null>(null);
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.alertsService
|
this.alertsService
|
||||||
.getAlerts()
|
.getAlerts()
|
||||||
.pipe(catchError(() => this.reportUnavailable()))
|
.pipe(catchError(() => this.reportUnavailable(this.alertsError)))
|
||||||
.subscribe((alerts) => this.alerts.set(alerts));
|
.subscribe((alerts) => {
|
||||||
|
this.alertsError.set(null);
|
||||||
|
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(this.predictionsError)))
|
||||||
|
.subscribe((summary) => {
|
||||||
|
this.predictionsError.set(null);
|
||||||
|
this.predictions.set(summary.sites);
|
||||||
|
});
|
||||||
|
|
||||||
// Piège : le catchError porte sur l'observable interne. Sur le flux externe il
|
// Piège : le catchError porte sur l'observable interne. Sur le flux externe il
|
||||||
// terminerait le timer, et le rafraîchissement ne repartirait jamais.
|
// terminerait le timer, et le rafraîchissement ne repartirait jamais.
|
||||||
timer(0, REFRESH_INTERVAL_MS)
|
timer(0, REFRESH_INTERVAL_MS)
|
||||||
.pipe(
|
.pipe(
|
||||||
switchMap(() =>
|
switchMap(() =>
|
||||||
this.statsService.getSummary().pipe(catchError(() => this.reportUnavailable())),
|
this.statsService.getSummary().pipe(catchError(() => this.reportUnavailable(this.statsError))),
|
||||||
),
|
),
|
||||||
takeUntilDestroyed(this.destroyRef),
|
takeUntilDestroyed(this.destroyRef),
|
||||||
)
|
)
|
||||||
.subscribe((stats) => {
|
.subscribe((stats) => {
|
||||||
this.error.set(null);
|
this.statsError.set(null);
|
||||||
this.stats.set(stats);
|
this.stats.set(stats);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
badgeToneForSeverity(severity: AlertSeverity): BadgeTone {
|
||||||
|
return TON_PAR_SEVERITE[severity];
|
||||||
|
}
|
||||||
|
|
||||||
|
badgeToneForPredictionStatus(status: PredictionStatus): BadgeTone {
|
||||||
|
return TON_PAR_STATUT_PREDICTION[status];
|
||||||
|
}
|
||||||
|
|
||||||
onLogout(): void {
|
onLogout(): void {
|
||||||
this.auth.logout().subscribe({
|
this.auth.logout().subscribe({
|
||||||
next: () => this.router.navigate(['/login']),
|
next: () => this.router.navigate(['/login']),
|
||||||
@@ -65,8 +128,8 @@ export class Dashboard implements OnInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private reportUnavailable(): Observable<never> {
|
private reportUnavailable(target: WritableSignal<string | null>): Observable<never> {
|
||||||
this.error.set(UNAVAILABLE_MESSAGE);
|
target.set(UNAVAILABLE_MESSAGE);
|
||||||
return EMPTY;
|
return EMPTY;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
<div class="site-detail">
|
||||||
|
<nav class="ev-breadcrumb">
|
||||||
|
<a routerLink="/dashboard">Tableau de bord</a>
|
||||||
|
<span>/</span>
|
||||||
|
<a routerLink="/sites">Sites</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<header class="site-detail__header">
|
||||||
|
<a routerLink="/dashboard" class="ev-brand-link">
|
||||||
|
<ev-brand class="site-detail__logo" />
|
||||||
|
</a>
|
||||||
|
<div>
|
||||||
|
<h1>{{ site()?.site_name ?? siteId() }}</h1>
|
||||||
|
@if (site(); as s) {
|
||||||
|
<p class="site-detail__subtitle">
|
||||||
|
{{ s.site_type }} · {{ s.location || 'Localisation inconnue' }}
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="site-detail__badges">
|
||||||
|
@if (site(); as s) {
|
||||||
|
<ev-badge [tone]="badgeToneForStatus(s.status)">{{ s.status ?? '-' }}</ev-badge>
|
||||||
|
}
|
||||||
|
@if (hasMeasurement() && qualityLabel(); as label) {
|
||||||
|
<ev-badge [tone]="qualityTone()">{{ label }}</ev-badge>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
@if (error(); as message) {
|
||||||
|
<ev-alert severity="danger" class="banner-error">{{ message }}</ev-alert>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (site(); as s) {
|
||||||
|
@if (hasMeasurement()) {
|
||||||
|
<section class="overview">
|
||||||
|
<ev-card class="card card--gauge">
|
||||||
|
<span class="card__label">Consommation vs capacité</span>
|
||||||
|
@let consumption = consumptionKw();
|
||||||
|
@if (consumption !== null) {
|
||||||
|
<app-consumption-gauge [consumption]="consumption" [capacity]="s.capacity_kw ?? 0" />
|
||||||
|
<span class="card__value">
|
||||||
|
{{ consumptionLabel() }} / {{ s.capacity_kw ?? '-' }} kW
|
||||||
|
</span>
|
||||||
|
} @else {
|
||||||
|
<p class="card__unavailable">
|
||||||
|
Consommation indisponible
|
||||||
|
<span class="metric__reason">({{ consumptionReason() }})</span>
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
</ev-card>
|
||||||
|
|
||||||
|
<ev-card class="metrics-card">
|
||||||
|
<span class="card__label">Mesure instantanée</span>
|
||||||
|
<dl class="metrics-grid">
|
||||||
|
@for (metric of metrics(); track metric.key) {
|
||||||
|
<div class="metric">
|
||||||
|
<dt>{{ metric.label }}</dt>
|
||||||
|
@if (metric.value !== null) {
|
||||||
|
<dd>{{ metric.value }}</dd>
|
||||||
|
} @else {
|
||||||
|
<dd class="metric__unavailable">
|
||||||
|
Indisponible
|
||||||
|
<span class="metric__reason">({{ metric.reason }})</span>
|
||||||
|
</dd>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
</ev-card>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@if (history().length > 0) {
|
||||||
|
<section class="chart-section">
|
||||||
|
<h2>Historique de consommation</h2>
|
||||||
|
<app-reading-history-chart [readings]="history()" />
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
} @else {
|
||||||
|
<ev-alert severity="warning" class="banner-empty">{{ noMeasurementMessage }}</ev-alert>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
<a routerLink="/sites" class="ev-link">Retour aux sites</a>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
color: var(--color-text);
|
||||||
|
padding: 2.5rem 2rem;
|
||||||
|
max-width: 1100px;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-detail__header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.85rem;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.75rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-detail__logo {
|
||||||
|
font-size: 1.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-detail__subtitle {
|
||||||
|
margin: 0.25rem 0 0;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-detail__badges {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
margin-left: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.banner-error {
|
||||||
|
display: block;
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.banner-empty {
|
||||||
|
display: block;
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.overview {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
|
||||||
|
gap: 1rem;
|
||||||
|
margin-bottom: 2.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
padding: 1.25rem;
|
||||||
|
gap: 0.35rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card--gauge {
|
||||||
|
align-items: center;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card__label {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card__value {
|
||||||
|
font-size: 1.6rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card__unavailable {
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metrics-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, 1fr);
|
||||||
|
gap: 0.75rem 1.5rem;
|
||||||
|
margin: 0.5rem 0 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric {
|
||||||
|
dt {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
dd {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.05rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric__unavailable {
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
font-weight: 400;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric__reason {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
h2 {
|
||||||
|
font-size: 1.1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
margin: 0 0 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chart-section {
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { ActivatedRoute, convertToParamMap, provideRouter } from '@angular/router';
|
||||||
|
import { vi } from 'vitest';
|
||||||
|
import { BehaviorSubject, of, throwError } from 'rxjs';
|
||||||
|
import { SiteDetail } from './site-detail';
|
||||||
|
import { SitesService } from '../../../core/services/sites.service';
|
||||||
|
import { ReadingsService } from '../../../core/services/readings.service';
|
||||||
|
|
||||||
|
const SITE = {
|
||||||
|
site_id: 'SITE001',
|
||||||
|
site_name: 'Site 1',
|
||||||
|
site_type: 'industriel',
|
||||||
|
location: 'Nantes',
|
||||||
|
capacity_kw: 500,
|
||||||
|
status: 'actif',
|
||||||
|
};
|
||||||
|
|
||||||
|
const CURRENT_COMPLET = {
|
||||||
|
timestamp: '2026-09-17T10:00:00Z',
|
||||||
|
site_id: 'SITE001',
|
||||||
|
site_type: 'industriel',
|
||||||
|
consumption_kw: 120,
|
||||||
|
consumption_kwh: null,
|
||||||
|
voltage_v: 230,
|
||||||
|
current_a: 12,
|
||||||
|
power_factor: 0.95,
|
||||||
|
temperature_celsius: 22,
|
||||||
|
humidity_percent: 55,
|
||||||
|
null_reasons: [] as string[],
|
||||||
|
data_quality: 'good' as const,
|
||||||
|
};
|
||||||
|
|
||||||
|
const SANS_MESURE = {
|
||||||
|
...CURRENT_COMPLET,
|
||||||
|
timestamp: null,
|
||||||
|
consumption_kw: null,
|
||||||
|
voltage_v: null,
|
||||||
|
current_a: null,
|
||||||
|
power_factor: null,
|
||||||
|
temperature_celsius: null,
|
||||||
|
humidity_percent: null,
|
||||||
|
data_quality: 'critical' as const,
|
||||||
|
};
|
||||||
|
|
||||||
|
const LECTURE = {
|
||||||
|
reading_id: 1,
|
||||||
|
site_id: 'SITE001',
|
||||||
|
timestamp: '2026-09-17T09:00:00Z',
|
||||||
|
source: 'api_history' as const,
|
||||||
|
consumption_kw: 118,
|
||||||
|
consumption_kwh: null,
|
||||||
|
consumption_euros: null,
|
||||||
|
voltage_v: 230,
|
||||||
|
current_a: 12,
|
||||||
|
power_factor: 0.95,
|
||||||
|
temperature_celsius: 22,
|
||||||
|
humidity_percent: 55,
|
||||||
|
solar_irradiance_wm2: null,
|
||||||
|
is_working_hours: true,
|
||||||
|
data_quality: 'good' as const,
|
||||||
|
null_reasons: null,
|
||||||
|
imputed_values: null,
|
||||||
|
imputation_method: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
function setup(
|
||||||
|
siteId: string,
|
||||||
|
sitesMock: Partial<SitesService>,
|
||||||
|
readingsMock: Partial<ReadingsService>,
|
||||||
|
) {
|
||||||
|
const paramMap = new BehaviorSubject(convertToParamMap({ siteId }));
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [SiteDetail],
|
||||||
|
providers: [
|
||||||
|
provideRouter([]),
|
||||||
|
{ provide: ActivatedRoute, useValue: { paramMap } },
|
||||||
|
{ provide: SitesService, useValue: sitesMock },
|
||||||
|
{ provide: ReadingsService, useValue: readingsMock },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
return { fixture: TestBed.createComponent(SiteDetail), paramMap };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('SiteDetail', () => {
|
||||||
|
it('charge le site, la mesure courante et son historique au démarrage', () => {
|
||||||
|
const { fixture } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{
|
||||||
|
getSite: vi.fn().mockReturnValue(of(SITE)),
|
||||||
|
getCurrent: vi.fn().mockReturnValue(of(CURRENT_COMPLET)),
|
||||||
|
},
|
||||||
|
{ getHistory: vi.fn().mockReturnValue(of([LECTURE])) },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.site()?.site_id).toBe('SITE001');
|
||||||
|
expect(fixture.componentInstance.current()?.consumption_kw).toBe(120);
|
||||||
|
expect(fixture.componentInstance.history().length).toBe(1);
|
||||||
|
expect(fixture.componentInstance.error()).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("signale l'indisponibilité quand un des appels échoue", () => {
|
||||||
|
const { fixture } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{
|
||||||
|
getSite: vi.fn().mockReturnValue(throwError(() => new Error('nope'))),
|
||||||
|
getCurrent: vi.fn().mockReturnValue(of(CURRENT_COMPLET)),
|
||||||
|
},
|
||||||
|
{ getHistory: vi.fn().mockReturnValue(of([])) },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.error()).not.toBeNull();
|
||||||
|
expect(fixture.componentInstance.site()).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('efface les données du site précédent quand le chargement du suivant échoue', () => {
|
||||||
|
const getSite = vi
|
||||||
|
.fn()
|
||||||
|
.mockReturnValueOnce(of(SITE))
|
||||||
|
.mockReturnValueOnce(throwError(() => new Error('404')));
|
||||||
|
const { fixture, paramMap } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{ getSite, getCurrent: vi.fn().mockReturnValue(of(CURRENT_COMPLET)) },
|
||||||
|
{ getHistory: vi.fn().mockReturnValue(of([LECTURE])) },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(fixture.componentInstance.site()?.site_id).toBe('SITE001');
|
||||||
|
|
||||||
|
paramMap.next(convertToParamMap({ siteId: 'SITE002' }));
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.error()).not.toBeNull();
|
||||||
|
expect(fixture.componentInstance.site()).toBeNull();
|
||||||
|
expect(fixture.componentInstance.current()).toBeNull();
|
||||||
|
expect(fixture.componentInstance.history()).toEqual([]);
|
||||||
|
expect(fixture.nativeElement.textContent).not.toContain('Site 1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('interroge le site et sa mesure courante en parallèle', () => {
|
||||||
|
const getSite = vi.fn().mockReturnValue(of(SITE));
|
||||||
|
const getCurrent = vi.fn().mockReturnValue(of(CURRENT_COMPLET));
|
||||||
|
const { fixture } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{ getSite, getCurrent },
|
||||||
|
{ getHistory: vi.fn().mockReturnValue(of([])) },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(getSite).toHaveBeenCalledWith('SITE001');
|
||||||
|
expect(getCurrent).toHaveBeenCalledWith('SITE001');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('signale la panne du capteur de consommation au lieu de tracer une jauge à zéro', () => {
|
||||||
|
const sansConsommation = {
|
||||||
|
...CURRENT_COMPLET,
|
||||||
|
consumption_kw: null,
|
||||||
|
null_reasons: ['consumption_sensor_failure'],
|
||||||
|
data_quality: 'partial' as const,
|
||||||
|
};
|
||||||
|
const { fixture } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{
|
||||||
|
getSite: vi.fn().mockReturnValue(of(SITE)),
|
||||||
|
getCurrent: vi.fn().mockReturnValue(of(sansConsommation)),
|
||||||
|
},
|
||||||
|
{ getHistory: vi.fn().mockReturnValue(of([LECTURE])) },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.consumptionKw()).toBeNull();
|
||||||
|
expect(fixture.componentInstance.consumptionReason()).toBe('capteur de consommation en panne');
|
||||||
|
expect(fixture.nativeElement.querySelector('app-consumption-gauge')).toBeNull();
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('Consommation indisponible');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('trace la jauge pour une consommation nulle réellement mesurée', () => {
|
||||||
|
const { fixture } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{
|
||||||
|
getSite: vi.fn().mockReturnValue(of(SITE)),
|
||||||
|
getCurrent: vi.fn().mockReturnValue(of({ ...CURRENT_COMPLET, consumption_kw: 0 })),
|
||||||
|
},
|
||||||
|
{ getHistory: vi.fn().mockReturnValue(of([LECTURE])) },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.consumptionLabel()).toBe('0.0 kW');
|
||||||
|
expect(fixture.nativeElement.querySelector('app-consumption-gauge')).not.toBeNull();
|
||||||
|
expect(fixture.nativeElement.textContent).not.toContain('Consommation indisponible');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('affiche explicitement les champs null avec leur raison plutôt que de les masquer', () => {
|
||||||
|
const partielle = {
|
||||||
|
...CURRENT_COMPLET,
|
||||||
|
voltage_v: null,
|
||||||
|
current_a: null,
|
||||||
|
power_factor: null,
|
||||||
|
null_reasons: ['electrical_sensor_failure'],
|
||||||
|
data_quality: 'partial' as const,
|
||||||
|
};
|
||||||
|
const { fixture } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{
|
||||||
|
getSite: vi.fn().mockReturnValue(of(SITE)),
|
||||||
|
getCurrent: vi.fn().mockReturnValue(of(partielle)),
|
||||||
|
},
|
||||||
|
{ getHistory: vi.fn().mockReturnValue(of([LECTURE])) },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const tension = fixture.componentInstance.metrics().find((m) => m.key === 'voltage_v');
|
||||||
|
expect(tension?.value).toBeNull();
|
||||||
|
expect(tension?.reason).toBe('capteur électrique en panne');
|
||||||
|
|
||||||
|
const texte = fixture.nativeElement.textContent;
|
||||||
|
expect(texte).toContain('Indisponible');
|
||||||
|
expect(texte).toContain('capteur électrique en panne');
|
||||||
|
expect(texte).toContain('Données partielles');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('recharge les données quand le paramètre de route siteId change', () => {
|
||||||
|
const getSite = vi.fn().mockReturnValue(of(SITE));
|
||||||
|
const { fixture, paramMap } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{ getSite, getCurrent: vi.fn().mockReturnValue(of(CURRENT_COMPLET)) },
|
||||||
|
{ getHistory: vi.fn().mockReturnValue(of([])) },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
paramMap.next(convertToParamMap({ siteId: 'SITE002' }));
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(getSite).toHaveBeenCalledWith('SITE002');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ancre la fenêtre d'historique sur la dernière mesure connue plutôt que sur l'horloge", () => {
|
||||||
|
const getHistory = vi.fn().mockReturnValue(of([]));
|
||||||
|
const { fixture } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{
|
||||||
|
getSite: vi.fn().mockReturnValue(of(SITE)),
|
||||||
|
getCurrent: vi.fn().mockReturnValue(of(CURRENT_COMPLET)),
|
||||||
|
},
|
||||||
|
{ getHistory },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(getHistory).toHaveBeenCalledWith(
|
||||||
|
'SITE001',
|
||||||
|
'2026-09-16T10:00:00.000Z',
|
||||||
|
'2026-09-17T10:00:00Z',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("annonce l'absence de mesure sans interroger l'historique quand timestamp est null", () => {
|
||||||
|
const getHistory = vi.fn().mockReturnValue(of([]));
|
||||||
|
const { fixture } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{
|
||||||
|
getSite: vi.fn().mockReturnValue(of(SITE)),
|
||||||
|
getCurrent: vi.fn().mockReturnValue(of(SANS_MESURE)),
|
||||||
|
},
|
||||||
|
{ getHistory },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(getHistory).not.toHaveBeenCalled();
|
||||||
|
expect(fixture.componentInstance.hasMeasurement()).toBe(false);
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('Aucune mesure remontée pour ce site.');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
import { Component, DestroyRef, computed, inject, signal } from '@angular/core';
|
||||||
|
import { takeUntilDestroyed, toObservable, toSignal } from '@angular/core/rxjs-interop';
|
||||||
|
import { ActivatedRoute, RouterLink } from '@angular/router';
|
||||||
|
import { catchError, EMPTY, filter, forkJoin, map, Observable, of, switchMap } from 'rxjs';
|
||||||
|
import { SitesService } from '../../../core/services/sites.service';
|
||||||
|
import { ReadingsService } from '../../../core/services/readings.service';
|
||||||
|
import { Site } from '../../../shared/models/site.model';
|
||||||
|
import { Reading, ReadingDataQuality } from '../../../shared/models/reading.model';
|
||||||
|
import { SiteCurrent } from '../../../shared/models/site-current.model';
|
||||||
|
import { Card } from '../../../shared/components/ui/card/card';
|
||||||
|
import { Alert } from '../../../shared/components/ui/alert/alert';
|
||||||
|
import { Badge, BadgeTone } from '../../../shared/components/ui/badge/badge';
|
||||||
|
import { Brand } from '../../../shared/components/ui/brand/brand';
|
||||||
|
import { ConsumptionGauge } from '../../../shared/components/consumption-gauge/consumption-gauge';
|
||||||
|
import { ReadingHistoryChart } from '../../../shared/components/reading-history-chart/reading-history-chart';
|
||||||
|
|
||||||
|
const UNAVAILABLE_MESSAGE = 'Détail du site indisponible, réessayez plus tard.';
|
||||||
|
const NO_MEASUREMENT_MESSAGE = 'Aucune mesure remontée pour ce site.';
|
||||||
|
const HISTORY_WINDOW_MS = 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
const TON_PAR_STATUT: Record<string, BadgeTone> = {
|
||||||
|
actif: 'success',
|
||||||
|
maintenance: 'warning',
|
||||||
|
hors_service: 'danger',
|
||||||
|
};
|
||||||
|
|
||||||
|
const TON_PAR_QUALITE: Record<ReadingDataQuality, BadgeTone> = {
|
||||||
|
good: 'success',
|
||||||
|
partial: 'warning',
|
||||||
|
degraded: 'danger',
|
||||||
|
critical: 'critical',
|
||||||
|
};
|
||||||
|
|
||||||
|
const LIBELLE_PAR_QUALITE: Record<ReadingDataQuality, string> = {
|
||||||
|
good: 'Données complètes',
|
||||||
|
partial: 'Données partielles',
|
||||||
|
degraded: 'Données dégradées',
|
||||||
|
critical: 'Données critiques',
|
||||||
|
};
|
||||||
|
|
||||||
|
type MetricKey =
|
||||||
|
| 'consumption_kw'
|
||||||
|
| 'voltage_v'
|
||||||
|
| 'current_a'
|
||||||
|
| 'power_factor'
|
||||||
|
| 'temperature_celsius'
|
||||||
|
| 'humidity_percent';
|
||||||
|
|
||||||
|
interface MetricDef {
|
||||||
|
key: MetricKey;
|
||||||
|
label: string;
|
||||||
|
format: (value: number) => string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const CONSUMPTION_DEF: MetricDef = {
|
||||||
|
key: 'consumption_kw',
|
||||||
|
label: 'Consommation',
|
||||||
|
format: (v) => `${v.toFixed(1)} kW`,
|
||||||
|
};
|
||||||
|
|
||||||
|
const METRIC_DEFS: MetricDef[] = [
|
||||||
|
CONSUMPTION_DEF,
|
||||||
|
{ key: 'voltage_v', label: 'Tension', format: (v) => `${v.toFixed(1)} V` },
|
||||||
|
{ key: 'current_a', label: 'Courant', format: (v) => `${v.toFixed(1)} A` },
|
||||||
|
{ key: 'power_factor', label: 'Cos φ', format: (v) => v.toFixed(2) },
|
||||||
|
{ key: 'temperature_celsius', label: 'Température', format: (v) => `${v.toFixed(1)} °C` },
|
||||||
|
{ key: 'humidity_percent', label: 'Humidité', format: (v) => `${v.toFixed(0)} %` },
|
||||||
|
];
|
||||||
|
|
||||||
|
// Contrainte : miroir de RAISON_VERS_CAPTEUR et CHAMPS_PAR_CAPTEUR (backend, services/sensor.py) ;
|
||||||
|
// `null_reasons` porte le code de panne du capteur, jamais le nom du champ resté vide.
|
||||||
|
const RAISONS_PAR_CHAMP: Record<MetricKey, string[]> = {
|
||||||
|
consumption_kw: ['consumption_sensor_failure', 'network_loss'],
|
||||||
|
voltage_v: ['electrical_sensor_failure', 'network_loss'],
|
||||||
|
current_a: ['electrical_sensor_failure', 'network_loss'],
|
||||||
|
power_factor: ['electrical_sensor_failure', 'network_loss'],
|
||||||
|
temperature_celsius: ['temperature_sensor_failure', 'network_loss'],
|
||||||
|
humidity_percent: ['humidity_sensor_failure', 'network_loss'],
|
||||||
|
};
|
||||||
|
|
||||||
|
const LIBELLE_PAR_RAISON: Record<string, string> = {
|
||||||
|
consumption_sensor_failure: 'capteur de consommation en panne',
|
||||||
|
electrical_sensor_failure: 'capteur électrique en panne',
|
||||||
|
temperature_sensor_failure: 'capteur de température en panne',
|
||||||
|
humidity_sensor_failure: "capteur d'humidité en panne",
|
||||||
|
network_loss: 'perte réseau',
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface MetricView {
|
||||||
|
key: MetricKey;
|
||||||
|
label: string;
|
||||||
|
value: string | null;
|
||||||
|
reason: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-site-detail',
|
||||||
|
standalone: true,
|
||||||
|
imports: [RouterLink, Card, Alert, Badge, Brand, ConsumptionGauge, ReadingHistoryChart],
|
||||||
|
templateUrl: './site-detail.html',
|
||||||
|
styleUrl: './site-detail.scss',
|
||||||
|
})
|
||||||
|
export class SiteDetail {
|
||||||
|
private route = inject(ActivatedRoute);
|
||||||
|
private sitesService = inject(SitesService);
|
||||||
|
private readingsService = inject(ReadingsService);
|
||||||
|
private destroyRef = inject(DestroyRef);
|
||||||
|
|
||||||
|
readonly noMeasurementMessage = NO_MEASUREMENT_MESSAGE;
|
||||||
|
|
||||||
|
siteId = toSignal(this.route.paramMap.pipe(map((params) => params.get('siteId') ?? '')));
|
||||||
|
|
||||||
|
site = signal<Site | null>(null);
|
||||||
|
current = signal<SiteCurrent | null>(null);
|
||||||
|
history = signal<Reading[]>([]);
|
||||||
|
error = signal<string | null>(null);
|
||||||
|
|
||||||
|
hasMeasurement = computed(() => this.current()?.timestamp != null);
|
||||||
|
|
||||||
|
consumptionKw = computed(() => this.current()?.consumption_kw ?? null);
|
||||||
|
|
||||||
|
consumptionLabel = computed(() => {
|
||||||
|
const kw = this.consumptionKw();
|
||||||
|
return kw != null ? CONSUMPTION_DEF.format(kw) : null;
|
||||||
|
});
|
||||||
|
|
||||||
|
consumptionReason = computed(() => this.reasonFor('consumption_kw', this.current()));
|
||||||
|
|
||||||
|
qualityLabel = computed(() => {
|
||||||
|
const quality = this.current()?.data_quality;
|
||||||
|
return quality ? LIBELLE_PAR_QUALITE[quality] : null;
|
||||||
|
});
|
||||||
|
|
||||||
|
qualityTone = computed<BadgeTone>(() => {
|
||||||
|
const quality = this.current()?.data_quality;
|
||||||
|
return quality ? TON_PAR_QUALITE[quality] : 'neutral';
|
||||||
|
});
|
||||||
|
|
||||||
|
metrics = computed<MetricView[]>(() => {
|
||||||
|
const current = this.current();
|
||||||
|
return METRIC_DEFS.map((def) => {
|
||||||
|
const valeur = current ? current[def.key] : null;
|
||||||
|
return {
|
||||||
|
key: def.key,
|
||||||
|
label: def.label,
|
||||||
|
value: valeur != null ? def.format(valeur) : null,
|
||||||
|
reason: valeur == null ? this.reasonFor(def.key, current) : '',
|
||||||
|
};
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
toObservable(this.siteId)
|
||||||
|
.pipe(
|
||||||
|
filter((siteId): siteId is string => !!siteId),
|
||||||
|
// Piège : switchMap sur le flux externe annule le chargement en cours dès qu'un
|
||||||
|
// nouveau siteId arrive, sinon une réponse en retard peut écraser le site affiché.
|
||||||
|
switchMap((siteId) => this.load(siteId)),
|
||||||
|
takeUntilDestroyed(this.destroyRef),
|
||||||
|
)
|
||||||
|
.subscribe((result) => {
|
||||||
|
this.error.set(null);
|
||||||
|
this.site.set(result.site);
|
||||||
|
this.current.set(result.current);
|
||||||
|
this.history.set(result.history);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
badgeToneForStatus(status: string | null): BadgeTone {
|
||||||
|
return status ? (TON_PAR_STATUT[status] ?? 'neutral') : 'neutral';
|
||||||
|
}
|
||||||
|
|
||||||
|
private load(siteId: string) {
|
||||||
|
return forkJoin({
|
||||||
|
site: this.sitesService.getSite(siteId),
|
||||||
|
current: this.sitesService.getCurrent(siteId),
|
||||||
|
}).pipe(
|
||||||
|
switchMap(({ site, current }) =>
|
||||||
|
this.loadHistory(siteId, current).pipe(map((history) => ({ site, current, history }))),
|
||||||
|
),
|
||||||
|
catchError(() => this.reportUnavailable()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private loadHistory(siteId: string, current: SiteCurrent): Observable<Reading[]> {
|
||||||
|
// Piège : le jeu de données s'arrête bien avant « maintenant » ; ancrer la fenêtre sur la
|
||||||
|
// dernière mesure connue plutôt que sur l'horloge évite un historique systématiquement vide.
|
||||||
|
const end = current.timestamp;
|
||||||
|
if (end === null) {
|
||||||
|
return of([]);
|
||||||
|
}
|
||||||
|
const start = new Date(new Date(end).getTime() - HISTORY_WINDOW_MS).toISOString();
|
||||||
|
return this.readingsService.getHistory(siteId, start, end);
|
||||||
|
}
|
||||||
|
|
||||||
|
private reasonFor(field: MetricKey, current: SiteCurrent | null): string {
|
||||||
|
const raisons = RAISONS_PAR_CHAMP[field];
|
||||||
|
const trouvees = (current?.null_reasons ?? [])
|
||||||
|
.filter((raison) => raisons.includes(raison))
|
||||||
|
.map((raison) => LIBELLE_PAR_RAISON[raison] ?? raison);
|
||||||
|
return trouvees.length > 0 ? trouvees.join(', ') : 'cause inconnue';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Piège : vider les signaux avec l'erreur, sinon la page garde le site précédemment chargé
|
||||||
|
// sous le bandeau et laisse lire les chiffres de A en croyant regarder B.
|
||||||
|
private reportUnavailable(): Observable<never> {
|
||||||
|
this.error.set(UNAVAILABLE_MESSAGE);
|
||||||
|
this.site.set(null);
|
||||||
|
this.current.set(null);
|
||||||
|
this.history.set([]);
|
||||||
|
return EMPTY;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
<div class="site-list">
|
||||||
|
<nav class="ev-breadcrumb">
|
||||||
|
<a routerLink="/dashboard">Tableau de bord</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<header class="site-list__header">
|
||||||
|
<a routerLink="/dashboard" class="ev-brand-link">
|
||||||
|
<ev-brand class="site-list__logo" />
|
||||||
|
</a>
|
||||||
|
<div>
|
||||||
|
<h1>Sites</h1>
|
||||||
|
<p class="site-list__subtitle">Vue d'ensemble du parc suivi</p>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
@if (error(); as message) {
|
||||||
|
<ev-alert severity="danger" class="banner-error">{{ message }}</ev-alert>
|
||||||
|
}
|
||||||
|
|
||||||
|
<ev-card class="table-card">
|
||||||
|
<table class="sites-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Nom</th>
|
||||||
|
<th>Type</th>
|
||||||
|
<th>Localisation</th>
|
||||||
|
<th>Capacité (kW)</th>
|
||||||
|
<th>Statut</th>
|
||||||
|
<th></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@for (site of sites(); track site.site_id) {
|
||||||
|
<tr>
|
||||||
|
<td>{{ site.site_name }}</td>
|
||||||
|
<td>{{ site.site_type }}</td>
|
||||||
|
<td>{{ site.location || '-' }}</td>
|
||||||
|
<td>{{ site.capacity_kw ?? '-' }}</td>
|
||||||
|
<td><ev-badge [tone]="badgeToneForStatus(site.status)">{{ site.status ?? '-' }}</ev-badge></td>
|
||||||
|
<td><a [routerLink]="['/sites', site.site_id]" class="ev-link">Détail</a></td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</ev-card>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
color: var(--color-text);
|
||||||
|
padding: 2.5rem 2rem;
|
||||||
|
max-width: 1100px;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-list__header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.85rem;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.75rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-list__logo {
|
||||||
|
font-size: 1.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-list__subtitle {
|
||||||
|
margin: 0.25rem 0 0;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.banner-error {
|
||||||
|
display: block;
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-card {
|
||||||
|
padding: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sites-table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
|
||||||
|
th,
|
||||||
|
td {
|
||||||
|
padding: 0.85rem 1.25rem;
|
||||||
|
text-align: left;
|
||||||
|
border-bottom: 1px solid var(--color-border-light);
|
||||||
|
}
|
||||||
|
|
||||||
|
th {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
tr:last-child td {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideRouter } from '@angular/router';
|
||||||
|
import { vi } from 'vitest';
|
||||||
|
import { of, throwError } from 'rxjs';
|
||||||
|
import { SiteList } from './site-list';
|
||||||
|
import { SitesService } from '../../../core/services/sites.service';
|
||||||
|
|
||||||
|
describe('SiteList', () => {
|
||||||
|
it('charge et affiche les sites au démarrage', () => {
|
||||||
|
const sitesMock = {
|
||||||
|
getSites: vi.fn().mockReturnValue(
|
||||||
|
of([
|
||||||
|
{
|
||||||
|
site_id: 'SITE001',
|
||||||
|
site_name: 'Site 1',
|
||||||
|
site_type: 'industriel',
|
||||||
|
location: 'Nantes',
|
||||||
|
capacity_kw: 500,
|
||||||
|
status: 'actif',
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [SiteList],
|
||||||
|
providers: [{ provide: SitesService, useValue: sitesMock }, provideRouter([])],
|
||||||
|
});
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(SiteList);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(sitesMock.getSites).toHaveBeenCalled();
|
||||||
|
expect(fixture.componentInstance.sites().length).toBe(1);
|
||||||
|
expect(fixture.componentInstance.error()).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("signale l'indisponibilité quand le chargement échoue", () => {
|
||||||
|
const sitesMock = { getSites: vi.fn().mockReturnValue(throwError(() => new Error('nope'))) };
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [SiteList],
|
||||||
|
providers: [{ provide: SitesService, useValue: sitesMock }, provideRouter([])],
|
||||||
|
});
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(SiteList);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.error()).not.toBeNull();
|
||||||
|
expect(fixture.componentInstance.sites().length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('affiche un tiret pour les champs nullables', () => {
|
||||||
|
const sitesMock = {
|
||||||
|
getSites: vi.fn().mockReturnValue(
|
||||||
|
of([
|
||||||
|
{
|
||||||
|
site_id: 'SITE002',
|
||||||
|
site_name: 'Site 2',
|
||||||
|
site_type: 'bureau',
|
||||||
|
location: null,
|
||||||
|
capacity_kw: null,
|
||||||
|
status: null,
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [SiteList],
|
||||||
|
providers: [{ provide: SitesService, useValue: sitesMock }, provideRouter([])],
|
||||||
|
});
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(SiteList);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const cells = fixture.nativeElement.querySelectorAll('td');
|
||||||
|
expect(cells[2].textContent.trim()).toBe('-');
|
||||||
|
expect(cells[3].textContent.trim()).toBe('-');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { Component, OnInit, inject, signal } from '@angular/core';
|
||||||
|
import { RouterLink } from '@angular/router';
|
||||||
|
import { catchError, EMPTY, Observable } from 'rxjs';
|
||||||
|
import { SitesService } from '../../../core/services/sites.service';
|
||||||
|
import { Site } from '../../../shared/models/site.model';
|
||||||
|
import { Card } from '../../../shared/components/ui/card/card';
|
||||||
|
import { Alert } from '../../../shared/components/ui/alert/alert';
|
||||||
|
import { Badge, BadgeTone } from '../../../shared/components/ui/badge/badge';
|
||||||
|
import { Brand } from '../../../shared/components/ui/brand/brand';
|
||||||
|
|
||||||
|
const UNAVAILABLE_MESSAGE = 'Liste des sites indisponible, réessayez plus tard.';
|
||||||
|
|
||||||
|
const TON_PAR_STATUT: Record<string, BadgeTone> = {
|
||||||
|
actif: 'success',
|
||||||
|
maintenance: 'warning',
|
||||||
|
hors_service: 'danger',
|
||||||
|
};
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-site-list',
|
||||||
|
standalone: true,
|
||||||
|
imports: [RouterLink, Card, Alert, Badge, Brand],
|
||||||
|
templateUrl: './site-list.html',
|
||||||
|
styleUrl: './site-list.scss',
|
||||||
|
})
|
||||||
|
export class SiteList implements OnInit {
|
||||||
|
private sitesService = inject(SitesService);
|
||||||
|
|
||||||
|
sites = signal<Site[]>([]);
|
||||||
|
error = signal<string | null>(null);
|
||||||
|
|
||||||
|
ngOnInit(): void {
|
||||||
|
this.sitesService
|
||||||
|
.getSites()
|
||||||
|
.pipe(catchError(() => this.reportUnavailable()))
|
||||||
|
.subscribe((sites) => this.sites.set(sites));
|
||||||
|
}
|
||||||
|
|
||||||
|
badgeToneForStatus(status: string | null): BadgeTone {
|
||||||
|
return status ? (TON_PAR_STATUT[status] ?? 'neutral') : 'neutral';
|
||||||
|
}
|
||||||
|
|
||||||
|
private reportUnavailable(): Observable<never> {
|
||||||
|
this.error.set(UNAVAILABLE_MESSAGE);
|
||||||
|
return EMPTY;
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
@@ -0,0 +1 @@
|
|||||||
|
<canvas #canvas></canvas>
|
||||||
+4
@@ -0,0 +1,4 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
height: 260px;
|
||||||
|
}
|
||||||
+101
@@ -0,0 +1,101 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { vi } from 'vitest';
|
||||||
|
import { Chart } from 'chart.js';
|
||||||
|
import { ReadingHistoryChart } from './reading-history-chart';
|
||||||
|
|
||||||
|
vi.mock('chart.js', () => {
|
||||||
|
class ChartMock {
|
||||||
|
static instances: ChartMock[] = [];
|
||||||
|
static register = vi.fn();
|
||||||
|
update = vi.fn();
|
||||||
|
destroy = vi.fn();
|
||||||
|
data: { labels?: unknown[]; datasets: Record<string, unknown>[] } = { datasets: [{}] };
|
||||||
|
constructor(_canvas: unknown, config?: { data?: ChartMock['data'] }) {
|
||||||
|
if (config?.data) {
|
||||||
|
this.data = config.data;
|
||||||
|
}
|
||||||
|
ChartMock.instances.push(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { Chart: ChartMock, registerables: [] };
|
||||||
|
});
|
||||||
|
|
||||||
|
type ChartDouble = {
|
||||||
|
destroy: ReturnType<typeof vi.fn>;
|
||||||
|
data: { labels?: unknown[]; datasets: Record<string, unknown>[] };
|
||||||
|
};
|
||||||
|
|
||||||
|
function lastChart(): ChartDouble | undefined {
|
||||||
|
return (Chart as unknown as { instances: ChartDouble[] }).instances.at(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const READING = {
|
||||||
|
reading_id: 1,
|
||||||
|
site_id: 'S1',
|
||||||
|
timestamp: '2026-09-17T10:00:00Z',
|
||||||
|
source: 'api_history' as const,
|
||||||
|
consumption_kw: 42,
|
||||||
|
consumption_kwh: null,
|
||||||
|
consumption_euros: null,
|
||||||
|
voltage_v: null,
|
||||||
|
current_a: null,
|
||||||
|
power_factor: null,
|
||||||
|
temperature_celsius: null,
|
||||||
|
humidity_percent: null,
|
||||||
|
solar_irradiance_wm2: null,
|
||||||
|
is_working_hours: null,
|
||||||
|
data_quality: 'good' as const,
|
||||||
|
null_reasons: null,
|
||||||
|
imputed_values: null,
|
||||||
|
imputation_method: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('ReadingHistoryChart', () => {
|
||||||
|
it('se crée sans erreur avec une liste de lectures valide', () => {
|
||||||
|
TestBed.configureTestingModule({ imports: [ReadingHistoryChart] });
|
||||||
|
const fixture = TestBed.createComponent(ReadingHistoryChart);
|
||||||
|
fixture.componentRef.setInput('readings', [READING]);
|
||||||
|
expect(() => fixture.detectChanges()).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('met à jour le graphique quand les lectures changent après initialisation', () => {
|
||||||
|
TestBed.configureTestingModule({ imports: [ReadingHistoryChart] });
|
||||||
|
const fixture = TestBed.createComponent(ReadingHistoryChart);
|
||||||
|
fixture.componentRef.setInput('readings', [READING]);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
fixture.componentRef.setInput('readings', [
|
||||||
|
{ ...READING, reading_id: 2, consumption_kw: 60, data_quality: 'critical' as const },
|
||||||
|
]);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(() => fixture.detectChanges()).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("trace du plus ancien au plus récent, quel que soit l'ordre reçu de l'API", () => {
|
||||||
|
TestBed.configureTestingModule({ imports: [ReadingHistoryChart] });
|
||||||
|
const fixture = TestBed.createComponent(ReadingHistoryChart);
|
||||||
|
// L'API trie en timestamp décroissant : le composant doit rétablir la chronologie.
|
||||||
|
fixture.componentRef.setInput('readings', [
|
||||||
|
{ ...READING, reading_id: 2, timestamp: '2026-09-17T11:00:00Z', consumption_kw: 60 },
|
||||||
|
{ ...READING, reading_id: 1, timestamp: '2026-09-17T10:00:00Z', consumption_kw: 42 },
|
||||||
|
]);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const chart = lastChart();
|
||||||
|
expect(chart?.data.labels).toEqual(['2026-09-17T10:00:00Z', '2026-09-17T11:00:00Z']);
|
||||||
|
expect(chart?.data.datasets[0]['data']).toEqual([42, 60]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('détruit le graphique quand le composant est détruit', () => {
|
||||||
|
TestBed.configureTestingModule({ imports: [ReadingHistoryChart] });
|
||||||
|
const fixture = TestBed.createComponent(ReadingHistoryChart);
|
||||||
|
fixture.componentRef.setInput('readings', [READING]);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const chart = lastChart();
|
||||||
|
fixture.destroy();
|
||||||
|
|
||||||
|
expect(chart?.destroy).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
+95
@@ -0,0 +1,95 @@
|
|||||||
|
import {
|
||||||
|
Component,
|
||||||
|
ElementRef,
|
||||||
|
ViewChild,
|
||||||
|
input,
|
||||||
|
effect,
|
||||||
|
AfterViewInit,
|
||||||
|
OnDestroy,
|
||||||
|
} from '@angular/core';
|
||||||
|
import { Chart, registerables } from 'chart.js';
|
||||||
|
import { Reading, ReadingDataQuality } from '../../models/reading.model';
|
||||||
|
|
||||||
|
Chart.register(...registerables);
|
||||||
|
|
||||||
|
const QUALITY_COLORS: Record<ReadingDataQuality, string> = {
|
||||||
|
good: '#3b82f6',
|
||||||
|
partial: '#f9a825',
|
||||||
|
degraded: '#ef6c00',
|
||||||
|
critical: '#c62828',
|
||||||
|
};
|
||||||
|
const UNKNOWN_QUALITY_COLOR = '#9ca3af';
|
||||||
|
|
||||||
|
interface ChartSeries {
|
||||||
|
labels: string[];
|
||||||
|
values: number[];
|
||||||
|
colors: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Piège : l'API renvoie les lectures du plus récent au plus ancien (ReadingRepository.list_history
|
||||||
|
// trie en timestamp desc) ; sans ce tri l'axe des abscisses se lirait à rebours.
|
||||||
|
function toSeries(readings: Reading[]): ChartSeries {
|
||||||
|
const ordered = [...readings].sort((a, b) => Date.parse(a.timestamp) - Date.parse(b.timestamp));
|
||||||
|
return {
|
||||||
|
labels: ordered.map((r) => r.timestamp),
|
||||||
|
values: ordered.map((r) => r.consumption_kw ?? 0),
|
||||||
|
colors: ordered.map((r) =>
|
||||||
|
r.data_quality ? QUALITY_COLORS[r.data_quality] : UNKNOWN_QUALITY_COLOR,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-reading-history-chart',
|
||||||
|
standalone: true,
|
||||||
|
templateUrl: './reading-history-chart.html',
|
||||||
|
styleUrl: './reading-history-chart.scss',
|
||||||
|
})
|
||||||
|
export class ReadingHistoryChart implements AfterViewInit, OnDestroy {
|
||||||
|
readings = input.required<Reading[]>();
|
||||||
|
|
||||||
|
@ViewChild('canvas') private canvasRef!: ElementRef<HTMLCanvasElement>;
|
||||||
|
private chart?: Chart<'line'>;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
effect(() => {
|
||||||
|
const series = toSeries(this.readings());
|
||||||
|
if (this.chart) {
|
||||||
|
this.chart.data.labels = series.labels;
|
||||||
|
this.chart.data.datasets[0].data = series.values;
|
||||||
|
this.chart.data.datasets[0].pointBackgroundColor = series.colors;
|
||||||
|
this.chart.update('none');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
ngAfterViewInit(): void {
|
||||||
|
const series = toSeries(this.readings());
|
||||||
|
this.chart = new Chart(this.canvasRef.nativeElement, {
|
||||||
|
type: 'line',
|
||||||
|
data: {
|
||||||
|
labels: series.labels,
|
||||||
|
datasets: [
|
||||||
|
{
|
||||||
|
data: series.values,
|
||||||
|
borderColor: '#3b82f6',
|
||||||
|
pointBackgroundColor: series.colors,
|
||||||
|
tension: 0.25,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
responsive: true,
|
||||||
|
maintainAspectRatio: false,
|
||||||
|
plugins: { legend: { display: false } },
|
||||||
|
scales: {
|
||||||
|
y: { beginAtZero: true, title: { display: true, text: 'Consommation (kW)' } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnDestroy(): void {
|
||||||
|
this.chart?.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<ng-content></ng-content>
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
border: 1px solid transparent;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
:host.ev-alert--success {
|
||||||
|
background: var(--color-success-bg);
|
||||||
|
border-color: var(--color-success);
|
||||||
|
color: var(--color-success);
|
||||||
|
}
|
||||||
|
|
||||||
|
:host.ev-alert--warning {
|
||||||
|
background: var(--color-warning-bg);
|
||||||
|
border-color: var(--color-warning);
|
||||||
|
color: var(--color-warning-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
:host.ev-alert--danger {
|
||||||
|
background: var(--color-danger-bg);
|
||||||
|
border-color: var(--color-danger-border);
|
||||||
|
color: var(--color-danger);
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { Component } from '@angular/core';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { Alert } from './alert';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
standalone: true,
|
||||||
|
imports: [Alert],
|
||||||
|
template: `<ev-alert severity="success">C'est fait</ev-alert>`,
|
||||||
|
})
|
||||||
|
class AlertHost {}
|
||||||
|
|
||||||
|
describe('Alert', () => {
|
||||||
|
it('applique la classe danger par défaut', async () => {
|
||||||
|
await TestBed.configureTestingModule({ imports: [Alert] }).compileComponents();
|
||||||
|
const fixture = TestBed.createComponent(Alert);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.nativeElement.classList).toContain('ev-alert--danger');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('applique la sévérité demandée et projette le contenu', async () => {
|
||||||
|
await TestBed.configureTestingModule({ imports: [AlertHost] }).compileComponents();
|
||||||
|
const fixture = TestBed.createComponent(AlertHost);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const el = fixture.nativeElement.querySelector('.ev-alert');
|
||||||
|
expect(el.classList).toContain('ev-alert--success');
|
||||||
|
expect(el.textContent).toContain("C'est fait");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { Component, HostBinding, input } from '@angular/core';
|
||||||
|
|
||||||
|
export type AlertSeverity = 'success' | 'warning' | 'danger';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'ev-alert',
|
||||||
|
standalone: true,
|
||||||
|
templateUrl: './alert.html',
|
||||||
|
styleUrl: './alert.scss',
|
||||||
|
})
|
||||||
|
export class Alert {
|
||||||
|
severity = input<AlertSeverity>('danger');
|
||||||
|
|
||||||
|
@HostBinding('class')
|
||||||
|
get hostClass(): string {
|
||||||
|
return `ev-alert ev-alert--${this.severity()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
@HostBinding('attr.role')
|
||||||
|
readonly role = 'alert';
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<span class="ev-badge" [class]="'ev-badge--' + tone()">
|
||||||
|
<ng-content></ng-content>
|
||||||
|
</span>
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
:host {
|
||||||
|
display: inline-flex;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-badge {
|
||||||
|
display: inline-block;
|
||||||
|
font-size: 0.7rem;
|
||||||
|
font-weight: 700;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
padding: 0.2rem 0.55rem;
|
||||||
|
border-radius: var(--radius-pill);
|
||||||
|
color: var(--color-text-inverse);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-badge--success {
|
||||||
|
background: var(--color-success);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-badge--warning {
|
||||||
|
background: var(--color-warning);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-badge--danger {
|
||||||
|
background: var(--color-danger);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-badge--critical {
|
||||||
|
background: var(--color-critical);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-badge--neutral {
|
||||||
|
background: var(--color-text-muted);
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { Component } from '@angular/core';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { Badge } from './badge';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
standalone: true,
|
||||||
|
imports: [Badge],
|
||||||
|
template: `<ev-badge tone="danger">critique</ev-badge>`,
|
||||||
|
})
|
||||||
|
class BadgeHost {}
|
||||||
|
|
||||||
|
describe('Badge', () => {
|
||||||
|
it('applique le ton neutral par défaut', async () => {
|
||||||
|
await TestBed.configureTestingModule({ imports: [Badge] }).compileComponents();
|
||||||
|
const fixture = TestBed.createComponent(Badge);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.nativeElement.querySelector('.ev-badge').classList).toContain('ev-badge--neutral');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('applique le ton demandé et projette le contenu', async () => {
|
||||||
|
await TestBed.configureTestingModule({ imports: [BadgeHost] }).compileComponents();
|
||||||
|
const fixture = TestBed.createComponent(BadgeHost);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const el = fixture.nativeElement.querySelector('.ev-badge');
|
||||||
|
expect(el.classList).toContain('ev-badge--danger');
|
||||||
|
expect(el.textContent).toContain('critique');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { Component, input } from '@angular/core';
|
||||||
|
|
||||||
|
export type BadgeTone = 'success' | 'warning' | 'danger' | 'critical' | 'neutral';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'ev-badge',
|
||||||
|
standalone: true,
|
||||||
|
templateUrl: './badge.html',
|
||||||
|
styleUrl: './badge.scss',
|
||||||
|
})
|
||||||
|
export class Badge {
|
||||||
|
tone = input<BadgeTone>('neutral');
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
<img src="/logo-icon.png" alt="" class="ev-brand__icon" />
|
||||||
|
<span class="ev-brand__name">EnerVision</span>
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
:host {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.45em;
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--color-text);
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-brand__icon {
|
||||||
|
height: 1.3em;
|
||||||
|
width: auto;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-brand__name {
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user