Compare commits
82
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ebf6476fb6 | ||
|
|
d2ca2644d2 | ||
|
|
91a1bfda33 | ||
|
|
fe100653d0 | ||
|
|
bccf7ed774 | ||
|
|
bf2b66e4ad | ||
|
|
8ea388ce9a | ||
|
|
b4da0bbefc | ||
|
|
25e0bb4ce1 | ||
|
|
ce3d1d1992 | ||
|
|
cb23895026 | ||
|
|
2c86e00629 | ||
|
|
7e504bee72 | ||
|
|
32155cbfc5 | ||
|
|
cb4df846cb | ||
|
|
d16de84559 | ||
|
|
ae4082c584 | ||
|
|
f18d4f9ef9 | ||
|
|
308769b325 | ||
|
|
90639b5618 | ||
|
|
e147ea69bc | ||
|
|
f0ff953a5e | ||
|
|
7fd8d1ce30 | ||
|
|
6785d06a9a | ||
|
|
c2bd1317ed | ||
|
|
d276070ee2 | ||
|
|
e10ab44dc7 | ||
|
|
32dd0587e9 | ||
|
|
83caa9006e | ||
|
|
91752a2b0b | ||
|
|
3c378c177f | ||
|
|
2adfdf0eb0 | ||
|
|
44f3416ffe | ||
|
|
342128ccff | ||
|
|
62d81e901d | ||
|
|
31886944ab | ||
|
|
63cbeafe3b | ||
|
|
f8d08c8686 | ||
|
|
be44b97d7a | ||
|
|
306c5a52e5 | ||
|
|
801379f956 | ||
|
|
2686880185 | ||
|
|
ae58a896d9 | ||
|
|
5a29faaa16 | ||
|
|
bc75528616 | ||
|
|
d7457e9fd9 | ||
|
|
3cd9a6b272 | ||
|
|
26f834485c | ||
|
|
777cd0ac64 | ||
|
|
c528ed239b | ||
|
|
a88e51c92a | ||
|
|
f3ea2785b3 | ||
|
|
901ceffd72 | ||
|
|
5545c166fd | ||
|
|
f0ad8e9990 | ||
|
|
3c01ab3ecc | ||
|
|
6f6f451eb4 | ||
|
|
cc3e38efa3 | ||
|
|
0a2ed5ad8f | ||
|
|
459ddf1792 | ||
|
|
de697b080d | ||
|
|
f238940867 | ||
|
|
b941880c22 | ||
|
|
9d2384a639 | ||
|
|
0c487fa7be | ||
|
|
b3efb98208 | ||
|
|
2d7b4bd74d | ||
|
|
56c6b79a5a | ||
|
|
19c38fe571 | ||
|
|
9a1af94d88 | ||
|
|
452cfdef85 | ||
|
|
96dd1f834c | ||
|
|
e66ef86729 | ||
|
|
0318ee6cc5 | ||
|
|
0ddfb1997d | ||
|
|
b96546cea3 | ||
|
|
f9c2a4610c | ||
|
|
b5fa7b0010 | ||
|
|
edd5e82d29 | ||
|
|
aeb07e14db | ||
|
|
7f710c9084 | ||
|
|
c3fd9327ea |
@@ -17,3 +17,57 @@ 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
|
||||||
|
FRONTEND_PORT=3000
|
||||||
|
|
||||||
|
# Mailpit capture les courriels du backend, rien ne sort vers l'extérieur.
|
||||||
|
MAILPIT_SMTP_PORT=1025
|
||||||
|
MAILPIT_UI_PORT=8025
|
||||||
|
|
||||||
|
# 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
|
||||||
|
|
||||||
|
# Airflow (webserver + scheduler, LocalExecutor). Base de métadonnées dédiée `airflow` dans le
|
||||||
|
# même conteneur `db` (cf. db/init/120-airflow-database.sql), pas un conteneur de plus.
|
||||||
|
AIRFLOW_PORT=8080
|
||||||
|
# Chiffre les connexions/variables stockées par Airflow. Générer la vôtre :
|
||||||
|
# python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
|
||||||
|
AIRFLOW_FERNET_KEY=change_me
|
||||||
|
# Clé Flask du webserver Airflow (signature de session), distincte de la précédente. Générer la
|
||||||
|
# vôtre : python -c "import secrets; print(secrets.token_urlsafe(48))"
|
||||||
|
AIRFLOW_WEBSERVER_SECRET_KEY=change_me
|
||||||
|
AIRFLOW_ADMIN_USERNAME=admin
|
||||||
|
# Compte Airflow créé au premier démarrage (service `airflow-init`), sans rapport avec les
|
||||||
|
# comptes `app_user` d'EnerVision.
|
||||||
|
AIRFLOW_ADMIN_PASSWORD=change_me
|
||||||
|
AIRFLOW_ADMIN_EMAIL=admin@enervision.fr
|
||||||
|
# `APP_SECRET_KEY` du backend, que le DAG `alertes` lance en sous-processus. Distincte de
|
||||||
|
# celle de l'API : la détection ne signe aucun jeton, et Airflow exécute du code depuis son
|
||||||
|
# interface (cf. ADR 0008). Générer la vôtre :
|
||||||
|
# python -c "import secrets; print(secrets.token_urlsafe(48))"
|
||||||
|
AIRFLOW_APP_SECRET_KEY=change_me
|
||||||
|
|
||||||
|
# Stack complète derrière le reverse proxy (docker-compose.prod.yml).
|
||||||
|
# PUBLIC_HOST alimente l'origine CORS, le lien de réinitialisation et le certificat.
|
||||||
|
PUBLIC_HOST=enervision.local
|
||||||
|
ACME_EMAIL=
|
||||||
|
|
||||||
|
# Deux environnements sur la même machine (ADR 0009) : un dossier, un `.env` et un projet Compose
|
||||||
|
# chacun. Le nom de projet préfixe volumes, réseau et conteneurs et l'emporte sur `name:`.
|
||||||
|
# Vide sur un poste de développement : le projet reste `enervision`.
|
||||||
|
COMPOSE_PROJECT_NAME=
|
||||||
|
# Origine publique, avec le port si le proxy HTTPS n'écoute pas 443. Vide : https://PUBLIC_HOST.
|
||||||
|
# Recette : PUBLIC_HOST=rec.enervision.local et PUBLIC_ORIGIN=https://rec.enervision.local:8443.
|
||||||
|
PUBLIC_ORIGIN=
|
||||||
|
# Ports publiés par le proxy. Vides : 80 et 443. Recette : PROXY_HTTPS_PORT=8443 et
|
||||||
|
# PROXY_HTTP_PORT=127.0.0.1:8081, la redirection vers 443 n'ayant pas à être joignable de
|
||||||
|
# l'extérieur. Décaler aussi POSTGRES_PORT, MAILPIT_UI_PORT et AIRFLOW_PORT (5434, 8026, 8082).
|
||||||
|
PROXY_HTTP_PORT=
|
||||||
|
PROXY_HTTPS_PORT=
|
||||||
|
# Réglages mémoire de la stack déployée. Sans eux, timescaledb-tune réserve 25 % de la RAM de la
|
||||||
|
# machine à chaque base au premier démarrage, et le webserver Airflow lance 4 workers gunicorn.
|
||||||
|
TS_TUNE_MEMORY=2GB
|
||||||
|
TS_TUNE_NUM_CPUS=2
|
||||||
|
AIRFLOW_WEBSERVER_WORKERS=2
|
||||||
|
|||||||
@@ -38,3 +38,9 @@ updates:
|
|||||||
directory: "/apps/frontend"
|
directory: "/apps/frontend"
|
||||||
schedule:
|
schedule:
|
||||||
interval: "weekly"
|
interval: "weekly"
|
||||||
|
|
||||||
|
# Images du reverse proxy et du compagnon ACME, épinglées dans les fichiers Compose
|
||||||
|
- package-ecosystem: "docker-compose"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
name: Airflow
|
||||||
|
|
||||||
|
# Piège : la version de Python vient de etl/airflow/.python-version. C'est 3.12 et non 3.14
|
||||||
|
# (contrairement à backend.yml et ml.yml) : apache-airflow 2.10 ne supporte pas 3.14. Le 3.14 de
|
||||||
|
# ml/ ne vit que dans l'image Docker, dans son propre environnement (cf. etl/airflow/Dockerfile).
|
||||||
|
#
|
||||||
|
# Piège : l'image COPY les fichiers de dépendances et le code de ml/ et de apps/backend/. Une
|
||||||
|
# modification de l'un ou de l'autre peut donc casser sa construction, d'où ces chemins dans
|
||||||
|
# les déclencheurs, alors même que ce workflow ne teste ni le modèle ni l'API.
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
paths:
|
||||||
|
- "etl/airflow/**"
|
||||||
|
- "ml/pyproject.toml"
|
||||||
|
- "ml/uv.lock"
|
||||||
|
- "ml/enervision_ml/**"
|
||||||
|
- "apps/backend/pyproject.toml"
|
||||||
|
- "apps/backend/uv.lock"
|
||||||
|
- "apps/backend/app/**"
|
||||||
|
- ".github/workflows/airflow.yml"
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- "etl/airflow/**"
|
||||||
|
- "ml/pyproject.toml"
|
||||||
|
- "ml/uv.lock"
|
||||||
|
- "ml/enervision_ml/**"
|
||||||
|
- "apps/backend/pyproject.toml"
|
||||||
|
- "apps/backend/uv.lock"
|
||||||
|
- "apps/backend/app/**"
|
||||||
|
- ".github/workflows/airflow.yml"
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: airflow-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
verification:
|
||||||
|
name: Lint et intégrité des DAGs
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: etl/airflow
|
||||||
|
|
||||||
|
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: etl/airflow/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 .
|
||||||
|
|
||||||
|
# Aucun test ne lance de tâche ni de scheduler : DagBag charge les fichiers de dags/ et
|
||||||
|
# vérifie import, planification, plafonds d'exécution et commande de chaque tâche.
|
||||||
|
- name: Tests d'intégrité des DAGs
|
||||||
|
run: uv run pytest
|
||||||
|
|
||||||
|
image:
|
||||||
|
name: Construction de l'image
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Récupère le dépôt
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Construit l'image (contexte à la racine, elle COPY ml/ et apps/backend/)
|
||||||
|
run: docker build -f etl/airflow/Dockerfile -t enervision-airflow:ci .
|
||||||
|
|
||||||
|
# Vérifie ce qui ne casse qu'à l'exécution, pas à la construction : libgomp1 absent
|
||||||
|
# (`OSError: libgomp.so.1` au premier import) ou environnement ml/ non figé.
|
||||||
|
- name: Vérifie que le pipeline ML s'importe sans réseau
|
||||||
|
run: >
|
||||||
|
docker run --rm --network none enervision-airflow:ci
|
||||||
|
bash -c "cd /opt/ml && env -u VIRTUAL_ENV uv run --no-sync python -m enervision_ml.train --help"
|
||||||
|
|
||||||
|
# `--help` sort par argparse avant `get_settings()` : ni base ni secret requis, et
|
||||||
|
# l'import des modules prouve que l'environnement /opt/backend est complet.
|
||||||
|
# Les deux commandes du DAG `alertes` et la commande du DAG historique sont couvertes.
|
||||||
|
- name: Vérifie que les trois commandes backend s'importent sans réseau
|
||||||
|
run: >
|
||||||
|
docker run --rm --network none enervision-airflow:ci
|
||||||
|
bash -c "cd /opt/backend
|
||||||
|
&& env -u VIRTUAL_ENV uv run --no-sync python -m app.detection.internal_alerts --help
|
||||||
|
&& env -u VIRTUAL_ENV uv run --no-sync python -m app.cli generate-recommendations --help
|
||||||
|
&& env -u VIRTUAL_ENV uv run --no-sync python -m app.etl.historical_import --help"
|
||||||
@@ -140,3 +140,29 @@ jobs:
|
|||||||
# Piège : sans `shell: bash`, un échec de `uv export` serait masqué par le pipe.
|
# Piège : sans `shell: bash`, un échec de `uv export` serait masqué par le pipe.
|
||||||
shell: bash
|
shell: bash
|
||||||
run: uv export --frozen --no-dev --no-emit-project --no-hashes | uvx pip-audit --requirement /dev/stdin --no-deps
|
run: uv export --frozen --no-dev --no-emit-project --no-hashes | uvx pip-audit --requirement /dev/stdin --no-deps
|
||||||
|
|
||||||
|
sast:
|
||||||
|
name: Analyse statique de sécurité
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Récupère le dépôt
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
# Pourquoi : pas de cache ici. uvx n'installe pas le projet, le verrou n'alimente donc
|
||||||
|
# aucune clé de cache ; la seule roue téléchargée est celle de Bandit.
|
||||||
|
- name: Installe uv
|
||||||
|
uses: astral-sh/setup-uv@v5
|
||||||
|
|
||||||
|
# Pourquoi : le périmètre est `app`, le code livré. Les tests emploient légitimement des
|
||||||
|
# secrets factices et des `assert` que Bandit signalerait sans qu'aucun n'atteigne la prod.
|
||||||
|
- name: Analyse le code livré (bloquant à partir de MEDIUM)
|
||||||
|
run: uvx bandit==1.9.4 --recursive app --severity-level medium --confidence-level medium
|
||||||
|
|
||||||
|
# Piège : sans cette seconde passe, un constat LOW disparaîtrait du journal sans trace.
|
||||||
|
- name: Rapport complet, tous niveaux
|
||||||
|
continue-on-error: true
|
||||||
|
run: uvx bandit==1.9.4 --recursive app
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
# Pourquoi : le runner tourne sur la VM ENI, adresse privée que les runners hébergés par GitHub
|
||||||
|
# ne joignent pas, et travaille dans un dossier stable par environnement plutôt que dans son
|
||||||
|
# espace de travail : `.env`, certificats et volumes y survivent d'un déploiement à l'autre.
|
||||||
|
# Piège : jamais de déclencheur `pull_request` ici. Sur un dépôt public, une PR de fork
|
||||||
|
# exécuterait son code sur la machine de production (ADR 0009) - job deploy.
|
||||||
|
|
||||||
|
name: Déploiement
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [dev, main]
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: deploy-${{ github.ref_name }}
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
deploy:
|
||||||
|
runs-on: [self-hosted, linux, eni-g3]
|
||||||
|
timeout-minutes: 30
|
||||||
|
environment:
|
||||||
|
name: ${{ github.ref_name == 'main' && 'prod' || 'rec' }}
|
||||||
|
url: ${{ github.ref_name == 'main' && 'https://enervision.local' || 'https://rec.enervision.local:8443' }}
|
||||||
|
env:
|
||||||
|
ENVIRONNEMENT: ${{ github.ref_name == 'main' && 'prod' || 'rec' }}
|
||||||
|
PORT_HTTPS: ${{ github.ref_name == 'main' && '443' || '8443' }}
|
||||||
|
steps:
|
||||||
|
- name: Aligner le dossier de l'environnement sur la branche poussée
|
||||||
|
run: |
|
||||||
|
cd "/srv/enervision/${ENVIRONNEMENT}"
|
||||||
|
git fetch --quiet origin "${GITHUB_REF_NAME}"
|
||||||
|
git checkout --quiet "${GITHUB_REF_NAME}"
|
||||||
|
git reset --quiet --hard "origin/${GITHUB_REF_NAME}"
|
||||||
|
git log -1 --format='%h %s'
|
||||||
|
|
||||||
|
- name: Reconstruire et redémarrer la stack
|
||||||
|
run: |
|
||||||
|
cd "/srv/enervision/${ENVIRONNEMENT}"
|
||||||
|
make stack-up
|
||||||
|
|
||||||
|
- name: Attendre que l'API réponde derrière le proxy
|
||||||
|
run: |
|
||||||
|
for tentative in $(seq 1 36); do
|
||||||
|
if curl --fail --silent --insecure "https://localhost:${PORT_HTTPS}/api/v1/health/ready"; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
echo "L'API ne répond pas après 3 minutes" >&2
|
||||||
|
cd "/srv/enervision/${ENVIRONNEMENT}"
|
||||||
|
docker compose ps
|
||||||
|
docker compose logs --tail=50 backend proxy
|
||||||
|
exit 1
|
||||||
@@ -57,3 +57,26 @@ jobs:
|
|||||||
# synthetiques ou un magasin SQLite local jetable (cf. ml/tests/test_train.py).
|
# synthetiques ou un magasin SQLite local jetable (cf. ml/tests/test_train.py).
|
||||||
- name: Tests
|
- name: Tests
|
||||||
run: uv run pytest
|
run: uv run pytest
|
||||||
|
|
||||||
|
sast:
|
||||||
|
name: Analyse statique de sécurité
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: ml
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Récupère le dépôt
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
# Pourquoi : pas de cache ici. uvx n'installe pas le projet, le verrou n'alimente donc
|
||||||
|
# aucune clé de cache ; la seule roue téléchargée est celle de Bandit.
|
||||||
|
- name: Installe uv
|
||||||
|
uses: astral-sh/setup-uv@v5
|
||||||
|
|
||||||
|
- name: Analyse le code livré (bloquant à partir de MEDIUM)
|
||||||
|
run: uvx bandit==1.9.4 --recursive enervision_ml --severity-level medium --confidence-level medium
|
||||||
|
|
||||||
|
- name: Rapport complet, tous niveaux
|
||||||
|
continue-on-error: true
|
||||||
|
run: uvx bandit==1.9.4 --recursive enervision_ml
|
||||||
|
|||||||
@@ -5,11 +5,15 @@ on:
|
|||||||
paths:
|
paths:
|
||||||
- "apps/frontend/**"
|
- "apps/frontend/**"
|
||||||
- "apps/backend/**"
|
- "apps/backend/**"
|
||||||
|
- "ml/**"
|
||||||
|
- "etl/airflow/**"
|
||||||
- ".github/workflows/sonarqube.yml"
|
- ".github/workflows/sonarqube.yml"
|
||||||
pull_request:
|
pull_request:
|
||||||
paths:
|
paths:
|
||||||
- "apps/frontend/**"
|
- "apps/frontend/**"
|
||||||
- "apps/backend/**"
|
- "apps/backend/**"
|
||||||
|
- "ml/**"
|
||||||
|
- "etl/airflow/**"
|
||||||
- ".github/workflows/sonarqube.yml"
|
- ".github/workflows/sonarqube.yml"
|
||||||
|
|
||||||
|
|
||||||
@@ -108,8 +112,36 @@ jobs:
|
|||||||
name: backend-coverage
|
name: backend-coverage
|
||||||
path: apps/backend/coverage.xml
|
path: apps/backend/coverage.xml
|
||||||
|
|
||||||
|
test-ml:
|
||||||
|
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: ml/uv.lock
|
||||||
|
|
||||||
|
- name: Installe l'interpréteur déclaré par .python-version
|
||||||
|
run: uv python install
|
||||||
|
working-directory: ml
|
||||||
|
|
||||||
|
- name: Synchronise les dépendances sans dévier du verrou
|
||||||
|
run: uv sync --all-groups --frozen
|
||||||
|
working-directory: ml
|
||||||
|
|
||||||
|
- name: Lancement des tests et génération du rapport de couverture (ML)
|
||||||
|
run: uv run pytest --cov-report=xml
|
||||||
|
working-directory: ml
|
||||||
|
|
||||||
|
- name: Upload coverage
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: ml-coverage
|
||||||
|
path: ml/coverage.xml
|
||||||
|
|
||||||
sonarqube:
|
sonarqube:
|
||||||
needs: [build-front, build-back, test-front, test-back]
|
needs: [build-front, build-back, test-front, test-back, test-ml]
|
||||||
name: SonarQube
|
name: SonarQube
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
@@ -126,6 +158,11 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
name: backend-coverage
|
name: backend-coverage
|
||||||
path: apps/backend
|
path: apps/backend
|
||||||
|
- name: Téléchargement du rapport de couverture (ML)
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: ml-coverage
|
||||||
|
path: ml
|
||||||
- name: SonarQube Scan
|
- name: SonarQube Scan
|
||||||
uses: SonarSource/sonarqube-scan-action@v8
|
uses: SonarSource/sonarqube-scan-action@v8
|
||||||
env:
|
env:
|
||||||
|
|||||||
@@ -66,6 +66,12 @@ ml/mlruns/
|
|||||||
ml/mlartifacts/
|
ml/mlartifacts/
|
||||||
ml/mlflow.db
|
ml/mlflow.db
|
||||||
|
|
||||||
|
# Airflow : base sqlite locale generee par les tests d'integrite des DAGs (etl/airflow/tests)
|
||||||
|
etl/airflow/tests/.airflow_home/
|
||||||
|
|
||||||
|
# TLS : certificats du reverse proxy, générés par script ou par certbot
|
||||||
|
infra/proxy/tls/*.pem
|
||||||
|
|
||||||
# IDE et OS
|
# IDE et OS
|
||||||
.idea/
|
.idea/
|
||||||
.vscode/
|
.vscode/
|
||||||
|
|||||||
@@ -1,17 +1,48 @@
|
|||||||
BACKEND := apps/backend
|
BACKEND := apps/backend
|
||||||
FRONTEND := apps/frontend
|
FRONTEND := apps/frontend
|
||||||
ML := ml
|
ML := ml
|
||||||
|
AIRFLOW := etl/airflow
|
||||||
|
COMPOSE_PROD := docker compose -f docker-compose.yml -f docker-compose.prod.yml
|
||||||
|
|
||||||
|
# Piège : sans `export`, une valeur passée en ligne de commande n'atteindrait pas docker compose.
|
||||||
|
# PUBLIC_HOST retombe sur le `.env`, que make ne lit pas, puis sur la valeur de `.env.example`.
|
||||||
|
PUBLIC_HOST ?= $(shell sed -n 's/^PUBLIC_HOST=//p' .env 2>/dev/null | tail -1)
|
||||||
|
PUBLIC_HOST := $(or $(strip $(PUBLIC_HOST)),enervision.local)
|
||||||
|
export PUBLIC_HOST
|
||||||
|
ifdef ACME_EMAIL
|
||||||
|
export ACME_EMAIL
|
||||||
|
endif
|
||||||
|
|
||||||
|
# Piege : make ne lit pas `.env`, que seul docker compose interpole. Les cibles hors conteneur
|
||||||
|
# (ml-*, demo-data, db-wait) joignent la base par le port publie et ont besoin de ces valeurs.
|
||||||
|
env-val = $(shell sed -n 's/^$(1)=//p' .env 2>/dev/null | tail -1)
|
||||||
|
PG_USER := $(or $(strip $(call env-val,POSTGRES_USER)),enervision)
|
||||||
|
PG_PASSWORD := $(or $(strip $(call env-val,POSTGRES_PASSWORD)),change_me)
|
||||||
|
PG_DB := $(or $(strip $(call env-val,POSTGRES_DB)),enervision)
|
||||||
|
PG_PORT := $(or $(strip $(call env-val,POSTGRES_PORT)),5433)
|
||||||
|
AIRFLOW_PORT := $(or $(strip $(call env-val,AIRFLOW_PORT)),8080)
|
||||||
|
MAILPIT_UI_PORT := $(or $(strip $(call env-val,MAILPIT_UI_PORT)),8025)
|
||||||
|
ML_DATABASE_URL ?= postgresql+psycopg://$(PG_USER):$(PG_PASSWORD)@localhost:$(PG_PORT)/$(PG_DB)
|
||||||
|
export ML_DATABASE_URL
|
||||||
|
|
||||||
|
# Le jeu historique s'arrete au 31/12/2024 : score et detection ancres a l'horloge reelle ne
|
||||||
|
# verraient qu'un parc muet depuis des mois. Cf. `--now` de enervision_ml.score.
|
||||||
|
DEMO_NOW ?= 2024-12-31T00:00:00Z
|
||||||
|
|
||||||
.DEFAULT_GOAL := help
|
.DEFAULT_GOAL := help
|
||||||
.PHONY: help install install-backend install-frontend install-ml dev dev-backend dev-frontend \
|
.PHONY: help install install-backend install-frontend install-ml install-airflow \
|
||||||
|
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 db-wait db-ensure-airflow \
|
||||||
ml-lint ml-typecheck ml-test ml-check ml-train ml-score
|
migrate bootstrap-admin services-up demo-data demo-data-force \
|
||||||
|
ml-lint ml-typecheck ml-test ml-check ml-train ml-score detect-alerts recommendations \
|
||||||
|
airflow-lint airflow-test airflow-check airflow-up airflow-down airflow-logs \
|
||||||
|
tls-selfsigned tls-acme tls-renew stack-up stack-down stack-logs
|
||||||
|
|
||||||
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 install-ml ## Installe les dépendances backend, frontend et ML
|
install: install-backend install-frontend install-ml install-airflow ## Installe les dépendances backend, frontend, ML et Airflow
|
||||||
|
|
||||||
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
|
||||||
@@ -22,12 +53,22 @@ install-frontend: ## Installe les dépendances du frontend
|
|||||||
install-ml: ## Installe les dépendances du pipeline ML
|
install-ml: ## Installe les dépendances du pipeline ML
|
||||||
cd $(ML) && uv sync --all-groups
|
cd $(ML) && uv sync --all-groups
|
||||||
|
|
||||||
dev: ## Lance toute la stack (backend + frontend) en rechargement à chaud
|
install-airflow: ## Installe les dépendances de lint/test des DAGs Airflow
|
||||||
|
cd $(AIRFLOW) && uv sync --all-groups
|
||||||
|
|
||||||
|
dev: services-up migrate demo-data ## Lance toute la stack : base, Mailpit, Airflow, puis backend et frontend
|
||||||
|
@echo "airflow -> http://localhost:$(AIRFLOW_PORT) mailpit -> http://localhost:$(MAILPIT_UI_PORT)"
|
||||||
@trap 'kill 0' EXIT INT TERM; \
|
@trap 'kill 0' EXIT INT TERM; \
|
||||||
$(MAKE) --no-print-directory dev-backend & \
|
$(MAKE) --no-print-directory dev-backend & \
|
||||||
$(MAKE) --no-print-directory dev-frontend & \
|
$(MAKE) --no-print-directory dev-frontend & \
|
||||||
wait
|
wait
|
||||||
|
|
||||||
|
services-up: ## Démarre les services conteneurisés dont `make dev` dépend (base, Mailpit, Airflow)
|
||||||
|
docker compose up -d db mailpit
|
||||||
|
@$(MAKE) --no-print-directory db-wait
|
||||||
|
@$(MAKE) --no-print-directory db-ensure-airflow
|
||||||
|
docker compose up -d airflow-init airflow-webserver airflow-scheduler
|
||||||
|
|
||||||
dev-backend: ## Lance l'API seule en rechargement à chaud
|
dev-backend: ## Lance l'API seule en rechargement à chaud
|
||||||
@echo "backend -> http://localhost:8000 (docs sur /docs)"
|
@echo "backend -> http://localhost:8000 (docs sur /docs)"
|
||||||
cd $(BACKEND) && uv run uvicorn app.main:create_app --factory --reload --host 0.0.0.0 --port 8000
|
cd $(BACKEND) && uv run uvicorn app.main:create_app --factory --reload --host 0.0.0.0 --port 8000
|
||||||
@@ -74,12 +115,68 @@ ml-check: ml-lint ml-typecheck ml-test ## Chaîne de vérification complète du
|
|||||||
ml-train: ## Entraine le modele LightGBM. CSV=chemin optionnel, sinon lit ML_DATABASE_URL
|
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),)
|
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
|
ml-score: ## Score le prochain pas horaire et l'ecrit dans `prediction`. CSV= et NOW= optionnels
|
||||||
cd $(ML) && uv run python -m enervision_ml.score $(if $(CSV),--csv $(CSV),)
|
cd $(ML) && uv run python -m enervision_ml.score $(if $(CSV),--csv $(CSV),) $(if $(NOW),--now $(NOW),)
|
||||||
|
|
||||||
|
detect-alerts: ## Détecte les alertes internes depuis les lectures en base. SITE= et NOW= optionnels
|
||||||
|
cd $(BACKEND) && uv run python -m app.detection.internal_alerts $(if $(SITE),--site-id $(SITE),) $(if $(NOW),--now $(NOW),)
|
||||||
|
|
||||||
|
recommendations: ## Genere les recommandations depuis les alertes en base. SITE=identifiant optionnel
|
||||||
|
cd $(BACKEND) && uv run python -m app.cli generate-recommendations $(if $(SITE),--site-id $(SITE),)
|
||||||
|
|
||||||
|
airflow-lint: ## Analyse statique des DAGs Airflow
|
||||||
|
cd $(AIRFLOW) && uv run ruff check .
|
||||||
|
|
||||||
|
airflow-test: ## Verifie que les DAGs s'importent sans erreur et ont la structure attendue
|
||||||
|
cd $(AIRFLOW) && uv run pytest
|
||||||
|
|
||||||
|
airflow-check: airflow-lint airflow-test ## Chaîne de vérification complète des DAGs Airflow
|
||||||
|
|
||||||
|
airflow-up: db-ensure-airflow ## Démarre Airflow (webserver + scheduler, LocalExecutor). db-up requis avant.
|
||||||
|
docker compose up -d airflow-init airflow-webserver airflow-scheduler
|
||||||
|
@echo "airflow -> http://localhost:$${AIRFLOW_PORT:-8080}"
|
||||||
|
|
||||||
|
airflow-down: ## Arrête le webserver et le scheduler Airflow
|
||||||
|
docker compose stop airflow-webserver airflow-scheduler
|
||||||
|
|
||||||
|
airflow-logs: ## Suit les journaux du scheduler Airflow (où tournent les tâches, LocalExecutor)
|
||||||
|
docker compose logs -f airflow-scheduler
|
||||||
|
|
||||||
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)
|
||||||
|
|
||||||
|
tls-selfsigned: ## Génère le certificat de démonstration. PUBLIC_HOST=..., FORCE=1 pour écraser
|
||||||
|
./scripts/tls-selfsigned.sh $(if $(FORCE),--force,)
|
||||||
|
|
||||||
|
# Piège : l'image backend ne migre pas au démarrage, et `/health/ready` ne teste que la connexion
|
||||||
|
# et l'extension. Sans `alembic upgrade head`, la stack démarre verte sur une base sans schéma.
|
||||||
|
stack-up: ## Démarre la stack derrière le reverse proxy, puis migre la base. PUBLIC_HOST=... au besoin
|
||||||
|
@test -f infra/proxy/tls/fullchain.pem \
|
||||||
|
|| { echo "Aucun certificat dans infra/proxy/tls. Lancer d'abord make tls-selfsigned"; exit 1; }
|
||||||
|
@openssl x509 -in infra/proxy/tls/fullchain.pem -noout -checkhost "$(PUBLIC_HOST)" >/dev/null \
|
||||||
|
|| { echo "Le certificat ne couvre pas $(PUBLIC_HOST). Relancer make tls-selfsigned PUBLIC_HOST=$(PUBLIC_HOST) FORCE=1"; exit 1; }
|
||||||
|
$(COMPOSE_PROD) up -d --build
|
||||||
|
$(COMPOSE_PROD) exec -T backend alembic upgrade head
|
||||||
|
|
||||||
|
stack-down: ## Arrête la stack complète en conservant les données
|
||||||
|
$(COMPOSE_PROD) stop
|
||||||
|
|
||||||
|
stack-logs: ## Suit les journaux du reverse proxy
|
||||||
|
$(COMPOSE_PROD) logs -f proxy
|
||||||
|
|
||||||
|
tls-acme: ## Demande un certificat Let's Encrypt. PUBLIC_HOST public et ACME_EMAIL requis
|
||||||
|
@test "$(PUBLIC_HOST)" != enervision.local \
|
||||||
|
|| { echo "PUBLIC_HOST doit être un domaine public résolvable, pas le nom de démonstration"; exit 1; }
|
||||||
|
$(COMPOSE_PROD) --profile acme run --rm certbot certonly --webroot -w /var/www/certbot \
|
||||||
|
-d $(PUBLIC_HOST) \
|
||||||
|
--email $${ACME_EMAIL:?ACME_EMAIL=... requis} \
|
||||||
|
--agree-tos --no-eff-email --deploy-hook /deploy-hook.sh
|
||||||
|
$(COMPOSE_PROD) exec proxy nginx -s reload
|
||||||
|
|
||||||
|
tls-renew: ## Renouvelle les certificats Let's Encrypt et recharge le proxy
|
||||||
|
$(COMPOSE_PROD) --profile acme run --rm certbot renew --deploy-hook /deploy-hook.sh
|
||||||
|
$(COMPOSE_PROD) exec proxy nginx -s reload
|
||||||
|
|
||||||
db-up: ## Démarre la base PostgreSQL TimescaleDB
|
db-up: ## Démarre la base PostgreSQL TimescaleDB
|
||||||
docker compose up -d db
|
docker compose up -d db
|
||||||
|
|
||||||
@@ -95,8 +192,36 @@ db-logs: ## Suit les journaux de la base
|
|||||||
db-psql: ## Ouvre une session psql sur la base applicative
|
db-psql: ## Ouvre une session psql sur la base applicative
|
||||||
docker compose exec db psql -U $${POSTGRES_USER:-enervision} -d $${POSTGRES_DB:-enervision}
|
docker compose exec db psql -U $${POSTGRES_USER:-enervision} -d $${POSTGRES_DB:-enervision}
|
||||||
|
|
||||||
|
db-wait: ## Attend que la base accepte les connexions
|
||||||
|
@for _ in $$(seq 1 60); do \
|
||||||
|
docker compose exec -T db pg_isready -U $(PG_USER) -d $(PG_DB) >/dev/null 2>&1 && exit 0; \
|
||||||
|
sleep 1; \
|
||||||
|
done; \
|
||||||
|
echo "La base n'accepte toujours pas de connexion apres 60s"; exit 1
|
||||||
|
|
||||||
|
# Piege : db/init ne rejoue qu'a la premiere initialisation du volume. Un `pgdata` cree avant
|
||||||
|
# db/init/120-airflow-database.sql n'a pas de base `airflow`, et airflow-init boucle dessus.
|
||||||
|
db-ensure-airflow: ## Crée la base de métadonnées Airflow si le volume pgdata est antérieur à db/init/120
|
||||||
|
@docker compose exec -T db psql -U $(PG_USER) -d postgres -tAc \
|
||||||
|
"SELECT 1 FROM pg_database WHERE datname = 'airflow'" | grep -q 1 \
|
||||||
|
|| docker compose exec -T db psql -U $(PG_USER) -d postgres -c "CREATE DATABASE airflow"
|
||||||
|
|
||||||
migrate: ## Applique les migrations Alembic
|
migrate: ## Applique les migrations Alembic
|
||||||
cd $(BACKEND) && uv run alembic upgrade head
|
cd $(BACKEND) && uv run alembic upgrade head
|
||||||
|
|
||||||
bootstrap-admin: ## Crée le premier administrateur, mot de passe saisi au clavier
|
bootstrap-admin: ## Crée le premier administrateur, mot de passe saisi au clavier
|
||||||
cd $(BACKEND) && uv run python -m app.cli create-admin --email $${EMAIL:?EMAIL=... requis}
|
cd $(BACKEND) && uv run python -m app.cli create-admin --email $${EMAIL:?EMAIL=... requis}
|
||||||
|
|
||||||
|
demo-data: ## Renseigne prédictions, alertes et recommandations si elles manquent. NOW= optionnel
|
||||||
|
@nombre=$$(docker compose exec -T db psql -U $(PG_USER) -d $(PG_DB) -tAc 'SELECT count(*) FROM alert') \
|
||||||
|
|| { echo "demo-data : base injoignable ou migrations non appliquees"; exit 1; }; \
|
||||||
|
if [ "$$nombre" = 0 ]; then \
|
||||||
|
$(MAKE) --no-print-directory demo-data-force; \
|
||||||
|
else \
|
||||||
|
echo "demo-data : $$nombre alerte(s) deja en base (make demo-data-force pour rejouer)"; \
|
||||||
|
fi
|
||||||
|
|
||||||
|
demo-data-force: ## Rejoue le peuplement sans regarder l'existant. Les trois etapes sont idempotentes
|
||||||
|
$(MAKE) --no-print-directory ml-score NOW=$(DEMO_NOW)
|
||||||
|
$(MAKE) --no-print-directory detect-alerts NOW=$(DEMO_NOW)
|
||||||
|
$(MAKE) --no-print-directory recommendations
|
||||||
|
|||||||
@@ -21,8 +21,9 @@ Ce que la documentation apporte à chacun : [docs/architecture/00-vue-ensemble.m
|
|||||||
| Backend | FastAPI, Python 3.14 | `apps/backend` | Initialise |
|
| Backend | FastAPI, Python 3.14 | `apps/backend` | Initialise |
|
||||||
| Frontend | Angular 22, Node 24 LTS | `apps/frontend` | Tableau de bord |
|
| Frontend | Angular 22, Node 24 LTS | `apps/frontend` | Tableau de bord |
|
||||||
| Base | PostgreSQL 17 + TimescaleDB | `db` | Initialise |
|
| Base | PostgreSQL 17 + TimescaleDB | `db` | Initialise |
|
||||||
| ETL | Apache Airflow | `etl/airflow` | A initialiser |
|
| ETL | Apache Airflow | `etl/airflow` | Quatre DAGs |
|
||||||
| Infra | Terraform (k3s single-node) | `infra/terraform` | Initialise |
|
| Infra | Terraform (k3s single-node) | `infra/terraform` | Initialise |
|
||||||
|
| Reverse proxy | Nginx, TLS | `infra/proxy` | En place |
|
||||||
| 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 |
|
| ML | LightGBM, MLflow | `ml` | Entrainement initialise |
|
||||||
@@ -47,13 +48,15 @@ L'etat detaille de chaque brique et les vues d'architecture sont dans
|
|||||||
│ ├── migrations/ Migrations SQL versionnees
|
│ ├── migrations/ Migrations SQL versionnees
|
||||||
│ └── seeds/ Jeux de donnees de reference
|
│ └── seeds/ Jeux de donnees de reference
|
||||||
├── etl/airflow/
|
├── etl/airflow/
|
||||||
│ ├── dags/ DAGs d'ingestion et d'agregation
|
│ ├── dags/ DAGs d'orchestration (pipeline ML, alertes, import historique)
|
||||||
│ ├── plugins/ Operateurs et hooks maison
|
│ ├── plugins/ Operateurs et hooks maison
|
||||||
│ ├── include/ Requetes SQL et ressources des DAGs
|
│ ├── include/ Requetes SQL et ressources des DAGs
|
||||||
│ └── tests/ Tests d'integrite des DAGs
|
│ └── tests/ Tests d'integrite des DAGs
|
||||||
├── infra/terraform/
|
├── infra/
|
||||||
│ ├── modules/ Modules reutilisables
|
│ ├── proxy/ Reverse proxy Nginx : terminaison TLS et routage
|
||||||
│ └── environments/ Racines Terraform, une par environnement
|
│ └── terraform/
|
||||||
|
│ ├── modules/ Modules reutilisables
|
||||||
|
│ └── environments/ Racines Terraform, une par environnement
|
||||||
├── ml/ Pipeline d'entrainement LightGBM, suivi MLflow
|
├── ml/ Pipeline d'entrainement LightGBM, suivi MLflow
|
||||||
├── monitoring/
|
├── monitoring/
|
||||||
│ ├── prometheus/ Collecte et regles d'alerte
|
│ ├── prometheus/ Collecte et regles d'alerte
|
||||||
@@ -72,25 +75,52 @@ Prerequis : uv, Docker, Node 24 LTS (npm fourni). Le poste doit disposer de Pyth
|
|||||||
cp .env.example .env # variables de docker-compose
|
cp .env.example .env # variables de docker-compose
|
||||||
cp apps/backend/.env.example apps/backend/.env # variables du backend hors conteneur
|
cp apps/backend/.env.example apps/backend/.env # variables du backend hors conteneur
|
||||||
|
|
||||||
make db-up # PostgreSQL + TimescaleDB, publie sur le port 5433
|
make install # dependances du backend, du frontend, du ML et des DAGs
|
||||||
make install # dependances du backend et du frontend
|
make dev # toute la stack, voir ci-dessous
|
||||||
make migrate # applique les migrations Alembic
|
|
||||||
make dev # backend sur http://localhost:8000 (docs sur /docs), frontend sur http://localhost:4200
|
|
||||||
make check # lint + typage + tests
|
make check # lint + typage + tests
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`make dev` enchaine tout : demarrage des services conteneurises (base sur le port 5433, Mailpit,
|
||||||
|
Airflow), migrations Alembic, peuplement de demonstration si les alertes manquent, puis backend
|
||||||
|
et frontend en rechargement a chaud sur le poste.
|
||||||
|
|
||||||
|
| Service | Adresse |
|
||||||
|
|---|---|
|
||||||
|
| Backend | <http://localhost:8000> (documentation sur `/docs`) |
|
||||||
|
| Frontend | <http://localhost:4200> |
|
||||||
|
| Airflow | <http://localhost:8080> (`AIRFLOW_ADMIN_USERNAME` / `AIRFLOW_ADMIN_PASSWORD` du `.env`) |
|
||||||
|
| Mailpit | <http://localhost:8025> |
|
||||||
|
|
||||||
|
Le `.env` doit porter les cles Airflow avant le premier `make dev` : `AIRFLOW_FERNET_KEY`,
|
||||||
|
`AIRFLOW_WEBSERVER_SECRET_KEY`, `AIRFLOW_APP_SECRET_KEY` et `AIRFLOW_ADMIN_PASSWORD`. Sans elles
|
||||||
|
`airflow-init` refuse de demarrer, et `airflow-webserver` comme `airflow-scheduler` avec lui.
|
||||||
|
|
||||||
|
Les cibles d'origine restent disponibles pour ne demarrer qu'une partie : `make db-up`,
|
||||||
|
`make airflow-up`, `make dev-backend`, `make dev-frontend`.
|
||||||
|
|
||||||
`make help` liste les cibles disponibles.
|
`make help` liste les cibles disponibles.
|
||||||
|
|
||||||
Deux fichiers d'environnement, deux usages : `.env` a la racine alimente `docker-compose.yml`,
|
Deux fichiers d'environnement, deux usages : `.env` a la racine alimente `docker-compose.yml`,
|
||||||
`apps/backend/.env` alimente le backend lance sur le poste. Le port 5433 est publie plutot que
|
`apps/backend/.env` alimente le backend lance sur le poste. Le port 5433 est publie plutot que
|
||||||
5432, souvent deja pris par une autre base.
|
5432, souvent deja pris par une autre base.
|
||||||
|
|
||||||
La boucle de developpement est `make db-up` puis `make dev` : seule la base tourne en
|
Le backend et le frontend tournent sur le poste, lances ensemble par `make dev` (logs
|
||||||
conteneur, le backend et le frontend tournent tous les deux sur le poste, lances ensemble par
|
entrelaces dans le meme terminal, Ctrl+C arrete les deux) ; la base, Mailpit et Airflow tournent
|
||||||
`make dev` (logs entrelaces dans le meme terminal, Ctrl+C arrete les deux). `make dev-backend`
|
en conteneur. Le service `backend` du `docker-compose.yml` sert la stack complete et la recette,
|
||||||
et `make dev-frontend` restent disponibles pour lancer un seul des deux. Le service `backend`
|
et n'embarque pas le source, donc toute modification y demande un
|
||||||
du `docker-compose.yml` sert la stack complete et la recette, et n'embarque pas le source, donc
|
`docker compose up -d --build backend`.
|
||||||
toute modification y demande un `docker compose up -d --build backend`.
|
|
||||||
|
### Donnees de demonstration
|
||||||
|
|
||||||
|
Le jeu historique s'arrete au 31/12/2024. `make demo-data` renseigne les tables que les vues
|
||||||
|
alertes, recommandations et previsions lisent, en ancrant le scoring et la detection a cette
|
||||||
|
date (`DEMO_NOW`) plutot qu'a l'horloge reelle, qui ne verrait qu'un parc muet depuis des mois.
|
||||||
|
La cible ne fait rien si des alertes existent deja ; `make demo-data-force` rejoue les trois
|
||||||
|
etapes, toutes idempotentes en base.
|
||||||
|
|
||||||
|
Un volume `pgdata` cree avant `db/init/120-airflow-database.sql` n'a pas de base `airflow` :
|
||||||
|
`db/init` ne rejoue qu'a la premiere initialisation. `make db-ensure-airflow`, appelee par
|
||||||
|
`make dev` et `make airflow-up`, la cree au besoin, sans detruire les donnees applicatives.
|
||||||
|
|
||||||
Verifier que la base repond et que l'extension est chargee :
|
Verifier que la base repond et que l'extension est chargee :
|
||||||
|
|
||||||
@@ -98,6 +128,27 @@ Verifier que la base repond et que l'extension est chargee :
|
|||||||
curl -s localhost:8000/api/v1/health/ready
|
curl -s localhost:8000/api/v1/health/ready
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Stack complète derrière le reverse proxy
|
||||||
|
|
||||||
|
Pour servir l'application comme sur la machine cible, en HTTPS et sous une seule origine.
|
||||||
|
L'overlay emploie `!override` et `!reset`, donc **Docker Compose 2.24.4 ou plus récent** :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make tls-selfsigned PUBLIC_HOST=enervision.local # certificat de démonstration
|
||||||
|
make stack-up PUBLIC_HOST=enervision.local # nginx en 80/443, rien d'autre n'est publié
|
||||||
|
```
|
||||||
|
|
||||||
|
Le navigateur avertit d'un émetteur inconnu : Let's Encrypt reste hors d'atteinte tant qu'aucun
|
||||||
|
nom de domaine public ne résout vers la machine. Routage, mode ACME et renouvellement dans
|
||||||
|
[`infra/proxy/README.md`](infra/proxy/README.md) ; la décision et ses motifs dans
|
||||||
|
[l'ADR 0007](docs/adr/0007-terminaison-tls-et-reverse-proxy-nginx.md).
|
||||||
|
|
||||||
|
Sur la VM ENI, deux environnements cohabitent, recette sur `dev` et production sur `main`,
|
||||||
|
chacun dans son dossier et son projet Compose : `scripts/provision-host.sh` les prépare, le
|
||||||
|
workflow `deploy.yml` les redéploie à chaque push par un runner auto-hébergé. Ports, noms
|
||||||
|
d'hôte et garde-fous dans [`docs/architecture/10-infra.md`](docs/architecture/10-infra.md) et
|
||||||
|
[l'ADR 0009](docs/adr/0009-deux-environnements-compose-sur-la-vm-eni.md).
|
||||||
|
|
||||||
## Conventions
|
## Conventions
|
||||||
|
|
||||||
- Branches : `feat/`, `fix/`, `chore/`, `docs/`, `test/` suivi d'un libelle court.
|
- Branches : `feat/`, `fix/`, `chore/`, `docs/`, `test/` suivi d'un libelle court.
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -11,13 +11,14 @@ WORKDIR /app
|
|||||||
RUN --mount=type=cache,target=/root/.cache/uv \
|
RUN --mount=type=cache,target=/root/.cache/uv \
|
||||||
--mount=type=bind,source=uv.lock,target=uv.lock \
|
--mount=type=bind,source=uv.lock,target=uv.lock \
|
||||||
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
|
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
|
||||||
uv sync --locked --no-install-project --no-dev
|
uv sync --locked --no-install-project --no-dev --no-build
|
||||||
|
|
||||||
|
# Le projet lui-meme n'est pas installe (pas de second `uv sync`) : il tourne depuis /app, le
|
||||||
|
# repertoire de travail, et rien ne lit ses metadonnees. L'installer imposerait de le construire
|
||||||
|
# (backend hatchling), donc de retirer `--no-build` de l'etape ci-dessus, qui garantit que
|
||||||
|
# l'installation des dependances n'execute aucun script de build (regle Sonar docker:S8541).
|
||||||
COPY . /app
|
COPY . /app
|
||||||
|
|
||||||
RUN --mount=type=cache,target=/root/.cache/uv \
|
|
||||||
uv sync --locked --no-dev
|
|
||||||
|
|
||||||
|
|
||||||
FROM python:3.14-slim AS runtime
|
FROM python:3.14-slim AS runtime
|
||||||
|
|
||||||
|
|||||||
@@ -113,6 +113,7 @@ Le sens de dependance est unique : `endpoints` vers `services` vers `repositorie
|
|||||||
| `/api/v1/sites/{site_id}` | Décrit un site | `lecteur` |
|
| `/api/v1/sites/{site_id}` | Décrit un site | `lecteur` |
|
||||||
| `/api/v1/recommendations` | Liste les recommandations | `lecteur` |
|
| `/api/v1/recommendations` | Liste les recommandations | `lecteur` |
|
||||||
| `/api/v1/recommendations/{recommendation_id}` | Décrit une recommandation | `lecteur` |
|
| `/api/v1/recommendations/{recommendation_id}` | Décrit une recommandation | `lecteur` |
|
||||||
|
| `/api/v1/recommendations/generate` | Génère les recommandations depuis les alertes (POST) | `admin` |
|
||||||
| `/metrics` | Métriques au format Prometheus | jeton si `APP_METRICS_TOKEN` |
|
| `/metrics` | Métriques au format Prometheus | jeton si `APP_METRICS_TOKEN` |
|
||||||
| `/docs`, `/openapi.json` | Documentation, fermée en `staging` et `prod` | public sinon |
|
| `/docs`, `/openapi.json` | Documentation, fermée en `staging` et `prod` | public sinon |
|
||||||
|
|
||||||
|
|||||||
@@ -192,7 +192,11 @@ AlertServiceDep = Annotated[AlertService, Depends(get_alert_service)]
|
|||||||
|
|
||||||
|
|
||||||
def get_recommendation_service(session: SessionDep) -> RecommendationService:
|
def get_recommendation_service(session: SessionDep) -> RecommendationService:
|
||||||
return RecommendationService(recommendations=RecommendationRepository(session))
|
return RecommendationService(
|
||||||
|
recommendations=RecommendationRepository(session),
|
||||||
|
alerts=AlertRepository(session),
|
||||||
|
transaction=session,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
RecommendationServiceDep = Annotated[RecommendationService, Depends(get_recommendation_service)]
|
RecommendationServiceDep = Annotated[RecommendationService, Depends(get_recommendation_service)]
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ TAGS: Final[list[dict[str, Any]]] = [
|
|||||||
"name": "recommendations",
|
"name": "recommendations",
|
||||||
"description": (
|
"description": (
|
||||||
"Consultation des recommandations issues des alertes. Accessible à partir du rôle "
|
"Consultation des recommandations issues des alertes. Accessible à partir du rôle "
|
||||||
"`lecteur`."
|
"`lecteur`. Leur génération par le moteur de règles est réservée au rôle `admin`."
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,13 +1,18 @@
|
|||||||
from fastapi import APIRouter, HTTPException, status
|
from fastapi import APIRouter, HTTPException, status
|
||||||
|
|
||||||
from app.api.deps import LecteurDep, RecommendationServiceDep
|
from app.api.deps import AdminDep, LecteurDep, RecommendationServiceDep
|
||||||
from app.api.openapi import REPONSE_VALIDATION, Reponses
|
from app.api.openapi import REPONSE_VALIDATION, REPONSES_ADMIN, Reponses
|
||||||
from app.schemas.errors import ErrorResponse
|
from app.schemas.errors import ErrorResponse
|
||||||
from app.schemas.recommendation import RecommendationResponse
|
from app.schemas.recommendation import (
|
||||||
|
RecommendationGenerationResponse,
|
||||||
|
RecommendationResponse,
|
||||||
|
)
|
||||||
from app.services.recommendation import RecommendationNotFoundError
|
from app.services.recommendation import RecommendationNotFoundError
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
|
REPONSES_GENERATION: Reponses = {**REPONSES_ADMIN, **REPONSE_VALIDATION}
|
||||||
|
|
||||||
REPONSES_INTROUVABLE: Reponses = {
|
REPONSES_INTROUVABLE: Reponses = {
|
||||||
**REPONSE_VALIDATION,
|
**REPONSE_VALIDATION,
|
||||||
404: {"model": ErrorResponse, "description": "Aucune recommandation ne porte cet identifiant."},
|
404: {"model": ErrorResponse, "description": "Aucune recommandation ne porte cet identifiant."},
|
||||||
@@ -38,3 +43,22 @@ async def get_recommendation(
|
|||||||
status_code=status.HTTP_404_NOT_FOUND, detail="Recommandation introuvable"
|
status_code=status.HTTP_404_NOT_FOUND, detail="Recommandation introuvable"
|
||||||
) from erreur
|
) from erreur
|
||||||
return RecommendationResponse.model_validate(recommendation)
|
return RecommendationResponse.model_validate(recommendation)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/generate",
|
||||||
|
response_model=RecommendationGenerationResponse,
|
||||||
|
summary="Génère les recommandations à partir des alertes",
|
||||||
|
responses=REPONSES_GENERATION,
|
||||||
|
)
|
||||||
|
async def generate_recommendations(
|
||||||
|
_: AdminDep,
|
||||||
|
service: RecommendationServiceDep,
|
||||||
|
site_id: str | None = None,
|
||||||
|
) -> RecommendationGenerationResponse:
|
||||||
|
rapport = await service.generate(site_id=site_id)
|
||||||
|
return RecommendationGenerationResponse(
|
||||||
|
alerts_examined=rapport.alertes_examinees,
|
||||||
|
recommendations_created=rapport.recommandations_creees,
|
||||||
|
already_present=rapport.deja_presentes,
|
||||||
|
)
|
||||||
|
|||||||
@@ -22,8 +22,11 @@ from app.core.hashing import build_hasher
|
|||||||
from app.core.roles import Role
|
from app.core.roles import Role
|
||||||
from app.db.session import get_session_factory
|
from app.db.session import get_session_factory
|
||||||
from app.main import create_app
|
from app.main import create_app
|
||||||
|
from app.repositories.alert import AlertRepository
|
||||||
|
from app.repositories.recommendation import RecommendationRepository
|
||||||
from app.repositories.user import UserRepository
|
from app.repositories.user import UserRepository
|
||||||
from app.schemas.auth import PASSWORD_MIN_LENGTH, SPECIAL_CHARACTERS, valide_complexite
|
from app.schemas.auth import PASSWORD_MIN_LENGTH, SPECIAL_CHARACTERS, valide_complexite
|
||||||
|
from app.services.recommendation import RecommendationService
|
||||||
|
|
||||||
LONGUEUR_MOT_DE_PASSE_GENERE = 24
|
LONGUEUR_MOT_DE_PASSE_GENERE = 24
|
||||||
CHEMIN_CONTRAT = Path(__file__).resolve().parent.parent / "openapi.json"
|
CHEMIN_CONTRAT = Path(__file__).resolve().parent.parent / "openapi.json"
|
||||||
@@ -63,6 +66,22 @@ async def create_admin(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def generate_recommendations(*, site_id: str | None) -> str:
|
||||||
|
async with get_session_factory()() as session:
|
||||||
|
service = RecommendationService(
|
||||||
|
recommendations=RecommendationRepository(session),
|
||||||
|
alerts=AlertRepository(session),
|
||||||
|
transaction=session,
|
||||||
|
)
|
||||||
|
rapport = await service.generate(site_id=site_id)
|
||||||
|
|
||||||
|
return (
|
||||||
|
f"{rapport.alertes_examinees} alerte(s) examinée(s), "
|
||||||
|
f"{rapport.recommandations_creees} recommandation(s) créée(s), "
|
||||||
|
f"{rapport.deja_presentes} déjà présente(s)"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# Piège : le schéma ne doit dépendre ni du `.env` du poste ni des variables `APP_*`, sinon le
|
# Piège : le schéma ne doit dépendre ni du `.env` du poste ni des variables `APP_*`, sinon le
|
||||||
# fichier versionné changerait de machine en machine et le test de dérive deviendrait un oracle
|
# fichier versionné changerait de machine en machine et le test de dérive deviendrait un oracle
|
||||||
# de configuration locale. Tout ce qui atteint le schéma est donc posé ici, `_env_file` compris.
|
# de configuration locale. Tout ce qui atteint le schéma est donc posé ici, `_env_file` compris.
|
||||||
@@ -109,6 +128,14 @@ def build_parser() -> argparse.ArgumentParser:
|
|||||||
"export-openapi", help="Écrit le contrat OpenAPI sur disque"
|
"export-openapi", help="Écrit le contrat OpenAPI sur disque"
|
||||||
)
|
)
|
||||||
contrat.add_argument("--output", default=str(CHEMIN_CONTRAT))
|
contrat.add_argument("--output", default=str(CHEMIN_CONTRAT))
|
||||||
|
|
||||||
|
recommandations = sous_commandes.add_parser(
|
||||||
|
"generate-recommendations",
|
||||||
|
help="Applique le moteur de règles aux alertes en base",
|
||||||
|
)
|
||||||
|
recommandations.add_argument(
|
||||||
|
"--site-id", default=None, help="Limite le traitement aux alertes d'un site"
|
||||||
|
)
|
||||||
return parser
|
return parser
|
||||||
|
|
||||||
|
|
||||||
@@ -152,6 +179,10 @@ def main(argv: list[str] | None = None) -> int:
|
|||||||
print(export_openapi(Path(arguments.output)))
|
print(export_openapi(Path(arguments.output)))
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
if arguments.commande == "generate-recommendations":
|
||||||
|
print(asyncio.run(generate_recommendations(site_id=arguments.site_id)))
|
||||||
|
return 0
|
||||||
|
|
||||||
mot_de_passe = read_password(generate=arguments.generate)
|
mot_de_passe = read_password(generate=arguments.generate)
|
||||||
|
|
||||||
succes, message = asyncio.run(
|
succes, message = asyncio.run(
|
||||||
|
|||||||
@@ -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,416 @@
|
|||||||
|
# Contrainte : la réponse de l'API Mock est une entrée hostile, pas une source de confiance.
|
||||||
|
# Voir OWASP API10 dans docs/architecture/owasp-traceabilite.md. Rien de ce qu'elle renvoie
|
||||||
|
# n'atteint la base sans passer par build_site_row() ou build_reading_row() : seuls les champs
|
||||||
|
# attendus sont recopiés, les grandeurs physiques sont bornées par PHYSICAL_BOUNDS et la taille
|
||||||
|
# des tableaux est plafonnée par MAX_SITES et par --limit. Une valeur hors bornes devient NULL
|
||||||
|
# et laisse sa trace dans null_reasons plutôt que de lever : le mock émet des anomalies par
|
||||||
|
# construction, et raw_data conserve de toute façon la réponse d'origine intacte.
|
||||||
|
|
||||||
|
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"
|
||||||
|
|
||||||
|
MAX_SITES = 100
|
||||||
|
|
||||||
|
MAX_LIMIT = 1000
|
||||||
|
|
||||||
|
# Les quatre seules valeurs que la contrainte ck_reading_quality accepte.
|
||||||
|
ACCEPTED_QUALITIES = frozenset({"good", "partial", "degraded", "critical"})
|
||||||
|
|
||||||
|
PHYSICAL_BOUNDS: dict[str, tuple[float, float]] = {
|
||||||
|
"consumption_kw": (0.0, 100_000.0),
|
||||||
|
"consumption_kwh": (0.0, 100_000.0),
|
||||||
|
"voltage_v": (0.0, 1_000.0),
|
||||||
|
"current_a": (0.0, 10_000.0),
|
||||||
|
"power_factor": (0.0, 1.0),
|
||||||
|
"temperature_celsius": (-90.0, 60.0),
|
||||||
|
"humidity_percent": (0.0, 100.0),
|
||||||
|
}
|
||||||
|
|
||||||
|
CAPACITY_BOUNDS = (0.0, 100_000.0)
|
||||||
|
|
||||||
|
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def read_text(payload: dict[str, Any], key: str) -> str:
|
||||||
|
value = payload.get(key)
|
||||||
|
|
||||||
|
if not isinstance(value, str) or not value:
|
||||||
|
raise ValueError(f"Champ {key} absent ou invalide dans la réponse de l'API Mock.")
|
||||||
|
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def optional_text(value: Any) -> str | None:
|
||||||
|
return value if isinstance(value, str) else None
|
||||||
|
|
||||||
|
|
||||||
|
def coerce_measure(
|
||||||
|
value: Any,
|
||||||
|
bounds: tuple[float, float],
|
||||||
|
) -> float | None:
|
||||||
|
if isinstance(value, bool) or not isinstance(value, int | float):
|
||||||
|
return None
|
||||||
|
|
||||||
|
lower, upper = bounds
|
||||||
|
|
||||||
|
# Écarte aussi NaN et les infinis, qu'aucune comparaison de bornes ne retient.
|
||||||
|
return float(value) if lower <= value <= upper else None
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_quality(
|
||||||
|
value: Any,
|
||||||
|
rejected: list[str],
|
||||||
|
) -> str | None:
|
||||||
|
quality = value if isinstance(value, str) and value in ACCEPTED_QUALITIES else None
|
||||||
|
|
||||||
|
if rejected:
|
||||||
|
return "critical" if quality == "critical" else "degraded"
|
||||||
|
|
||||||
|
return quality
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_null_reasons(
|
||||||
|
value: Any,
|
||||||
|
rejected: list[str],
|
||||||
|
) -> list[str]:
|
||||||
|
reported = [str(reason) for reason in value] if isinstance(value, list) else []
|
||||||
|
|
||||||
|
return reported + rejected
|
||||||
|
|
||||||
|
|
||||||
|
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.")
|
||||||
|
|
||||||
|
if len(payload) > MAX_SITES:
|
||||||
|
raise ValueError(f"La réponse /api/v1/sites dépasse le plafond de {MAX_SITES} sites.")
|
||||||
|
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def build_site_row(
|
||||||
|
site: dict[str, Any],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"site_id": read_text(site, "site_id"),
|
||||||
|
"site_type": read_text(site, "site_type"),
|
||||||
|
"site_name": read_text(site, "site_name"),
|
||||||
|
"location": optional_text(site.get("location")),
|
||||||
|
"capacity_kw": coerce_measure(site.get("capacity_kw"), CAPACITY_BOUNDS),
|
||||||
|
"status": optional_text(site.get("status")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def upsert_sites(
|
||||||
|
connection: AsyncConnection,
|
||||||
|
sites: list[dict[str, Any]],
|
||||||
|
) -> None:
|
||||||
|
rows = [build_site_row(site) for site in sites]
|
||||||
|
|
||||||
|
if not rows:
|
||||||
|
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
|
||||||
|
"""
|
||||||
|
),
|
||||||
|
rows,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def fetch_readings(
|
||||||
|
client: httpx.AsyncClient,
|
||||||
|
site_id: str,
|
||||||
|
start_time: datetime,
|
||||||
|
end_time: datetime,
|
||||||
|
limit: int = MAX_LIMIT,
|
||||||
|
) -> 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.")
|
||||||
|
|
||||||
|
if len(payload) > limit:
|
||||||
|
raise ValueError(f"La réponse /api/v1/readings dépasse la limite demandée de {limit}.")
|
||||||
|
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def build_reading_row(
|
||||||
|
reading: dict[str, Any],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
measures: dict[str, float | None] = {}
|
||||||
|
rejected: list[str] = []
|
||||||
|
|
||||||
|
for name, bounds in PHYSICAL_BOUNDS.items():
|
||||||
|
received = reading.get(name)
|
||||||
|
measures[name] = coerce_measure(received, bounds)
|
||||||
|
|
||||||
|
if received is not None and measures[name] is None:
|
||||||
|
rejected.append(f"out_of_physical_bounds:{name}")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"site_id": read_text(reading, "site_id"),
|
||||||
|
"timestamp": parse_datetime(read_text(reading, "timestamp")),
|
||||||
|
"source": SOURCE_HISTORY,
|
||||||
|
"dataset_id": None,
|
||||||
|
**measures,
|
||||||
|
"consumption_euros": None,
|
||||||
|
"solar_irradiance_wm2": None,
|
||||||
|
"is_working_hours": None,
|
||||||
|
"data_quality": resolve_quality(reading.get("data_quality"), rejected),
|
||||||
|
"null_reasons": resolve_null_reasons(reading.get("null_reasons"), rejected),
|
||||||
|
"imputed_values": None,
|
||||||
|
"imputation_method": None,
|
||||||
|
"raw_data": json.dumps(
|
||||||
|
reading,
|
||||||
|
ensure_ascii=False,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# Le conflit vise l'index unique uq_reading_source plutôt que la table entière : sans cible
|
||||||
|
# nommée, DO NOTHING avalerait aussi une violation de clé primaire.
|
||||||
|
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 (site_id, timestamp, source, (coalesce(dataset_id, 0)))
|
||||||
|
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 = read_text(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=MAX_LIMIT,
|
||||||
|
)
|
||||||
|
|
||||||
|
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 > MAX_LIMIT:
|
||||||
|
raise ValueError(f"--limit doit être compris entre 1 et {MAX_LIMIT}.")
|
||||||
|
|
||||||
|
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()
|
||||||
@@ -6,6 +6,10 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||||||
|
|
||||||
from app.models.energy import Alert
|
from app.models.energy import Alert
|
||||||
|
|
||||||
|
# Douze colonnes par alerte, contre quatre pour une recommandation : le plafond asyncpg de
|
||||||
|
# 32 767 parametres tombe a 2 730 lignes, d'ou un lot plus petit que `recommendation.py`.
|
||||||
|
TAILLE_DE_LOT = 1000
|
||||||
|
|
||||||
|
|
||||||
class AlertRepository:
|
class AlertRepository:
|
||||||
def __init__(self, session: AsyncSession) -> None:
|
def __init__(self, session: AsyncSession) -> None:
|
||||||
@@ -44,12 +48,17 @@ class AlertRepository:
|
|||||||
}
|
}
|
||||||
for alerte in alerts
|
for alerte in alerts
|
||||||
]
|
]
|
||||||
requete = (
|
creees: list[Alert] = []
|
||||||
insert(Alert)
|
# Piège : asyncpg plafonne une requête à 32 767 paramètres. Une détection sur une fenêtre
|
||||||
.values(valeurs)
|
# chargée dépasse ce seuil, et l'`INSERT` d'un seul tenant échouerait.
|
||||||
.on_conflict_do_nothing(constraint="uq_alert_source_reference")
|
for debut in range(0, len(valeurs), TAILLE_DE_LOT):
|
||||||
.returning(Alert)
|
requete = (
|
||||||
)
|
insert(Alert)
|
||||||
resultat = await self._session.execute(requete)
|
.values(valeurs[debut : debut + TAILLE_DE_LOT])
|
||||||
|
.on_conflict_do_nothing(constraint="uq_alert_source_reference")
|
||||||
|
.returning(Alert)
|
||||||
|
)
|
||||||
|
resultat = await self._session.execute(requete)
|
||||||
|
creees.extend(resultat.scalars().all())
|
||||||
await self._session.flush()
|
await self._session.flush()
|
||||||
return resultat.scalars().all()
|
return creees
|
||||||
|
|||||||
@@ -1,11 +1,24 @@
|
|||||||
from collections.abc import Sequence
|
from collections.abc import Sequence
|
||||||
|
from dataclasses import asdict, dataclass
|
||||||
|
|
||||||
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 Recommendation
|
from app.models.energy import Recommendation
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class NouvelleRecommandation:
|
||||||
|
alert_id: int
|
||||||
|
action: str
|
||||||
|
explanation: str
|
||||||
|
rule_reference: str
|
||||||
|
|
||||||
|
|
||||||
|
TAILLE_DE_LOT = 1000
|
||||||
|
|
||||||
|
|
||||||
class RecommendationRepository:
|
class RecommendationRepository:
|
||||||
def __init__(self, session: AsyncSession) -> None:
|
def __init__(self, session: AsyncSession) -> None:
|
||||||
self._session = session
|
self._session = session
|
||||||
@@ -20,3 +33,19 @@ class RecommendationRepository:
|
|||||||
)
|
)
|
||||||
recommendation: Recommendation | None = await self._session.scalar(requete)
|
recommendation: Recommendation | None = await self._session.scalar(requete)
|
||||||
return recommendation
|
return recommendation
|
||||||
|
|
||||||
|
# Pourquoi : l'idempotence est déléguée à `uq_recommendation_alert_rule` plutôt qu'à une
|
||||||
|
# lecture préalable, qui laisserait une fenêtre entre le contrôle et l'insertion.
|
||||||
|
async def create_missing(self, nouvelles: Sequence[NouvelleRecommandation]) -> int:
|
||||||
|
creees = 0
|
||||||
|
# Piège : asyncpg plafonne une requête à 32 767 paramètres, soit 8 191 lignes de quatre
|
||||||
|
# colonnes. Au-delà de ce seuil un `INSERT` d'un seul tenant échouerait.
|
||||||
|
for debut in range(0, len(nouvelles), TAILLE_DE_LOT):
|
||||||
|
requete = (
|
||||||
|
insert(Recommendation)
|
||||||
|
.values([asdict(nouvelle) for nouvelle in nouvelles[debut : debut + TAILLE_DE_LOT]])
|
||||||
|
.on_conflict_do_nothing(constraint="uq_recommendation_alert_rule")
|
||||||
|
.returning(Recommendation.recommendation_id)
|
||||||
|
)
|
||||||
|
creees += len((await self._session.scalars(requete)).all())
|
||||||
|
return creees
|
||||||
|
|||||||
@@ -12,3 +12,9 @@ class RecommendationResponse(BaseModel):
|
|||||||
explanation: str
|
explanation: str
|
||||||
rule_reference: str
|
rule_reference: str
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class RecommendationGenerationResponse(BaseModel):
|
||||||
|
alerts_examined: int
|
||||||
|
recommendations_created: int
|
||||||
|
already_present: int
|
||||||
|
|||||||
@@ -1,7 +1,15 @@
|
|||||||
from collections.abc import Sequence
|
from collections.abc import Sequence
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Protocol
|
||||||
|
|
||||||
from app.models.energy import Recommendation
|
from app.models.energy import Recommendation
|
||||||
|
from app.repositories.alert import AlertRepository
|
||||||
from app.repositories.recommendation import RecommendationRepository
|
from app.repositories.recommendation import RecommendationRepository
|
||||||
|
from app.services.recommendation_rules import applique_les_regles
|
||||||
|
|
||||||
|
|
||||||
|
class Transaction(Protocol):
|
||||||
|
async def commit(self) -> None: ...
|
||||||
|
|
||||||
|
|
||||||
class RecommendationError(Exception):
|
class RecommendationError(Exception):
|
||||||
@@ -12,9 +20,24 @@ class RecommendationNotFoundError(RecommendationError):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class RapportGeneration:
|
||||||
|
alertes_examinees: int
|
||||||
|
recommandations_creees: int
|
||||||
|
deja_presentes: int
|
||||||
|
|
||||||
|
|
||||||
class RecommendationService:
|
class RecommendationService:
|
||||||
def __init__(self, *, recommendations: RecommendationRepository) -> None:
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
recommendations: RecommendationRepository,
|
||||||
|
alerts: AlertRepository,
|
||||||
|
transaction: Transaction,
|
||||||
|
) -> None:
|
||||||
self._recommendations = recommendations
|
self._recommendations = recommendations
|
||||||
|
self._alerts = alerts
|
||||||
|
self._transaction = transaction
|
||||||
|
|
||||||
async def list_all(self) -> Sequence[Recommendation]:
|
async def list_all(self) -> Sequence[Recommendation]:
|
||||||
return await self._recommendations.list_all()
|
return await self._recommendations.list_all()
|
||||||
@@ -24,3 +47,16 @@ class RecommendationService:
|
|||||||
if recommendation is None:
|
if recommendation is None:
|
||||||
raise RecommendationNotFoundError(recommendation_id)
|
raise RecommendationNotFoundError(recommendation_id)
|
||||||
return recommendation
|
return recommendation
|
||||||
|
|
||||||
|
async def generate(self, *, site_id: str | None = None) -> RapportGeneration:
|
||||||
|
alertes = await self._alerts.list_all(site_id=site_id)
|
||||||
|
nouvelles = [nouvelle for alerte in alertes for nouvelle in applique_les_regles(alerte)]
|
||||||
|
|
||||||
|
creees = await self._recommendations.create_missing(nouvelles)
|
||||||
|
await self._transaction.commit()
|
||||||
|
|
||||||
|
return RapportGeneration(
|
||||||
|
alertes_examinees=len(alertes),
|
||||||
|
recommandations_creees=creees,
|
||||||
|
deja_presentes=len(nouvelles) - creees,
|
||||||
|
)
|
||||||
|
|||||||
@@ -0,0 +1,117 @@
|
|||||||
|
# Piège : `rule_reference` est la clé d'idempotence en base, portée par la contrainte
|
||||||
|
# `uq_recommendation_alert_rule`. Renommer une référence déjà livrée ne remplace pas les
|
||||||
|
# recommandations existantes, il en crée de nouvelles à côté. Une règle qui change de sens
|
||||||
|
# prend donc une référence suffixée `-v2` - REGLES.
|
||||||
|
|
||||||
|
from collections.abc import Callable
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Final
|
||||||
|
|
||||||
|
from app.models.energy import Alert
|
||||||
|
from app.repositories.recommendation import NouvelleRecommandation
|
||||||
|
from app.schemas.alert import AlertSeverity, AlertType
|
||||||
|
|
||||||
|
FACTEUR_DEPASSEMENT_MAJEUR: Final = 1.2
|
||||||
|
POURCENTAGE_DEPASSEMENT_MAJEUR: Final = round((FACTEUR_DEPASSEMENT_MAJEUR - 1) * 100)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class Regle:
|
||||||
|
reference: str
|
||||||
|
action: str
|
||||||
|
declencheur: Callable[[Alert], bool]
|
||||||
|
motif: Callable[[Alert], str]
|
||||||
|
|
||||||
|
|
||||||
|
def _du_type(attendu: AlertType) -> Callable[[Alert], bool]:
|
||||||
|
return lambda alerte: alerte.type == attendu
|
||||||
|
|
||||||
|
|
||||||
|
def _de_severite(attendue: AlertSeverity) -> Callable[[Alert], bool]:
|
||||||
|
return lambda alerte: alerte.severity == attendue
|
||||||
|
|
||||||
|
|
||||||
|
# Un seuil nul ou négatif rendrait le rapport `value / threshold` arbitraire : l'alerte ne
|
||||||
|
# renseigne alors aucun dépassement exploitable, et la règle ne se déclenche pas.
|
||||||
|
def _depasse_largement_le_seuil(alerte: Alert) -> bool:
|
||||||
|
if alerte.value is None or alerte.threshold is None or alerte.threshold <= 0:
|
||||||
|
return False
|
||||||
|
return alerte.value >= alerte.threshold * FACTEUR_DEPASSEMENT_MAJEUR
|
||||||
|
|
||||||
|
|
||||||
|
REGLES: Final[tuple[Regle, ...]] = (
|
||||||
|
Regle(
|
||||||
|
reference="spike-delestage-v1",
|
||||||
|
action="Délester les équipements non prioritaires sur le créneau du pic",
|
||||||
|
declencheur=_du_type(AlertType.SPIKE),
|
||||||
|
motif=lambda alerte: f"Pic de consommation signalé sur le site {alerte.site_id}",
|
||||||
|
),
|
||||||
|
Regle(
|
||||||
|
reference="threshold-reduction-v1",
|
||||||
|
action="Ramener la puissance appelée sous le seuil contractuel",
|
||||||
|
declencheur=_du_type(AlertType.THRESHOLD),
|
||||||
|
motif=lambda alerte: f"Seuil de consommation dépassé sur le site {alerte.site_id}",
|
||||||
|
),
|
||||||
|
Regle(
|
||||||
|
reference="outage-secours-v1",
|
||||||
|
action="Basculer sur l'alimentation de secours et prévenir l'exploitant",
|
||||||
|
declencheur=_du_type(AlertType.OUTAGE),
|
||||||
|
motif=lambda alerte: (
|
||||||
|
f"Risque de surcharge ou de coupure imminente sur le site {alerte.site_id}"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Regle(
|
||||||
|
reference="sensor-maintenance-v1",
|
||||||
|
action="Planifier une intervention de maintenance sur le capteur",
|
||||||
|
declencheur=_du_type(AlertType.SENSOR),
|
||||||
|
motif=lambda alerte: (
|
||||||
|
f"Capteur défaillant sur le site {alerte.site_id}, les mesures ne sont plus fiables"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Regle(
|
||||||
|
reference="anomaly-verification-v1",
|
||||||
|
action="Confronter la mesure à la prévision et vérifier le paramétrage du site",
|
||||||
|
declencheur=_du_type(AlertType.ANOMALY),
|
||||||
|
motif=lambda alerte: (
|
||||||
|
f"Écart anormal entre la mesure et le comportement attendu du site {alerte.site_id}"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Regle(
|
||||||
|
reference="escalade-astreinte-v1",
|
||||||
|
action="Escalader à l'astreinte sous une heure",
|
||||||
|
declencheur=_de_severite(AlertSeverity.CRITICAL),
|
||||||
|
motif=lambda alerte: f"Alerte de sévérité critique sur le site {alerte.site_id}",
|
||||||
|
),
|
||||||
|
Regle(
|
||||||
|
reference="contrat-puissance-v1",
|
||||||
|
action="Réévaluer la puissance souscrite au contrat",
|
||||||
|
declencheur=_depasse_largement_le_seuil,
|
||||||
|
motif=lambda alerte: (
|
||||||
|
f"Dépassement d'au moins {POURCENTAGE_DEPASSEMENT_MAJEUR} % du seuil "
|
||||||
|
f"sur le site {alerte.site_id}"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def applique_les_regles(alerte: Alert) -> list[NouvelleRecommandation]:
|
||||||
|
contexte = _contexte_de_mesure(alerte)
|
||||||
|
return [
|
||||||
|
NouvelleRecommandation(
|
||||||
|
alert_id=alerte.alert_id,
|
||||||
|
action=regle.action,
|
||||||
|
explanation=f"{regle.motif(alerte)}{contexte}.",
|
||||||
|
rule_reference=regle.reference,
|
||||||
|
)
|
||||||
|
for regle in REGLES
|
||||||
|
if regle.declencheur(alerte)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _contexte_de_mesure(alerte: Alert) -> str:
|
||||||
|
if alerte.value is None:
|
||||||
|
return ""
|
||||||
|
grandeur = alerte.metric or "valeur"
|
||||||
|
if alerte.threshold is None:
|
||||||
|
return f" ({grandeur} mesurée à {alerte.value})"
|
||||||
|
return f" ({grandeur} mesurée à {alerte.value}, seuil {alerte.threshold})"
|
||||||
+108
-1
@@ -1453,6 +1453,90 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"/api/v1/recommendations/generate": {
|
||||||
|
"post": {
|
||||||
|
"tags": [
|
||||||
|
"recommendations"
|
||||||
|
],
|
||||||
|
"summary": "Génère les recommandations à partir des alertes",
|
||||||
|
"operationId": "generate_recommendations_api_v1_recommendations_generate_post",
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"Jeton d'accès": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"name": "site_id",
|
||||||
|
"in": "query",
|
||||||
|
"required": false,
|
||||||
|
"schema": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Site Id"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "Successful Response",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/RecommendationGenerationResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"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": "Droits insuffisants, ou mot de passe provisoire à changer quand `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"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"/api/v1/stats/summary": {
|
"/api/v1/stats/summary": {
|
||||||
"get": {
|
"get": {
|
||||||
"tags": [
|
"tags": [
|
||||||
@@ -2344,6 +2428,29 @@
|
|||||||
],
|
],
|
||||||
"title": "ReadingSource"
|
"title": "ReadingSource"
|
||||||
},
|
},
|
||||||
|
"RecommendationGenerationResponse": {
|
||||||
|
"properties": {
|
||||||
|
"alerts_examined": {
|
||||||
|
"type": "integer",
|
||||||
|
"title": "Alerts Examined"
|
||||||
|
},
|
||||||
|
"recommendations_created": {
|
||||||
|
"type": "integer",
|
||||||
|
"title": "Recommendations Created"
|
||||||
|
},
|
||||||
|
"already_present": {
|
||||||
|
"type": "integer",
|
||||||
|
"title": "Already Present"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"alerts_examined",
|
||||||
|
"recommendations_created",
|
||||||
|
"already_present"
|
||||||
|
],
|
||||||
|
"title": "RecommendationGenerationResponse"
|
||||||
|
},
|
||||||
"RecommendationResponse": {
|
"RecommendationResponse": {
|
||||||
"properties": {
|
"properties": {
|
||||||
"recommendation_id": {
|
"recommendation_id": {
|
||||||
@@ -3153,7 +3260,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "recommendations",
|
"name": "recommendations",
|
||||||
"description": "Consultation des recommandations issues des alertes. Accessible à partir du rôle `lecteur`."
|
"description": "Consultation des recommandations issues des alertes. Accessible à partir du rôle `lecteur`. Leur génération par le moteur de règles est réservée au rôle `admin`."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "stats",
|
"name": "stats",
|
||||||
|
|||||||
@@ -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",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ ROLE_MINIMUM: Final[dict[Route, Role]] = {
|
|||||||
("GET", "/api/v1/alerts"): Role.LECTEUR,
|
("GET", "/api/v1/alerts"): Role.LECTEUR,
|
||||||
("GET", "/api/v1/recommendations"): Role.LECTEUR,
|
("GET", "/api/v1/recommendations"): Role.LECTEUR,
|
||||||
("GET", "/api/v1/recommendations/{recommendation_id}"): Role.LECTEUR,
|
("GET", "/api/v1/recommendations/{recommendation_id}"): Role.LECTEUR,
|
||||||
|
("POST", "/api/v1/recommendations/generate"): Role.ADMIN,
|
||||||
("GET", "/api/v1/stats/summary"): Role.LECTEUR,
|
("GET", "/api/v1/stats/summary"): Role.LECTEUR,
|
||||||
("GET", "/api/v1/readings"): Role.LECTEUR,
|
("GET", "/api/v1/readings"): Role.LECTEUR,
|
||||||
("GET", "/api/v1/predictions"): Role.LECTEUR,
|
("GET", "/api/v1/predictions"): Role.LECTEUR,
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ from app.api.deps import get_current_principal, get_recommendation_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 Recommendation
|
from app.models.energy import Recommendation
|
||||||
from app.services.recommendation import RecommendationNotFoundError
|
from app.services.recommendation import RapportGeneration, RecommendationNotFoundError
|
||||||
|
|
||||||
MOMENT = datetime(2024, 1, 1, tzinfo=UTC)
|
MOMENT = datetime(2024, 1, 1, tzinfo=UTC)
|
||||||
|
|
||||||
@@ -40,6 +40,7 @@ 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.recommendation = recommendation()
|
self.recommendation = recommendation()
|
||||||
|
self.site_demande: str | None = None
|
||||||
|
|
||||||
async def list_all(self) -> list[Recommendation]:
|
async def list_all(self) -> list[Recommendation]:
|
||||||
return [self.recommendation]
|
return [self.recommendation]
|
||||||
@@ -49,6 +50,10 @@ class FauxService:
|
|||||||
raise self._erreur
|
raise self._erreur
|
||||||
return self.recommendation
|
return self.recommendation
|
||||||
|
|
||||||
|
async def generate(self, *, site_id: str | None = None) -> RapportGeneration:
|
||||||
|
self.site_demande = site_id
|
||||||
|
return RapportGeneration(alertes_examinees=2, recommandations_creees=3, deja_presentes=1)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def lecteur_connecte(app: FastAPI) -> Iterator[None]:
|
def lecteur_connecte(app: FastAPI) -> Iterator[None]:
|
||||||
@@ -142,3 +147,56 @@ async def test_get_recommendation_returns_404_when_the_session_finds_nothing(
|
|||||||
response = await client.get("/api/v1/recommendations/404")
|
response = await client.get("/api/v1/recommendations/404")
|
||||||
|
|
||||||
assert response.status_code == 404
|
assert response.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def admin_connecte(app: FastAPI) -> Iterator[None]:
|
||||||
|
app.dependency_overrides[get_current_principal] = lambda: principal(Role.ADMIN)
|
||||||
|
yield
|
||||||
|
app.dependency_overrides.pop(get_current_principal, None)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def servi_en_admin(app: FastAPI, admin_connecte: None) -> Iterator[Callable[[], FauxService]]:
|
||||||
|
def installe() -> FauxService:
|
||||||
|
service = FauxService()
|
||||||
|
app.dependency_overrides[get_recommendation_service] = lambda: service
|
||||||
|
return service
|
||||||
|
|
||||||
|
yield installe
|
||||||
|
app.dependency_overrides.pop(get_recommendation_service, None)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_recommendations_returns_the_generation_report(
|
||||||
|
servi_en_admin: Callable[[], FauxService], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
servi_en_admin()
|
||||||
|
|
||||||
|
response = await client.post("/api/v1/recommendations/generate")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == {
|
||||||
|
"alerts_examined": 2,
|
||||||
|
"recommendations_created": 3,
|
||||||
|
"already_present": 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_recommendations_forwards_the_requested_site(
|
||||||
|
servi_en_admin: Callable[[], FauxService], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
service = servi_en_admin()
|
||||||
|
|
||||||
|
await client.post("/api/v1/recommendations/generate", params={"site_id": "SITE002"})
|
||||||
|
|
||||||
|
assert service.site_demande == "SITE002"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_recommendations_refuses_a_reader(
|
||||||
|
servi: Callable[..., FauxService], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
servi()
|
||||||
|
|
||||||
|
response = await client.post("/api/v1/recommendations/generate")
|
||||||
|
|
||||||
|
assert response.status_code == 403
|
||||||
|
|||||||
@@ -112,8 +112,10 @@ async def test_duplicate_reading_is_rejected_when_key_matches(
|
|||||||
)
|
)
|
||||||
await data_connection.execute(statement)
|
await data_connection.execute(statement)
|
||||||
|
|
||||||
|
savepoint = data_connection.begin_nested()
|
||||||
|
|
||||||
with pytest.raises(IntegrityError):
|
with pytest.raises(IntegrityError):
|
||||||
async with data_connection.begin_nested():
|
async with savepoint:
|
||||||
await data_connection.execute(statement)
|
await data_connection.execute(statement)
|
||||||
|
|
||||||
|
|
||||||
@@ -147,9 +149,12 @@ async def test_invalid_reading_is_rejected_when_constraints_fail(
|
|||||||
}
|
}
|
||||||
values.update(changes)
|
values.update(changes)
|
||||||
|
|
||||||
|
statement = insert(Reading).values(**values)
|
||||||
|
savepoint = data_connection.begin_nested()
|
||||||
|
|
||||||
with pytest.raises(IntegrityError):
|
with pytest.raises(IntegrityError):
|
||||||
async with data_connection.begin_nested():
|
async with savepoint:
|
||||||
await data_connection.execute(insert(Reading).values(**values))
|
await data_connection.execute(statement)
|
||||||
|
|
||||||
|
|
||||||
async def test_prediction_requires_period_when_energy_is_predicted(
|
async def test_prediction_requires_period_when_energy_is_predicted(
|
||||||
@@ -164,8 +169,10 @@ async def test_prediction_requires_period_when_energy_is_predicted(
|
|||||||
model_reference="test-model/1",
|
model_reference="test-model/1",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
savepoint = data_connection.begin_nested()
|
||||||
|
|
||||||
with pytest.raises(IntegrityError):
|
with pytest.raises(IntegrityError):
|
||||||
async with data_connection.begin_nested():
|
async with savepoint:
|
||||||
await data_connection.execute(statement)
|
await data_connection.execute(statement)
|
||||||
|
|
||||||
|
|
||||||
@@ -212,21 +219,22 @@ async def test_alert_rejects_prediction_when_site_differs(
|
|||||||
)
|
)
|
||||||
).scalar_one()
|
).scalar_one()
|
||||||
|
|
||||||
|
statement = insert(Alert).values(
|
||||||
|
source_alert_id=str(uuid4()),
|
||||||
|
site_id=other_site,
|
||||||
|
source="enervision",
|
||||||
|
timestamp=MOMENT,
|
||||||
|
type="spike",
|
||||||
|
severity="high",
|
||||||
|
message="Test",
|
||||||
|
prediction_id=prediction_id,
|
||||||
|
raw_data={},
|
||||||
|
)
|
||||||
|
savepoint = data_connection.begin_nested()
|
||||||
|
|
||||||
with pytest.raises(IntegrityError):
|
with pytest.raises(IntegrityError):
|
||||||
async with data_connection.begin_nested():
|
async with savepoint:
|
||||||
await data_connection.execute(
|
await data_connection.execute(statement)
|
||||||
insert(Alert).values(
|
|
||||||
source_alert_id=str(uuid4()),
|
|
||||||
site_id=other_site,
|
|
||||||
source="enervision",
|
|
||||||
timestamp=MOMENT,
|
|
||||||
type="spike",
|
|
||||||
severity="high",
|
|
||||||
message="Test",
|
|
||||||
prediction_id=prediction_id,
|
|
||||||
raw_data={},
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
async def test_recommendation_is_unique_when_alert_and_rule_match(
|
async def test_recommendation_is_unique_when_alert_and_rule_match(
|
||||||
@@ -256,6 +264,8 @@ async def test_recommendation_is_unique_when_alert_and_rule_match(
|
|||||||
)
|
)
|
||||||
await data_connection.execute(statement)
|
await data_connection.execute(statement)
|
||||||
|
|
||||||
|
savepoint = data_connection.begin_nested()
|
||||||
|
|
||||||
with pytest.raises(IntegrityError):
|
with pytest.raises(IntegrityError):
|
||||||
async with data_connection.begin_nested():
|
async with savepoint:
|
||||||
await data_connection.execute(statement)
|
await data_connection.execute(statement)
|
||||||
|
|||||||
@@ -1,239 +1,245 @@
|
|||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from app.etl.historical_import import (
|
from app.etl.historical_import import (
|
||||||
SOURCE_NAME,
|
SOURCE_NAME,
|
||||||
build_reading_batch,
|
build_reading_batch,
|
||||||
classify_quality,
|
classify_quality,
|
||||||
compute_sha256,
|
compute_sha256,
|
||||||
load_metadata,
|
load_metadata,
|
||||||
normalize_timestamps,
|
normalize_timestamps,
|
||||||
validate_source,
|
validate_source,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def make_metadata() -> dict:
|
def make_metadata() -> dict:
|
||||||
return {
|
return {
|
||||||
"total_records": 2,
|
"total_records": 2,
|
||||||
"sites": {
|
"sites": {
|
||||||
"SITE001": {},
|
"SITE001": {},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def make_dataframe() -> pd.DataFrame:
|
def make_dataframe() -> pd.DataFrame:
|
||||||
return pd.DataFrame(
|
return pd.DataFrame(
|
||||||
[
|
[
|
||||||
{
|
{
|
||||||
"timestamp": "2023-01-01 00:00:00",
|
"timestamp": "2023-01-01 00:00:00",
|
||||||
"site_id": "SITE001",
|
"site_id": "SITE001",
|
||||||
"site_type": "office",
|
"site_type": "office",
|
||||||
"site_name": "Site 1",
|
"site_name": "Site 1",
|
||||||
"consumption_kwh": 10.5,
|
"consumption_kwh": 10.5,
|
||||||
"consumption_euros": 2.5,
|
"consumption_euros": 2.5,
|
||||||
"temperature_celsius": 20.0,
|
"temperature_celsius": 20.0,
|
||||||
"humidity_percent": 50.0,
|
"humidity_percent": 50.0,
|
||||||
"solar_irradiance_wm2": 0.0,
|
"solar_irradiance_wm2": 0.0,
|
||||||
"hour": 0,
|
"hour": 0,
|
||||||
"day_of_week": 6,
|
"day_of_week": 6,
|
||||||
"day_name": "Sunday",
|
"day_name": "Sunday",
|
||||||
"month": 1,
|
"month": 1,
|
||||||
"is_weekend": True,
|
"is_weekend": True,
|
||||||
"is_working_hours": False,
|
"is_working_hours": False,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"timestamp": "2023-01-01 01:00:00",
|
"timestamp": "2023-01-01 01:00:00",
|
||||||
"site_id": "SITE001",
|
"site_id": "SITE001",
|
||||||
"site_type": "office",
|
"site_type": "office",
|
||||||
"site_name": "Site 1",
|
"site_name": "Site 1",
|
||||||
"consumption_kwh": 11.0,
|
"consumption_kwh": 11.0,
|
||||||
"consumption_euros": 2.7,
|
"consumption_euros": 2.7,
|
||||||
"temperature_celsius": 19.5,
|
"temperature_celsius": 19.5,
|
||||||
"humidity_percent": 52.0,
|
"humidity_percent": 52.0,
|
||||||
"solar_irradiance_wm2": 0.0,
|
"solar_irradiance_wm2": 0.0,
|
||||||
"hour": 1,
|
"hour": 1,
|
||||||
"day_of_week": 6,
|
"day_of_week": 6,
|
||||||
"day_name": "Sunday",
|
"day_name": "Sunday",
|
||||||
"month": 1,
|
"month": 1,
|
||||||
"is_weekend": True,
|
"is_weekend": True,
|
||||||
"is_working_hours": False,
|
"is_working_hours": False,
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_compute_sha256(tmp_path):
|
def test_compute_sha256(tmp_path):
|
||||||
file_path = tmp_path / "dataset.csv"
|
file_path = tmp_path / "dataset.csv"
|
||||||
content = b"hello-enervision"
|
content = b"hello-enervision"
|
||||||
|
|
||||||
file_path.write_bytes(content)
|
file_path.write_bytes(content)
|
||||||
|
|
||||||
expected = hashlib.sha256(content).hexdigest()
|
expected = hashlib.sha256(content).hexdigest()
|
||||||
|
|
||||||
assert compute_sha256(file_path) == expected
|
assert compute_sha256(file_path) == expected
|
||||||
|
|
||||||
|
|
||||||
def test_load_metadata(tmp_path):
|
def test_load_metadata(tmp_path):
|
||||||
metadata_path = tmp_path / "metadata.json"
|
metadata_path = tmp_path / "metadata.json"
|
||||||
|
|
||||||
metadata = {
|
metadata = {
|
||||||
"total_records": 2,
|
"total_records": 2,
|
||||||
"sites": {
|
"sites": {
|
||||||
"SITE001": {},
|
"SITE001": {},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
metadata_path.write_text(
|
metadata_path.write_text(
|
||||||
json.dumps(metadata),
|
json.dumps(metadata),
|
||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
|
|
||||||
assert load_metadata(metadata_path) == metadata
|
assert load_metadata(metadata_path) == metadata
|
||||||
|
|
||||||
|
|
||||||
def test_validate_source_accepts_valid_dataset():
|
def test_validate_source_accepts_valid_dataset():
|
||||||
frame = make_dataframe()
|
frame = make_dataframe()
|
||||||
|
|
||||||
validate_source(
|
validate_source(
|
||||||
frame,
|
frame,
|
||||||
make_metadata(),
|
make_metadata(),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_validate_source_rejects_missing_column():
|
def test_validate_source_rejects_missing_column():
|
||||||
frame = make_dataframe().drop(columns=["consumption_kwh"])
|
frame = make_dataframe().drop(columns=["consumption_kwh"])
|
||||||
|
|
||||||
with pytest.raises(
|
metadata = make_metadata()
|
||||||
ValueError,
|
|
||||||
match="Colonnes obligatoires absentes",
|
with pytest.raises(
|
||||||
):
|
ValueError,
|
||||||
validate_source(
|
match="Colonnes obligatoires absentes",
|
||||||
frame,
|
):
|
||||||
make_metadata(),
|
validate_source(
|
||||||
)
|
frame,
|
||||||
|
metadata,
|
||||||
|
)
|
||||||
def test_validate_source_rejects_duplicates():
|
|
||||||
frame = make_dataframe()
|
|
||||||
|
def test_validate_source_rejects_duplicates():
|
||||||
frame.loc[1, "timestamp"] = frame.loc[
|
frame = make_dataframe()
|
||||||
0,
|
|
||||||
"timestamp",
|
frame.loc[1, "timestamp"] = frame.loc[
|
||||||
]
|
0,
|
||||||
|
"timestamp",
|
||||||
with pytest.raises(
|
]
|
||||||
ValueError,
|
|
||||||
match="doublons",
|
metadata = make_metadata()
|
||||||
):
|
|
||||||
validate_source(
|
with pytest.raises(
|
||||||
frame,
|
ValueError,
|
||||||
make_metadata(),
|
match="doublons",
|
||||||
)
|
):
|
||||||
|
validate_source(
|
||||||
|
frame,
|
||||||
def test_validate_source_rejects_unknown_site():
|
metadata,
|
||||||
frame = make_dataframe()
|
)
|
||||||
|
|
||||||
frame.loc[1, "site_id"] = "SITE999"
|
|
||||||
|
def test_validate_source_rejects_unknown_site():
|
||||||
with pytest.raises(
|
frame = make_dataframe()
|
||||||
ValueError,
|
|
||||||
match="Sites incohérents",
|
frame.loc[1, "site_id"] = "SITE999"
|
||||||
):
|
|
||||||
validate_source(
|
metadata = make_metadata()
|
||||||
frame,
|
|
||||||
make_metadata(),
|
with pytest.raises(
|
||||||
)
|
ValueError,
|
||||||
|
match="Sites incohérents",
|
||||||
|
):
|
||||||
def test_normalize_timestamps_adds_timezone():
|
validate_source(
|
||||||
frame = make_dataframe()
|
frame,
|
||||||
|
metadata,
|
||||||
normalized = normalize_timestamps(
|
)
|
||||||
frame,
|
|
||||||
"UTC",
|
|
||||||
)
|
def test_normalize_timestamps_adds_timezone():
|
||||||
|
frame = make_dataframe()
|
||||||
assert normalized["timestamp"].dt.tz is not None
|
|
||||||
|
normalized = normalize_timestamps(
|
||||||
assert "_source_timestamp" in normalized.columns
|
frame,
|
||||||
|
"UTC",
|
||||||
|
)
|
||||||
def test_classify_quality_good():
|
|
||||||
row = make_dataframe().iloc[0].to_dict()
|
assert normalized["timestamp"].dt.tz is not None
|
||||||
|
|
||||||
quality, reasons = classify_quality(row)
|
assert "_source_timestamp" in normalized.columns
|
||||||
|
|
||||||
assert quality == "good"
|
|
||||||
assert reasons == []
|
def test_classify_quality_good():
|
||||||
|
row = make_dataframe().iloc[0].to_dict()
|
||||||
|
|
||||||
def test_classify_quality_degraded_when_consumption_missing():
|
quality, reasons = classify_quality(row)
|
||||||
row = make_dataframe().iloc[0].to_dict()
|
|
||||||
row["consumption_kwh"] = None
|
assert quality == "good"
|
||||||
|
assert reasons == []
|
||||||
quality, reasons = classify_quality(row)
|
|
||||||
|
|
||||||
assert quality == "degraded"
|
def test_classify_quality_degraded_when_consumption_missing():
|
||||||
|
row = make_dataframe().iloc[0].to_dict()
|
||||||
assert "missing:consumption_kwh" in reasons
|
row["consumption_kwh"] = None
|
||||||
|
|
||||||
|
quality, reasons = classify_quality(row)
|
||||||
def test_build_reading_batch_respects_database_contract():
|
|
||||||
frame = normalize_timestamps(
|
assert quality == "degraded"
|
||||||
make_dataframe(),
|
|
||||||
"UTC",
|
assert "missing:consumption_kwh" in reasons
|
||||||
)
|
|
||||||
|
|
||||||
rows = build_reading_batch(
|
def test_build_reading_batch_respects_database_contract():
|
||||||
frame.iloc[:1],
|
frame = normalize_timestamps(
|
||||||
dataset_id=3,
|
make_dataframe(),
|
||||||
)
|
"UTC",
|
||||||
|
)
|
||||||
assert len(rows) == 1
|
|
||||||
|
rows = build_reading_batch(
|
||||||
row = rows[0]
|
frame.iloc[:1],
|
||||||
|
dataset_id=3,
|
||||||
assert row["dataset_id"] == 3
|
)
|
||||||
|
|
||||||
# Important :
|
assert len(rows) == 1
|
||||||
# contrainte ck_reading_dataset_source.
|
|
||||||
assert row["source"] == "csv"
|
row = rows[0]
|
||||||
assert SOURCE_NAME == "csv"
|
|
||||||
|
assert row["dataset_id"] == 3
|
||||||
# Important :
|
|
||||||
# contrainte ck_reading_imputation.
|
# Important :
|
||||||
assert row["imputed_values"] is None
|
# contrainte ck_reading_dataset_source.
|
||||||
assert row["imputation_method"] is None
|
assert row["source"] == "csv"
|
||||||
|
assert SOURCE_NAME == "csv"
|
||||||
assert row["data_quality"] == "good"
|
|
||||||
assert row["null_reasons"] == []
|
# Important :
|
||||||
|
# contrainte ck_reading_imputation.
|
||||||
|
assert row["imputed_values"] is None
|
||||||
def test_build_reading_batch_keeps_missing_values():
|
assert row["imputation_method"] is None
|
||||||
frame = make_dataframe()
|
|
||||||
|
assert row["data_quality"] == "good"
|
||||||
frame.loc[0, "temperature_celsius"] = None
|
assert row["null_reasons"] == []
|
||||||
|
|
||||||
frame = normalize_timestamps(
|
|
||||||
frame,
|
def test_build_reading_batch_keeps_missing_values():
|
||||||
"UTC",
|
frame = make_dataframe()
|
||||||
)
|
|
||||||
|
frame.loc[0, "temperature_celsius"] = None
|
||||||
rows = build_reading_batch(
|
|
||||||
frame.iloc[:1],
|
frame = normalize_timestamps(
|
||||||
dataset_id=3,
|
frame,
|
||||||
)
|
"UTC",
|
||||||
|
)
|
||||||
row = rows[0]
|
|
||||||
|
rows = build_reading_batch(
|
||||||
assert row["temperature_celsius"] is None
|
frame.iloc[:1],
|
||||||
|
dataset_id=3,
|
||||||
assert "missing:temperature_celsius" in row["null_reasons"]
|
)
|
||||||
|
|
||||||
# RAW ingestion : aucune imputation.
|
row = rows[0]
|
||||||
assert row["imputed_values"] is None
|
|
||||||
assert row["imputation_method"] is None
|
assert row["temperature_celsius"] is None
|
||||||
|
|
||||||
|
assert "missing:temperature_celsius" in row["null_reasons"]
|
||||||
|
|
||||||
|
# RAW ingestion : aucune imputation.
|
||||||
|
assert row["imputed_values"] is None
|
||||||
|
assert row["imputation_method"] is None
|
||||||
|
|||||||
@@ -0,0 +1,834 @@
|
|||||||
|
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 (
|
||||||
|
MAX_SITES,
|
||||||
|
READING_INSERT,
|
||||||
|
SOURCE_HISTORY,
|
||||||
|
build_reading_batch,
|
||||||
|
build_reading_row,
|
||||||
|
build_site_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_sites_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/sites doit être une liste",
|
||||||
|
):
|
||||||
|
await fetch_sites(client)
|
||||||
|
|
||||||
|
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_fetch_sites_rejects_a_response_above_the_cap() -> None:
|
||||||
|
def handler(request: Request) -> Response:
|
||||||
|
return Response(
|
||||||
|
status_code=200,
|
||||||
|
json=[make_site() for _ in range(MAX_SITES + 1)],
|
||||||
|
)
|
||||||
|
|
||||||
|
transport = MockTransport(handler)
|
||||||
|
|
||||||
|
async with AsyncClient(
|
||||||
|
transport=transport,
|
||||||
|
base_url="https://mock.test",
|
||||||
|
) as client:
|
||||||
|
with pytest.raises(
|
||||||
|
ValueError,
|
||||||
|
match=f"dépasse le plafond de {MAX_SITES} sites",
|
||||||
|
):
|
||||||
|
await fetch_sites(client)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_fetch_readings_rejects_a_response_above_the_requested_limit() -> None:
|
||||||
|
def handler(request: Request) -> Response:
|
||||||
|
return Response(
|
||||||
|
status_code=200,
|
||||||
|
json=[make_reading(), make_reading(), make_reading()],
|
||||||
|
)
|
||||||
|
|
||||||
|
transport = MockTransport(handler)
|
||||||
|
|
||||||
|
async with AsyncClient(
|
||||||
|
transport=transport,
|
||||||
|
base_url="https://mock.test",
|
||||||
|
) as client:
|
||||||
|
with pytest.raises(
|
||||||
|
ValueError,
|
||||||
|
match="dépasse la limite demandée de 2",
|
||||||
|
):
|
||||||
|
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=2,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_reading_row_neutralises_values_outside_physical_bounds() -> None:
|
||||||
|
reading = make_reading()
|
||||||
|
|
||||||
|
reading["power_factor"] = 42.0
|
||||||
|
reading["temperature_celsius"] = 1e30
|
||||||
|
reading["humidity_percent"] = -1.0
|
||||||
|
|
||||||
|
row = build_reading_row(reading)
|
||||||
|
|
||||||
|
assert row["power_factor"] is None
|
||||||
|
assert row["temperature_celsius"] is None
|
||||||
|
assert row["humidity_percent"] is None
|
||||||
|
|
||||||
|
assert row["null_reasons"] == [
|
||||||
|
"out_of_physical_bounds:power_factor",
|
||||||
|
"out_of_physical_bounds:temperature_celsius",
|
||||||
|
"out_of_physical_bounds:humidity_percent",
|
||||||
|
]
|
||||||
|
|
||||||
|
assert row["data_quality"] == "degraded"
|
||||||
|
|
||||||
|
assert json.loads(row["raw_data"])["power_factor"] == 42.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_reading_row_rejects_a_measure_that_is_not_a_number() -> None:
|
||||||
|
reading = make_reading()
|
||||||
|
|
||||||
|
reading["consumption_kw"] = "87.34"
|
||||||
|
|
||||||
|
row = build_reading_row(reading)
|
||||||
|
|
||||||
|
assert row["consumption_kw"] is None
|
||||||
|
assert "out_of_physical_bounds:consumption_kw" in row["null_reasons"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_reading_row_drops_a_quality_the_database_refuses() -> None:
|
||||||
|
reading = make_reading()
|
||||||
|
|
||||||
|
reading["data_quality"] = "unknown"
|
||||||
|
|
||||||
|
row = build_reading_row(reading)
|
||||||
|
|
||||||
|
assert row["data_quality"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_reading_row_requires_an_identifier() -> None:
|
||||||
|
reading = make_reading()
|
||||||
|
|
||||||
|
del reading["site_id"]
|
||||||
|
|
||||||
|
with pytest.raises(
|
||||||
|
ValueError,
|
||||||
|
match="Champ site_id absent ou invalide",
|
||||||
|
):
|
||||||
|
build_reading_row(reading)
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_site_row_keeps_only_the_expected_columns() -> None:
|
||||||
|
site = make_site()
|
||||||
|
|
||||||
|
site["unexpected"] = "valeur hostile"
|
||||||
|
site["capacity_kw"] = -5.0
|
||||||
|
site["status"] = 12
|
||||||
|
|
||||||
|
row = build_site_row(site)
|
||||||
|
|
||||||
|
assert set(row) == {
|
||||||
|
"site_id",
|
||||||
|
"site_type",
|
||||||
|
"site_name",
|
||||||
|
"location",
|
||||||
|
"capacity_kw",
|
||||||
|
"status",
|
||||||
|
}
|
||||||
|
|
||||||
|
assert row["capacity_kw"] is None
|
||||||
|
assert row["status"] is None
|
||||||
|
|
||||||
|
|
||||||
|
async def test_upsert_sites_sends_only_the_expected_columns() -> None:
|
||||||
|
connection = AsyncMock()
|
||||||
|
|
||||||
|
site = make_site()
|
||||||
|
site["unexpected"] = "valeur hostile"
|
||||||
|
|
||||||
|
await upsert_sites(
|
||||||
|
connection,
|
||||||
|
[site],
|
||||||
|
)
|
||||||
|
|
||||||
|
rows = connection.execute.await_args.args[1]
|
||||||
|
|
||||||
|
assert "unexpected" not in rows[0]
|
||||||
|
assert rows[0]["site_id"] == "SITE001"
|
||||||
|
|
||||||
|
|
||||||
|
@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()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.integration
|
||||||
|
async def test_out_of_bounds_reading_is_stored_neutralised(
|
||||||
|
session: AsyncSession,
|
||||||
|
) -> None:
|
||||||
|
reading = make_reading()
|
||||||
|
reading["power_factor"] = 42.0
|
||||||
|
|
||||||
|
row = build_reading_row(reading)
|
||||||
|
|
||||||
|
connection = await session.connection()
|
||||||
|
|
||||||
|
await upsert_sites(
|
||||||
|
connection,
|
||||||
|
[make_site()],
|
||||||
|
)
|
||||||
|
|
||||||
|
await session.execute(
|
||||||
|
READING_INSERT,
|
||||||
|
[row],
|
||||||
|
)
|
||||||
|
|
||||||
|
result = await session.execute(
|
||||||
|
text(
|
||||||
|
"""
|
||||||
|
SELECT power_factor, data_quality, null_reasons, raw_data ->> 'power_factor'
|
||||||
|
FROM reading
|
||||||
|
WHERE site_id = :site_id
|
||||||
|
AND timestamp = :timestamp
|
||||||
|
AND source = :source
|
||||||
|
"""
|
||||||
|
),
|
||||||
|
{
|
||||||
|
"site_id": row["site_id"],
|
||||||
|
"timestamp": row["timestamp"],
|
||||||
|
"source": row["source"],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
stored = result.one()
|
||||||
|
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert stored[0] is None
|
||||||
|
assert stored[1] == "degraded"
|
||||||
|
assert stored[2] == ["out_of_physical_bounds:power_factor"]
|
||||||
|
assert stored[3] == "42.0"
|
||||||
@@ -5,6 +5,7 @@ import pytest
|
|||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from app.models.energy import Alert
|
from app.models.energy import Alert
|
||||||
|
from app.repositories import alert as module_alert
|
||||||
from app.repositories.alert import AlertRepository
|
from app.repositories.alert import AlertRepository
|
||||||
from app.schemas.alert import AlertSeverity
|
from app.schemas.alert import AlertSeverity
|
||||||
from tests.repositories.test_site import creer as creer_site
|
from tests.repositories.test_site import creer as creer_site
|
||||||
@@ -146,3 +147,20 @@ async def test_create_many_does_nothing_for_an_empty_list(session: AsyncSession)
|
|||||||
creees = await depot.create_many([])
|
creees = await depot.create_many([])
|
||||||
|
|
||||||
assert creees == []
|
assert creees == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_create_many_inserts_every_alert_across_several_batches(
|
||||||
|
session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
monkeypatch.setattr(module_alert, "TAILLE_DE_LOT", 2)
|
||||||
|
site = await creer_site(session)
|
||||||
|
depot = AlertRepository(session)
|
||||||
|
a_inserer = [
|
||||||
|
_alerte_a_inserer(site_id=site.site_id, source_alert_id=f"threshold:lot-{index}")
|
||||||
|
for index in range(5)
|
||||||
|
]
|
||||||
|
|
||||||
|
creees = await depot.create_many(a_inserer)
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert len(creees) == 5
|
||||||
|
|||||||
@@ -49,8 +49,10 @@ async def test_the_database_refuses_to_mutate_the_audit_log(
|
|||||||
) -> None:
|
) -> None:
|
||||||
await une_ligne(session)
|
await une_ligne(session)
|
||||||
|
|
||||||
|
requete = text(instruction)
|
||||||
|
|
||||||
with pytest.raises(DBAPIError, match="ajout seul"):
|
with pytest.raises(DBAPIError, match="ajout seul"):
|
||||||
await session.execute(text(instruction))
|
await session.execute(requete)
|
||||||
await session.rollback()
|
await session.rollback()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -131,11 +131,14 @@ async def test_the_database_refuses_two_tokens_sharing_a_fingerprint(
|
|||||||
user_agent=None,
|
user_agent=None,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
empreinte = fingerprint_refresh(secret)
|
||||||
|
expiration = datetime.now(UTC) + DUREE
|
||||||
|
|
||||||
with pytest.raises(IntegrityError):
|
with pytest.raises(IntegrityError):
|
||||||
await depot.create(
|
await depot.create(
|
||||||
user_id=compte,
|
user_id=compte,
|
||||||
token_hash=fingerprint_refresh(secret),
|
token_hash=empreinte,
|
||||||
expires_at=datetime.now(UTC) + DUREE,
|
expires_at=expiration,
|
||||||
client_ip=None,
|
client_ip=None,
|
||||||
user_agent=None,
|
user_agent=None,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -5,7 +5,8 @@ import pytest
|
|||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from app.models.energy import Alert, Recommendation, Site
|
from app.models.energy import Alert, Recommendation, Site
|
||||||
from app.repositories.recommendation import RecommendationRepository
|
from app.repositories import recommendation as module_recommendation
|
||||||
|
from app.repositories.recommendation import NouvelleRecommandation, RecommendationRepository
|
||||||
|
|
||||||
pytestmark = pytest.mark.integration
|
pytestmark = pytest.mark.integration
|
||||||
|
|
||||||
@@ -83,3 +84,59 @@ async def test_list_all_returns_the_recommendations_sorted_by_identifier(
|
|||||||
await session.rollback()
|
await session.rollback()
|
||||||
|
|
||||||
assert identifiants == sorted(identifiants)
|
assert identifiants == sorted(identifiants)
|
||||||
|
|
||||||
|
|
||||||
|
def nouvelle(alert_id: int, reference: str = "spike-delestage-v1") -> NouvelleRecommandation:
|
||||||
|
return NouvelleRecommandation(
|
||||||
|
alert_id=alert_id,
|
||||||
|
action="Délester les équipements non prioritaires",
|
||||||
|
explanation="Pic de consommation signalé.",
|
||||||
|
rule_reference=reference,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_create_missing_inserts_the_proposals(session: AsyncSession) -> None:
|
||||||
|
depot = RecommendationRepository(session)
|
||||||
|
alert_id = await creer_alerte(session)
|
||||||
|
|
||||||
|
creees = await depot.create_missing(
|
||||||
|
[nouvelle(alert_id), nouvelle(alert_id, "escalade-astreinte-v1")]
|
||||||
|
)
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert creees == 2
|
||||||
|
|
||||||
|
|
||||||
|
async def test_create_missing_ignores_a_rule_already_held_for_the_alert(
|
||||||
|
session: AsyncSession,
|
||||||
|
) -> None:
|
||||||
|
depot = RecommendationRepository(session)
|
||||||
|
alert_id = await creer_alerte(session)
|
||||||
|
await depot.create_missing([nouvelle(alert_id)])
|
||||||
|
|
||||||
|
creees = await depot.create_missing([nouvelle(alert_id)])
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert creees == 0
|
||||||
|
|
||||||
|
|
||||||
|
async def test_create_missing_returns_zero_without_any_proposal(session: AsyncSession) -> None:
|
||||||
|
creees = await RecommendationRepository(session).create_missing([])
|
||||||
|
|
||||||
|
assert creees == 0
|
||||||
|
|
||||||
|
|
||||||
|
async def test_create_missing_inserts_every_proposal_across_several_batches(
|
||||||
|
session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
monkeypatch.setattr(module_recommendation, "TAILLE_DE_LOT", 2)
|
||||||
|
depot = RecommendationRepository(session)
|
||||||
|
alert_id = await creer_alerte(session)
|
||||||
|
propositions = [nouvelle(alert_id, f"regle-{index}-v1") for index in range(5)]
|
||||||
|
|
||||||
|
creees = await depot.create_missing(propositions)
|
||||||
|
enregistrees = [r for r in await depot.list_all() if r.alert_id == alert_id]
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert creees == 5
|
||||||
|
assert len(enregistrees) == 5
|
||||||
|
|||||||
@@ -178,12 +178,16 @@ async def test_the_database_refuses_two_tokens_sharing_a_fingerprint(
|
|||||||
user_agent=None,
|
user_agent=None,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
famille = uuid.uuid4()
|
||||||
|
empreinte = fingerprint_refresh(secret)
|
||||||
|
expiration = datetime.now(UTC) + DUREE
|
||||||
|
|
||||||
with pytest.raises(IntegrityError):
|
with pytest.raises(IntegrityError):
|
||||||
await depot.create(
|
await depot.create(
|
||||||
user_id=compte,
|
user_id=compte,
|
||||||
family_id=uuid.uuid4(),
|
family_id=famille,
|
||||||
token_hash=fingerprint_refresh(secret),
|
token_hash=empreinte,
|
||||||
expires_at=datetime.now(UTC) + DUREE,
|
expires_at=expiration,
|
||||||
client_ip=None,
|
client_ip=None,
|
||||||
user_agent=None,
|
user_agent=None,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -31,14 +31,12 @@ async def test_the_database_refuses_an_email_written_in_upper_case(
|
|||||||
) -> None:
|
) -> None:
|
||||||
saisie = adresse().upper()
|
saisie = adresse().upper()
|
||||||
|
|
||||||
|
requete = text(
|
||||||
|
"insert into app_user (email, password_hash, role) values (:e, '$argon2id$x', 'lecteur')"
|
||||||
|
)
|
||||||
|
|
||||||
with pytest.raises(IntegrityError):
|
with pytest.raises(IntegrityError):
|
||||||
await session.execute(
|
await session.execute(requete, {"e": saisie})
|
||||||
text(
|
|
||||||
"insert into app_user (email, password_hash, role) "
|
|
||||||
"values (:e, '$argon2id$x', 'lecteur')"
|
|
||||||
),
|
|
||||||
{"e": saisie},
|
|
||||||
)
|
|
||||||
await session.rollback()
|
await session.rollback()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -116,13 +116,11 @@ async def test_list_history_normalizes_naive_datetimes_to_utc() -> None:
|
|||||||
async def test_list_history_raises_when_start_is_after_end() -> None:
|
async def test_list_history_raises_when_start_is_after_end() -> None:
|
||||||
service = ReadingService(readings=FakeRepository([]))
|
service = ReadingService(readings=FakeRepository([]))
|
||||||
|
|
||||||
|
debut = datetime(2026, 9, 2, tzinfo=UTC)
|
||||||
|
fin = datetime(2026, 9, 1, tzinfo=UTC)
|
||||||
|
|
||||||
with pytest.raises(FenetreInverseeError):
|
with pytest.raises(FenetreInverseeError):
|
||||||
await service.list_history(
|
await service.list_history(start=debut, end=fin, limit=500, offset=0)
|
||||||
start=datetime(2026, 9, 2, tzinfo=UTC),
|
|
||||||
end=datetime(2026, 9, 1, tzinfo=UTC),
|
|
||||||
limit=500,
|
|
||||||
offset=0,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
async def test_list_history_raises_when_start_equals_end() -> None:
|
async def test_list_history_raises_when_start_equals_end() -> None:
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
|
from collections.abc import Sequence
|
||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from app.models.energy import Recommendation
|
from app.models.energy import Alert, Recommendation
|
||||||
|
from app.repositories.recommendation import NouvelleRecommandation
|
||||||
from app.services.recommendation import RecommendationNotFoundError, RecommendationService
|
from app.services.recommendation import RecommendationNotFoundError, RecommendationService
|
||||||
|
|
||||||
|
MOMENT = datetime(2024, 1, 1, tzinfo=UTC)
|
||||||
|
|
||||||
|
|
||||||
def recommendation(recommendation_id: int = 1) -> Recommendation:
|
def recommendation(recommendation_id: int = 1) -> Recommendation:
|
||||||
return Recommendation(
|
return Recommendation(
|
||||||
@@ -13,13 +17,33 @@ def recommendation(recommendation_id: int = 1) -> Recommendation:
|
|||||||
action="Vérifier la consommation",
|
action="Vérifier la consommation",
|
||||||
explanation="Pic détecté",
|
explanation="Pic détecté",
|
||||||
rule_reference="spike-v1",
|
rule_reference="spike-v1",
|
||||||
created_at=datetime(2024, 1, 1, tzinfo=UTC),
|
created_at=MOMENT,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def alerte(alert_id: int = 1, site_id: str = "SITE001", severity: str = "high") -> Alert:
|
||||||
|
return Alert(
|
||||||
|
alert_id=alert_id,
|
||||||
|
source_alert_id=f"ALR-{alert_id}",
|
||||||
|
site_id=site_id,
|
||||||
|
source="api_mock",
|
||||||
|
timestamp=MOMENT,
|
||||||
|
type="spike",
|
||||||
|
severity=severity,
|
||||||
|
message="Pic de consommation",
|
||||||
|
value=None,
|
||||||
|
threshold=None,
|
||||||
|
metric=None,
|
||||||
|
prediction_id=None,
|
||||||
|
raw_data={},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class FakeRepository:
|
class FakeRepository:
|
||||||
def __init__(self, recommendations: list[Recommendation]) -> None:
|
def __init__(self, recommendations: list[Recommendation], creees: int | None = None) -> None:
|
||||||
self._recommendations = recommendations
|
self._recommendations = recommendations
|
||||||
|
self._creees = creees
|
||||||
|
self.recues: list[NouvelleRecommandation] = []
|
||||||
|
|
||||||
async def list_all(self) -> list[Recommendation]:
|
async def list_all(self) -> list[Recommendation]:
|
||||||
return self._recommendations
|
return self._recommendations
|
||||||
@@ -29,27 +53,111 @@ class FakeRepository:
|
|||||||
(r for r in self._recommendations if r.recommendation_id == recommendation_id), None
|
(r for r in self._recommendations if r.recommendation_id == recommendation_id), None
|
||||||
)
|
)
|
||||||
|
|
||||||
|
async def create_missing(self, nouvelles: Sequence[NouvelleRecommandation]) -> int:
|
||||||
|
self.recues = list(nouvelles)
|
||||||
|
return len(self.recues) if self._creees is None else self._creees
|
||||||
|
|
||||||
async def test_list_all_returns_the_repository_recommendations() -> None:
|
|
||||||
service = RecommendationService(
|
class FakeAlertRepository:
|
||||||
recommendations=FakeRepository([recommendation(1), recommendation(2)])
|
def __init__(self, alertes: list[Alert]) -> None:
|
||||||
|
self._alertes = alertes
|
||||||
|
self.site_demande: str | None = None
|
||||||
|
|
||||||
|
async def list_all(
|
||||||
|
self, *, site_id: str | None = None, severity: str | None = None
|
||||||
|
) -> list[Alert]:
|
||||||
|
self.site_demande = site_id
|
||||||
|
if site_id is None:
|
||||||
|
return self._alertes
|
||||||
|
return [a for a in self._alertes if a.site_id == site_id]
|
||||||
|
|
||||||
|
|
||||||
|
class FakeTransaction:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.commits = 0
|
||||||
|
|
||||||
|
async def commit(self) -> None:
|
||||||
|
self.commits += 1
|
||||||
|
|
||||||
|
|
||||||
|
def service(
|
||||||
|
recommendations: FakeRepository | None = None,
|
||||||
|
alerts: FakeAlertRepository | None = None,
|
||||||
|
transaction: FakeTransaction | None = None,
|
||||||
|
) -> RecommendationService:
|
||||||
|
return RecommendationService(
|
||||||
|
recommendations=recommendations or FakeRepository([]),
|
||||||
|
alerts=alerts or FakeAlertRepository([]),
|
||||||
|
transaction=transaction or FakeTransaction(),
|
||||||
)
|
)
|
||||||
|
|
||||||
recommendations = await service.list_all()
|
|
||||||
|
async def test_list_all_returns_the_repository_recommendations() -> None:
|
||||||
|
depot = FakeRepository([recommendation(1), recommendation(2)])
|
||||||
|
|
||||||
|
recommendations = await service(recommendations=depot).list_all()
|
||||||
|
|
||||||
assert [r.recommendation_id for r in recommendations] == [1, 2]
|
assert [r.recommendation_id for r in recommendations] == [1, 2]
|
||||||
|
|
||||||
|
|
||||||
async def test_get_by_id_returns_the_matching_recommendation() -> None:
|
async def test_get_by_id_returns_the_matching_recommendation() -> None:
|
||||||
service = RecommendationService(recommendations=FakeRepository([recommendation(1)]))
|
trouve = await service(recommendations=FakeRepository([recommendation(1)])).get_by_id(1)
|
||||||
|
|
||||||
trouve = await service.get_by_id(1)
|
|
||||||
|
|
||||||
assert trouve.recommendation_id == 1
|
assert trouve.recommendation_id == 1
|
||||||
|
|
||||||
|
|
||||||
async def test_get_by_id_raises_when_the_recommendation_is_unknown() -> None:
|
async def test_get_by_id_raises_when_the_recommendation_is_unknown() -> None:
|
||||||
service = RecommendationService(recommendations=FakeRepository([]))
|
|
||||||
|
|
||||||
with pytest.raises(RecommendationNotFoundError):
|
with pytest.raises(RecommendationNotFoundError):
|
||||||
await service.get_by_id(404)
|
await service().get_by_id(404)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_persists_one_proposal_per_triggered_rule() -> None:
|
||||||
|
depot = FakeRepository([])
|
||||||
|
|
||||||
|
rapport = await service(
|
||||||
|
recommendations=depot, alerts=FakeAlertRepository([alerte(severity="critical")])
|
||||||
|
).generate()
|
||||||
|
|
||||||
|
assert {n.rule_reference for n in depot.recues} == {
|
||||||
|
"spike-delestage-v1",
|
||||||
|
"escalade-astreinte-v1",
|
||||||
|
}
|
||||||
|
assert rapport.recommandations_creees == 2
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_commits_once() -> None:
|
||||||
|
transaction = FakeTransaction()
|
||||||
|
|
||||||
|
await service(alerts=FakeAlertRepository([alerte()]), transaction=transaction).generate()
|
||||||
|
|
||||||
|
assert transaction.commits == 1
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_restricts_the_alerts_to_the_requested_site() -> None:
|
||||||
|
alertes = FakeAlertRepository([alerte(1, site_id="SITE001"), alerte(2, site_id="SITE002")])
|
||||||
|
depot = FakeRepository([])
|
||||||
|
|
||||||
|
rapport = await service(recommendations=depot, alerts=alertes).generate(site_id="SITE002")
|
||||||
|
|
||||||
|
assert alertes.site_demande == "SITE002"
|
||||||
|
assert rapport.alertes_examinees == 1
|
||||||
|
assert {n.alert_id for n in depot.recues} == {2}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_reports_nothing_when_no_alert_matches() -> None:
|
||||||
|
rapport = await service().generate()
|
||||||
|
|
||||||
|
assert rapport.alertes_examinees == 0
|
||||||
|
assert rapport.recommandations_creees == 0
|
||||||
|
assert rapport.deja_presentes == 0
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_counts_the_proposals_the_database_already_held() -> None:
|
||||||
|
depot = FakeRepository([], creees=0)
|
||||||
|
|
||||||
|
rapport = await service(
|
||||||
|
recommendations=depot, alerts=FakeAlertRepository([alerte()])
|
||||||
|
).generate()
|
||||||
|
|
||||||
|
assert rapport.recommandations_creees == 0
|
||||||
|
assert rapport.deja_presentes == 1
|
||||||
|
|||||||
@@ -0,0 +1,142 @@
|
|||||||
|
from datetime import UTC, datetime
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.models.energy import Alert
|
||||||
|
from app.services.recommendation_rules import FACTEUR_DEPASSEMENT_MAJEUR, applique_les_regles
|
||||||
|
|
||||||
|
MOMENT = datetime(2024, 1, 1, tzinfo=UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def alerte(
|
||||||
|
*,
|
||||||
|
alert_id: int = 1,
|
||||||
|
type_alerte: str = "spike",
|
||||||
|
severity: str = "high",
|
||||||
|
value: float | None = None,
|
||||||
|
threshold: float | None = None,
|
||||||
|
metric: str | None = None,
|
||||||
|
site_id: str = "SITE001",
|
||||||
|
) -> Alert:
|
||||||
|
return Alert(
|
||||||
|
alert_id=alert_id,
|
||||||
|
source_alert_id=f"ALR-{alert_id}",
|
||||||
|
site_id=site_id,
|
||||||
|
source="api_mock",
|
||||||
|
timestamp=MOMENT,
|
||||||
|
type=type_alerte,
|
||||||
|
severity=severity,
|
||||||
|
message="Alerte de test",
|
||||||
|
value=value,
|
||||||
|
threshold=threshold,
|
||||||
|
metric=metric,
|
||||||
|
prediction_id=None,
|
||||||
|
raw_data={},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("type_alerte", "attendue"),
|
||||||
|
[
|
||||||
|
("spike", "spike-delestage-v1"),
|
||||||
|
("threshold", "threshold-reduction-v1"),
|
||||||
|
("outage", "outage-secours-v1"),
|
||||||
|
("sensor", "sensor-maintenance-v1"),
|
||||||
|
("anomaly", "anomaly-verification-v1"),
|
||||||
|
],
|
||||||
|
ids=["pic", "seuil", "coupure", "capteur", "anomalie"],
|
||||||
|
)
|
||||||
|
def test_each_alert_type_yields_its_own_rule(type_alerte: str, attendue: str) -> None:
|
||||||
|
proposees = applique_les_regles(alerte(type_alerte=type_alerte))
|
||||||
|
|
||||||
|
assert [p.rule_reference for p in proposees] == [attendue]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_critical_alert_adds_the_escalation_rule() -> None:
|
||||||
|
proposees = applique_les_regles(alerte(severity="critical"))
|
||||||
|
|
||||||
|
assert "escalade-astreinte-v1" in {p.rule_reference for p in proposees}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("severity", ["low", "medium", "high"], ids=["faible", "moyenne", "haute"])
|
||||||
|
def test_a_non_critical_alert_does_not_escalate(severity: str) -> None:
|
||||||
|
proposees = applique_les_regles(alerte(severity=severity))
|
||||||
|
|
||||||
|
assert "escalade-astreinte-v1" not in {p.rule_reference for p in proposees}
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_large_overshoot_adds_the_contract_rule() -> None:
|
||||||
|
proposees = applique_les_regles(
|
||||||
|
alerte(value=720.0 * FACTEUR_DEPASSEMENT_MAJEUR, threshold=720.0)
|
||||||
|
)
|
||||||
|
|
||||||
|
assert "contrat-puissance-v1" in {p.rule_reference for p in proposees}
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_overshoot_below_the_factor_does_not_add_the_contract_rule() -> None:
|
||||||
|
proposees = applique_les_regles(alerte(value=800.0, threshold=720.0))
|
||||||
|
|
||||||
|
assert "contrat-puissance-v1" not in {p.rule_reference for p in proposees}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("value", "threshold"),
|
||||||
|
[(None, 720.0), (900.0, None), (900.0, 0.0), (900.0, -10.0)],
|
||||||
|
ids=["sans mesure", "sans seuil", "seuil nul", "seuil negatif"],
|
||||||
|
)
|
||||||
|
def test_the_contract_rule_stays_silent_without_an_exploitable_threshold(
|
||||||
|
value: float | None, threshold: float | None
|
||||||
|
) -> None:
|
||||||
|
proposees = applique_les_regles(alerte(value=value, threshold=threshold))
|
||||||
|
|
||||||
|
assert "contrat-puissance-v1" not in {p.rule_reference for p in proposees}
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_explanation_quotes_the_measure_and_the_threshold() -> None:
|
||||||
|
proposees = applique_les_regles(alerte(value=812.5, threshold=720.0, metric="consumption_kw"))
|
||||||
|
|
||||||
|
assert "(consumption_kw mesurée à 812.5, seuil 720.0)" in proposees[0].explanation
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_explanation_quotes_the_measure_alone_when_no_threshold_is_known() -> None:
|
||||||
|
proposees = applique_les_regles(alerte(value=812.5, metric="consumption_kw"))
|
||||||
|
|
||||||
|
assert "(consumption_kw mesurée à 812.5)" in proposees[0].explanation
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_explanation_omits_the_measure_when_the_alert_carries_none() -> None:
|
||||||
|
proposees = applique_les_regles(alerte())
|
||||||
|
|
||||||
|
assert "(" not in proposees[0].explanation
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_explanation_names_the_site() -> None:
|
||||||
|
proposees = applique_les_regles(alerte(site_id="SITE042"))
|
||||||
|
|
||||||
|
assert "SITE042" in proposees[0].explanation
|
||||||
|
|
||||||
|
|
||||||
|
def test_every_proposal_carries_the_alert_identifier() -> None:
|
||||||
|
proposees = applique_les_regles(alerte(alert_id=77, severity="critical"))
|
||||||
|
|
||||||
|
assert {p.alert_id for p in proposees} == {77}
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_alert_never_yields_the_same_rule_twice() -> None:
|
||||||
|
proposees = applique_les_regles(
|
||||||
|
alerte(severity="critical", value=900.0, threshold=720.0, metric="consumption_kw")
|
||||||
|
)
|
||||||
|
|
||||||
|
assert len(proposees) == len({p.rule_reference for p in proposees})
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_critical_alert_over_the_threshold_yields_the_three_rules() -> None:
|
||||||
|
proposees = applique_les_regles(
|
||||||
|
alerte(severity="critical", value=900.0, threshold=720.0, metric="consumption_kw")
|
||||||
|
)
|
||||||
|
|
||||||
|
assert {p.rule_reference for p in proposees} == {
|
||||||
|
"spike-delestage-v1",
|
||||||
|
"escalade-astreinte-v1",
|
||||||
|
"contrat-puissance-v1",
|
||||||
|
}
|
||||||
@@ -235,5 +235,7 @@ async def test_every_operation_refuses_an_unknown_account(action: str) -> None:
|
|||||||
if action == "set_active":
|
if action == "set_active":
|
||||||
arguments["is_active"] = False
|
arguments["is_active"] = False
|
||||||
|
|
||||||
|
methode = getattr(attirail.service, action)
|
||||||
|
|
||||||
with pytest.raises(UserNotFoundError):
|
with pytest.raises(UserNotFoundError):
|
||||||
await getattr(attirail.service, action)(**arguments)
|
await methode(**arguments)
|
||||||
|
|||||||
@@ -19,13 +19,17 @@ def test_build_parser_reads_the_create_admin_arguments() -> None:
|
|||||||
|
|
||||||
|
|
||||||
def test_build_parser_requires_a_subcommand() -> None:
|
def test_build_parser_requires_a_subcommand() -> None:
|
||||||
|
parser = cli.build_parser()
|
||||||
|
|
||||||
with pytest.raises(SystemExit):
|
with pytest.raises(SystemExit):
|
||||||
cli.build_parser().parse_args([])
|
parser.parse_args([])
|
||||||
|
|
||||||
|
|
||||||
def test_build_parser_requires_an_email() -> None:
|
def test_build_parser_requires_an_email() -> None:
|
||||||
|
parser = cli.build_parser()
|
||||||
|
|
||||||
with pytest.raises(SystemExit):
|
with pytest.raises(SystemExit):
|
||||||
cli.build_parser().parse_args(["create-admin"])
|
parser.parse_args(["create-admin"])
|
||||||
|
|
||||||
|
|
||||||
def test_read_password_generates_a_long_secret_when_asked(
|
def test_read_password_generates_a_long_secret_when_asked(
|
||||||
@@ -118,3 +122,30 @@ def test_main_exports_the_contract_without_asking_for_a_password(
|
|||||||
assert code == 0
|
assert code == 0
|
||||||
assert destination.exists()
|
assert destination.exists()
|
||||||
assert str(destination) in capsys.readouterr().out
|
assert str(destination) in capsys.readouterr().out
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_parser_reads_the_generate_recommendations_arguments() -> None:
|
||||||
|
arguments = cli.build_parser().parse_args(["generate-recommendations", "--site-id", "SITE002"])
|
||||||
|
|
||||||
|
assert arguments.commande == "generate-recommendations"
|
||||||
|
assert arguments.site_id == "SITE002"
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_parser_defaults_the_generation_to_every_site() -> None:
|
||||||
|
arguments = cli.build_parser().parse_args(["generate-recommendations"])
|
||||||
|
|
||||||
|
assert arguments.site_id is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_main_generates_the_recommendations_without_asking_for_a_password(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||||
|
) -> None:
|
||||||
|
async def fausse_generation(*, site_id: str | None) -> str:
|
||||||
|
return f"génération lancée pour {site_id}"
|
||||||
|
|
||||||
|
monkeypatch.setattr(cli, "generate_recommendations", fausse_generation)
|
||||||
|
|
||||||
|
code = cli.main(["generate-recommendations", "--site-id", "SITE002"])
|
||||||
|
|
||||||
|
assert code == 0
|
||||||
|
assert "SITE002" in capsys.readouterr().out
|
||||||
|
|||||||
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" },
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ RUN npm run build
|
|||||||
# ==================
|
# ==================
|
||||||
|
|
||||||
|
|
||||||
FROM dhi.io/nginx:1.28.0-alpine3.21-dev AS runner
|
FROM nginx:1.28-alpine AS runner
|
||||||
|
|
||||||
# Copie de la configuration de nginx
|
# Copie de la configuration de nginx
|
||||||
COPY --chown=root:root --chmod=755 nginx.conf /etc/nginx/nginx.conf
|
COPY --chown=root:root --chmod=755 nginx.conf /etc/nginx/nginx.conf
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Conventions de tests unitaires — Frontend
|
# Conventions de tests unitaires : Frontend
|
||||||
|
|
||||||
## Outil
|
## Outil
|
||||||
Vitest (intégré nativement à Angular CLI, pas d'installation à faire).
|
Vitest (intégré nativement à Angular CLI, pas d'installation à faire).
|
||||||
@@ -83,3 +83,6 @@ describe('MonComposant', () => {
|
|||||||
## Lancer les tests
|
## Lancer les tests
|
||||||
- Développement (mode watch) : `npm test`
|
- Développement (mode watch) : `npm test`
|
||||||
- Rapport de couverture (CI) : `npm run test:ci -- --coverage`, puis ouvrir `coverage/index.html`
|
- Rapport de couverture (CI) : `npm run test:ci -- --coverage`, puis ouvrir `coverage/index.html`
|
||||||
|
- Un fichier ou un dossier seulement :
|
||||||
|
`npx ng test --watch=false --coverage=false --include=src/app/core/services/alerts.service.spec.ts`
|
||||||
|
(répéter `--include` pour plusieurs cibles ; un dossier joue tous ses specs)
|
||||||
|
|||||||
@@ -34,6 +34,11 @@
|
|||||||
},
|
},
|
||||||
"configurations": {
|
"configurations": {
|
||||||
"production": {
|
"production": {
|
||||||
|
"optimization": {
|
||||||
|
"styles": {
|
||||||
|
"inlineCritical": false
|
||||||
|
}
|
||||||
|
},
|
||||||
"budgets": [
|
"budgets": [
|
||||||
{
|
{
|
||||||
"type": "initial",
|
"type": "initial",
|
||||||
|
|||||||
@@ -1,21 +1,36 @@
|
|||||||
import { Routes } from '@angular/router';
|
import { Routes } from '@angular/router';
|
||||||
import {authGuard} from './core/guards/auth-guard';
|
import { authGuard } from './core/guards/auth-guard';
|
||||||
|
|
||||||
export const routes: Routes = [
|
export const routes: Routes = [
|
||||||
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
|
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
|
||||||
{ path: 'login', loadComponent: () => import('./features/auth/login/login').then(m => m.Login) },
|
{
|
||||||
{ path: 'change-password', loadComponent: () => import('./features/auth/change-password/change-password').then(m => m.ChangePassword) },
|
path: 'login',
|
||||||
{ path: 'forgot-password', loadComponent: () => import('./features/auth/forgot-password/forgot-password').then(m => m.ForgotPassword) },
|
loadComponent: () => import('./features/auth/login/login').then((m) => m.Login),
|
||||||
{ path: 'reset-password', loadComponent: () => import('./features/auth/reset-password/reset-password').then(m => m.ResetPassword) },
|
},
|
||||||
|
{
|
||||||
|
path: 'change-password',
|
||||||
|
loadComponent: () =>
|
||||||
|
import('./features/auth/change-password/change-password').then((m) => m.ChangePassword),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'forgot-password',
|
||||||
|
loadComponent: () =>
|
||||||
|
import('./features/auth/forgot-password/forgot-password').then((m) => m.ForgotPassword),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'reset-password',
|
||||||
|
loadComponent: () =>
|
||||||
|
import('./features/auth/reset-password/reset-password').then((m) => m.ResetPassword),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: 'dashboard',
|
path: 'dashboard',
|
||||||
canActivate: [authGuard],
|
canActivate: [authGuard],
|
||||||
loadComponent: () => import('./features/dashboard/dashboard').then(m => m.Dashboard),
|
loadComponent: () => import('./features/dashboard/dashboard').then((m) => m.Dashboard),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'sites',
|
path: 'sites',
|
||||||
canActivate: [authGuard],
|
canActivate: [authGuard],
|
||||||
loadComponent: () => import('./features/sites/site-list/site-list').then(m => m.SiteList),
|
loadComponent: () => import('./features/sites/site-list/site-list').then((m) => m.SiteList),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'sites/:siteId',
|
path: 'sites/:siteId',
|
||||||
@@ -23,4 +38,17 @@ export const routes: Routes = [
|
|||||||
loadComponent: () =>
|
loadComponent: () =>
|
||||||
import('./features/sites/site-detail/site-detail').then((m) => m.SiteDetail),
|
import('./features/sites/site-detail/site-detail').then((m) => m.SiteDetail),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'recommendations',
|
||||||
|
canActivate: [authGuard],
|
||||||
|
loadComponent: () =>
|
||||||
|
import('./features/recommendations/recommendations').then((m) => m.RecommendationsView),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'monitoring/sensors',
|
||||||
|
canActivate: [authGuard],
|
||||||
|
data: { role: 'admin' },
|
||||||
|
loadComponent: () =>
|
||||||
|
import('./features/monitoring/sensor-status/sensor-status').then((m) => m.SensorStatusView),
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -8,8 +8,10 @@ import { STATS_SUMMARY_FIXTURE } from '../mocks/stats-summary.fixture';
|
|||||||
describe('mockApiInterceptor', () => {
|
describe('mockApiInterceptor', () => {
|
||||||
let http: HttpClient;
|
let http: HttpClient;
|
||||||
let httpMock: HttpTestingController;
|
let httpMock: HttpTestingController;
|
||||||
|
let useMockFixturesInitial: boolean;
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
|
useMockFixturesInitial = environment.useMockFixtures;
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
provideHttpClient(withInterceptors([mockApiInterceptor])),
|
provideHttpClient(withInterceptors([mockApiInterceptor])),
|
||||||
@@ -21,7 +23,7 @@ describe('mockApiInterceptor', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
environment.useMockFixtures = true;
|
environment.useMockFixtures = useMockFixturesInitial;
|
||||||
httpMock.verify();
|
httpMock.verify();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -2,53 +2,63 @@ import { Alert } from '../../shared/models/alert.model';
|
|||||||
|
|
||||||
export const ALERTS_FIXTURE: Alert[] = [
|
export const ALERTS_FIXTURE: Alert[] = [
|
||||||
{
|
{
|
||||||
alert_id: 'ALR-SITE002-1718458320',
|
alert_id: 5,
|
||||||
timestamp: '2026-09-15T11:12:00',
|
|
||||||
site_id: 'SITE002',
|
site_id: 'SITE002',
|
||||||
|
timestamp: '2026-09-15T11:12:00Z',
|
||||||
|
type: 'threshold',
|
||||||
severity: 'critical',
|
severity: 'critical',
|
||||||
type: 'outage',
|
message: 'Puissance appelée 812.5 kW au-dessus de la capacité du site (720.0 kW)',
|
||||||
message: 'Risque de surcharge sur Usine Lyon Vénissieux',
|
|
||||||
value: 812.5,
|
value: 812.5,
|
||||||
threshold: 720.0,
|
threshold: 720.0,
|
||||||
|
metric: 'consumption_kw',
|
||||||
|
prediction_id: null,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
alert_id: 'ALR-SITE003-1718458321',
|
alert_id: 4,
|
||||||
timestamp: '2026-09-15T11:05:00',
|
|
||||||
site_id: 'SITE003',
|
site_id: 'SITE003',
|
||||||
|
timestamp: '2026-09-15T11:05:00Z',
|
||||||
|
type: 'outage',
|
||||||
severity: 'critical',
|
severity: 'critical',
|
||||||
type: 'sensor',
|
message: 'Aucune lecture depuis 5:00:00 (dernière lecture : 2026-09-15T06:05:00+00:00)',
|
||||||
message: 'Perte réseau totale sur Data Center Marseille',
|
value: null,
|
||||||
value: 0,
|
threshold: null,
|
||||||
threshold: 0,
|
metric: null,
|
||||||
|
prediction_id: null,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
alert_id: 'ALR-SITE005-1718458322',
|
alert_id: 3,
|
||||||
timestamp: '2026-09-15T10:47:00',
|
|
||||||
site_id: 'SITE005',
|
site_id: 'SITE005',
|
||||||
|
timestamp: '2026-09-15T10:47:00Z',
|
||||||
|
type: 'spike',
|
||||||
severity: 'high',
|
severity: 'high',
|
||||||
type: 'threshold',
|
message: 'Variation brutale entre deux lectures consécutives (260.0 kW -> 410.0 kW)',
|
||||||
message: 'Usine Toulouse approche de son seuil de capacité',
|
|
||||||
value: 410.0,
|
value: 410.0,
|
||||||
threshold: 480.0,
|
threshold: 260.0,
|
||||||
|
metric: 'consumption_kw',
|
||||||
|
prediction_id: null,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
alert_id: 'ALR-SITE006-1718458323',
|
alert_id: 2,
|
||||||
timestamp: '2026-09-15T10:30:00',
|
|
||||||
site_id: 'SITE006',
|
site_id: 'SITE006',
|
||||||
severity: 'medium',
|
timestamp: '2026-09-15T10:30:00Z',
|
||||||
type: 'sensor',
|
type: 'sensor',
|
||||||
message: 'Capteur de température défaillant sur Bureau Lille',
|
severity: 'medium',
|
||||||
value: 0,
|
message: 'Qualité de mesure degraded (capteur hors ligne, valeur nulle)',
|
||||||
threshold: 0,
|
value: null,
|
||||||
|
threshold: null,
|
||||||
|
metric: null,
|
||||||
|
prediction_id: null,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
alert_id: 'ALR-SITE004-1718458324',
|
alert_id: 1,
|
||||||
timestamp: '2026-09-15T09:58:00',
|
|
||||||
site_id: 'SITE004',
|
site_id: 'SITE004',
|
||||||
severity: 'low',
|
timestamp: '2026-09-15T09:58:00Z',
|
||||||
type: 'anomaly',
|
type: 'anomaly',
|
||||||
message: 'Comportement de consommation inhabituel sur Bureau Bordeaux',
|
severity: 'low',
|
||||||
|
message: 'Écart de 13% entre la consommation mesurée (62.0 kWh) et la prévision (55.0 kWh)',
|
||||||
value: 62.0,
|
value: 62.0,
|
||||||
threshold: 55.0,
|
threshold: 55.0,
|
||||||
|
metric: 'consumption_kwh',
|
||||||
|
prediction_id: 42,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -3,6 +3,20 @@ import { provideHttpClient } from '@angular/common/http';
|
|||||||
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
|
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
|
||||||
import { AlertsService } from './alerts.service';
|
import { AlertsService } from './alerts.service';
|
||||||
import { environment } from '../../../environments/environment';
|
import { environment } from '../../../environments/environment';
|
||||||
|
import { Alert } from '../../shared/models/alert.model';
|
||||||
|
|
||||||
|
const ALERT_API: Alert = {
|
||||||
|
alert_id: 1,
|
||||||
|
site_id: 'site-1',
|
||||||
|
timestamp: '2026-09-16T00:00:00Z',
|
||||||
|
type: 'threshold',
|
||||||
|
severity: 'high',
|
||||||
|
message: 'Dépassement du seuil configuré',
|
||||||
|
value: 812.5,
|
||||||
|
threshold: 720.0,
|
||||||
|
metric: 'consumption_kw',
|
||||||
|
prediction_id: null,
|
||||||
|
};
|
||||||
|
|
||||||
describe('AlertsService', () => {
|
describe('AlertsService', () => {
|
||||||
let service: AlertsService;
|
let service: AlertsService;
|
||||||
@@ -18,26 +32,35 @@ describe('AlertsService', () => {
|
|||||||
|
|
||||||
afterEach(() => httpMock.verify());
|
afterEach(() => httpMock.verify());
|
||||||
|
|
||||||
it("appelle le bon endpoint et retourne un tableau d'alertes", () => {
|
it("appelle le bon endpoint sans paramètre et retourne un tableau d'alertes", () => {
|
||||||
let result: unknown;
|
let result: Alert[] = [];
|
||||||
service.getAlerts().subscribe((r) => (result = r));
|
service.getAlerts().subscribe((r) => (result = r));
|
||||||
|
|
||||||
const req = httpMock.expectOne(`${environment.apiUrl}/alerts`);
|
const req = httpMock.expectOne(
|
||||||
expect(req.request.method).toBe('GET');
|
(r) => r.url === `${environment.apiUrl}/alerts` && r.method === 'GET',
|
||||||
|
);
|
||||||
|
expect(req.request.params.keys()).toEqual([]);
|
||||||
|
req.flush([ALERT_API]);
|
||||||
|
|
||||||
req.flush([
|
expect(result.length).toBe(1);
|
||||||
{
|
expect(result[0].alert_id).toBe(1);
|
||||||
alert_id: 'ALR-TEST-1',
|
expect(result[0].prediction_id).toBeNull();
|
||||||
timestamp: '2026-09-15T12:00:00',
|
});
|
||||||
site_id: 'SITE001',
|
|
||||||
severity: 'high',
|
|
||||||
type: 'threshold',
|
|
||||||
message: 'Test',
|
|
||||||
value: 100,
|
|
||||||
threshold: 90,
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
|
|
||||||
expect((result as unknown[]).length).toBe(1);
|
it('transmet les filtres site_id et severity en paramètres de requête', () => {
|
||||||
|
service.getAlerts({ site_id: 'SITE001', severity: 'high' }).subscribe();
|
||||||
|
|
||||||
|
const req = httpMock.expectOne((r) => r.url === `${environment.apiUrl}/alerts`);
|
||||||
|
expect(req.request.params.get('site_id')).toBe('SITE001');
|
||||||
|
expect(req.request.params.get('severity')).toBe('high');
|
||||||
|
req.flush([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ne pose pas de paramètre pour un filtre omis', () => {
|
||||||
|
service.getAlerts({ site_id: 'SITE001' }).subscribe();
|
||||||
|
|
||||||
|
const req = httpMock.expectOne((r) => r.url === `${environment.apiUrl}/alerts`);
|
||||||
|
expect(req.request.params.has('severity')).toBe(false);
|
||||||
|
req.flush([]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,13 +1,25 @@
|
|||||||
import { Service, inject } from '@angular/core';
|
import { Service, inject } from '@angular/core';
|
||||||
import { HttpClient } from '@angular/common/http';
|
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||||
import { environment } from '../../../environments/environment';
|
import { environment } from '../../../environments/environment';
|
||||||
import { Alert } from '../../shared/models/alert.model';
|
import { Alert, AlertSeverity } from '../../shared/models/alert.model';
|
||||||
|
|
||||||
|
export interface AlertFilters {
|
||||||
|
site_id?: string;
|
||||||
|
severity?: AlertSeverity;
|
||||||
|
}
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export class AlertsService {
|
export class AlertsService {
|
||||||
private http = inject(HttpClient);
|
private http = inject(HttpClient);
|
||||||
|
|
||||||
getAlerts() {
|
getAlerts(filters: AlertFilters = {}) {
|
||||||
return this.http.get<Alert[]>(`${environment.apiUrl}/alerts`);
|
let params = new HttpParams();
|
||||||
|
if (filters.site_id) {
|
||||||
|
params = params.set('site_id', filters.site_id);
|
||||||
|
}
|
||||||
|
if (filters.severity) {
|
||||||
|
params = params.set('severity', filters.severity);
|
||||||
|
}
|
||||||
|
return this.http.get<Alert[]>(`${environment.apiUrl}/alerts`, { params });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
|
||||||
|
import { RecommendationsService } from './recommendations.service';
|
||||||
|
import { environment } from '../../../environments/environment';
|
||||||
|
import { Recommendation } from '../../shared/models/recommendation.model';
|
||||||
|
|
||||||
|
const RECOMMANDATION_API: Recommendation = {
|
||||||
|
recommendation_id: 1,
|
||||||
|
alert_id: 1,
|
||||||
|
action: 'Vérifier la consommation',
|
||||||
|
explanation: 'Pic détecté',
|
||||||
|
rule_reference: 'spike-v1',
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('RecommendationsService', () => {
|
||||||
|
let service: RecommendationsService;
|
||||||
|
let httpMock: HttpTestingController;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [provideHttpClient(), provideHttpClientTesting()],
|
||||||
|
});
|
||||||
|
service = TestBed.inject(RecommendationsService);
|
||||||
|
httpMock = TestBed.inject(HttpTestingController);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => httpMock.verify());
|
||||||
|
|
||||||
|
it('liste les recommandations depuis le bon endpoint', () => {
|
||||||
|
let result: Recommendation[] = [];
|
||||||
|
service.getRecommendations().subscribe((r) => (result = r));
|
||||||
|
|
||||||
|
const req = httpMock.expectOne(`${environment.apiUrl}/recommendations`);
|
||||||
|
expect(req.request.method).toBe('GET');
|
||||||
|
req.flush([RECOMMANDATION_API]);
|
||||||
|
|
||||||
|
expect(result.length).toBe(1);
|
||||||
|
expect(result[0].alert_id).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('décrit une recommandation par son identifiant', () => {
|
||||||
|
service.getRecommendation(42).subscribe();
|
||||||
|
|
||||||
|
const req = httpMock.expectOne(`${environment.apiUrl}/recommendations/42`);
|
||||||
|
expect(req.request.method).toBe('GET');
|
||||||
|
req.flush({ ...RECOMMANDATION_API, recommendation_id: 42 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('déclenche la génération en POST avec le site en paramètre de requête', () => {
|
||||||
|
let result: unknown;
|
||||||
|
service.generate('SITE001').subscribe((r) => (result = r));
|
||||||
|
|
||||||
|
const req = httpMock.expectOne(
|
||||||
|
(r) => r.url === `${environment.apiUrl}/recommendations/generate` && r.method === 'POST',
|
||||||
|
);
|
||||||
|
expect(req.request.params.get('site_id')).toBe('SITE001');
|
||||||
|
expect(req.request.body).toBeNull();
|
||||||
|
req.flush({ alerts_examined: 2, recommendations_created: 3, already_present: 1 });
|
||||||
|
|
||||||
|
expect(result).toEqual({ alerts_examined: 2, recommendations_created: 3, already_present: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('génère pour tout le parc quand aucun site n’est donné', () => {
|
||||||
|
service.generate().subscribe();
|
||||||
|
|
||||||
|
const req = httpMock.expectOne(
|
||||||
|
(r) => r.url === `${environment.apiUrl}/recommendations/generate` && r.method === 'POST',
|
||||||
|
);
|
||||||
|
expect(req.request.params.has('site_id')).toBe(false);
|
||||||
|
req.flush({ alerts_examined: 0, recommendations_created: 0, already_present: 0 });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { Service, inject } from '@angular/core';
|
||||||
|
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||||
|
import { environment } from '../../../environments/environment';
|
||||||
|
import {
|
||||||
|
Recommendation,
|
||||||
|
RecommendationGenerationReport,
|
||||||
|
} from '../../shared/models/recommendation.model';
|
||||||
|
|
||||||
|
@Service()
|
||||||
|
export class RecommendationsService {
|
||||||
|
private http = inject(HttpClient);
|
||||||
|
|
||||||
|
getRecommendations() {
|
||||||
|
return this.http.get<Recommendation[]>(`${environment.apiUrl}/recommendations`);
|
||||||
|
}
|
||||||
|
|
||||||
|
getRecommendation(recommendationId: number) {
|
||||||
|
return this.http.get<Recommendation>(
|
||||||
|
`${environment.apiUrl}/recommendations/${recommendationId}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
generate(siteId?: string) {
|
||||||
|
let params = new HttpParams();
|
||||||
|
if (siteId) {
|
||||||
|
params = params.set('site_id', siteId);
|
||||||
|
}
|
||||||
|
return this.http.post<RecommendationGenerationReport>(
|
||||||
|
`${environment.apiUrl}/recommendations/generate`,
|
||||||
|
null,
|
||||||
|
{ params },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
|
||||||
|
import { SensorsService } from './sensors.service';
|
||||||
|
import { environment } from '../../../environments/environment';
|
||||||
|
|
||||||
|
describe('SensorsService', () => {
|
||||||
|
let service: SensorsService;
|
||||||
|
let httpMock: HttpTestingController;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [provideHttpClient(), provideHttpClientTesting()],
|
||||||
|
});
|
||||||
|
service = TestBed.inject(SensorsService);
|
||||||
|
httpMock = TestBed.inject(HttpTestingController);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => httpMock.verify());
|
||||||
|
|
||||||
|
it("appelle l'endpoint /sensors/status et retourne la réponse", () => {
|
||||||
|
let result: unknown;
|
||||||
|
service.getStatus().subscribe((r) => (result = r));
|
||||||
|
|
||||||
|
const req = httpMock.expectOne(`${environment.apiUrl}/sensors/status`);
|
||||||
|
expect(req.request.method).toBe('GET');
|
||||||
|
|
||||||
|
req.flush({
|
||||||
|
timestamp: '2026-09-18T08:00:00',
|
||||||
|
sites: [
|
||||||
|
{
|
||||||
|
site_id: 'SITE001',
|
||||||
|
site_name: 'Test',
|
||||||
|
overall: 'ok',
|
||||||
|
sensors: {
|
||||||
|
consumption: { status: 'ok', since: null },
|
||||||
|
electrical: { status: 'ok', since: null },
|
||||||
|
temperature: { status: 'ok', since: null },
|
||||||
|
humidity: { status: 'ok', since: null },
|
||||||
|
network: { status: 'ok', since: 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 {SensorStatusResponse} from '../../shared/models/sensor-status.model';
|
||||||
|
|
||||||
|
@Service()
|
||||||
|
export class SensorsService {
|
||||||
|
private http = inject(HttpClient);
|
||||||
|
|
||||||
|
getStatus() {
|
||||||
|
return this.http.get<SensorStatusResponse>(`${environment.apiUrl}/sensors/status`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,7 +10,11 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="dashboard__actions">
|
<div class="dashboard__actions">
|
||||||
|
@if (auth.principal()?.role === 'admin') {
|
||||||
|
<a routerLink="/monitoring/sensors" class="ev-link">Supervision des capteurs</a>
|
||||||
|
}
|
||||||
<a routerLink="/sites" class="ev-link">Voir les sites</a>
|
<a routerLink="/sites" class="ev-link">Voir les sites</a>
|
||||||
|
<a routerLink="/recommendations" class="ev-link">Recommandations</a>
|
||||||
<ev-button
|
<ev-button
|
||||||
class="logout-button"
|
class="logout-button"
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
@@ -24,87 +28,120 @@
|
|||||||
@if (statsError(); as message) {
|
@if (statsError(); as message) {
|
||||||
<ev-alert severity="danger" class="banner-error">{{ message }}</ev-alert>
|
<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) {
|
@if (predictionsError(); as message) {
|
||||||
<ev-alert severity="danger" class="banner-error">{{ message }}</ev-alert>
|
<ev-alert severity="danger" class="banner-error">{{ message }}</ev-alert>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (stats(); as s) {
|
@if (stats(); as s) {
|
||||||
<section class="overview">
|
<p class="dashboard__status">
|
||||||
<ev-card class="card card--gauge">
|
<span class="dashboard__pulse" aria-hidden="true"></span>
|
||||||
<span class="card__label">Consommation vs capacité</span>
|
Actualisé à {{ s.timestamp | date: 'HH:mm:ss' }} · {{ s.total_sites }} sites suivis
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<section class="overview" aria-label="Indicateurs du parc">
|
||||||
|
<ev-card class="kpi kpi--gauge">
|
||||||
|
<span class="kpi__label">Consommation vs capacité</span>
|
||||||
<app-consumption-gauge
|
<app-consumption-gauge
|
||||||
[consumption]="s.total_consumption_kw"
|
[consumption]="s.total_consumption_kw"
|
||||||
[capacity]="s.total_capacity_kw"
|
[capacity]="s.total_capacity_kw"
|
||||||
/>
|
/>
|
||||||
<span class="card__value"
|
<span class="kpi__value">
|
||||||
>{{ s.total_consumption_kw | number: '1.0-1' }} /
|
{{ s.total_consumption_kw | number: '1.0-1' }}
|
||||||
{{ s.total_capacity_kw | number }} kW</span
|
<small>/ {{ s.total_capacity_kw | number }} kW</small>
|
||||||
|
</span>
|
||||||
|
</ev-card>
|
||||||
|
|
||||||
|
<ev-card class="kpi">
|
||||||
|
<span class="kpi__label">Charge moyenne du parc</span>
|
||||||
|
<span class="kpi__value"
|
||||||
|
>{{ s.average_load_percent | number: '1.0-0' }} <small>%</small></span
|
||||||
>
|
>
|
||||||
</ev-card>
|
<div
|
||||||
|
class="progress-bar"
|
||||||
<ev-card class="card">
|
role="progressbar"
|
||||||
<span class="card__label">Charge moyenne du parc</span>
|
aria-valuemin="0"
|
||||||
<span class="card__value">{{ s.average_load_percent }} %</span>
|
aria-valuemax="100"
|
||||||
<div class="progress-bar">
|
[attr.aria-valuenow]="s.average_load_percent"
|
||||||
<div class="progress-bar__fill" [style.width.%]="s.average_load_percent"></div>
|
>
|
||||||
|
<div
|
||||||
|
class="progress-bar__fill"
|
||||||
|
[class]="'progress-bar__fill--' + loadTone(s.average_load_percent)"
|
||||||
|
[style.width.%]="s.average_load_percent"
|
||||||
|
></div>
|
||||||
</div>
|
</div>
|
||||||
|
<span class="kpi__hint">{{ loadHint(s.average_load_percent) }}</span>
|
||||||
</ev-card>
|
</ev-card>
|
||||||
|
|
||||||
<ev-card class="card">
|
<ev-card class="kpi">
|
||||||
<span class="card__label">Sites suivis</span>
|
<span class="kpi__label">Sites suivis</span>
|
||||||
<span class="card__value">{{ s.total_sites }}</span>
|
<span class="kpi__value">{{ s.total_sites }}</span>
|
||||||
|
<a routerLink="/sites" class="ev-link kpi__link">Voir la liste des sites</a>
|
||||||
</ev-card>
|
</ev-card>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="chart-section">
|
|
||||||
<h2>Charge et alerte visuelle par site</h2>
|
|
||||||
<app-site-load-chart [sites]="s.sites" />
|
|
||||||
</section>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (alerts().length > 0) {
|
<div class="dashboard__grid">
|
||||||
<section class="alerts-section">
|
<div class="dashboard__main">
|
||||||
<h2>Alertes actives</h2>
|
@if (stats(); as s) {
|
||||||
<ul class="alerts-list">
|
<section class="chart-section">
|
||||||
@for (alert of alerts(); track alert.alert_id) {
|
<h2>Charge par site</h2>
|
||||||
<li class="alert-item">
|
<ev-card class="chart-card">
|
||||||
<ev-badge [tone]="badgeToneForSeverity(alert.severity)">{{ alert.severity }}</ev-badge>
|
<app-site-load-chart [sites]="s.sites" />
|
||||||
<span class="alert-item__message">{{ alert.message }}</span>
|
</ev-card>
|
||||||
</li>
|
</section>
|
||||||
|
}
|
||||||
|
|
||||||
|
<section class="predictions-section">
|
||||||
|
<h2>Prévisions de consommation</h2>
|
||||||
|
@if (predictions().length > 0) {
|
||||||
|
<ev-card class="ev-table-card">
|
||||||
|
<table class="ev-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Site</th>
|
||||||
|
<th>Prévision</th>
|
||||||
|
<th>Échéance</th>
|
||||||
|
<th></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@for (site of predictions(); track site.site_id) {
|
||||||
|
<tr>
|
||||||
|
<td>{{ site.site_name }}</td>
|
||||||
|
@if (site.prediction; as prediction) {
|
||||||
|
@if (prediction.status === 'available') {
|
||||||
|
<td class="ev-table__number">
|
||||||
|
{{ prediction.predicted_value | number: '1.0-1' }} kWh
|
||||||
|
</td>
|
||||||
|
<td>{{ prediction.target_at | date: "dd/MM 'à' HH:mm" }}</td>
|
||||||
|
} @else {
|
||||||
|
<td>
|
||||||
|
<ev-badge [tone]="badgeToneForPredictionStatus(prediction.status)">{{
|
||||||
|
prediction.status === 'insufficient_data'
|
||||||
|
? 'Historique insuffisant'
|
||||||
|
: 'Erreur'
|
||||||
|
}}</ev-badge>
|
||||||
|
</td>
|
||||||
|
<td class="ev-table__muted">-</td>
|
||||||
|
}
|
||||||
|
} @else {
|
||||||
|
<td><ev-badge tone="neutral">Pas encore de prévision</ev-badge></td>
|
||||||
|
<td class="ev-table__muted">-</td>
|
||||||
|
}
|
||||||
|
<td><a [routerLink]="['/sites', site.site_id]" class="ev-link">Détail</a></td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</ev-card>
|
||||||
|
} @else if (!predictionsError()) {
|
||||||
|
<p class="dashboard__empty">Aucune prévision disponible pour le moment.</p>
|
||||||
}
|
}
|
||||||
</ul>
|
</section>
|
||||||
</section>
|
</div>
|
||||||
}
|
|
||||||
|
|
||||||
@if (predictions().length > 0) {
|
<aside class="dashboard__side" aria-label="Alertes actives">
|
||||||
<section class="predictions-section">
|
<app-alert-feed />
|
||||||
<h2>Prévisions de consommation</h2>
|
</aside>
|
||||||
<ul class="predictions-list">
|
</div>
|
||||||
@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>
|
||||||
|
|||||||
@@ -8,9 +8,11 @@
|
|||||||
|
|
||||||
.dashboard__header {
|
.dashboard__header {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
align-items: flex-start;
|
align-items: flex-start;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
margin-bottom: 2rem;
|
gap: var(--space-3);
|
||||||
|
margin-bottom: var(--space-3);
|
||||||
}
|
}
|
||||||
|
|
||||||
.dashboard__brand {
|
.dashboard__brand {
|
||||||
@@ -20,8 +22,9 @@
|
|||||||
|
|
||||||
h1 {
|
h1 {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
font-size: 1.75rem;
|
font-size: var(--font-size-xl);
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
|
letter-spacing: -0.01em;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,19 +34,69 @@
|
|||||||
|
|
||||||
.dashboard__subtitle {
|
.dashboard__subtitle {
|
||||||
margin: 0.25rem 0 0;
|
margin: 0.25rem 0 0;
|
||||||
|
font-size: var(--font-size-sm);
|
||||||
color: var(--color-text-muted);
|
color: var(--color-text-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
.dashboard__actions {
|
.dashboard__actions {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 1rem;
|
gap: var(--space-2);
|
||||||
|
|
||||||
|
.ev-link {
|
||||||
|
padding: 0.45rem 0.9rem;
|
||||||
|
border-radius: var(--radius-pill);
|
||||||
|
background: var(--color-primary-light);
|
||||||
|
color: var(--color-primary-hover);
|
||||||
|
font-size: var(--font-size-sm);
|
||||||
|
transition: background 0.15s ease;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: var(--color-primary);
|
||||||
|
color: var(--color-text-inverse);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.dashboard__status {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-2);
|
||||||
|
margin: 0 0 var(--space-4);
|
||||||
|
font-size: var(--font-size-sm);
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.dashboard__pulse {
|
||||||
|
width: 0.6rem;
|
||||||
|
height: 0.6rem;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--color-success);
|
||||||
|
animation: pulse 2s ease-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes pulse {
|
||||||
|
0% {
|
||||||
|
box-shadow: 0 0 0 0 rgba(22, 163, 74, 0.45);
|
||||||
|
}
|
||||||
|
|
||||||
|
100% {
|
||||||
|
box-shadow: 0 0 0 8px rgba(22, 163, 74, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.dashboard__pulse {
|
||||||
|
animation: none;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
h2 {
|
h2 {
|
||||||
font-size: 1.1rem;
|
margin: 0 0 var(--space-3);
|
||||||
|
font-size: var(--font-size-lg);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
margin: 0 0 1rem;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.banner-error {
|
.banner-error {
|
||||||
@@ -54,107 +107,124 @@ h2 {
|
|||||||
.overview {
|
.overview {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||||
gap: 1rem;
|
gap: var(--space-3);
|
||||||
margin-bottom: 2.5rem;
|
margin-bottom: var(--space-5);
|
||||||
}
|
}
|
||||||
|
|
||||||
.card {
|
.kpi {
|
||||||
padding: 1.25rem;
|
position: relative;
|
||||||
gap: 0.35rem;
|
overflow: hidden;
|
||||||
|
padding: var(--space-4);
|
||||||
|
gap: var(--space-1);
|
||||||
|
transition:
|
||||||
|
box-shadow 0.15s ease,
|
||||||
|
transform 0.15s ease;
|
||||||
|
|
||||||
|
&::before {
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
inset: 0 0 auto 0;
|
||||||
|
height: 3px;
|
||||||
|
background: var(--color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
box-shadow: var(--shadow-card-hover);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.card--gauge {
|
.kpi--gauge {
|
||||||
align-items: center;
|
align-items: center;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.card__label {
|
.kpi__label {
|
||||||
font-size: 0.8rem;
|
font-size: var(--font-size-xs);
|
||||||
|
font-weight: 600;
|
||||||
color: var(--color-text-muted);
|
color: var(--color-text-muted);
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
letter-spacing: 0.02em;
|
letter-spacing: 0.06em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.card__value {
|
.kpi__value {
|
||||||
font-size: 1.6rem;
|
font-size: var(--font-size-2xl);
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
|
line-height: 1.1;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
|
||||||
|
small {
|
||||||
|
font-size: var(--font-size-sm);
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.kpi__hint {
|
||||||
|
font-size: var(--font-size-xs);
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.kpi__link {
|
||||||
|
margin-top: auto;
|
||||||
|
font-size: var(--font-size-sm);
|
||||||
}
|
}
|
||||||
|
|
||||||
.progress-bar {
|
.progress-bar {
|
||||||
height: 6px;
|
height: 8px;
|
||||||
|
margin: var(--space-1) 0;
|
||||||
background: var(--color-border-light);
|
background: var(--color-border-light);
|
||||||
border-radius: var(--radius-pill);
|
border-radius: var(--radius-pill);
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
margin-top: 0.25rem;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.progress-bar__fill {
|
.progress-bar__fill {
|
||||||
height: 100%;
|
height: 100%;
|
||||||
background: var(--color-primary);
|
|
||||||
border-radius: var(--radius-pill);
|
border-radius: var(--radius-pill);
|
||||||
|
background: var(--color-success);
|
||||||
transition: width 0.3s ease;
|
transition: width 0.3s ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.progress-bar__fill--warning {
|
||||||
|
background: var(--color-warning);
|
||||||
|
}
|
||||||
|
|
||||||
|
.progress-bar__fill--danger {
|
||||||
|
background: var(--color-danger);
|
||||||
|
}
|
||||||
|
|
||||||
|
.dashboard__grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr) minmax(320px, 380px);
|
||||||
|
gap: var(--space-4);
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dashboard__side {
|
||||||
|
position: sticky;
|
||||||
|
top: var(--space-3);
|
||||||
|
}
|
||||||
|
|
||||||
.chart-section {
|
.chart-section {
|
||||||
margin-bottom: 2.5rem;
|
margin-bottom: var(--space-5);
|
||||||
}
|
}
|
||||||
|
|
||||||
.alerts-list {
|
.chart-card {
|
||||||
list-style: none;
|
padding: var(--space-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.dashboard__empty {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0;
|
font-size: var(--font-size-sm);
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 0.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.alert-item {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 0.75rem;
|
|
||||||
padding: 0.7rem 1rem;
|
|
||||||
border-radius: var(--radius-md);
|
|
||||||
background: var(--color-danger-bg);
|
|
||||||
border: 1px solid var(--color-danger-border);
|
|
||||||
}
|
|
||||||
|
|
||||||
.alert-item__message {
|
|
||||||
font-size: 0.9rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.predictions-list {
|
|
||||||
list-style: none;
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 0.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.prediction-item {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: space-between;
|
|
||||||
gap: 0.75rem;
|
|
||||||
padding: 0.7rem 1rem;
|
|
||||||
border-radius: var(--radius-md);
|
|
||||||
background: var(--color-surface);
|
|
||||||
border: 1px solid var(--color-border-light);
|
|
||||||
}
|
|
||||||
|
|
||||||
.prediction-item__site {
|
|
||||||
font-size: 0.9rem;
|
|
||||||
font-weight: 600;
|
|
||||||
}
|
|
||||||
|
|
||||||
.prediction-item__value {
|
|
||||||
font-size: 0.9rem;
|
|
||||||
font-weight: 600;
|
|
||||||
}
|
|
||||||
|
|
||||||
.prediction-item__target {
|
|
||||||
margin-left: 0.35rem;
|
|
||||||
font-size: 0.8rem;
|
|
||||||
font-weight: 400;
|
|
||||||
color: var(--color-text-muted);
|
color: var(--color-text-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.dashboard__grid {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dashboard__side {
|
||||||
|
position: static;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { vi } from 'vitest';
|
import { vi } from 'vitest';
|
||||||
import { of, throwError } from 'rxjs';
|
import { Observable, of, throwError } from 'rxjs';
|
||||||
|
import { Router, provideRouter } from '@angular/router';
|
||||||
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 { SitesService } from '../../core/services/sites.service';
|
||||||
import { PredictionsService } from '../../core/services/predictions.service';
|
import { PredictionsService } from '../../core/services/predictions.service';
|
||||||
import {AuthService} from '../../core/services/auth.service';
|
import { AuthService } from '../../core/services/auth.service';
|
||||||
import {Router, provideRouter} from '@angular/router';
|
|
||||||
|
|
||||||
vi.mock('chart.js', () => {
|
vi.mock('chart.js', () => {
|
||||||
class ChartMock {
|
class ChartMock {
|
||||||
@@ -18,66 +19,73 @@ vi.mock('chart.js', () => {
|
|||||||
return { Chart: ChartMock, registerables: [] };
|
return { Chart: ChartMock, registerables: [] };
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const STATS = { total_sites: 7, sites: [] };
|
||||||
|
|
||||||
function predictionsMock(sites: unknown[] = []) {
|
function predictionsMock(sites: unknown[] = []) {
|
||||||
return { getPredictions: vi.fn().mockReturnValue(of({ timestamp: '2026-09-18T09:00:00Z', sites })) };
|
return {
|
||||||
|
getPredictions: vi.fn().mockReturnValue(of({ timestamp: '2026-09-18T09:00:00Z', sites })),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function setup(
|
||||||
|
options: {
|
||||||
|
stats?: Observable<unknown>;
|
||||||
|
predictions?: { getPredictions: ReturnType<typeof vi.fn> };
|
||||||
|
auth?: Record<string, unknown>;
|
||||||
|
} = {},
|
||||||
|
) {
|
||||||
|
const statsMock = { getSummary: vi.fn().mockReturnValue(options.stats ?? of(STATS)) };
|
||||||
|
const predictions = options.predictions ?? predictionsMock();
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [Dashboard],
|
||||||
|
providers: [
|
||||||
|
{ provide: StatsService, useValue: statsMock },
|
||||||
|
{ provide: AlertsService, useValue: { getAlerts: vi.fn().mockReturnValue(of([])) } },
|
||||||
|
{ provide: SitesService, useValue: { getSites: vi.fn().mockReturnValue(of([])) } },
|
||||||
|
{ provide: PredictionsService, useValue: predictions },
|
||||||
|
...(options.auth ? [{ provide: AuthService, useValue: options.auth }] : []),
|
||||||
|
provideRouter([]),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
return { fixture: TestBed.createComponent(Dashboard), statsMock, predictions };
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('Dashboard', () => {
|
describe('Dashboard', () => {
|
||||||
afterEach(() => vi.useRealTimers());
|
afterEach(() => vi.useRealTimers());
|
||||||
|
|
||||||
it('charge les stats, les alertes et les prévisions au démarrage', async () => {
|
it('charge les stats et les prévisions au démarrage', async () => {
|
||||||
const statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
const { fixture, statsMock, predictions } = setup({
|
||||||
const alertsMock = { getAlerts: vi.fn().mockReturnValue(of([{ alert_id: 'A1' }])) };
|
predictions: predictionsMock([{ site_id: 'SITE001', site_name: 'Test', prediction: null }]),
|
||||||
const predictions = predictionsMock([{ site_id: 'SITE001', site_name: 'Test', prediction: null }]);
|
|
||||||
|
|
||||||
TestBed.configureTestingModule({
|
|
||||||
imports: [Dashboard],
|
|
||||||
providers: [
|
|
||||||
{ provide: StatsService, useValue: statsMock },
|
|
||||||
{ provide: AlertsService, useValue: alertsMock },
|
|
||||||
{ provide: PredictionsService, useValue: predictions },
|
|
||||||
provideRouter([]),
|
|
||||||
],
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(Dashboard);
|
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
// laisse le timer(0, ...) se déclencher avant de vérifier
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
expect(statsMock.getSummary).toHaveBeenCalled();
|
expect(statsMock.getSummary).toHaveBeenCalled();
|
||||||
expect(alertsMock.getAlerts).toHaveBeenCalled();
|
|
||||||
expect(predictions.getPredictions).toHaveBeenCalled();
|
expect(predictions.getPredictions).toHaveBeenCalled();
|
||||||
expect(fixture.componentInstance.alerts().length).toBe(1);
|
|
||||||
expect(fixture.componentInstance.predictions().length).toBe(1);
|
expect(fixture.componentInstance.predictions().length).toBe(1);
|
||||||
expect(fixture.componentInstance.statsError()).toBeNull();
|
expect(fixture.componentInstance.statsError()).toBeNull();
|
||||||
expect(fixture.componentInstance.alertsError()).toBeNull();
|
|
||||||
expect(fixture.componentInstance.predictionsError()).toBeNull();
|
expect(fixture.componentInstance.predictionsError()).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('délègue les alertes au widget app-alert-feed', () => {
|
||||||
|
const { fixture } = setup();
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.nativeElement.querySelector('app-alert-feed')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
it("signale l'indisponibilité puis repart au rafraîchissement suivant", () => {
|
it("signale l'indisponibilité puis repart au rafraîchissement suivant", () => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
const statsMock = {
|
const { fixture, statsMock } = setup({
|
||||||
getSummary: vi
|
stats: throwError(() => new Error('API injoignable')),
|
||||||
.fn()
|
|
||||||
.mockReturnValueOnce(throwError(() => new Error('API injoignable')))
|
|
||||||
.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([]),
|
|
||||||
],
|
|
||||||
});
|
});
|
||||||
|
statsMock.getSummary
|
||||||
|
.mockReturnValueOnce(throwError(() => new Error('API injoignable')))
|
||||||
|
.mockReturnValue(of(STATS));
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(Dashboard);
|
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
vi.advanceTimersByTime(1);
|
vi.advanceTimersByTime(1);
|
||||||
@@ -91,45 +99,11 @@ describe('Dashboard', () => {
|
|||||||
expect(fixture.componentInstance.statsError()).toBeNull();
|
expect(fixture.componentInstance.statsError()).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("n'interrompt pas la page quand le chargement des alertes échoue", () => {
|
|
||||||
const statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
|
||||||
const alertsMock = { getAlerts: vi.fn().mockReturnValue(throwError(() => new Error('nope'))) };
|
|
||||||
|
|
||||||
TestBed.configureTestingModule({
|
|
||||||
imports: [Dashboard],
|
|
||||||
providers: [
|
|
||||||
{ provide: StatsService, useValue: statsMock },
|
|
||||||
{ provide: AlertsService, useValue: alertsMock },
|
|
||||||
{ provide: PredictionsService, useValue: predictionsMock() },
|
|
||||||
provideRouter([]),
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(Dashboard);
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
expect(fixture.componentInstance.alerts().length).toBe(0);
|
|
||||||
expect(fixture.componentInstance.alertsError()).not.toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("n'interrompt pas la page quand le chargement des prévisions échoue", () => {
|
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 { fixture } = setup({
|
||||||
const alertsMock = { getAlerts: vi.fn().mockReturnValue(of([])) };
|
predictions: { getPredictions: vi.fn().mockReturnValue(throwError(() => new Error('nope'))) },
|
||||||
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();
|
fixture.detectChanges();
|
||||||
|
|
||||||
expect(fixture.componentInstance.predictions().length).toBe(0);
|
expect(fixture.componentInstance.predictions().length).toBe(0);
|
||||||
@@ -138,25 +112,11 @@ describe('Dashboard', () => {
|
|||||||
|
|
||||||
it("un rafraîchissement de stats n'efface pas une erreur de prévisions en attente", () => {
|
it("un rafraîchissement de stats n'efface pas une erreur de prévisions en attente", () => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
const statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
const { fixture } = setup({
|
||||||
const alertsMock = { getAlerts: vi.fn().mockReturnValue(of([])) };
|
predictions: { getPredictions: vi.fn().mockReturnValue(throwError(() => new Error('nope'))) },
|
||||||
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();
|
fixture.detectChanges();
|
||||||
|
|
||||||
expect(fixture.componentInstance.predictionsError()).not.toBeNull();
|
expect(fixture.componentInstance.predictionsError()).not.toBeNull();
|
||||||
|
|
||||||
// Plusieurs cycles de `timer(0, 10_000)` (stats) plus tard, l'erreur des prévisions doit
|
// Plusieurs cycles de `timer(0, 10_000)` (stats) plus tard, l'erreur des prévisions doit
|
||||||
@@ -168,105 +128,106 @@ describe('Dashboard', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('appelle logout et redirige vers /login au clic sur le bouton de déconnexion', () => {
|
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 authMock = {
|
||||||
const alertsMock = { getAlerts: vi.fn().mockReturnValue(of([])) };
|
logout: vi.fn().mockReturnValue(of(undefined)),
|
||||||
const authMock = { logout: vi.fn().mockReturnValue(of(undefined)), clearSession: vi.fn() };
|
clearSession: vi.fn(),
|
||||||
|
principal: vi.fn().mockReturnValue({ role: 'admin' }),
|
||||||
|
};
|
||||||
|
const { fixture } = setup({ auth: authMock });
|
||||||
|
fixture.detectChanges();
|
||||||
|
const router = TestBed.inject(Router);
|
||||||
|
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||||
|
|
||||||
TestBed.configureTestingModule({
|
fixture.nativeElement.querySelector('.logout-button').click();
|
||||||
imports: [Dashboard],
|
|
||||||
providers: [
|
expect(authMock.logout).toHaveBeenCalled();
|
||||||
{ provide: StatsService, useValue: statsMock },
|
expect(navigateSpy).toHaveBeenCalledWith(['/login']);
|
||||||
{ 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');
|
|
||||||
button.click();
|
|
||||||
|
|
||||||
expect(authMock.logout).toHaveBeenCalled();
|
|
||||||
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 authMock = {
|
||||||
const alertsMock = { getAlerts: vi.fn().mockReturnValue(of([])) };
|
logout: vi.fn().mockReturnValue(throwError(() => new Error('réseau indisponible'))),
|
||||||
const authMock = {
|
clearSession: vi.fn(),
|
||||||
logout: vi.fn().mockReturnValue(throwError(() => new Error('réseau indisponible'))),
|
principal: vi.fn().mockReturnValue({ role: 'admin' }),
|
||||||
clearSession: vi.fn(),
|
};
|
||||||
};
|
const { fixture } = setup({ auth: authMock });
|
||||||
TestBed.configureTestingModule({
|
fixture.detectChanges();
|
||||||
imports: [Dashboard],
|
const router = TestBed.inject(Router);
|
||||||
providers: [
|
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||||
{ provide: StatsService, useValue: statsMock },
|
|
||||||
{ provide: AlertsService, useValue: alertsMock },
|
fixture.nativeElement.querySelector('.logout-button').click();
|
||||||
{ provide: PredictionsService, useValue: predictionsMock() },
|
|
||||||
{ provide: AuthService, useValue: authMock },
|
expect(authMock.clearSession).toHaveBeenCalled();
|
||||||
provideRouter([]),
|
expect(navigateSpy).toHaveBeenCalledWith(['/login']);
|
||||||
],
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(Dashboard);
|
it('affiche l’heure du dernier relevé et les indicateurs du parc', () => {
|
||||||
fixture.detectChanges();
|
vi.useFakeTimers();
|
||||||
|
const { fixture } = setup({
|
||||||
const router = TestBed.inject(Router);
|
stats: of({
|
||||||
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
timestamp: '2026-09-18T09:00:00Z',
|
||||||
|
total_sites: 7,
|
||||||
const button = fixture.nativeElement.querySelector('.logout-button');
|
total_consumption_kw: 1234.5,
|
||||||
button.click();
|
total_capacity_kw: 5000,
|
||||||
|
average_load_percent: 24.7,
|
||||||
expect(authMock.clearSession).toHaveBeenCalled();
|
sites: [],
|
||||||
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);
|
fixture.detectChanges();
|
||||||
|
vi.advanceTimersByTime(1);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const texte = fixture.nativeElement.textContent as string;
|
||||||
|
expect(texte).toContain('Actualisé à');
|
||||||
|
expect(texte).toContain('7 sites suivis');
|
||||||
|
expect(texte).toContain('Marge confortable');
|
||||||
|
expect(fixture.nativeElement.querySelector('.progress-bar__fill--success')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('présente les prévisions en tableau avec un lien vers chaque site', () => {
|
||||||
|
const { fixture } = setup({
|
||||||
|
predictions: predictionsMock([
|
||||||
|
{
|
||||||
|
site_id: 'SITE001',
|
||||||
|
site_name: 'Usine Nantes',
|
||||||
|
prediction: {
|
||||||
|
target_at: '2026-09-18T10:00:00Z',
|
||||||
|
target_metric: 'consumption_kwh',
|
||||||
|
period_minutes: 60,
|
||||||
|
predicted_value: 118.4,
|
||||||
|
status: 'available',
|
||||||
|
failure_reason: null,
|
||||||
|
model_reference: 'lightgbm-v1',
|
||||||
|
created_at: '2026-09-18T09:00:00Z',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ site_id: 'SITE002', site_name: 'Bureau Lille', prediction: null },
|
||||||
|
]),
|
||||||
|
});
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const table = fixture.nativeElement.querySelector('table.ev-table');
|
||||||
|
expect(table).not.toBeNull();
|
||||||
|
expect(table.textContent).toContain('118.4 kWh');
|
||||||
|
expect(table.textContent).toContain('Pas encore de prévision');
|
||||||
|
expect(fixture.nativeElement.querySelector('a[href="/sites/SITE001"]')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('colore la charge moyenne selon les seuils 70 % et 90 %', () => {
|
||||||
|
const { fixture } = setup();
|
||||||
const dashboard = fixture.componentInstance;
|
const dashboard = fixture.componentInstance;
|
||||||
|
|
||||||
expect(dashboard.badgeToneForSeverity('low')).toBe('success');
|
expect(dashboard.loadTone(69.9)).toBe('success');
|
||||||
expect(dashboard.badgeToneForSeverity('medium')).toBe('warning');
|
expect(dashboard.loadTone(70)).toBe('warning');
|
||||||
expect(dashboard.badgeToneForSeverity('high')).toBe('danger');
|
expect(dashboard.loadTone(89.9)).toBe('warning');
|
||||||
expect(dashboard.badgeToneForSeverity('critical')).toBe('critical');
|
expect(dashboard.loadTone(90)).toBe('danger');
|
||||||
expect(dashboard.badgeToneForSeverity('high')).not.toBe(
|
expect(dashboard.loadHint(95)).toBe('Proche de la capacité du parc');
|
||||||
dashboard.badgeToneForSeverity('critical'),
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('distingue le ton des statuts de prévision', () => {
|
it('distingue le ton des statuts de prévision', () => {
|
||||||
const statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
const { fixture } = setup();
|
||||||
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;
|
const dashboard = fixture.componentInstance;
|
||||||
|
|
||||||
expect(dashboard.badgeToneForPredictionStatus('available')).toBe('success');
|
expect(dashboard.badgeToneForPredictionStatus('available')).toBe('success');
|
||||||
|
|||||||
@@ -6,11 +6,10 @@ 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 { AlertFeed } from '../../shared/components/alert-feed/alert-feed';
|
||||||
import { PredictionsService } from '../../core/services/predictions.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, AlertSeverity } from '../../shared/models/alert.model';
|
|
||||||
import { PredictionStatus, SitePredictionSummary } from '../../shared/models/prediction.model';
|
import { PredictionStatus, SitePredictionSummary } from '../../shared/models/prediction.model';
|
||||||
import { Card } from '../../shared/components/ui/card/card';
|
import { Card } from '../../shared/components/ui/card/card';
|
||||||
import { Alert as EvAlert } from '../../shared/components/ui/alert/alert';
|
import { Alert as EvAlert } from '../../shared/components/ui/alert/alert';
|
||||||
@@ -22,22 +21,19 @@ 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> = {
|
// `error` n'a pas encore de précédent côté API mais figure dans `ck_prediction_status` :
|
||||||
low: 'success',
|
// mieux vaut un ton défini que `undefined` le jour où ce statut apparaît.
|
||||||
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> = {
|
const TON_PAR_STATUT_PREDICTION: Record<PredictionStatus, BadgeTone> = {
|
||||||
available: 'success',
|
available: 'success',
|
||||||
insufficient_data: 'warning',
|
insufficient_data: 'warning',
|
||||||
error: 'danger',
|
error: 'danger',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const SEUIL_CHARGE_SOUTENUE = 70;
|
||||||
|
const SEUIL_CHARGE_CRITIQUE = 90;
|
||||||
|
|
||||||
|
export type LoadTone = 'success' | 'warning' | 'danger';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-dashboard',
|
selector: 'app-dashboard',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
@@ -47,6 +43,7 @@ const TON_PAR_STATUT_PREDICTION: Record<PredictionStatus, BadgeTone> = {
|
|||||||
RouterLink,
|
RouterLink,
|
||||||
ConsumptionGauge,
|
ConsumptionGauge,
|
||||||
SiteLoadChart,
|
SiteLoadChart,
|
||||||
|
AlertFeed,
|
||||||
Card,
|
Card,
|
||||||
EvAlert,
|
EvAlert,
|
||||||
Badge,
|
Badge,
|
||||||
@@ -58,32 +55,20 @@ const TON_PAR_STATUT_PREDICTION: Record<PredictionStatus, BadgeTone> = {
|
|||||||
})
|
})
|
||||||
export class Dashboard implements OnInit {
|
export class Dashboard implements OnInit {
|
||||||
private statsService = inject(StatsService);
|
private statsService = inject(StatsService);
|
||||||
private alertsService = inject(AlertsService);
|
public auth = inject(AuthService);
|
||||||
private predictionsService = inject(PredictionsService);
|
private predictionsService = inject(PredictionsService);
|
||||||
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[]>([]);
|
|
||||||
predictions = signal<SitePredictionSummary[]>([]);
|
predictions = signal<SitePredictionSummary[]>([]);
|
||||||
|
|
||||||
// Un signal par flux, pas un seul `error` partagé : sinon le tick suivant de `timer` (stats)
|
// Piège : un signal d'erreur par flux, sinon le tick suivant de `timer` (stats) efface en
|
||||||
// efface silencieusement un message d'échec des prévisions ou des alertes après 10s au plus,
|
// silence l'échec des prévisions après 10 s au plus, sans retry ni indication à l'utilisateur.
|
||||||
// sans retry ni indication pour l'utilisateur que la section correspondante est restée vide.
|
|
||||||
statsError = signal<string | null>(null);
|
statsError = signal<string | null>(null);
|
||||||
alertsError = signal<string | null>(null);
|
|
||||||
predictionsError = signal<string | null>(null);
|
predictionsError = signal<string | null>(null);
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.alertsService
|
|
||||||
.getAlerts()
|
|
||||||
.pipe(catchError(() => this.reportUnavailable(this.alertsError)))
|
|
||||||
.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
|
// 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`.
|
// chargement au démarrage suffit, pas besoin du rafraîchissement périodique de `stats`.
|
||||||
this.predictionsService
|
this.predictionsService
|
||||||
@@ -99,7 +84,9 @@ export class Dashboard implements OnInit {
|
|||||||
timer(0, REFRESH_INTERVAL_MS)
|
timer(0, REFRESH_INTERVAL_MS)
|
||||||
.pipe(
|
.pipe(
|
||||||
switchMap(() =>
|
switchMap(() =>
|
||||||
this.statsService.getSummary().pipe(catchError(() => this.reportUnavailable(this.statsError))),
|
this.statsService
|
||||||
|
.getSummary()
|
||||||
|
.pipe(catchError(() => this.reportUnavailable(this.statsError))),
|
||||||
),
|
),
|
||||||
takeUntilDestroyed(this.destroyRef),
|
takeUntilDestroyed(this.destroyRef),
|
||||||
)
|
)
|
||||||
@@ -109,14 +96,28 @@ export class Dashboard implements OnInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
badgeToneForSeverity(severity: AlertSeverity): BadgeTone {
|
|
||||||
return TON_PAR_SEVERITE[severity];
|
|
||||||
}
|
|
||||||
|
|
||||||
badgeToneForPredictionStatus(status: PredictionStatus): BadgeTone {
|
badgeToneForPredictionStatus(status: PredictionStatus): BadgeTone {
|
||||||
return TON_PAR_STATUT_PREDICTION[status];
|
return TON_PAR_STATUT_PREDICTION[status];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
loadTone(percent: number): LoadTone {
|
||||||
|
if (percent >= SEUIL_CHARGE_CRITIQUE) {
|
||||||
|
return 'danger';
|
||||||
|
}
|
||||||
|
return percent >= SEUIL_CHARGE_SOUTENUE ? 'warning' : 'success';
|
||||||
|
}
|
||||||
|
|
||||||
|
loadHint(percent: number): string {
|
||||||
|
switch (this.loadTone(percent)) {
|
||||||
|
case 'danger':
|
||||||
|
return 'Proche de la capacité du parc';
|
||||||
|
case 'warning':
|
||||||
|
return 'Charge soutenue';
|
||||||
|
default:
|
||||||
|
return 'Marge confortable';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
onLogout(): void {
|
onLogout(): void {
|
||||||
this.auth.logout().subscribe({
|
this.auth.logout().subscribe({
|
||||||
next: () => this.router.navigate(['/login']),
|
next: () => this.router.navigate(['/login']),
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
<div class="sensor-status">
|
||||||
|
<nav class="ev-breadcrumb">
|
||||||
|
<a routerLink="/dashboard">Tableau de bord</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<header class="sensor-status__header">
|
||||||
|
<a routerLink="/dashboard" class="ev-brand-link">
|
||||||
|
<ev-brand class="sensor-status__logo" />
|
||||||
|
</a>
|
||||||
|
<div>
|
||||||
|
<h1>Supervision des capteurs</h1>
|
||||||
|
<p class="sensor-status__subtitle">État de santé par capteur et par site</p>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
@if (error(); as message) {
|
||||||
|
<ev-alert severity="danger" class="banner-error">{{ message }}</ev-alert>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (data(); as d) {
|
||||||
|
<div class="sites-grid">
|
||||||
|
@for (site of d.sites; track site.site_id) {
|
||||||
|
<ev-card class="site-card">
|
||||||
|
<div class="site-card__header">
|
||||||
|
<span class="site-card__name">{{ site.site_name }}</span>
|
||||||
|
<ev-badge [tone]="badgeToneForOverall(site.overall)">{{ site.overall }}</ev-badge>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ul class="sensor-list">
|
||||||
|
@for (entry of sensorEntries; track entry[0]) {
|
||||||
|
@let diagnostic = sensorOf(site.sensors, entry[0]);
|
||||||
|
<li class="sensor-item">
|
||||||
|
<span class="sensor-dot" [class]="'sensor-dot--' + diagnostic.status"></span>
|
||||||
|
<span class="sensor-item__label">{{ entry[1] }}</span>
|
||||||
|
@if (diagnostic.status === 'failing') {
|
||||||
|
<span class="sensor-item__since">
|
||||||
|
@if (diagnostic.since; as since) {
|
||||||
|
dernière lecture le {{ since | date: 'dd/MM/yyyy HH:mm' }}
|
||||||
|
} @else {
|
||||||
|
aucune lecture reçue
|
||||||
|
}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
</ev-card>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
color: var(--color-text);
|
||||||
|
padding: 2.5rem 2rem;
|
||||||
|
max-width: 1100px;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sensor-status__header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.85rem;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.75rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.sensor-status__logo {
|
||||||
|
font-size: 1.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sensor-status__subtitle {
|
||||||
|
margin: 0.25rem 0 0;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.banner-error {
|
||||||
|
display: block;
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sites-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-card__header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
margin-bottom: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-card__name {
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sensor-list {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sensor-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sensor-dot {
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
border-radius: 50%;
|
||||||
|
flex-shrink: 0;
|
||||||
|
|
||||||
|
&--ok {
|
||||||
|
background: var(--color-success);
|
||||||
|
}
|
||||||
|
&--failing {
|
||||||
|
background: var(--color-danger);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.sensor-item__label {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sensor-item__since {
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
font-size: 0.75rem;
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { of, throwError } from 'rxjs';
|
||||||
|
import { vi } from 'vitest';
|
||||||
|
import { SensorStatusView } from './sensor-status';
|
||||||
|
import { SensorsService } from '../../../core/services/sensors.service';
|
||||||
|
import { SiteSensors } from '../../../shared/models/sensor-status.model';
|
||||||
|
import {provideRouter} from '@angular/router';
|
||||||
|
|
||||||
|
const OK_SENSORS: SiteSensors = {
|
||||||
|
consumption: { status: 'ok', since: null },
|
||||||
|
electrical: { status: 'ok', since: null },
|
||||||
|
temperature: { status: 'ok', since: null },
|
||||||
|
humidity: { status: 'ok', since: null },
|
||||||
|
network: { status: 'ok', since: null },
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('SensorStatusView', () => {
|
||||||
|
let sensorsMock: { getStatus: ReturnType<typeof vi.fn> };
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
sensorsMock = { getStatus: vi.fn() };
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [SensorStatusView],
|
||||||
|
providers: [
|
||||||
|
{ provide: SensorsService, useValue: sensorsMock },
|
||||||
|
provideRouter([]),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('charge et affiche les données au démarrage', () => {
|
||||||
|
sensorsMock.getStatus.mockReturnValue(
|
||||||
|
of({
|
||||||
|
timestamp: '2026-09-18T08:00:00',
|
||||||
|
sites: [
|
||||||
|
{ site_id: 'SITE001', site_name: 'Bureau Test', overall: 'ok', sensors: OK_SENSORS },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(SensorStatusView);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.data()?.sites.length).toBe(1);
|
||||||
|
expect(fixture.componentInstance.error()).toBeNull();
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('Bureau Test');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("affiche un message d'erreur si l'appel échoue", () => {
|
||||||
|
sensorsMock.getStatus.mockReturnValue(throwError(() => new Error('boom')));
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(SensorStatusView);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.error()).toBe(
|
||||||
|
'État des capteurs indisponible, réessayez plus tard.'
|
||||||
|
);
|
||||||
|
expect(fixture.componentInstance.data()).toBeNull();
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('État des capteurs indisponible');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('associe le bon ton de badge à chaque statut global', () => {
|
||||||
|
sensorsMock.getStatus.mockReturnValue(of({ timestamp: '2026-09-18T08:00:00', sites: [] }));
|
||||||
|
const fixture = TestBed.createComponent(SensorStatusView);
|
||||||
|
const component = fixture.componentInstance;
|
||||||
|
|
||||||
|
expect(component.badgeToneForOverall('ok')).toBe('success');
|
||||||
|
expect(component.badgeToneForOverall('degraded')).toBe('warning');
|
||||||
|
expect(component.badgeToneForOverall('critical')).toBe('critical');
|
||||||
|
expect(component.badgeToneForOverall('inconnu')).toBe('neutral');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('retourne le bon diagnostic via sensorOf', () => {
|
||||||
|
sensorsMock.getStatus.mockReturnValue(of({ timestamp: '2026-09-18T08:00:00', sites: [] }));
|
||||||
|
const fixture = TestBed.createComponent(SensorStatusView);
|
||||||
|
const component = fixture.componentInstance;
|
||||||
|
|
||||||
|
expect(component.sensorOf(OK_SENSORS, 'temperature')).toEqual({ status: 'ok', since: null });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('affiche la date de la dernière lecture reçue pour un capteur en panne', () => {
|
||||||
|
const sensors: SiteSensors = {
|
||||||
|
...OK_SENSORS,
|
||||||
|
temperature: { status: 'failing', since: '2026-09-18T08:00:00' },
|
||||||
|
};
|
||||||
|
sensorsMock.getStatus.mockReturnValue(
|
||||||
|
of({
|
||||||
|
timestamp: '2026-09-18T08:00:00',
|
||||||
|
sites: [{ site_id: 'SITE001', site_name: 'Bureau Test', overall: 'degraded', sensors }],
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(SensorStatusView);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('dernière lecture le');
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('18/09/2026 08:00');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("annonce l'absence de lecture quand un site n'en a jamais reçu", () => {
|
||||||
|
const sensors: SiteSensors = {
|
||||||
|
consumption: { status: 'failing', since: null },
|
||||||
|
electrical: { status: 'failing', since: null },
|
||||||
|
temperature: { status: 'failing', since: null },
|
||||||
|
humidity: { status: 'failing', since: null },
|
||||||
|
network: { status: 'failing', since: null },
|
||||||
|
};
|
||||||
|
sensorsMock.getStatus.mockReturnValue(
|
||||||
|
of({
|
||||||
|
timestamp: '2026-09-18T08:00:00',
|
||||||
|
sites: [{ site_id: 'SITE001', site_name: 'Bureau Test', overall: 'critical', sensors }],
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(SensorStatusView);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('aucune lecture reçue');
|
||||||
|
expect(fixture.nativeElement.textContent).not.toContain('dernière lecture le');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import { Component, OnInit, inject, signal } from '@angular/core';
|
||||||
|
import { RouterLink } from '@angular/router';
|
||||||
|
import { catchError, EMPTY, Observable } from 'rxjs';
|
||||||
|
import {Badge, BadgeTone} from '../../../shared/components/ui/badge/badge';
|
||||||
|
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 {SensorsService} from '../../../core/services/sensors.service';
|
||||||
|
import {SensorDiagnostic, SensorStatusResponse} from '../../../shared/models/sensor-status.model';
|
||||||
|
import { DatePipe } from '@angular/common';
|
||||||
|
|
||||||
|
const UNAVAILABLE_MESSAGE = 'État des capteurs indisponible, réessayez plus tard.';
|
||||||
|
|
||||||
|
const SENSOR_LABELS: Record<string, string> = {
|
||||||
|
consumption: 'Consommation',
|
||||||
|
electrical: 'Électrique',
|
||||||
|
temperature: 'Température',
|
||||||
|
humidity: 'Humidité',
|
||||||
|
network: 'Réseau',
|
||||||
|
};
|
||||||
|
|
||||||
|
const TON_PAR_OVERALL: Record<string, BadgeTone> = {
|
||||||
|
ok: 'success',
|
||||||
|
degraded: 'warning',
|
||||||
|
critical: 'critical',
|
||||||
|
};
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-sensor-status',
|
||||||
|
standalone: true,
|
||||||
|
imports: [RouterLink, Card, Alert, Badge, Brand, DatePipe],
|
||||||
|
templateUrl: './sensor-status.html',
|
||||||
|
styleUrl: './sensor-status.scss',
|
||||||
|
})
|
||||||
|
export class SensorStatusView implements OnInit {
|
||||||
|
private sensorsService = inject(SensorsService);
|
||||||
|
|
||||||
|
data = signal<SensorStatusResponse | null>(null);
|
||||||
|
error = signal<string | null>(null);
|
||||||
|
|
||||||
|
readonly sensorEntries = Object.entries(SENSOR_LABELS);
|
||||||
|
|
||||||
|
ngOnInit(): void {
|
||||||
|
this.sensorsService
|
||||||
|
.getStatus()
|
||||||
|
.pipe(catchError(() => this.reportUnavailable()))
|
||||||
|
.subscribe((response) => {
|
||||||
|
this.error.set(null);
|
||||||
|
this.data.set(response);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
sensorOf(sensors: Record<string, SensorDiagnostic>, key: string): SensorDiagnostic {
|
||||||
|
return sensors[key];
|
||||||
|
}
|
||||||
|
|
||||||
|
badgeToneForOverall(overall: string): BadgeTone {
|
||||||
|
return TON_PAR_OVERALL[overall] ?? 'neutral';
|
||||||
|
}
|
||||||
|
|
||||||
|
private reportUnavailable(): Observable<never> {
|
||||||
|
this.error.set(UNAVAILABLE_MESSAGE);
|
||||||
|
return EMPTY;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
<div class="recommendations">
|
||||||
|
<nav class="ev-breadcrumb">
|
||||||
|
<a routerLink="/dashboard">Tableau de bord</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<header class="recommendations__header">
|
||||||
|
<a routerLink="/dashboard" class="ev-brand-link">
|
||||||
|
<ev-brand class="recommendations__logo" />
|
||||||
|
</a>
|
||||||
|
<div>
|
||||||
|
<h1>Recommandations</h1>
|
||||||
|
<p class="recommendations__subtitle">
|
||||||
|
Actions proposées par le moteur de règles à partir des alertes
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div class="recommendations__toolbar">
|
||||||
|
<label class="recommendations__filter">
|
||||||
|
<span class="form-label">Site</span>
|
||||||
|
<select class="form-select" data-testid="site-filter" (change)="onSiteChange($event)">
|
||||||
|
<option value="" [selected]="!siteFilter()">Tous les sites</option>
|
||||||
|
@for (site of sites(); track site.site_id) {
|
||||||
|
<option [value]="site.site_id" [selected]="site.site_id === siteFilter()">
|
||||||
|
{{ site.site_name }}
|
||||||
|
</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
@if (isAdmin()) {
|
||||||
|
<ev-button
|
||||||
|
variant="secondary"
|
||||||
|
[fullWidth]="false"
|
||||||
|
[disabled]="generating()"
|
||||||
|
data-testid="generate"
|
||||||
|
(click)="onGenerate()"
|
||||||
|
>
|
||||||
|
{{ generating() ? 'Génération en cours…' : 'Générer les recommandations' }}
|
||||||
|
</ev-button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@if (generationReport(); as report) {
|
||||||
|
<ev-alert severity="success" class="recommendations__banner">{{ bilan(report) }}.</ev-alert>
|
||||||
|
}
|
||||||
|
@if (generationError(); as message) {
|
||||||
|
<ev-alert severity="danger" class="recommendations__banner">{{ message }}</ev-alert>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (alertId(); as id) {
|
||||||
|
<p class="recommendations__focus">
|
||||||
|
Alerte n° {{ id }} ·
|
||||||
|
<a routerLink="/recommendations" class="ev-link">Toutes les recommandations</a>
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
<app-recommendation-list [siteId]="siteFilter()" [alertId]="alertId()" [sites]="sites()" />
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
color: var(--color-text);
|
||||||
|
padding: 2.5rem 2rem;
|
||||||
|
max-width: 1100px;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recommendations__header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.85rem;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.75rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.recommendations__logo {
|
||||||
|
font-size: 1.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recommendations__subtitle {
|
||||||
|
margin: 0.25rem 0 0;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.recommendations__toolbar {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: flex-end;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: var(--space-3);
|
||||||
|
margin-bottom: var(--space-4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.recommendations__filter {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
min-width: 14rem;
|
||||||
|
|
||||||
|
.form-label {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.recommendations__banner {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: var(--space-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.recommendations__focus {
|
||||||
|
margin: 0 0 var(--space-3);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { By } from '@angular/platform-browser';
|
||||||
|
import { ActivatedRoute, convertToParamMap, provideRouter } from '@angular/router';
|
||||||
|
import { vi } from 'vitest';
|
||||||
|
import { BehaviorSubject, of, throwError } from 'rxjs';
|
||||||
|
import { RecommendationsView, parseAlertId } from './recommendations';
|
||||||
|
import { RecommendationList } from '../../shared/components/recommendation-list/recommendation-list';
|
||||||
|
import { SitesService } from '../../core/services/sites.service';
|
||||||
|
import { AlertsService } from '../../core/services/alerts.service';
|
||||||
|
import { RecommendationsService } from '../../core/services/recommendations.service';
|
||||||
|
import { AuthService } from '../../core/services/auth.service';
|
||||||
|
|
||||||
|
const SITES = [
|
||||||
|
{
|
||||||
|
site_id: 'SITE001',
|
||||||
|
site_name: 'Usine Nantes',
|
||||||
|
site_type: 'industriel',
|
||||||
|
location: 'Nantes',
|
||||||
|
capacity_kw: 500,
|
||||||
|
status: 'actif',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const BILAN = { alerts_examined: 2, recommendations_created: 3, already_present: 1 };
|
||||||
|
|
||||||
|
function setup(options: { query?: Record<string, string>; role?: string } = {}) {
|
||||||
|
const query = options.query ?? {};
|
||||||
|
const queryParamMap = new BehaviorSubject(convertToParamMap(query));
|
||||||
|
const generate = vi.fn().mockReturnValue(of(BILAN));
|
||||||
|
const getRecommendations = vi.fn().mockReturnValue(of([]));
|
||||||
|
const getAlerts = vi.fn().mockReturnValue(of([]));
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [RecommendationsView],
|
||||||
|
providers: [
|
||||||
|
provideRouter([]),
|
||||||
|
{
|
||||||
|
provide: ActivatedRoute,
|
||||||
|
useValue: { queryParamMap, snapshot: { queryParamMap: convertToParamMap(query) } },
|
||||||
|
},
|
||||||
|
{ provide: SitesService, useValue: { getSites: vi.fn().mockReturnValue(of(SITES)) } },
|
||||||
|
{ provide: AlertsService, useValue: { getAlerts } },
|
||||||
|
{ provide: RecommendationsService, useValue: { getRecommendations, generate } },
|
||||||
|
{
|
||||||
|
provide: AuthService,
|
||||||
|
useValue: { principal: vi.fn().mockReturnValue({ role: options.role ?? 'lecteur' }) },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const fixture = TestBed.createComponent(RecommendationsView);
|
||||||
|
fixture.detectChanges();
|
||||||
|
fixture.detectChanges();
|
||||||
|
return { fixture, queryParamMap, generate, getRecommendations, getAlerts };
|
||||||
|
}
|
||||||
|
|
||||||
|
function listeEnfant(fixture: ReturnType<typeof setup>['fixture']): RecommendationList {
|
||||||
|
return fixture.debugElement.query(By.directive(RecommendationList)).componentInstance;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('parseAlertId', () => {
|
||||||
|
it("n'accepte qu'un entier strictement positif", () => {
|
||||||
|
expect(parseAlertId('12')).toBe(12);
|
||||||
|
expect(parseAlertId('0')).toBeNull();
|
||||||
|
expect(parseAlertId('-3')).toBeNull();
|
||||||
|
expect(parseAlertId('abc')).toBeNull();
|
||||||
|
expect(parseAlertId('12abc')).toBeNull();
|
||||||
|
expect(parseAlertId(null)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('RecommendationsView', () => {
|
||||||
|
it("cible l'alerte donnée par ?alert= et la transmet à la liste", () => {
|
||||||
|
const { fixture } = setup({ query: { alert: '12' } });
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.alertId()).toBe(12);
|
||||||
|
expect(listeEnfant(fixture).alertId()).toBe(12);
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('Alerte n° 12');
|
||||||
|
expect(fixture.nativeElement.querySelector('a[href="/recommendations"]')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignore un paramètre alert invalide', () => {
|
||||||
|
const { fixture } = setup({ query: { alert: 'abc' } });
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.alertId()).toBeNull();
|
||||||
|
expect(fixture.nativeElement.textContent).not.toContain('Alerte n°');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('applique le site donné par ?site= au filtre et à la liste', () => {
|
||||||
|
const { fixture, getAlerts } = setup({ query: { site: 'SITE001' } });
|
||||||
|
|
||||||
|
expect(getAlerts).toHaveBeenCalledWith({ site_id: 'SITE001' });
|
||||||
|
const option = fixture.nativeElement.querySelector(
|
||||||
|
'option[value="SITE001"]',
|
||||||
|
) as HTMLOptionElement;
|
||||||
|
expect(option.selected).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('relance la liste sur le site choisi dans le filtre', () => {
|
||||||
|
const { fixture, getAlerts } = setup();
|
||||||
|
const select = fixture.nativeElement.querySelector(
|
||||||
|
'[data-testid="site-filter"]',
|
||||||
|
) as HTMLSelectElement;
|
||||||
|
|
||||||
|
select.value = 'SITE001';
|
||||||
|
select.dispatchEvent(new Event('change'));
|
||||||
|
fixture.detectChanges();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(getAlerts).toHaveBeenLastCalledWith({ site_id: 'SITE001' });
|
||||||
|
expect(listeEnfant(fixture).siteId()).toBe('SITE001');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cache le bouton de génération aux lecteurs', () => {
|
||||||
|
const { fixture } = setup({ role: 'lecteur' });
|
||||||
|
|
||||||
|
expect(fixture.nativeElement.querySelector('[data-testid="generate"]')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('permet à un admin de générer pour le site filtré, affiche le bilan et recharge la liste', () => {
|
||||||
|
const { fixture, generate, getRecommendations } = setup({
|
||||||
|
role: 'admin',
|
||||||
|
query: { site: 'SITE001' },
|
||||||
|
});
|
||||||
|
|
||||||
|
fixture.nativeElement.querySelector('[data-testid="generate"]').click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(generate).toHaveBeenCalledWith('SITE001');
|
||||||
|
expect(fixture.nativeElement.textContent).toContain(
|
||||||
|
'3 recommandations créées, 1 déjà présente, 2 alertes examinées.',
|
||||||
|
);
|
||||||
|
expect(getRecommendations).toHaveBeenCalledTimes(2);
|
||||||
|
expect(fixture.componentInstance.generating()).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('génère pour tout le parc quand aucun site n’est filtré', () => {
|
||||||
|
const { fixture, generate } = setup({ role: 'admin' });
|
||||||
|
|
||||||
|
fixture.componentInstance.onGenerate();
|
||||||
|
|
||||||
|
expect(generate).toHaveBeenCalledWith(undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("signale l'échec de la génération sans casser la page", () => {
|
||||||
|
const { fixture, generate } = setup({ role: 'admin' });
|
||||||
|
generate.mockReturnValue(throwError(() => new Error('403')));
|
||||||
|
|
||||||
|
fixture.componentInstance.onGenerate();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.generationError()).not.toBeNull();
|
||||||
|
expect(fixture.nativeElement.textContent).toContain(
|
||||||
|
'La génération des recommandations a échoué',
|
||||||
|
);
|
||||||
|
expect(fixture.componentInstance.generating()).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accorde le bilan au singulier', () => {
|
||||||
|
const { fixture } = setup();
|
||||||
|
|
||||||
|
expect(
|
||||||
|
fixture.componentInstance.bilan({
|
||||||
|
alerts_examined: 1,
|
||||||
|
recommendations_created: 1,
|
||||||
|
already_present: 0,
|
||||||
|
}),
|
||||||
|
).toBe('1 recommandation créée, 0 déjà présente, 1 alerte examinée');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { Component, computed, inject, signal, viewChild } from '@angular/core';
|
||||||
|
import { toSignal } from '@angular/core/rxjs-interop';
|
||||||
|
import { ActivatedRoute, RouterLink } from '@angular/router';
|
||||||
|
import { catchError, map, of } from 'rxjs';
|
||||||
|
import { SitesService } from '../../core/services/sites.service';
|
||||||
|
import { RecommendationsService } from '../../core/services/recommendations.service';
|
||||||
|
import { AuthService } from '../../core/services/auth.service';
|
||||||
|
import { Site } from '../../shared/models/site.model';
|
||||||
|
import { RecommendationGenerationReport } from '../../shared/models/recommendation.model';
|
||||||
|
import { RecommendationList } from '../../shared/components/recommendation-list/recommendation-list';
|
||||||
|
import { Alert as EvAlert } from '../../shared/components/ui/alert/alert';
|
||||||
|
import { Brand } from '../../shared/components/ui/brand/brand';
|
||||||
|
import { Button } from '../../shared/components/ui/button/button';
|
||||||
|
|
||||||
|
const GENERATION_FAILED_MESSAGE =
|
||||||
|
'La génération des recommandations a échoué, réessayez plus tard.';
|
||||||
|
|
||||||
|
export function parseAlertId(raw: string | null): number | null {
|
||||||
|
return raw !== null && /^[1-9]\d*$/.test(raw) ? Number(raw) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function pluriel(nombre: number, singulier: string, plurielForme: string): string {
|
||||||
|
return `${nombre} ${nombre > 1 ? plurielForme : singulier}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-recommendations',
|
||||||
|
standalone: true,
|
||||||
|
imports: [RouterLink, RecommendationList, EvAlert, Brand, Button],
|
||||||
|
templateUrl: './recommendations.html',
|
||||||
|
styleUrl: './recommendations.scss',
|
||||||
|
})
|
||||||
|
export class RecommendationsView {
|
||||||
|
private route = inject(ActivatedRoute);
|
||||||
|
private sitesService = inject(SitesService);
|
||||||
|
private recommendationsService = inject(RecommendationsService);
|
||||||
|
private auth = inject(AuthService);
|
||||||
|
|
||||||
|
alertId = toSignal(
|
||||||
|
this.route.queryParamMap.pipe(map((params) => parseAlertId(params.get('alert')))),
|
||||||
|
{ initialValue: null },
|
||||||
|
);
|
||||||
|
siteFilter = signal<string | null>(this.route.snapshot.queryParamMap.get('site'));
|
||||||
|
sites = toSignal(this.sitesService.getSites().pipe(catchError(() => of([] as Site[]))), {
|
||||||
|
initialValue: [] as Site[],
|
||||||
|
});
|
||||||
|
|
||||||
|
list = viewChild.required(RecommendationList);
|
||||||
|
|
||||||
|
isAdmin = computed(() => this.auth.principal()?.role === 'admin');
|
||||||
|
generating = signal(false);
|
||||||
|
generationReport = signal<RecommendationGenerationReport | null>(null);
|
||||||
|
generationError = signal<string | null>(null);
|
||||||
|
|
||||||
|
onSiteChange(event: Event): void {
|
||||||
|
this.siteFilter.set((event.target as HTMLSelectElement).value || null);
|
||||||
|
}
|
||||||
|
|
||||||
|
onGenerate(): void {
|
||||||
|
if (this.generating()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.generating.set(true);
|
||||||
|
this.generationError.set(null);
|
||||||
|
this.recommendationsService.generate(this.siteFilter() ?? undefined).subscribe({
|
||||||
|
next: (report) => {
|
||||||
|
this.generating.set(false);
|
||||||
|
this.generationReport.set(report);
|
||||||
|
this.list().reload();
|
||||||
|
},
|
||||||
|
error: () => {
|
||||||
|
this.generating.set(false);
|
||||||
|
this.generationError.set(GENERATION_FAILED_MESSAGE);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
bilan(report: RecommendationGenerationReport): string {
|
||||||
|
return [
|
||||||
|
pluriel(report.recommendations_created, 'recommandation créée', 'recommandations créées'),
|
||||||
|
pluriel(report.already_present, 'déjà présente', 'déjà présentes'),
|
||||||
|
pluriel(report.alerts_examined, 'alerte examinée', 'alertes examinées'),
|
||||||
|
].join(', ');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -81,5 +81,16 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
<section class="recommendations-section">
|
||||||
|
<h2>Recommandations</h2>
|
||||||
|
<app-recommendation-list [siteId]="siteId() ?? null" [sites]="siteAsList()" />
|
||||||
|
<a
|
||||||
|
routerLink="/recommendations"
|
||||||
|
[queryParams]="{ site: siteId() }"
|
||||||
|
class="ev-link recommendations-section__link"
|
||||||
|
>Voir dans la vue recommandations</a
|
||||||
|
>
|
||||||
|
</section>
|
||||||
|
|
||||||
<a routerLink="/sites" class="ev-link">Retour aux sites</a>
|
<a routerLink="/sites" class="ev-link">Retour aux sites</a>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -117,3 +117,12 @@ h2 {
|
|||||||
.chart-section {
|
.chart-section {
|
||||||
margin-bottom: 2rem;
|
margin-bottom: 2rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.recommendations-section {
|
||||||
|
margin: 2.5rem 0 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recommendations-section__link {
|
||||||
|
display: inline-block;
|
||||||
|
margin-top: 1rem;
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import { BehaviorSubject, of, throwError } from 'rxjs';
|
|||||||
import { SiteDetail } from './site-detail';
|
import { SiteDetail } from './site-detail';
|
||||||
import { SitesService } from '../../../core/services/sites.service';
|
import { SitesService } from '../../../core/services/sites.service';
|
||||||
import { ReadingsService } from '../../../core/services/readings.service';
|
import { ReadingsService } from '../../../core/services/readings.service';
|
||||||
|
import { AlertsService } from '../../../core/services/alerts.service';
|
||||||
|
import { RecommendationsService } from '../../../core/services/recommendations.service';
|
||||||
|
|
||||||
const SITE = {
|
const SITE = {
|
||||||
site_id: 'SITE001',
|
site_id: 'SITE001',
|
||||||
@@ -69,6 +71,7 @@ function setup(
|
|||||||
readingsMock: Partial<ReadingsService>,
|
readingsMock: Partial<ReadingsService>,
|
||||||
) {
|
) {
|
||||||
const paramMap = new BehaviorSubject(convertToParamMap({ siteId }));
|
const paramMap = new BehaviorSubject(convertToParamMap({ siteId }));
|
||||||
|
const getAlerts = vi.fn().mockReturnValue(of([]));
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
imports: [SiteDetail],
|
imports: [SiteDetail],
|
||||||
providers: [
|
providers: [
|
||||||
@@ -76,9 +79,14 @@ function setup(
|
|||||||
{ provide: ActivatedRoute, useValue: { paramMap } },
|
{ provide: ActivatedRoute, useValue: { paramMap } },
|
||||||
{ provide: SitesService, useValue: sitesMock },
|
{ provide: SitesService, useValue: sitesMock },
|
||||||
{ provide: ReadingsService, useValue: readingsMock },
|
{ provide: ReadingsService, useValue: readingsMock },
|
||||||
|
{ provide: AlertsService, useValue: { getAlerts } },
|
||||||
|
{
|
||||||
|
provide: RecommendationsService,
|
||||||
|
useValue: { getRecommendations: vi.fn().mockReturnValue(of([])) },
|
||||||
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
return { fixture: TestBed.createComponent(SiteDetail), paramMap };
|
return { fixture: TestBed.createComponent(SiteDetail), paramMap, getAlerts };
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('SiteDetail', () => {
|
describe('SiteDetail', () => {
|
||||||
@@ -261,6 +269,27 @@ describe('SiteDetail', () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('demande les recommandations du site consulté à travers ses alertes', () => {
|
||||||
|
const { fixture, getAlerts } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{
|
||||||
|
getSite: vi.fn().mockReturnValue(of(SITE)),
|
||||||
|
getCurrent: vi.fn().mockReturnValue(of(CURRENT_COMPLET)),
|
||||||
|
},
|
||||||
|
{ getHistory: vi.fn().mockReturnValue(of([])) },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(getAlerts).toHaveBeenCalledWith({ site_id: 'SITE001' });
|
||||||
|
expect(fixture.nativeElement.querySelector('app-recommendation-list')).not.toBeNull();
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('Recommandations');
|
||||||
|
expect(
|
||||||
|
fixture.nativeElement.querySelector('a[href="/recommendations?site=SITE001"]'),
|
||||||
|
).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
it("annonce l'absence de mesure sans interroger l'historique quand timestamp est null", () => {
|
it("annonce l'absence de mesure sans interroger l'historique quand timestamp est null", () => {
|
||||||
const getHistory = vi.fn().mockReturnValue(of([]));
|
const getHistory = vi.fn().mockReturnValue(of([]));
|
||||||
const { fixture } = setup(
|
const { fixture } = setup(
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { Badge, BadgeTone } from '../../../shared/components/ui/badge/badge';
|
|||||||
import { Brand } from '../../../shared/components/ui/brand/brand';
|
import { Brand } from '../../../shared/components/ui/brand/brand';
|
||||||
import { ConsumptionGauge } from '../../../shared/components/consumption-gauge/consumption-gauge';
|
import { ConsumptionGauge } from '../../../shared/components/consumption-gauge/consumption-gauge';
|
||||||
import { ReadingHistoryChart } from '../../../shared/components/reading-history-chart/reading-history-chart';
|
import { ReadingHistoryChart } from '../../../shared/components/reading-history-chart/reading-history-chart';
|
||||||
|
import { RecommendationList } from '../../../shared/components/recommendation-list/recommendation-list';
|
||||||
|
|
||||||
const UNAVAILABLE_MESSAGE = 'Détail du site indisponible, réessayez plus tard.';
|
const UNAVAILABLE_MESSAGE = 'Détail du site indisponible, réessayez plus tard.';
|
||||||
const NO_MEASUREMENT_MESSAGE = 'Aucune mesure remontée pour ce site.';
|
const NO_MEASUREMENT_MESSAGE = 'Aucune mesure remontée pour ce site.';
|
||||||
@@ -96,7 +97,16 @@ export interface MetricView {
|
|||||||
@Component({
|
@Component({
|
||||||
selector: 'app-site-detail',
|
selector: 'app-site-detail',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [RouterLink, Card, Alert, Badge, Brand, ConsumptionGauge, ReadingHistoryChart],
|
imports: [
|
||||||
|
RouterLink,
|
||||||
|
Card,
|
||||||
|
Alert,
|
||||||
|
Badge,
|
||||||
|
Brand,
|
||||||
|
ConsumptionGauge,
|
||||||
|
ReadingHistoryChart,
|
||||||
|
RecommendationList,
|
||||||
|
],
|
||||||
templateUrl: './site-detail.html',
|
templateUrl: './site-detail.html',
|
||||||
styleUrl: './site-detail.scss',
|
styleUrl: './site-detail.scss',
|
||||||
})
|
})
|
||||||
@@ -117,6 +127,11 @@ export class SiteDetail {
|
|||||||
|
|
||||||
hasMeasurement = computed(() => this.current()?.timestamp != null);
|
hasMeasurement = computed(() => this.current()?.timestamp != null);
|
||||||
|
|
||||||
|
siteAsList = computed<Site[]>(() => {
|
||||||
|
const site = this.site();
|
||||||
|
return site ? [site] : [];
|
||||||
|
});
|
||||||
|
|
||||||
consumptionKw = computed(() => this.current()?.consumption_kw ?? null);
|
consumptionKw = computed(() => this.current()?.consumption_kw ?? null);
|
||||||
|
|
||||||
consumptionLabel = computed(() => {
|
consumptionLabel = computed(() => {
|
||||||
|
|||||||
@@ -17,8 +17,8 @@
|
|||||||
<ev-alert severity="danger" class="banner-error">{{ message }}</ev-alert>
|
<ev-alert severity="danger" class="banner-error">{{ message }}</ev-alert>
|
||||||
}
|
}
|
||||||
|
|
||||||
<ev-card class="table-card">
|
<ev-card class="ev-table-card">
|
||||||
<table class="sites-table">
|
<table class="ev-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>Nom</th>
|
<th>Nom</th>
|
||||||
@@ -36,7 +36,9 @@
|
|||||||
<td>{{ site.site_type }}</td>
|
<td>{{ site.site_type }}</td>
|
||||||
<td>{{ site.location || '-' }}</td>
|
<td>{{ site.location || '-' }}</td>
|
||||||
<td>{{ site.capacity_kw ?? '-' }}</td>
|
<td>{{ site.capacity_kw ?? '-' }}</td>
|
||||||
<td><ev-badge [tone]="badgeToneForStatus(site.status)">{{ site.status ?? '-' }}</ev-badge></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>
|
<td><a [routerLink]="['/sites', site.site_id]" class="ev-link">Détail</a></td>
|
||||||
</tr>
|
</tr>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,32 +32,3 @@
|
|||||||
display: block;
|
display: block;
|
||||||
margin: 0 0 1.5rem;
|
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,95 @@
|
|||||||
|
<section class="alert-feed">
|
||||||
|
<header class="alert-feed__header">
|
||||||
|
<div>
|
||||||
|
<h2 class="alert-feed__title">Alertes actives</h2>
|
||||||
|
@if (!loading() || alerts().length > 0) {
|
||||||
|
<p class="alert-feed__count">
|
||||||
|
{{ alerts().length }} {{ alerts().length > 1 ? 'alertes' : 'alerte' }}
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="alert-feed__filters">
|
||||||
|
@if (!siteId()) {
|
||||||
|
<label class="alert-feed__filter">
|
||||||
|
<span class="form-label">Site</span>
|
||||||
|
<select class="form-select" data-testid="site-filter" (change)="onSiteChange($event)">
|
||||||
|
<option value="">Tous les sites</option>
|
||||||
|
@for (site of sites(); track site.site_id) {
|
||||||
|
<option [value]="site.site_id">{{ site.site_name }}</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
}
|
||||||
|
<label class="alert-feed__filter">
|
||||||
|
<span class="form-label">Sévérité</span>
|
||||||
|
<select
|
||||||
|
class="form-select"
|
||||||
|
data-testid="severity-filter"
|
||||||
|
(change)="onSeverityChange($event)"
|
||||||
|
>
|
||||||
|
<option value="">Toutes</option>
|
||||||
|
@for (severite of severites; track severite) {
|
||||||
|
<option [value]="severite">{{ severityLabel(severite) }}</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
@if (error(); as message) {
|
||||||
|
<ev-alert severity="danger" class="alert-feed__banner">{{ message }}</ev-alert>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (loading() && alerts().length === 0 && !error()) {
|
||||||
|
<p class="alert-feed__state" aria-live="polite">Chargement des alertes…</p>
|
||||||
|
} @else if (alerts().length === 0 && !error()) {
|
||||||
|
<ev-alert severity="success" class="alert-feed__banner"
|
||||||
|
>Aucune alerte pour ces critères.</ev-alert
|
||||||
|
>
|
||||||
|
}
|
||||||
|
|
||||||
|
<ul class="alert-feed__list" [attr.aria-busy]="loading()">
|
||||||
|
@for (alert of visibleAlerts(); track alert.alert_id) {
|
||||||
|
<li class="alert-feed__item" [class]="'alert-feed__item--' + alert.severity">
|
||||||
|
<span class="alert-feed__icon">
|
||||||
|
<ev-icon [name]="alert.type" [label]="typeLabel(alert.type)" />
|
||||||
|
</span>
|
||||||
|
<div class="alert-feed__body">
|
||||||
|
<div class="alert-feed__meta">
|
||||||
|
<ev-badge [tone]="toneFor(alert.severity)">{{
|
||||||
|
severityLabel(alert.severity)
|
||||||
|
}}</ev-badge>
|
||||||
|
<span class="alert-feed__type">{{ typeLabel(alert.type) }}</span>
|
||||||
|
<span class="alert-feed__site">{{ siteName(alert.site_id) }}</span>
|
||||||
|
<time class="alert-feed__time" [attr.datetime]="alert.timestamp">
|
||||||
|
{{ alert.timestamp | date: 'dd/MM/yyyy HH:mm' }}
|
||||||
|
</time>
|
||||||
|
</div>
|
||||||
|
<p class="alert-feed__message">{{ alert.message }}</p>
|
||||||
|
@if (alert.value !== null) {
|
||||||
|
<p class="alert-feed__values">
|
||||||
|
<strong>{{ alert.value | number: '1.0-1' }} {{ unitFor(alert.metric) }}</strong>
|
||||||
|
@if (alert.threshold !== null) {
|
||||||
|
<span
|
||||||
|
>seuil {{ alert.threshold | number: '1.0-1' }} {{ unitFor(alert.metric) }}</span
|
||||||
|
>
|
||||||
|
}
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
@if (hiddenCount() > 0) {
|
||||||
|
<ev-button
|
||||||
|
variant="secondary"
|
||||||
|
[fullWidth]="false"
|
||||||
|
class="alert-feed__more"
|
||||||
|
data-testid="show-more"
|
||||||
|
(click)="showMore()"
|
||||||
|
>
|
||||||
|
Afficher plus ({{ hiddenCount() }} restantes)
|
||||||
|
</ev-button>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-feed__header {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: flex-end;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: var(--space-3);
|
||||||
|
margin-bottom: var(--space-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-feed__title {
|
||||||
|
margin: 0;
|
||||||
|
font-size: var(--font-size-lg);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-feed__count {
|
||||||
|
margin: 0.15rem 0 0;
|
||||||
|
font-size: var(--font-size-sm);
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-feed__filters {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: var(--space-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-feed__filter {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
min-width: 10rem;
|
||||||
|
|
||||||
|
.form-label {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-feed__banner {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: var(--space-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-feed__state {
|
||||||
|
margin: 0 0 var(--space-3);
|
||||||
|
font-size: var(--font-size-sm);
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-feed__list {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--space-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-feed__item {
|
||||||
|
display: flex;
|
||||||
|
gap: var(--space-3);
|
||||||
|
padding: var(--space-2) var(--space-3);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
background: var(--color-surface);
|
||||||
|
border: 1px solid var(--color-border-light);
|
||||||
|
border-left: 4px solid var(--color-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-feed__item--medium {
|
||||||
|
border-left-color: var(--color-warning);
|
||||||
|
background: var(--color-warning-bg);
|
||||||
|
|
||||||
|
.alert-feed__icon {
|
||||||
|
color: var(--color-warning-text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-feed__item--high {
|
||||||
|
border-left-color: var(--color-danger);
|
||||||
|
background: var(--color-danger-bg);
|
||||||
|
|
||||||
|
.alert-feed__icon {
|
||||||
|
color: var(--color-danger);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-feed__item--critical {
|
||||||
|
border-left-color: var(--color-critical);
|
||||||
|
background: var(--color-danger-bg);
|
||||||
|
|
||||||
|
.alert-feed__icon {
|
||||||
|
color: var(--color-critical);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-feed__icon {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
flex-shrink: 0;
|
||||||
|
width: 2.25rem;
|
||||||
|
height: 2.25rem;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--color-surface);
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
font-size: var(--font-size-lg);
|
||||||
|
box-shadow: var(--shadow-card);
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-feed__body {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.25rem;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-feed__meta {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-2);
|
||||||
|
font-size: var(--font-size-xs);
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-feed__type {
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--color-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-feed__message {
|
||||||
|
margin: 0;
|
||||||
|
font-size: var(--font-size-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-feed__values {
|
||||||
|
display: flex;
|
||||||
|
gap: var(--space-2);
|
||||||
|
margin: 0;
|
||||||
|
font-size: var(--font-size-xs);
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
|
||||||
|
strong {
|
||||||
|
color: var(--color-text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-feed__more {
|
||||||
|
display: inline-block;
|
||||||
|
margin-top: var(--space-3);
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||||
|
import { vi } from 'vitest';
|
||||||
|
import { of, throwError } from 'rxjs';
|
||||||
|
import { AlertFeed } from './alert-feed';
|
||||||
|
import { AlertsService } from '../../../core/services/alerts.service';
|
||||||
|
import { SitesService } from '../../../core/services/sites.service';
|
||||||
|
import { Alert } from '../../models/alert.model';
|
||||||
|
import { Site } from '../../models/site.model';
|
||||||
|
|
||||||
|
const SITES: Site[] = [
|
||||||
|
{
|
||||||
|
site_id: 'SITE001',
|
||||||
|
site_name: 'Usine Nantes',
|
||||||
|
site_type: 'industriel',
|
||||||
|
location: 'Nantes',
|
||||||
|
capacity_kw: 500,
|
||||||
|
status: 'actif',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
function alerte(surcharges: Partial<Alert> = {}): Alert {
|
||||||
|
return {
|
||||||
|
alert_id: 1,
|
||||||
|
site_id: 'SITE001',
|
||||||
|
timestamp: '2026-09-15T11:12:00Z',
|
||||||
|
type: 'spike',
|
||||||
|
severity: 'critical',
|
||||||
|
message: 'Variation brutale entre deux lectures consécutives',
|
||||||
|
value: 812.5,
|
||||||
|
threshold: 400,
|
||||||
|
metric: 'consumption_kw',
|
||||||
|
prediction_id: null,
|
||||||
|
...surcharges,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function setup(
|
||||||
|
alertsMock: { getAlerts: ReturnType<typeof vi.fn> },
|
||||||
|
sitesMock: { getSites: ReturnType<typeof vi.fn> } = {
|
||||||
|
getSites: vi.fn().mockReturnValue(of(SITES)),
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [AlertFeed],
|
||||||
|
providers: [
|
||||||
|
{ provide: AlertsService, useValue: alertsMock },
|
||||||
|
{ provide: SitesService, useValue: sitesMock },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
return TestBed.createComponent(AlertFeed);
|
||||||
|
}
|
||||||
|
|
||||||
|
function premierChargement(fixture: ComponentFixture<AlertFeed>) {
|
||||||
|
fixture.detectChanges();
|
||||||
|
vi.advanceTimersByTime(1);
|
||||||
|
fixture.detectChanges();
|
||||||
|
}
|
||||||
|
|
||||||
|
function texte(fixture: ComponentFixture<AlertFeed>): string {
|
||||||
|
return (fixture.nativeElement as HTMLElement).textContent ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function choisir(fixture: ComponentFixture<AlertFeed>, testId: string, value: string) {
|
||||||
|
const select = fixture.nativeElement.querySelector(
|
||||||
|
`[data-testid="${testId}"]`,
|
||||||
|
) as HTMLSelectElement;
|
||||||
|
select.value = value;
|
||||||
|
select.dispatchEvent(new Event('change'));
|
||||||
|
fixture.detectChanges();
|
||||||
|
vi.advanceTimersByTime(1);
|
||||||
|
fixture.detectChanges();
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('AlertFeed', () => {
|
||||||
|
beforeEach(() => vi.useFakeTimers());
|
||||||
|
afterEach(() => vi.useRealTimers());
|
||||||
|
|
||||||
|
it('charge les alertes au démarrage sans filtre et les affiche avec leur contexte', () => {
|
||||||
|
const getAlerts = vi.fn().mockReturnValue(of([alerte()]));
|
||||||
|
const fixture = setup({ getAlerts });
|
||||||
|
|
||||||
|
premierChargement(fixture);
|
||||||
|
|
||||||
|
expect(getAlerts).toHaveBeenCalledTimes(1);
|
||||||
|
expect(getAlerts.mock.calls[0][0]).toEqual({});
|
||||||
|
const contenu = texte(fixture);
|
||||||
|
expect(contenu).toContain('Usine Nantes');
|
||||||
|
expect(contenu).toContain('Critique');
|
||||||
|
expect(contenu).toContain('Pic de consommation');
|
||||||
|
expect(contenu).toContain('15/09/2026');
|
||||||
|
expect(contenu).toContain('812.5 kW');
|
||||||
|
expect(contenu).toContain('seuil 400 kW');
|
||||||
|
expect(fixture.nativeElement.querySelector('ev-icon svg')).not.toBeNull();
|
||||||
|
expect(fixture.nativeElement.querySelector('.alert-feed__item--critical')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('annonce le chargement avant la première réponse', () => {
|
||||||
|
const fixture = setup({ getAlerts: vi.fn().mockReturnValue(of([])) });
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.loading()).toBe(true);
|
||||||
|
expect(texte(fixture)).toContain('Chargement des alertes');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("annonce l'absence d'alerte pour les critères choisis", () => {
|
||||||
|
const fixture = setup({ getAlerts: vi.fn().mockReturnValue(of([])) });
|
||||||
|
|
||||||
|
premierChargement(fixture);
|
||||||
|
|
||||||
|
expect(texte(fixture)).toContain('Aucune alerte pour ces critères.');
|
||||||
|
expect(fixture.nativeElement.querySelectorAll('li').length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('relance la requête avec la sévérité choisie et revient à la première page', () => {
|
||||||
|
const getAlerts = vi.fn().mockReturnValue(of([alerte()]));
|
||||||
|
const fixture = setup({ getAlerts });
|
||||||
|
premierChargement(fixture);
|
||||||
|
fixture.componentInstance.showMore();
|
||||||
|
|
||||||
|
choisir(fixture, 'severity-filter', 'high');
|
||||||
|
|
||||||
|
expect(getAlerts).toHaveBeenCalledTimes(2);
|
||||||
|
expect(getAlerts.mock.calls[1][0]).toEqual({ severity: 'high' });
|
||||||
|
expect(fixture.componentInstance.visibleCount()).toBe(10);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('relance la requête avec le site choisi dans le filtre', () => {
|
||||||
|
const getAlerts = vi.fn().mockReturnValue(of([]));
|
||||||
|
const fixture = setup({ getAlerts });
|
||||||
|
premierChargement(fixture);
|
||||||
|
|
||||||
|
choisir(fixture, 'site-filter', 'SITE001');
|
||||||
|
|
||||||
|
expect(getAlerts.mock.calls[1][0]).toEqual({ site_id: 'SITE001' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('masque le filtre site et force site_id quand le parent fixe le site', () => {
|
||||||
|
const getAlerts = vi.fn().mockReturnValue(of([]));
|
||||||
|
const fixture = setup({ getAlerts });
|
||||||
|
fixture.componentRef.setInput('siteId', 'SITE001');
|
||||||
|
|
||||||
|
premierChargement(fixture);
|
||||||
|
|
||||||
|
expect(getAlerts.mock.calls[0][0]).toEqual({ site_id: 'SITE001' });
|
||||||
|
expect(fixture.nativeElement.querySelector('[data-testid="site-filter"]')).toBeNull();
|
||||||
|
expect(fixture.nativeElement.querySelector('[data-testid="severity-filter"]')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("signale l'indisponibilité en gardant la liste, puis repart au rafraîchissement suivant", () => {
|
||||||
|
const getAlerts = vi
|
||||||
|
.fn()
|
||||||
|
.mockReturnValueOnce(of([alerte()]))
|
||||||
|
.mockReturnValueOnce(throwError(() => new Error('API injoignable')))
|
||||||
|
.mockReturnValue(of([alerte(), alerte({ alert_id: 2 })]));
|
||||||
|
const fixture = setup({ getAlerts });
|
||||||
|
premierChargement(fixture);
|
||||||
|
|
||||||
|
vi.advanceTimersByTime(60_000);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(getAlerts).toHaveBeenCalledTimes(2);
|
||||||
|
expect(fixture.componentInstance.error()).not.toBeNull();
|
||||||
|
expect(fixture.componentInstance.alerts().length).toBe(1);
|
||||||
|
expect(texte(fixture)).toContain('Alertes indisponibles');
|
||||||
|
|
||||||
|
vi.advanceTimersByTime(60_000);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(getAlerts).toHaveBeenCalledTimes(3);
|
||||||
|
expect(fixture.componentInstance.error()).toBeNull();
|
||||||
|
expect(fixture.componentInstance.alerts().length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('pagine côté client par dix et dévoile le reste à la demande', () => {
|
||||||
|
const alertes = Array.from({ length: 25 }, (_, i) => alerte({ alert_id: i + 1 }));
|
||||||
|
const fixture = setup({ getAlerts: vi.fn().mockReturnValue(of(alertes)) });
|
||||||
|
premierChargement(fixture);
|
||||||
|
|
||||||
|
expect(fixture.nativeElement.querySelectorAll('li').length).toBe(10);
|
||||||
|
expect(texte(fixture)).toContain('Afficher plus (15 restantes)');
|
||||||
|
|
||||||
|
fixture.nativeElement.querySelector('[data-testid="show-more"]').click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(fixture.nativeElement.querySelectorAll('li').length).toBe(20);
|
||||||
|
|
||||||
|
fixture.nativeElement.querySelector('[data-testid="show-more"]').click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(fixture.nativeElement.querySelectorAll('li').length).toBe(25);
|
||||||
|
expect(fixture.nativeElement.querySelector('[data-testid="show-more"]')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("replie sur l'identifiant quand le site est inconnu ou que la liste des sites échoue", () => {
|
||||||
|
const fixture = setup(
|
||||||
|
{ getAlerts: vi.fn().mockReturnValue(of([alerte({ site_id: 'SITE999' })])) },
|
||||||
|
{ getSites: vi.fn().mockReturnValue(throwError(() => new Error('nope'))) },
|
||||||
|
);
|
||||||
|
|
||||||
|
premierChargement(fixture);
|
||||||
|
|
||||||
|
expect(texte(fixture)).toContain('SITE999');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("n'affiche pas de mesure pour une alerte sans valeur", () => {
|
||||||
|
const fixture = setup({
|
||||||
|
getAlerts: vi
|
||||||
|
.fn()
|
||||||
|
.mockReturnValue(
|
||||||
|
of([alerte({ type: 'outage', value: null, threshold: null, metric: null })]),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
premierChargement(fixture);
|
||||||
|
|
||||||
|
expect(fixture.nativeElement.querySelector('.alert-feed__values')).toBeNull();
|
||||||
|
expect(texte(fixture)).toContain('Coupure');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
import { Component, DestroyRef, computed, inject, input, signal } from '@angular/core';
|
||||||
|
import { takeUntilDestroyed, toObservable, toSignal } from '@angular/core/rxjs-interop';
|
||||||
|
import { DatePipe, DecimalPipe } from '@angular/common';
|
||||||
|
import { catchError, EMPTY, Observable, of, switchMap, tap, timer } from 'rxjs';
|
||||||
|
import { AlertFilters, AlertsService } from '../../../core/services/alerts.service';
|
||||||
|
import { SitesService } from '../../../core/services/sites.service';
|
||||||
|
import { Alert, AlertMetric, AlertSeverity, AlertType } from '../../models/alert.model';
|
||||||
|
import { Site } from '../../models/site.model';
|
||||||
|
import {
|
||||||
|
LIBELLE_PAR_SEVERITE,
|
||||||
|
LIBELLE_PAR_TYPE,
|
||||||
|
SEVERITES,
|
||||||
|
TON_PAR_SEVERITE,
|
||||||
|
UNITE_PAR_METRIQUE,
|
||||||
|
} from '../../models/alert-presentation';
|
||||||
|
import { Badge, BadgeTone } from '../ui/badge/badge';
|
||||||
|
import { Button } from '../ui/button/button';
|
||||||
|
import { Alert as EvAlert } from '../ui/alert/alert';
|
||||||
|
import { Icon } from '../ui/icon/icon';
|
||||||
|
|
||||||
|
// Le DAG de détection tourne toutes les heures : une minute suffit largement pour suivre le flux.
|
||||||
|
const REFRESH_INTERVAL_MS = 60_000;
|
||||||
|
const PAGE_SIZE = 10;
|
||||||
|
const UNAVAILABLE_MESSAGE = 'Alertes indisponibles, la liste affichée date du dernier chargement.';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-alert-feed',
|
||||||
|
standalone: true,
|
||||||
|
imports: [DatePipe, DecimalPipe, Badge, Button, EvAlert, Icon],
|
||||||
|
templateUrl: './alert-feed.html',
|
||||||
|
styleUrl: './alert-feed.scss',
|
||||||
|
})
|
||||||
|
export class AlertFeed {
|
||||||
|
private alertsService = inject(AlertsService);
|
||||||
|
private sitesService = inject(SitesService);
|
||||||
|
private destroyRef = inject(DestroyRef);
|
||||||
|
|
||||||
|
siteId = input<string | null>(null);
|
||||||
|
|
||||||
|
readonly severites = SEVERITES;
|
||||||
|
severity = signal<AlertSeverity | null>(null);
|
||||||
|
siteFilter = signal<string | null>(null);
|
||||||
|
|
||||||
|
alerts = signal<Alert[]>([]);
|
||||||
|
loading = signal(true);
|
||||||
|
error = signal<string | null>(null);
|
||||||
|
visibleCount = signal(PAGE_SIZE);
|
||||||
|
|
||||||
|
sites = toSignal(this.sitesService.getSites().pipe(catchError(() => of([] as Site[]))), {
|
||||||
|
initialValue: [] as Site[],
|
||||||
|
});
|
||||||
|
|
||||||
|
private filters = computed<AlertFilters>(() => ({
|
||||||
|
site_id: this.siteId() ?? this.siteFilter() ?? undefined,
|
||||||
|
severity: this.severity() ?? undefined,
|
||||||
|
}));
|
||||||
|
|
||||||
|
private siteNameById = computed(
|
||||||
|
() => new Map(this.sites().map((site) => [site.site_id, site.site_name])),
|
||||||
|
);
|
||||||
|
|
||||||
|
visibleAlerts = computed(() => this.alerts().slice(0, this.visibleCount()));
|
||||||
|
hiddenCount = computed(() => Math.max(this.alerts().length - this.visibleCount(), 0));
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
toObservable(this.filters)
|
||||||
|
.pipe(
|
||||||
|
tap(() => {
|
||||||
|
this.loading.set(true);
|
||||||
|
this.visibleCount.set(PAGE_SIZE);
|
||||||
|
}),
|
||||||
|
// Piège : catchError sur l'observable interne ; sur le flux externe il terminerait le
|
||||||
|
// timer et le rafraîchissement ne repartirait jamais.
|
||||||
|
switchMap((filters) =>
|
||||||
|
timer(0, REFRESH_INTERVAL_MS).pipe(
|
||||||
|
switchMap(() =>
|
||||||
|
this.alertsService
|
||||||
|
.getAlerts(filters)
|
||||||
|
.pipe(catchError(() => this.reportUnavailable())),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
takeUntilDestroyed(this.destroyRef),
|
||||||
|
)
|
||||||
|
.subscribe((alerts) => {
|
||||||
|
this.loading.set(false);
|
||||||
|
this.error.set(null);
|
||||||
|
this.alerts.set(alerts);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
onSiteChange(event: Event): void {
|
||||||
|
this.siteFilter.set((event.target as HTMLSelectElement).value || null);
|
||||||
|
}
|
||||||
|
|
||||||
|
onSeverityChange(event: Event): void {
|
||||||
|
const value = (event.target as HTMLSelectElement).value;
|
||||||
|
this.severity.set(value ? (value as AlertSeverity) : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
showMore(): void {
|
||||||
|
this.visibleCount.update((count) => count + PAGE_SIZE);
|
||||||
|
}
|
||||||
|
|
||||||
|
toneFor(severity: AlertSeverity): BadgeTone {
|
||||||
|
return TON_PAR_SEVERITE[severity];
|
||||||
|
}
|
||||||
|
|
||||||
|
severityLabel(severity: AlertSeverity): string {
|
||||||
|
return LIBELLE_PAR_SEVERITE[severity];
|
||||||
|
}
|
||||||
|
|
||||||
|
typeLabel(type: AlertType): string {
|
||||||
|
return LIBELLE_PAR_TYPE[type];
|
||||||
|
}
|
||||||
|
|
||||||
|
siteName(siteId: string): string {
|
||||||
|
return this.siteNameById().get(siteId) ?? siteId;
|
||||||
|
}
|
||||||
|
|
||||||
|
unitFor(metric: AlertMetric | null): string {
|
||||||
|
return metric ? UNITE_PAR_METRIQUE[metric] : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
private reportUnavailable(): Observable<never> {
|
||||||
|
this.loading.set(false);
|
||||||
|
this.error.set(UNAVAILABLE_MESSAGE);
|
||||||
|
return EMPTY;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
@if (error(); as message) {
|
||||||
|
<ev-alert severity="danger" class="reco-list__banner">{{ message }}</ev-alert>
|
||||||
|
} @else if (loading() && !hasData()) {
|
||||||
|
<p class="reco-list__state" aria-live="polite">Chargement des recommandations…</p>
|
||||||
|
} @else if (visibleGroups().length === 0) {
|
||||||
|
<ev-alert severity="success" class="reco-list__banner">{{ emptyMessage() }}</ev-alert>
|
||||||
|
}
|
||||||
|
|
||||||
|
<div class="reco-list" [attr.aria-busy]="loading()">
|
||||||
|
@for (group of visibleGroups(); track group.alert.alert_id) {
|
||||||
|
<ev-card
|
||||||
|
class="reco-group"
|
||||||
|
[class.reco-group--focus]="group.alert.alert_id === alertId()"
|
||||||
|
[id]="'alerte-' + group.alert.alert_id"
|
||||||
|
>
|
||||||
|
<header class="reco-group__alert">
|
||||||
|
<div class="reco-group__meta">
|
||||||
|
<ev-badge [tone]="toneFor(group.alert.severity)">{{
|
||||||
|
severityLabel(group.alert.severity)
|
||||||
|
}}</ev-badge>
|
||||||
|
<span class="reco-group__type">{{ typeLabel(group.alert.type) }}</span>
|
||||||
|
@if (!siteId()) {
|
||||||
|
<a [routerLink]="['/sites', group.alert.site_id]" class="ev-link">{{
|
||||||
|
group.siteName
|
||||||
|
}}</a>
|
||||||
|
}
|
||||||
|
<time [attr.datetime]="group.alert.timestamp">{{
|
||||||
|
group.alert.timestamp | date: 'dd/MM/yyyy HH:mm'
|
||||||
|
}}</time>
|
||||||
|
</div>
|
||||||
|
<p class="reco-group__message">{{ group.alert.message }}</p>
|
||||||
|
</header>
|
||||||
|
<ol class="reco-group__items">
|
||||||
|
@for (reco of group.recommendations; track reco.recommendation_id) {
|
||||||
|
<li class="reco">
|
||||||
|
<div class="reco__head">
|
||||||
|
<strong class="reco__action">{{ reco.action }}</strong>
|
||||||
|
<ev-badge [tone]="ruleTone(reco.rule_reference)">{{
|
||||||
|
ruleLabel(reco.rule_reference)
|
||||||
|
}}</ev-badge>
|
||||||
|
</div>
|
||||||
|
<p class="reco__explanation">{{ reco.explanation }}</p>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ol>
|
||||||
|
</ev-card>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.reco-list__banner {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: var(--space-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.reco-list__state {
|
||||||
|
margin: 0 0 var(--space-3);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.reco-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--space-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.reco-group {
|
||||||
|
padding: var(--space-4);
|
||||||
|
gap: var(--space-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.reco-group--focus {
|
||||||
|
border-color: var(--color-primary);
|
||||||
|
box-shadow: 0 0 0 3px var(--color-primary-light);
|
||||||
|
}
|
||||||
|
|
||||||
|
.reco-group__alert {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--space-1);
|
||||||
|
padding-bottom: var(--space-3);
|
||||||
|
border-bottom: 1px solid var(--color-border-light);
|
||||||
|
}
|
||||||
|
|
||||||
|
.reco-group__meta {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-2);
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.reco-group__type {
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--color-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.reco-group__message {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.reco-group__items {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--space-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.reco {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.25rem;
|
||||||
|
padding: var(--space-2) var(--space-3);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
background: var(--color-bg);
|
||||||
|
border-left: 3px solid var(--color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.reco__head {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: var(--space-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.reco__action {
|
||||||
|
font-size: 0.95rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.reco__explanation {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
+244
@@ -0,0 +1,244 @@
|
|||||||
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||||
|
import { provideRouter } from '@angular/router';
|
||||||
|
import { vi } from 'vitest';
|
||||||
|
import { NEVER, of, throwError } from 'rxjs';
|
||||||
|
import { RecommendationList, joinByAlert } from './recommendation-list';
|
||||||
|
import { AlertsService } from '../../../core/services/alerts.service';
|
||||||
|
import { RecommendationsService } from '../../../core/services/recommendations.service';
|
||||||
|
import { Alert } from '../../models/alert.model';
|
||||||
|
import { Recommendation } from '../../models/recommendation.model';
|
||||||
|
import { Site } from '../../models/site.model';
|
||||||
|
|
||||||
|
const SITES: Site[] = [
|
||||||
|
{
|
||||||
|
site_id: 'SITE001',
|
||||||
|
site_name: 'Usine Nantes',
|
||||||
|
site_type: 'industriel',
|
||||||
|
location: 'Nantes',
|
||||||
|
capacity_kw: 500,
|
||||||
|
status: 'actif',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
site_id: 'SITE002',
|
||||||
|
site_name: 'Bureau Lille',
|
||||||
|
site_type: 'bureau',
|
||||||
|
location: 'Lille',
|
||||||
|
capacity_kw: 80,
|
||||||
|
status: 'actif',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
function alerte(surcharges: Partial<Alert>): Alert {
|
||||||
|
return {
|
||||||
|
alert_id: 1,
|
||||||
|
site_id: 'SITE001',
|
||||||
|
timestamp: '2026-09-15T09:00:00Z',
|
||||||
|
type: 'threshold',
|
||||||
|
severity: 'high',
|
||||||
|
message: 'Puissance appelée au-dessus de la capacité du site',
|
||||||
|
value: 812.5,
|
||||||
|
threshold: 720,
|
||||||
|
metric: 'consumption_kw',
|
||||||
|
prediction_id: null,
|
||||||
|
...surcharges,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function reco(surcharges: Partial<Recommendation>): Recommendation {
|
||||||
|
return {
|
||||||
|
recommendation_id: 1,
|
||||||
|
alert_id: 1,
|
||||||
|
action: 'Ramener la puissance appelée sous le seuil contractuel',
|
||||||
|
explanation: 'Seuil de consommation dépassé sur le site SITE001.',
|
||||||
|
rule_reference: 'threshold-reduction-v1',
|
||||||
|
created_at: '2026-09-15T09:05:00Z',
|
||||||
|
...surcharges,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const ALERTES: Alert[] = [
|
||||||
|
alerte({ alert_id: 1, site_id: 'SITE001', timestamp: '2026-09-15T09:00:00Z' }),
|
||||||
|
alerte({
|
||||||
|
alert_id: 2,
|
||||||
|
site_id: 'SITE002',
|
||||||
|
timestamp: '2026-09-15T11:00:00Z',
|
||||||
|
severity: 'critical',
|
||||||
|
type: 'spike',
|
||||||
|
message: 'Variation brutale entre deux lectures consécutives',
|
||||||
|
}),
|
||||||
|
alerte({ alert_id: 3, site_id: 'SITE001', timestamp: '2026-09-15T10:00:00Z', severity: 'low' }),
|
||||||
|
];
|
||||||
|
|
||||||
|
const RECOMMANDATIONS: Recommendation[] = [
|
||||||
|
reco({
|
||||||
|
recommendation_id: 3,
|
||||||
|
alert_id: 2,
|
||||||
|
action: "Escalader à l'astreinte sous une heure",
|
||||||
|
rule_reference: 'escalade-astreinte-v1',
|
||||||
|
}),
|
||||||
|
reco({ recommendation_id: 1, alert_id: 1 }),
|
||||||
|
reco({
|
||||||
|
recommendation_id: 2,
|
||||||
|
alert_id: 2,
|
||||||
|
action: 'Délester les équipements non prioritaires sur le créneau du pic',
|
||||||
|
rule_reference: 'spike-delestage-v1',
|
||||||
|
}),
|
||||||
|
reco({ recommendation_id: 4, alert_id: 99, rule_reference: 'orpheline-v1' }),
|
||||||
|
];
|
||||||
|
|
||||||
|
function setup(
|
||||||
|
alertsMock: { getAlerts: ReturnType<typeof vi.fn> },
|
||||||
|
recosMock: { getRecommendations: ReturnType<typeof vi.fn> },
|
||||||
|
inputs: Record<string, unknown> = {},
|
||||||
|
) {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [RecommendationList],
|
||||||
|
providers: [
|
||||||
|
provideRouter([]),
|
||||||
|
{ provide: AlertsService, useValue: alertsMock },
|
||||||
|
{ provide: RecommendationsService, useValue: recosMock },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const fixture = TestBed.createComponent(RecommendationList);
|
||||||
|
for (const [nom, valeur] of Object.entries(inputs)) {
|
||||||
|
fixture.componentRef.setInput(nom, valeur);
|
||||||
|
}
|
||||||
|
return fixture;
|
||||||
|
}
|
||||||
|
|
||||||
|
function rendre(fixture: ComponentFixture<RecommendationList>) {
|
||||||
|
fixture.detectChanges();
|
||||||
|
fixture.detectChanges();
|
||||||
|
}
|
||||||
|
|
||||||
|
function texte(fixture: ComponentFixture<RecommendationList>): string {
|
||||||
|
return (fixture.nativeElement as HTMLElement).textContent ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
const recosOk = () => ({ getRecommendations: vi.fn().mockReturnValue(of(RECOMMANDATIONS)) });
|
||||||
|
|
||||||
|
describe('joinByAlert', () => {
|
||||||
|
it('groupe par alerte, du plus récent au plus ancien, recommandations par identifiant', () => {
|
||||||
|
const groupes = joinByAlert(ALERTES, RECOMMANDATIONS, new Map([['SITE001', 'Usine Nantes']]));
|
||||||
|
|
||||||
|
expect(groupes.map((g) => g.alert.alert_id)).toEqual([2, 1]);
|
||||||
|
expect(groupes[0].recommendations.map((r) => r.recommendation_id)).toEqual([2, 3]);
|
||||||
|
expect(groupes[1].siteName).toBe('Usine Nantes');
|
||||||
|
expect(groupes[0].siteName).toBe('SITE002');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignore les alertes sans recommandation et les recommandations orphelines', () => {
|
||||||
|
const groupes = joinByAlert(ALERTES, RECOMMANDATIONS, new Map());
|
||||||
|
|
||||||
|
expect(groupes.some((g) => g.alert.alert_id === 3)).toBe(false);
|
||||||
|
expect(groupes.flatMap((g) => g.recommendations).some((r) => r.alert_id === 99)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('RecommendationList', () => {
|
||||||
|
it('charge alertes et recommandations puis affiche les groupes avec leur contexte', () => {
|
||||||
|
const getAlerts = vi.fn().mockReturnValue(of(ALERTES));
|
||||||
|
const fixture = setup({ getAlerts }, recosOk(), { sites: SITES });
|
||||||
|
|
||||||
|
rendre(fixture);
|
||||||
|
|
||||||
|
expect(getAlerts).toHaveBeenCalledWith({});
|
||||||
|
expect(fixture.nativeElement.querySelectorAll('.reco-group').length).toBe(2);
|
||||||
|
const contenu = texte(fixture);
|
||||||
|
expect(contenu).toContain('Usine Nantes');
|
||||||
|
expect(contenu).toContain('Bureau Lille');
|
||||||
|
expect(contenu).toContain('Critique');
|
||||||
|
expect(contenu).toContain('Pic de consommation');
|
||||||
|
expect(contenu).toContain('Escalade astreinte');
|
||||||
|
expect(contenu).toContain('Délester les équipements');
|
||||||
|
expect(contenu).toContain('15/09/2026');
|
||||||
|
expect(fixture.nativeElement.querySelector('a[href="/sites/SITE002"]')).not.toBeNull();
|
||||||
|
expect(fixture.componentInstance.total()).toBe(3);
|
||||||
|
expect(fixture.componentInstance.error()).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filtre les alertes du site côté API et masque le lien vers le site', () => {
|
||||||
|
const getAlerts = vi.fn().mockReturnValue(of(ALERTES.filter((a) => a.site_id === 'SITE001')));
|
||||||
|
const fixture = setup({ getAlerts }, recosOk(), { siteId: 'SITE001', sites: SITES });
|
||||||
|
|
||||||
|
rendre(fixture);
|
||||||
|
|
||||||
|
expect(getAlerts).toHaveBeenCalledWith({ site_id: 'SITE001' });
|
||||||
|
expect(fixture.nativeElement.querySelectorAll('.reco-group').length).toBe(1);
|
||||||
|
expect(fixture.nativeElement.querySelector('a[href^="/sites/"]')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ne garde que le groupe de l'alerte ciblée et le met en évidence", () => {
|
||||||
|
const fixture = setup({ getAlerts: vi.fn().mockReturnValue(of(ALERTES)) }, recosOk(), {
|
||||||
|
alertId: 2,
|
||||||
|
});
|
||||||
|
|
||||||
|
rendre(fixture);
|
||||||
|
|
||||||
|
const groupes = fixture.nativeElement.querySelectorAll('.reco-group');
|
||||||
|
expect(groupes.length).toBe(1);
|
||||||
|
expect(groupes[0].classList.contains('reco-group--focus')).toBe(true);
|
||||||
|
expect(groupes[0].id).toBe('alerte-2');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("annonce l'absence de recommandation pour une alerte inconnue", () => {
|
||||||
|
const fixture = setup({ getAlerts: vi.fn().mockReturnValue(of(ALERTES)) }, recosOk(), {
|
||||||
|
alertId: 123,
|
||||||
|
});
|
||||||
|
|
||||||
|
rendre(fixture);
|
||||||
|
|
||||||
|
expect(texte(fixture)).toContain('Aucune recommandation pour cette alerte.');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("annonce l'absence de recommandation pour le site consulté", () => {
|
||||||
|
const fixture = setup(
|
||||||
|
{ getAlerts: vi.fn().mockReturnValue(of([])) },
|
||||||
|
{ getRecommendations: vi.fn().mockReturnValue(of([])) },
|
||||||
|
{ siteId: 'SITE001' },
|
||||||
|
);
|
||||||
|
|
||||||
|
rendre(fixture);
|
||||||
|
|
||||||
|
expect(texte(fixture)).toContain('Aucune recommandation pour ce site.');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("signale l'indisponibilité et n'affiche aucun groupe si un des deux appels échoue", () => {
|
||||||
|
const fixture = setup(
|
||||||
|
{ getAlerts: vi.fn().mockReturnValue(of(ALERTES)) },
|
||||||
|
{ getRecommendations: vi.fn().mockReturnValue(throwError(() => new Error('nope'))) },
|
||||||
|
);
|
||||||
|
|
||||||
|
rendre(fixture);
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.error()).not.toBeNull();
|
||||||
|
expect(fixture.componentInstance.groups()).toEqual([]);
|
||||||
|
expect(texte(fixture)).toContain('Recommandations indisponibles');
|
||||||
|
expect(fixture.nativeElement.querySelectorAll('.reco-group').length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('annonce le chargement tant que la réponse ne vient pas', () => {
|
||||||
|
const fixture = setup(
|
||||||
|
{ getAlerts: vi.fn().mockReturnValue(NEVER) },
|
||||||
|
{ getRecommendations: vi.fn().mockReturnValue(NEVER) },
|
||||||
|
);
|
||||||
|
|
||||||
|
rendre(fixture);
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.loading()).toBe(true);
|
||||||
|
expect(texte(fixture)).toContain('Chargement des recommandations');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('recharge les deux flux à la demande', () => {
|
||||||
|
const getAlerts = vi.fn().mockReturnValue(of(ALERTES));
|
||||||
|
const recos = recosOk();
|
||||||
|
const fixture = setup({ getAlerts }, recos);
|
||||||
|
rendre(fixture);
|
||||||
|
|
||||||
|
fixture.componentInstance.reload();
|
||||||
|
rendre(fixture);
|
||||||
|
|
||||||
|
expect(getAlerts).toHaveBeenCalledTimes(2);
|
||||||
|
expect(recos.getRecommendations).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
import { Component, DestroyRef, computed, inject, input, signal } from '@angular/core';
|
||||||
|
import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';
|
||||||
|
import { DatePipe } from '@angular/common';
|
||||||
|
import { RouterLink } from '@angular/router';
|
||||||
|
import { catchError, EMPTY, forkJoin, Observable, switchMap, tap } from 'rxjs';
|
||||||
|
import { AlertsService } from '../../../core/services/alerts.service';
|
||||||
|
import { RecommendationsService } from '../../../core/services/recommendations.service';
|
||||||
|
import { Alert, AlertSeverity, AlertType } from '../../models/alert.model';
|
||||||
|
import { Recommendation } from '../../models/recommendation.model';
|
||||||
|
import { Site } from '../../models/site.model';
|
||||||
|
import {
|
||||||
|
LIBELLE_PAR_SEVERITE,
|
||||||
|
LIBELLE_PAR_TYPE,
|
||||||
|
TON_PAR_SEVERITE,
|
||||||
|
} from '../../models/alert-presentation';
|
||||||
|
import { libelleRegle, tonRegle } from '../../models/recommendation-presentation';
|
||||||
|
import { Card } from '../ui/card/card';
|
||||||
|
import { Badge, BadgeTone } from '../ui/badge/badge';
|
||||||
|
import { Alert as EvAlert } from '../ui/alert/alert';
|
||||||
|
|
||||||
|
const UNAVAILABLE_MESSAGE = 'Recommandations indisponibles, réessayez plus tard.';
|
||||||
|
|
||||||
|
export interface RecommendedAlertView {
|
||||||
|
alert: Alert;
|
||||||
|
siteName: string;
|
||||||
|
recommendations: Recommendation[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Chargement {
|
||||||
|
alerts: Alert[];
|
||||||
|
recommendations: Recommendation[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pourquoi : une recommandation ne porte que alert_id, jamais site_id, et /recommendations n'a
|
||||||
|
// aucun filtre ; la jointure se fait ici, en O(alertes), acceptable à la taille du jeu de données.
|
||||||
|
export function joinByAlert(
|
||||||
|
alerts: Alert[],
|
||||||
|
recommendations: Recommendation[],
|
||||||
|
siteNames: Map<string, string>,
|
||||||
|
): RecommendedAlertView[] {
|
||||||
|
const parAlerte = new Map<number, Recommendation[]>();
|
||||||
|
for (const recommandation of recommendations) {
|
||||||
|
const liste = parAlerte.get(recommandation.alert_id) ?? [];
|
||||||
|
liste.push(recommandation);
|
||||||
|
parAlerte.set(recommandation.alert_id, liste);
|
||||||
|
}
|
||||||
|
return alerts
|
||||||
|
.filter((alert) => parAlerte.has(alert.alert_id))
|
||||||
|
.map((alert) => ({
|
||||||
|
alert,
|
||||||
|
siteName: siteNames.get(alert.site_id) ?? alert.site_id,
|
||||||
|
recommendations: [...(parAlerte.get(alert.alert_id) ?? [])].sort(
|
||||||
|
(a, b) => a.recommendation_id - b.recommendation_id,
|
||||||
|
),
|
||||||
|
}))
|
||||||
|
.sort((a, b) => Date.parse(b.alert.timestamp) - Date.parse(a.alert.timestamp));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-recommendation-list',
|
||||||
|
standalone: true,
|
||||||
|
imports: [DatePipe, RouterLink, Card, Badge, EvAlert],
|
||||||
|
templateUrl: './recommendation-list.html',
|
||||||
|
styleUrl: './recommendation-list.scss',
|
||||||
|
})
|
||||||
|
export class RecommendationList {
|
||||||
|
private alertsService = inject(AlertsService);
|
||||||
|
private recommendationsService = inject(RecommendationsService);
|
||||||
|
private destroyRef = inject(DestroyRef);
|
||||||
|
|
||||||
|
siteId = input<string | null>(null);
|
||||||
|
alertId = input<number | null>(null);
|
||||||
|
sites = input<Site[]>([]);
|
||||||
|
|
||||||
|
private data = signal<Chargement | null>(null);
|
||||||
|
private reloadTick = signal(0);
|
||||||
|
loading = signal(true);
|
||||||
|
error = signal<string | null>(null);
|
||||||
|
|
||||||
|
private trigger = computed(() => ({ siteId: this.siteId(), tick: this.reloadTick() }));
|
||||||
|
|
||||||
|
private siteNameById = computed(
|
||||||
|
() => new Map(this.sites().map((site) => [site.site_id, site.site_name])),
|
||||||
|
);
|
||||||
|
|
||||||
|
hasData = computed(() => this.data() !== null);
|
||||||
|
|
||||||
|
groups = computed<RecommendedAlertView[]>(() => {
|
||||||
|
const data = this.data();
|
||||||
|
return data ? joinByAlert(data.alerts, data.recommendations, this.siteNameById()) : [];
|
||||||
|
});
|
||||||
|
|
||||||
|
visibleGroups = computed(() => {
|
||||||
|
const alertId = this.alertId();
|
||||||
|
const groups = this.groups();
|
||||||
|
return alertId === null ? groups : groups.filter((group) => group.alert.alert_id === alertId);
|
||||||
|
});
|
||||||
|
|
||||||
|
total = computed(() =>
|
||||||
|
this.visibleGroups().reduce((somme, group) => somme + group.recommendations.length, 0),
|
||||||
|
);
|
||||||
|
|
||||||
|
emptyMessage = computed(() => {
|
||||||
|
if (this.alertId() !== null) {
|
||||||
|
return 'Aucune recommandation pour cette alerte.';
|
||||||
|
}
|
||||||
|
return this.siteId()
|
||||||
|
? 'Aucune recommandation pour ce site.'
|
||||||
|
: 'Aucune recommandation pour le moment.';
|
||||||
|
});
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
toObservable(this.trigger)
|
||||||
|
.pipe(
|
||||||
|
tap(() => this.loading.set(true)),
|
||||||
|
switchMap(({ siteId }) =>
|
||||||
|
forkJoin({
|
||||||
|
alerts: this.alertsService.getAlerts(siteId ? { site_id: siteId } : {}),
|
||||||
|
recommendations: this.recommendationsService.getRecommendations(),
|
||||||
|
}).pipe(catchError(() => this.reportUnavailable())),
|
||||||
|
),
|
||||||
|
takeUntilDestroyed(this.destroyRef),
|
||||||
|
)
|
||||||
|
.subscribe((data) => {
|
||||||
|
this.loading.set(false);
|
||||||
|
this.error.set(null);
|
||||||
|
this.data.set(data);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
reload(): void {
|
||||||
|
this.reloadTick.update((tick) => tick + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
toneFor(severity: AlertSeverity): BadgeTone {
|
||||||
|
return TON_PAR_SEVERITE[severity];
|
||||||
|
}
|
||||||
|
|
||||||
|
severityLabel(severity: AlertSeverity): string {
|
||||||
|
return LIBELLE_PAR_SEVERITE[severity];
|
||||||
|
}
|
||||||
|
|
||||||
|
typeLabel(type: AlertType): string {
|
||||||
|
return LIBELLE_PAR_TYPE[type];
|
||||||
|
}
|
||||||
|
|
||||||
|
ruleLabel(reference: string): string {
|
||||||
|
return libelleRegle(reference);
|
||||||
|
}
|
||||||
|
|
||||||
|
ruleTone(reference: string): BadgeTone {
|
||||||
|
return tonRegle(reference);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Piège : vider les données avec l'erreur ; une demi-jointure (alertes sans recommandations,
|
||||||
|
// ou l'inverse) afficherait des groupes faux plutôt que rien.
|
||||||
|
private reportUnavailable(): Observable<never> {
|
||||||
|
this.loading.set(false);
|
||||||
|
this.error.set(UNAVAILABLE_MESSAGE);
|
||||||
|
this.data.set(null);
|
||||||
|
return EMPTY;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
<svg
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
focusable="false"
|
||||||
|
[attr.role]="label() ? 'img' : null"
|
||||||
|
[attr.aria-label]="label()"
|
||||||
|
[attr.aria-hidden]="label() ? null : 'true'"
|
||||||
|
>
|
||||||
|
@switch (name()) {
|
||||||
|
@case ('spike') {
|
||||||
|
<polyline points="3 17 8 12 11 15 21 5" />
|
||||||
|
<polyline points="15 5 21 5 21 11" />
|
||||||
|
}
|
||||||
|
@case ('threshold') {
|
||||||
|
<line x1="3" y1="10" x2="21" y2="10" stroke-dasharray="3 3" />
|
||||||
|
<polyline points="4 19 9 13 13 15 20 6" />
|
||||||
|
}
|
||||||
|
@case ('anomaly') {
|
||||||
|
<polyline points="3 12 7 12 9.5 6 12.5 18 15 12 21 12" />
|
||||||
|
}
|
||||||
|
@case ('outage') {
|
||||||
|
<path d="M7.5 6.5a7 7 0 1 0 9 0" />
|
||||||
|
<line x1="12" y1="3" x2="12" y2="11" />
|
||||||
|
}
|
||||||
|
@case ('sensor') {
|
||||||
|
<circle cx="12" cy="13" r="2" />
|
||||||
|
<path d="M8.5 9.5a5 5 0 0 0 0 7" />
|
||||||
|
<path d="M15.5 9.5a5 5 0 0 1 0 7" />
|
||||||
|
<path d="M5.5 6.5a9 9 0 0 0 0 13" />
|
||||||
|
<path d="M18.5 6.5a9 9 0 0 1 0 13" />
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.0 KiB |
@@ -0,0 +1,12 @@
|
|||||||
|
:host {
|
||||||
|
display: inline-flex;
|
||||||
|
flex-shrink: 0;
|
||||||
|
width: 1em;
|
||||||
|
height: 1em;
|
||||||
|
vertical-align: -0.125em;
|
||||||
|
}
|
||||||
|
|
||||||
|
svg {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { Icon, IconName } from './icon';
|
||||||
|
|
||||||
|
const NOMS: IconName[] = ['spike', 'threshold', 'anomaly', 'outage', 'sensor'];
|
||||||
|
|
||||||
|
function rendre(name: IconName, label: string | null = null) {
|
||||||
|
const fixture = TestBed.createComponent(Icon);
|
||||||
|
fixture.componentRef.setInput('name', name);
|
||||||
|
fixture.componentRef.setInput('label', label);
|
||||||
|
fixture.detectChanges();
|
||||||
|
return fixture.nativeElement as HTMLElement;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('Icon', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.configureTestingModule({ imports: [Icon] });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dessine un tracé distinct pour chacun des cinq types', () => {
|
||||||
|
const traces = NOMS.map((name) => rendre(name).querySelector('svg')?.innerHTML.trim());
|
||||||
|
|
||||||
|
for (const trace of traces) {
|
||||||
|
expect(trace).toBeTruthy();
|
||||||
|
}
|
||||||
|
expect(new Set(traces).size).toBe(NOMS.length);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reste décoratif sans libellé', () => {
|
||||||
|
const svg = rendre('spike').querySelector('svg');
|
||||||
|
|
||||||
|
expect(svg?.getAttribute('aria-hidden')).toBe('true');
|
||||||
|
expect(svg?.hasAttribute('role')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('expose un rôle image et un libellé accessible quand on lui en donne un', () => {
|
||||||
|
const svg = rendre('outage', 'Coupure').querySelector('svg');
|
||||||
|
|
||||||
|
expect(svg?.getAttribute('role')).toBe('img');
|
||||||
|
expect(svg?.getAttribute('aria-label')).toBe('Coupure');
|
||||||
|
expect(svg?.hasAttribute('aria-hidden')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hérite de la couleur du parent via currentColor', () => {
|
||||||
|
const svg = rendre('sensor').querySelector('svg');
|
||||||
|
|
||||||
|
expect(svg?.getAttribute('stroke')).toBe('currentColor');
|
||||||
|
expect(svg?.getAttribute('fill')).toBe('none');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { Component, input } from '@angular/core';
|
||||||
|
|
||||||
|
export type IconName = 'spike' | 'threshold' | 'anomaly' | 'outage' | 'sensor';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'ev-icon',
|
||||||
|
standalone: true,
|
||||||
|
templateUrl: './icon.html',
|
||||||
|
styleUrl: './icon.scss',
|
||||||
|
})
|
||||||
|
export class Icon {
|
||||||
|
name = input.required<IconName>();
|
||||||
|
label = input<string | null>(null);
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import {
|
||||||
|
LIBELLE_PAR_SEVERITE,
|
||||||
|
LIBELLE_PAR_TYPE,
|
||||||
|
SEVERITES,
|
||||||
|
TON_PAR_SEVERITE,
|
||||||
|
TYPES_ALERTE,
|
||||||
|
UNITE_PAR_METRIQUE,
|
||||||
|
} from './alert-presentation';
|
||||||
|
|
||||||
|
describe('alert-presentation', () => {
|
||||||
|
it('distingue le ton des sévérités high et critical', () => {
|
||||||
|
expect(TON_PAR_SEVERITE.high).toBe('danger');
|
||||||
|
expect(TON_PAR_SEVERITE.critical).toBe('critical');
|
||||||
|
expect(TON_PAR_SEVERITE.high).not.toBe(TON_PAR_SEVERITE.critical);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("n'affiche pas une alerte faible avec le ton de succès", () => {
|
||||||
|
expect(TON_PAR_SEVERITE.low).toBe('neutral');
|
||||||
|
expect(TON_PAR_SEVERITE.medium).toBe('warning');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('donne un libellé français à chaque sévérité et à chaque type', () => {
|
||||||
|
for (const severite of SEVERITES) {
|
||||||
|
expect(LIBELLE_PAR_SEVERITE[severite]).toBeTruthy();
|
||||||
|
}
|
||||||
|
for (const type of TYPES_ALERTE) {
|
||||||
|
expect(LIBELLE_PAR_TYPE[type]).toBeTruthy();
|
||||||
|
}
|
||||||
|
expect(SEVERITES.length).toBe(4);
|
||||||
|
expect(TYPES_ALERTE.length).toBe(5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('associe une unité à chaque métrique du contrat', () => {
|
||||||
|
expect(UNITE_PAR_METRIQUE.consumption_kw).toBe('kW');
|
||||||
|
expect(UNITE_PAR_METRIQUE.consumption_kwh).toBe('kWh');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { BadgeTone } from '../components/ui/badge/badge';
|
||||||
|
import { AlertMetric, AlertSeverity, AlertType } from './alert.model';
|
||||||
|
|
||||||
|
// Pourquoi : `low` en neutre plutôt qu'en vert, une alerte faible reste une alerte ; le vert se
|
||||||
|
// lisait comme « tout va bien » à côté des rouges.
|
||||||
|
export const TON_PAR_SEVERITE: Record<AlertSeverity, BadgeTone> = {
|
||||||
|
low: 'neutral',
|
||||||
|
medium: 'warning',
|
||||||
|
high: 'danger',
|
||||||
|
critical: 'critical',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const LIBELLE_PAR_SEVERITE: Record<AlertSeverity, string> = {
|
||||||
|
low: 'Faible',
|
||||||
|
medium: 'Moyenne',
|
||||||
|
high: 'Élevée',
|
||||||
|
critical: 'Critique',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const LIBELLE_PAR_TYPE: Record<AlertType, string> = {
|
||||||
|
spike: 'Pic de consommation',
|
||||||
|
threshold: 'Seuil dépassé',
|
||||||
|
anomaly: 'Anomalie',
|
||||||
|
outage: 'Coupure',
|
||||||
|
sensor: 'Capteur',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const UNITE_PAR_METRIQUE: Record<AlertMetric, string> = {
|
||||||
|
consumption_kw: 'kW',
|
||||||
|
consumption_kwh: 'kWh',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const SEVERITES: readonly AlertSeverity[] = ['low', 'medium', 'high', 'critical'];
|
||||||
|
|
||||||
|
export const TYPES_ALERTE: readonly AlertType[] = [
|
||||||
|
'spike',
|
||||||
|
'threshold',
|
||||||
|
'anomaly',
|
||||||
|
'outage',
|
||||||
|
'sensor',
|
||||||
|
];
|
||||||
@@ -1,13 +1,16 @@
|
|||||||
export type AlertSeverity = 'low' | 'medium' | 'high' | 'critical';
|
export type AlertSeverity = 'low' | 'medium' | 'high' | 'critical';
|
||||||
export type AlertType = 'spike' | 'threshold' | 'anomaly' | 'outage' | 'sensor';
|
export type AlertType = 'spike' | 'threshold' | 'anomaly' | 'outage' | 'sensor';
|
||||||
|
export type AlertMetric = 'consumption_kw' | 'consumption_kwh';
|
||||||
|
|
||||||
export interface Alert {
|
export interface Alert {
|
||||||
alert_id: string;
|
alert_id: number;
|
||||||
timestamp: string;
|
|
||||||
site_id: string;
|
site_id: string;
|
||||||
severity: AlertSeverity;
|
timestamp: string;
|
||||||
type: AlertType;
|
type: AlertType;
|
||||||
|
severity: AlertSeverity;
|
||||||
message: string;
|
message: string;
|
||||||
value: number;
|
value: number | null;
|
||||||
threshold: number;
|
threshold: number | null;
|
||||||
|
metric: AlertMetric | null;
|
||||||
|
prediction_id: number | null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { libelleRegle, tonRegle } from './recommendation-presentation';
|
||||||
|
|
||||||
|
describe('recommendation-presentation', () => {
|
||||||
|
it('traduit les sept règles connues du moteur', () => {
|
||||||
|
expect(libelleRegle('spike-delestage-v1')).toBe('Délestage');
|
||||||
|
expect(libelleRegle('threshold-reduction-v1')).toBe('Réduction de puissance');
|
||||||
|
expect(libelleRegle('outage-secours-v1')).toBe('Alimentation de secours');
|
||||||
|
expect(libelleRegle('sensor-maintenance-v1')).toBe('Maintenance capteur');
|
||||||
|
expect(libelleRegle('anomaly-verification-v1')).toBe('Vérification');
|
||||||
|
expect(libelleRegle('escalade-astreinte-v1')).toBe('Escalade astreinte');
|
||||||
|
expect(libelleRegle('contrat-puissance-v1')).toBe('Contrat de puissance');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('affiche telle quelle une référence de règle inconnue', () => {
|
||||||
|
expect(libelleRegle('spike-delestage-v2')).toBe('spike-delestage-v2');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("réserve le ton critique à l'escalade vers l'astreinte", () => {
|
||||||
|
expect(tonRegle('escalade-astreinte-v1')).toBe('critical');
|
||||||
|
expect(tonRegle('spike-delestage-v1')).toBe('neutral');
|
||||||
|
expect(tonRegle('inconnue-v9')).toBe('neutral');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { BadgeTone } from '../components/ui/badge/badge';
|
||||||
|
|
||||||
|
// Contrainte : une règle dont le sens change reçoit un suffixe -v2 côté backend (ADR 0006) ;
|
||||||
|
// une référence inconnue s'affiche donc telle quelle plutôt que de casser la vue.
|
||||||
|
const LIBELLE_PAR_REGLE: Record<string, string> = {
|
||||||
|
'spike-delestage-v1': 'Délestage',
|
||||||
|
'threshold-reduction-v1': 'Réduction de puissance',
|
||||||
|
'outage-secours-v1': 'Alimentation de secours',
|
||||||
|
'sensor-maintenance-v1': 'Maintenance capteur',
|
||||||
|
'anomaly-verification-v1': 'Vérification',
|
||||||
|
'escalade-astreinte-v1': 'Escalade astreinte',
|
||||||
|
'contrat-puissance-v1': 'Contrat de puissance',
|
||||||
|
};
|
||||||
|
|
||||||
|
const REGLE_ESCALADE = 'escalade-astreinte-v1';
|
||||||
|
|
||||||
|
export function libelleRegle(reference: string): string {
|
||||||
|
return LIBELLE_PAR_REGLE[reference] ?? reference;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function tonRegle(reference: string): BadgeTone {
|
||||||
|
return reference === REGLE_ESCALADE ? 'critical' : 'neutral';
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
export interface Recommendation {
|
||||||
|
recommendation_id: number;
|
||||||
|
alert_id: number;
|
||||||
|
action: string;
|
||||||
|
explanation: string;
|
||||||
|
rule_reference: string;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RecommendationGenerationReport {
|
||||||
|
alerts_examined: number;
|
||||||
|
recommendations_created: number;
|
||||||
|
already_present: number;
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
export type SensorStatus = 'ok' | 'failing';
|
||||||
|
export type OverallStatus = 'ok' | 'degraded' | 'critical';
|
||||||
|
|
||||||
|
export interface SensorDiagnostic {
|
||||||
|
status: SensorStatus;
|
||||||
|
since: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SiteSensors {
|
||||||
|
consumption: SensorDiagnostic;
|
||||||
|
electrical: SensorDiagnostic;
|
||||||
|
temperature: SensorDiagnostic;
|
||||||
|
humidity: SensorDiagnostic;
|
||||||
|
network: SensorDiagnostic;
|
||||||
|
[key: string]: SensorDiagnostic;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SiteSensorStatus {
|
||||||
|
site_id: string;
|
||||||
|
site_name: string;
|
||||||
|
sensors: SiteSensors;
|
||||||
|
overall: OverallStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SensorStatusResponse {
|
||||||
|
timestamp: string;
|
||||||
|
sites: SiteSensorStatus[];
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
@use 'styles/forms';
|
@use 'styles/forms';
|
||||||
@use 'styles/auth-page';
|
@use 'styles/auth-page';
|
||||||
@use 'styles/links';
|
@use 'styles/links';
|
||||||
|
@use 'styles/tables';
|
||||||
|
|
||||||
body {
|
body {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
|
|||||||
@@ -29,3 +29,18 @@
|
|||||||
color: var(--color-disabled);
|
color: var(--color-disabled);
|
||||||
margin-top: 0.25rem;
|
margin-top: 0.25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Piège : le chevron est un SVG en data URI, où aucun token CSS n'est lisible ; sa couleur
|
||||||
|
// reprend en dur la valeur de --color-text-muted.
|
||||||
|
.form-select {
|
||||||
|
@extend .form-input;
|
||||||
|
padding-right: 2.25rem;
|
||||||
|
color: var(--color-text);
|
||||||
|
background-color: var(--color-surface);
|
||||||
|
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' fill='none' stroke='%236b7280' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M6 8l4 4 4-4'/%3E%3C/svg%3E");
|
||||||
|
background-repeat: no-repeat;
|
||||||
|
background-position: right 0.6rem center;
|
||||||
|
background-size: 1rem;
|
||||||
|
appearance: none;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
// Piège : `ev-card` pose son padding sur `:host`, compilé en `[_nghost-…]` (même spécificité
|
||||||
|
// qu'une classe) et injecté après la feuille globale ; il faut le sélecteur d'élément pour gagner.
|
||||||
|
ev-card.ev-table-card {
|
||||||
|
padding: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-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: var(--font-size-xs);
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
}
|
||||||
|
|
||||||
|
tbody tr:last-child td {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
tbody tr:hover td {
|
||||||
|
background: var(--color-bg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-table__number {
|
||||||
|
font-weight: 600;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-table__muted {
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
@@ -29,10 +29,17 @@
|
|||||||
|
|
||||||
// Typo, rayons, ombre
|
// Typo, rayons, ombre
|
||||||
--font-family: 'Segoe UI', system-ui, sans-serif;
|
--font-family: 'Segoe UI', system-ui, sans-serif;
|
||||||
|
--font-size-xs: 0.75rem;
|
||||||
|
--font-size-sm: 0.85rem;
|
||||||
|
--font-size-md: 1rem;
|
||||||
|
--font-size-lg: 1.25rem;
|
||||||
|
--font-size-xl: 1.75rem;
|
||||||
|
--font-size-2xl: 2.25rem;
|
||||||
--radius-sm: 8px;
|
--radius-sm: 8px;
|
||||||
--radius-md: 12px;
|
--radius-md: 12px;
|
||||||
--radius-pill: 999px;
|
--radius-pill: 999px;
|
||||||
--shadow-card: 0 1px 3px rgba(0, 0, 0, 0.06);
|
--shadow-card: 0 1px 3px rgba(0, 0, 0, 0.06);
|
||||||
|
--shadow-card-hover: 0 6px 16px rgba(0, 0, 0, 0.08);
|
||||||
|
|
||||||
// Espacements
|
// Espacements
|
||||||
--space-1: 0.35rem;
|
--space-1: 0.35rem;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
{
|
{
|
||||||
"compileOnSave": false,
|
"compileOnSave": false,
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
|
"strict": true,
|
||||||
"noImplicitOverride": true,
|
"noImplicitOverride": true,
|
||||||
"noPropertyAccessFromIndexSignature": true,
|
"noPropertyAccessFromIndexSignature": true,
|
||||||
"noImplicitReturns": true,
|
"noImplicitReturns": true,
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
-- Base de metadonnees Airflow (webserver + scheduler, LocalExecutor). Separee de la base
|
||||||
|
-- applicative : les tables internes d'Airflow (dag_run, task_instance, ...) n'ont rien a faire
|
||||||
|
-- dans le schema metier. Meme conteneur Postgres que `enervision`/`enervision_test` plutot qu'un
|
||||||
|
-- service dedie, pour ne pas ajouter un conteneur de plus (issue #115).
|
||||||
|
CREATE DATABASE airflow;
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
# Piège : `APP_ENV` et `APP_DEBUG` sont en dur et non en `${APP_ENV:-prod}` : le `.env` du poste
|
||||||
|
# vaut `local` et reprendrait le dessus, ce qui laisserait le cookie sans `__Secure-` et
|
||||||
|
# rouvrirait `/docs`. Hors `local`, l'API exige en retour une origine CORS non vide.
|
||||||
|
# Piège : les listes de ports se cumulent à la fusion des deux fichiers. `!reset` est le seul
|
||||||
|
# moyen de dépublier 8000 et 3000 : sans lui, l'API resterait joignable en clair à côté du proxy.
|
||||||
|
# Piège : pas de `:?` sur `PUBLIC_HOST`. Compose interpole tout le fichier, y compris pour
|
||||||
|
# `stop` et `logs` : la garde vit dans `make stack-up`, qui la compare au certificat servi.
|
||||||
|
# Pourquoi : ports du proxy et origine publique en variables, pour que deux environnements
|
||||||
|
# cohabitent sur la même machine, chacun dans son projet Compose (ADR 0009).
|
||||||
|
|
||||||
|
name: enervision
|
||||||
|
|
||||||
|
services:
|
||||||
|
db:
|
||||||
|
ports: !override
|
||||||
|
- "127.0.0.1:${POSTGRES_PORT:-5433}:5432"
|
||||||
|
environment:
|
||||||
|
TS_TUNE_MEMORY: ${TS_TUNE_MEMORY:-2GB}
|
||||||
|
TS_TUNE_NUM_CPUS: ${TS_TUNE_NUM_CPUS:-2}
|
||||||
|
|
||||||
|
mailpit:
|
||||||
|
ports: !override
|
||||||
|
- "127.0.0.1:${MAILPIT_UI_PORT:-8025}:8025"
|
||||||
|
|
||||||
|
airflow-webserver:
|
||||||
|
ports: !override
|
||||||
|
- "127.0.0.1:${AIRFLOW_PORT:-8080}:8080"
|
||||||
|
environment:
|
||||||
|
AIRFLOW__WEBSERVER__WORKERS: ${AIRFLOW_WEBSERVER_WORKERS:-2}
|
||||||
|
|
||||||
|
backend:
|
||||||
|
ports: !reset null
|
||||||
|
command:
|
||||||
|
- uvicorn
|
||||||
|
- app.main:create_app
|
||||||
|
- --factory
|
||||||
|
- --host
|
||||||
|
- 0.0.0.0
|
||||||
|
- --port
|
||||||
|
- "8000"
|
||||||
|
- --proxy-headers
|
||||||
|
- --forwarded-allow-ips=*
|
||||||
|
environment:
|
||||||
|
APP_ENV: prod
|
||||||
|
APP_DEBUG: "false"
|
||||||
|
APP_TRUST_PROXY_HEADERS: "true"
|
||||||
|
APP_CORS_ORIGINS: ${PUBLIC_ORIGIN:-https://${PUBLIC_HOST:-enervision.local}}
|
||||||
|
APP_FRONTEND_RESET_PASSWORD_URL: ${PUBLIC_ORIGIN:-https://${PUBLIC_HOST:-enervision.local}}/reset-password
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
ports: !reset null
|
||||||
|
|
||||||
|
proxy:
|
||||||
|
image: nginx:1.28-alpine
|
||||||
|
depends_on:
|
||||||
|
backend:
|
||||||
|
condition: service_healthy
|
||||||
|
frontend:
|
||||||
|
condition: service_started
|
||||||
|
ports:
|
||||||
|
- "${PROXY_HTTP_PORT:-80}:80"
|
||||||
|
- "${PROXY_HTTPS_PORT:-443}:443"
|
||||||
|
volumes:
|
||||||
|
- ./infra/proxy/nginx.conf:/etc/nginx/nginx.conf:ro
|
||||||
|
- ./infra/proxy/conf.d:/etc/nginx/conf.d:ro
|
||||||
|
- ./infra/proxy/tls:/etc/nginx/tls:ro
|
||||||
|
- acme_webroot:/var/www/certbot
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
certbot:
|
||||||
|
image: certbot/certbot:v5.8.0
|
||||||
|
profiles: ["acme"]
|
||||||
|
volumes:
|
||||||
|
- letsencrypt:/etc/letsencrypt
|
||||||
|
- acme_webroot:/var/www/certbot
|
||||||
|
- ./infra/proxy/tls:/tls
|
||||||
|
- ./infra/proxy/acme-deploy-hook.sh:/deploy-hook.sh:ro
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
acme_webroot:
|
||||||
|
letsencrypt:
|
||||||
+103
-2
@@ -5,6 +5,42 @@
|
|||||||
|
|
||||||
name: enervision
|
name: enervision
|
||||||
|
|
||||||
|
# Piege : LocalExecutor fait tourner les taches comme sous-processus du scheduler, jamais du
|
||||||
|
# webserver. `airflow_ml_state` (modele entraine, magasin MLflow) n'a donc besoin d'etre monte
|
||||||
|
# que sur `airflow-scheduler` en pratique, mais reste partage avec le webserver pour que ce
|
||||||
|
# dernier puisse au besoin l'inspecter sans en devenir dependant.
|
||||||
|
x-airflow-common: &airflow-common
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: etl/airflow/Dockerfile
|
||||||
|
environment: &airflow-common-env
|
||||||
|
AIRFLOW__CORE__EXECUTOR: LocalExecutor
|
||||||
|
AIRFLOW__CORE__LOAD_EXAMPLES: "false"
|
||||||
|
# Piege : pas de `:?` sur les secrets Airflow. Compose interpole le fichier entier avant de
|
||||||
|
# filtrer les services : une variable requise manquante casserait aussi `make db-up`,
|
||||||
|
# `make dev`... pour quiconque n'a pas encore complete son `.env`. Le refus est porte par
|
||||||
|
# `airflow-init` (ci-dessous), dont `webserver` et `scheduler` dependent.
|
||||||
|
AIRFLOW__CORE__FERNET_KEY: ${AIRFLOW_FERNET_KEY:-}
|
||||||
|
AIRFLOW__WEBSERVER__SECRET_KEY: ${AIRFLOW_WEBSERVER_SECRET_KEY:-}
|
||||||
|
AIRFLOW__DATABASE__SQL_ALCHEMY_CONN: postgresql+psycopg2://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/airflow
|
||||||
|
# Role `enervision_ml` dedie pas encore provisionne (dette assumee, cf. ADR 0003) :
|
||||||
|
# memes identifiants que le backend en attendant.
|
||||||
|
ML_DATABASE_URL: postgresql+psycopg://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
|
||||||
|
MLFLOW_TRACKING_URI: sqlite:////opt/ml/state/mlflow.db
|
||||||
|
# Le DAG `alertes` lance le backend en sous-processus : il lit `DATABASE_URL`, en
|
||||||
|
# dialecte asyncpg, là où le pipeline ML lit `ML_DATABASE_URL`.
|
||||||
|
DATABASE_URL: postgresql+asyncpg://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
|
||||||
|
# Clé distincte de celle de l'API : la détection ne signe ni ne vérifie aucun jeton, et
|
||||||
|
# Airflow permet d'exécuter du code depuis son interface (cf. ADR 0008).
|
||||||
|
APP_SECRET_KEY: ${AIRFLOW_APP_SECRET_KEY:-}
|
||||||
|
volumes:
|
||||||
|
- ./etl/airflow/dags:/opt/airflow/dags
|
||||||
|
- ./etl/airflow/plugins:/opt/airflow/plugins
|
||||||
|
- ./data/raw:/opt/data/raw:ro
|
||||||
|
- airflow_logs:/opt/airflow/logs
|
||||||
|
- airflow_ml_state:/opt/ml/state
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
services:
|
services:
|
||||||
db:
|
db:
|
||||||
image: timescale/timescaledb-ha:pg17
|
image: timescale/timescaledb-ha:pg17
|
||||||
@@ -19,6 +55,7 @@ services:
|
|||||||
- pgdata:/home/postgres/pgdata/data
|
- pgdata:/home/postgres/pgdata/data
|
||||||
- ./db/init/100-extensions.sql:/docker-entrypoint-initdb.d/100-extensions.sql:ro
|
- ./db/init/100-extensions.sql:/docker-entrypoint-initdb.d/100-extensions.sql:ro
|
||||||
- ./db/init/110-test-database.sql:/docker-entrypoint-initdb.d/110-test-database.sql:ro
|
- ./db/init/110-test-database.sql:/docker-entrypoint-initdb.d/110-test-database.sql:ro
|
||||||
|
- ./db/init/120-airflow-database.sql:/docker-entrypoint-initdb.d/120-airflow-database.sql:ro
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
||||||
interval: 10s
|
interval: 10s
|
||||||
@@ -50,6 +87,12 @@ services:
|
|||||||
APP_SECRET_KEY: ${APP_SECRET_KEY:?}
|
APP_SECRET_KEY: ${APP_SECRET_KEY:?}
|
||||||
APP_CORS_ORIGINS: ${APP_CORS_ORIGINS:-http://localhost:4200}
|
APP_CORS_ORIGINS: ${APP_CORS_ORIGINS:-http://localhost:4200}
|
||||||
DATABASE_URL: postgresql+asyncpg://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
|
DATABASE_URL: postgresql+asyncpg://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
|
||||||
|
|
||||||
|
APP_MOCK_API_BASE_URL: ${APP_MOCK_API_BASE_URL:-https://api-mock.charlieandre.fr}
|
||||||
|
APP_MOCK_API_USERNAME: ${APP_MOCK_API_USERNAME:-}
|
||||||
|
APP_MOCK_API_PASSWORD: ${APP_MOCK_API_PASSWORD:-}
|
||||||
|
APP_MOCK_API_TIMEOUT_SECONDS: ${APP_MOCK_API_TIMEOUT_SECONDS:-10}
|
||||||
|
|
||||||
APP_FRONTEND_RESET_PASSWORD_URL: ${APP_FRONTEND_RESET_PASSWORD_URL:-http://localhost:4200/reset-password}
|
APP_FRONTEND_RESET_PASSWORD_URL: ${APP_FRONTEND_RESET_PASSWORD_URL:-http://localhost:4200/reset-password}
|
||||||
APP_SMTP_HOST: mailpit
|
APP_SMTP_HOST: mailpit
|
||||||
APP_SMTP_PORT: "1025"
|
APP_SMTP_PORT: "1025"
|
||||||
@@ -62,9 +105,67 @@ services:
|
|||||||
frontend:
|
frontend:
|
||||||
build: ./apps/frontend
|
build: ./apps/frontend
|
||||||
ports:
|
ports:
|
||||||
- "${FRONTEND_PORT:-3000}:80"
|
- "${FRONTEND_PORT:-3000}:3000"
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
|
# Conteneur unique, jamais redemarre. La migration et la creation du premier compte sont
|
||||||
|
# portees par l'entrypoint de l'image (`_AIRFLOW_DB_MIGRATE`, `_AIRFLOW_WWW_USER_*`), qui porte
|
||||||
|
# aussi leur code de sortie : une migration ratee (ex. base `airflow` absente sur un volume
|
||||||
|
# `pgdata` deja peuple) fait echouer ce service, et `webserver`/`scheduler`, qui attendent son
|
||||||
|
# succes, ne demarrent pas sur une base non migree. Le mot de passe passe par l'environnement,
|
||||||
|
# jamais par `argv` (ni `ps`, ni `docker compose config`).
|
||||||
|
# Sans mot de passe, l'entrypoint refuse lui-meme de creer le compte ; la commande ci-dessous
|
||||||
|
# refuse en plus les deux cles de chiffrement vides.
|
||||||
|
airflow-init:
|
||||||
|
<<: *airflow-common
|
||||||
|
restart: "no"
|
||||||
|
environment:
|
||||||
|
<<: *airflow-common-env
|
||||||
|
_AIRFLOW_DB_MIGRATE: "true"
|
||||||
|
_AIRFLOW_WWW_USER_CREATE: "true"
|
||||||
|
_AIRFLOW_WWW_USER_USERNAME: ${AIRFLOW_ADMIN_USERNAME:-admin}
|
||||||
|
_AIRFLOW_WWW_USER_PASSWORD: ${AIRFLOW_ADMIN_PASSWORD:-}
|
||||||
|
_AIRFLOW_WWW_USER_EMAIL: ${AIRFLOW_ADMIN_EMAIL:-admin@enervision.fr}
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
command:
|
||||||
|
- bash
|
||||||
|
- -c
|
||||||
|
- |
|
||||||
|
set -euo pipefail
|
||||||
|
: "$${AIRFLOW__CORE__FERNET_KEY:?AIRFLOW_FERNET_KEY manquant dans .env}"
|
||||||
|
: "$${AIRFLOW__WEBSERVER__SECRET_KEY:?AIRFLOW_WEBSERVER_SECRET_KEY manquant dans .env}"
|
||||||
|
: "$${APP_SECRET_KEY:?AIRFLOW_APP_SECRET_KEY manquant dans .env}"
|
||||||
|
exec airflow version
|
||||||
|
|
||||||
|
airflow-webserver:
|
||||||
|
<<: *airflow-common
|
||||||
|
command: webserver
|
||||||
|
ports:
|
||||||
|
- "${AIRFLOW_PORT:-8080}:8080"
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
airflow-init:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "curl", "--fail", "http://localhost:8080/health"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 5
|
||||||
|
start_period: 60s
|
||||||
|
|
||||||
|
airflow-scheduler:
|
||||||
|
<<: *airflow-common
|
||||||
|
command: scheduler
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
airflow-init:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
pgdata:
|
pgdata:
|
||||||
|
airflow_logs:
|
||||||
|
airflow_ml_state:
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user