Compare commits
84
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd1da05587 | ||
|
|
9376420868 | ||
|
|
d535959fbe | ||
|
|
33807e3038 | ||
|
|
c914d41f33 | ||
|
|
d3047f53e8 | ||
|
|
ec63798807 | ||
|
|
1e168ef03e | ||
|
|
ddf7e17788 | ||
|
|
56e8f95729 | ||
|
|
91d435748c | ||
|
|
0b41580310 | ||
|
|
e3d436ea53 | ||
|
|
c453700b13 | ||
|
|
f427f8a8f3 | ||
|
|
7be8a44e89 | ||
|
|
2095ad6bd3 | ||
|
|
fb06bf0062 | ||
|
|
e27142c7db | ||
|
|
77feabcbad | ||
|
|
18a4be6e38 | ||
|
|
feee6c3ffc | ||
|
|
173f91f26f | ||
|
|
1cd3688256 | ||
|
|
7eef960a30 | ||
|
|
12fb8860d1 | ||
|
|
7c2936f2ef | ||
|
|
9d3e402ca4 | ||
|
|
7db57f162c | ||
|
|
9ccc603d88 | ||
|
|
297d85a0ca | ||
|
|
af58172742 | ||
|
|
b433e01fa8 | ||
|
|
5eb74aa64a | ||
|
|
cc0a58ac4c | ||
|
|
2400b6f05e | ||
|
|
9e33c276d6 | ||
|
|
6cb9ac00cb | ||
|
|
c1f63889c1 | ||
|
|
5875e8c239 | ||
|
|
c8383014a8 | ||
|
|
3cf9194d4c | ||
|
|
8def1e23af | ||
|
|
e26948932e | ||
|
|
41acdb54b6 | ||
|
|
5d921a9b1e | ||
|
|
56c134beb0 | ||
|
|
8fb5ab9f65 | ||
|
|
e22feac2c4 | ||
|
|
5581cb1ef3 | ||
|
|
1d8c986386 | ||
|
|
85cb7c9eeb | ||
|
|
39b1d28ead | ||
|
|
5394257855 | ||
|
|
19cfac1cff | ||
|
|
1fce577a78 | ||
|
|
1afaee069f | ||
|
|
7bc9a09489 | ||
|
|
4ee2109628 | ||
|
|
ec1c05ad54 | ||
|
|
334ca5982b | ||
|
|
2465021d61 | ||
|
|
278299c2b1 | ||
|
|
4f69199734 | ||
|
|
1cca4f130c | ||
|
|
016f226fdb | ||
|
|
88f4f9a601 | ||
|
|
ed7311d4ef | ||
|
|
ff68a51424 | ||
|
|
11f9b1bcd5 | ||
|
|
41c18a3bb1 | ||
|
|
00ef725249 | ||
|
|
34f35f3ca0 | ||
|
|
f5cac1c2a8 | ||
|
|
8e07168a5e | ||
|
|
d167b64188 | ||
|
|
2ad7692f1c | ||
|
|
cd4fd962be | ||
|
|
517144f7e5 | ||
|
|
cc7ca2d359 | ||
|
|
bbafe7d119 | ||
|
|
9c78c6dc38 | ||
|
|
2f97e4d434 | ||
|
|
07ea8d21dc |
@@ -0,0 +1,40 @@
|
|||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
# Frontend — npm
|
||||||
|
- package-ecosystem: "npm"
|
||||||
|
directory: "/apps/frontend"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
open-pull-requests-limit: 5
|
||||||
|
groups:
|
||||||
|
frontend-dependencies:
|
||||||
|
patterns:
|
||||||
|
- "*"
|
||||||
|
|
||||||
|
# Backend — uv (lit pyproject.toml / uv.lock)
|
||||||
|
- package-ecosystem: "uv"
|
||||||
|
directory: "/apps/backend"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
open-pull-requests-limit: 5
|
||||||
|
groups:
|
||||||
|
backend-dependencies:
|
||||||
|
patterns:
|
||||||
|
- "*"
|
||||||
|
|
||||||
|
# Les workflows GitHub Actions eux-mêmes ont aussi des dépendances à jour
|
||||||
|
- package-ecosystem: "github-actions"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
|
||||||
|
# Si un Dockerfile existe pour le backend
|
||||||
|
- package-ecosystem: "docker"
|
||||||
|
directory: "/apps/backend"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
|
||||||
|
- package-ecosystem: "docker"
|
||||||
|
directory: "/apps/frontend"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
@@ -56,3 +56,87 @@ jobs:
|
|||||||
# Le marqueur `integration` est exclu par défaut, donc aucune base n'est nécessaire ici.
|
# Le marqueur `integration` est exclu par défaut, donc aucune base n'est nécessaire ici.
|
||||||
- name: Tests et couverture
|
- name: Tests et couverture
|
||||||
run: uv run pytest --cov-fail-under=85
|
run: uv run pytest --cov-fail-under=85
|
||||||
|
|
||||||
|
# Piège : l'image est celle de docker-compose.yml, pas une image `postgres` nue. La première
|
||||||
|
# migration (`5353c0e4f094`) échoue volontairement si l'extension TimescaleDB manque, et un
|
||||||
|
# écart d'image entre la CI et le poste rendrait ce job vert sur une base qui n'est pas la nôtre.
|
||||||
|
integration:
|
||||||
|
name: Tests exigeant une base
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
services:
|
||||||
|
db:
|
||||||
|
image: timescale/timescaledb-ha:pg17
|
||||||
|
env:
|
||||||
|
POSTGRES_USER: enervision
|
||||||
|
POSTGRES_PASSWORD: change_me
|
||||||
|
POSTGRES_DB: enervision_test
|
||||||
|
ports:
|
||||||
|
- "5433:5432"
|
||||||
|
options: >-
|
||||||
|
--health-cmd "pg_isready -U enervision -d enervision_test"
|
||||||
|
--health-interval 10s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 12
|
||||||
|
--health-start-period 40s
|
||||||
|
|
||||||
|
env:
|
||||||
|
DATABASE_URL: postgresql+asyncpg://enervision:change_me@localhost:5433/enervision_test
|
||||||
|
APP_SECRET_KEY: secret-de-test-assez-long-pour-le-validateur
|
||||||
|
PGPASSWORD: change_me
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Récupère le dépôt
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Installe uv
|
||||||
|
uses: astral-sh/setup-uv@v5
|
||||||
|
with:
|
||||||
|
enable-cache: true
|
||||||
|
cache-dependency-glob: apps/backend/uv.lock
|
||||||
|
|
||||||
|
- name: Installe l'interpréteur déclaré par .python-version
|
||||||
|
run: uv python install
|
||||||
|
|
||||||
|
- name: Synchronise les dépendances sans dévier du verrou
|
||||||
|
run: uv sync --all-groups --frozen
|
||||||
|
|
||||||
|
# Sur le poste, c'est db/init/110-test-database.sql qui pose l'extension. Ce fichier n'est
|
||||||
|
# pas monté ici, et sans lui `alembic upgrade head` s'arrête sur la garde de la révision 1.
|
||||||
|
- name: Active TimescaleDB sur la base de test
|
||||||
|
run: psql -h localhost -p 5433 -U enervision -d enervision_test -c "CREATE EXTENSION IF NOT EXISTS timescaledb"
|
||||||
|
|
||||||
|
- name: Applique les migrations
|
||||||
|
run: uv run alembic upgrade head
|
||||||
|
|
||||||
|
# `-m` en ligne de commande écrase celui d'`addopts`. La couverture est désactivée : ce job
|
||||||
|
# ne joue qu'une partie de la suite, son taux n'aurait aucun sens face au seuil de 85 %.
|
||||||
|
- name: Tests d'intégration
|
||||||
|
run: uv run pytest -m integration --no-cov
|
||||||
|
|
||||||
|
security-audit:
|
||||||
|
name: Audit des dépendances
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Récupère le dépôt
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Installe uv
|
||||||
|
uses: astral-sh/setup-uv@v5
|
||||||
|
with:
|
||||||
|
enable-cache: true
|
||||||
|
cache-dependency-glob: apps/backend/uv.lock
|
||||||
|
|
||||||
|
# L'audit porte sur le verrou, pas sur l'environnement : sinon pip-audit auditerait
|
||||||
|
# aussi les paquets que son propre `--with` injecte, hors dépendances du projet.
|
||||||
|
- name: Audite les dépendances livrées
|
||||||
|
# Piège : sans `shell: bash`, un échec de `uv export` serait masqué par le pipe.
|
||||||
|
shell: bash
|
||||||
|
run: uv export --frozen --no-dev --no-emit-project --no-hashes | uvx pip-audit --requirement /dev/stdin --no-deps
|
||||||
|
|||||||
@@ -1,20 +1,6 @@
|
|||||||
name: Frontend
|
name: Frontend
|
||||||
# Pipeline à choix multiple
|
|
||||||
|
|
||||||
on:
|
on:
|
||||||
# workflow_dispatch -> lancement manuel des jobs
|
|
||||||
workflow_dispatch:
|
|
||||||
inputs:
|
|
||||||
job_choice:
|
|
||||||
required: true
|
|
||||||
description: "Choix du job"
|
|
||||||
type: choice
|
|
||||||
default: all
|
|
||||||
options:
|
|
||||||
- build
|
|
||||||
- sonarqube
|
|
||||||
- test
|
|
||||||
- all # lancer tous les jobs
|
|
||||||
push:
|
push:
|
||||||
paths:
|
paths:
|
||||||
- "apps/frontend/**"
|
- "apps/frontend/**"
|
||||||
@@ -23,8 +9,9 @@ on:
|
|||||||
paths:
|
paths:
|
||||||
- "apps/frontend/**"
|
- "apps/frontend/**"
|
||||||
- ".github/workflows/frontend.yml"
|
- ".github/workflows/frontend.yml"
|
||||||
# Ordre de lancement des jobs
|
|
||||||
# build -> test -> sonarqube -> deploy
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
@@ -42,6 +29,18 @@ jobs:
|
|||||||
- run: npm run build
|
- run: npm run build
|
||||||
working-directory: apps/frontend
|
working-directory: apps/frontend
|
||||||
|
|
||||||
|
security-audit:
|
||||||
|
name: Audit des dépendances
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
- uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
# Seuil high : une vulnérabilité moderate de devDependency ne doit pas bloquer une livraison.
|
||||||
|
- run: npm audit --audit-level=high --package-lock-only
|
||||||
|
working-directory: apps/frontend
|
||||||
|
|
||||||
test:
|
test:
|
||||||
needs: build
|
needs: build
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -52,26 +51,14 @@ jobs:
|
|||||||
node-version: 24
|
node-version: 24
|
||||||
cache: npm
|
cache: npm
|
||||||
cache-dependency-path: apps/frontend/package-lock.json
|
cache-dependency-path: apps/frontend/package-lock.json
|
||||||
- run: npm ci
|
- name : Installation des dépendances (Front)
|
||||||
|
run: npm ci
|
||||||
working-directory: apps/frontend
|
working-directory: apps/frontend
|
||||||
- run: npm test -- --watch=false
|
- name : Lancement des tests et génénration du rapport de couverture (Front)
|
||||||
|
run: npm test --watch=false --code-coverage --coverageReporters=lcov
|
||||||
working-directory: apps/frontend
|
working-directory: apps/frontend
|
||||||
|
- name: Upload coverage
|
||||||
sonarqube:
|
uses: actions/upload-artifact@v4
|
||||||
needs: [build, test]
|
|
||||||
name: SonarQube
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
|
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
|
name: frontend-coverage
|
||||||
- name: SonarQube Scan
|
path: apps/frontend/coverage/frontend/lcov.info
|
||||||
uses: SonarSource/sonarqube-scan-action@7006c4492b2e0ee0f816d36501671557c97f5995 # v8.1.0
|
|
||||||
env:
|
|
||||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
|
||||||
|
|
||||||
|
|
||||||
# deploy:
|
|
||||||
# runs-on: ubuntu-latest
|
|
||||||
# steps:
|
|
||||||
# - run: echo "DEPLOY job is running"
|
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
name: ML
|
||||||
|
|
||||||
|
# Piège : la version de Python vient de ml/.python-version, et doit rester en 3.14 (cf.
|
||||||
|
# .github/workflows/backend.yml, même contrainte).
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
paths:
|
||||||
|
- "ml/**"
|
||||||
|
- ".github/workflows/ml.yml"
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- "ml/**"
|
||||||
|
- ".github/workflows/ml.yml"
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ml-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
verification:
|
||||||
|
name: Lint, typage et tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: ml
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Récupère le dépôt
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Installe uv
|
||||||
|
uses: astral-sh/setup-uv@v5
|
||||||
|
with:
|
||||||
|
enable-cache: true
|
||||||
|
cache-dependency-glob: ml/uv.lock
|
||||||
|
|
||||||
|
- name: Installe l'interpréteur déclaré par .python-version
|
||||||
|
run: uv python install
|
||||||
|
|
||||||
|
- name: Synchronise les dépendances sans dévier du verrou
|
||||||
|
run: uv sync --all-groups --frozen
|
||||||
|
|
||||||
|
- name: Vérifie le formatage
|
||||||
|
run: uv run ruff format --check .
|
||||||
|
|
||||||
|
- name: Analyse statique
|
||||||
|
run: uv run ruff check --output-format=github .
|
||||||
|
|
||||||
|
- name: Typage
|
||||||
|
run: uv run mypy enervision_ml tests
|
||||||
|
|
||||||
|
# Aucun test ne touche PostgreSQL ni MLflow distant : tout tourne sur donnees
|
||||||
|
# synthetiques ou un magasin SQLite local jetable (cf. ml/tests/test_train.py).
|
||||||
|
- name: Tests
|
||||||
|
run: uv run pytest
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
name: SonarQube
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
paths:
|
||||||
|
- "apps/frontend/**"
|
||||||
|
- "apps/backend/**"
|
||||||
|
- ".github/workflows/sonarqube.yml"
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- "apps/frontend/**"
|
||||||
|
- "apps/backend/**"
|
||||||
|
- ".github/workflows/sonarqube.yml"
|
||||||
|
|
||||||
|
|
||||||
|
# Build l'ensemble du projet, puis lance les tests
|
||||||
|
# Génère les rapports de couverture, puis lance l'analyse SonarQube
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-front:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
- uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
cache: npm
|
||||||
|
cache-dependency-path: apps/frontend/package-lock.json
|
||||||
|
|
||||||
|
- run: npm ci
|
||||||
|
working-directory: apps/frontend
|
||||||
|
- run: npm run build
|
||||||
|
working-directory: apps/frontend
|
||||||
|
|
||||||
|
test-front:
|
||||||
|
needs: build-front
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
- uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
cache: npm
|
||||||
|
cache-dependency-path: apps/frontend/package-lock.json
|
||||||
|
|
||||||
|
- name : Installation des dépendances (Front)
|
||||||
|
run: npm ci
|
||||||
|
working-directory: apps/frontend
|
||||||
|
|
||||||
|
- name : Lancement des tests et génénration du rapport de couverture (Front)
|
||||||
|
run: npm test --watch=false --code-coverage --coverageReporters=lcov
|
||||||
|
working-directory: apps/frontend
|
||||||
|
|
||||||
|
- name: Upload coverage
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: frontend-coverage
|
||||||
|
path: apps/frontend/coverage/frontend/lcov.info
|
||||||
|
|
||||||
|
build-back:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
- name: Installe uv
|
||||||
|
uses: astral-sh/setup-uv@v5
|
||||||
|
with:
|
||||||
|
enable-cache: true
|
||||||
|
cache-dependency-glob: apps/backend/uv.lock
|
||||||
|
- name: Installe l'interpréteur déclaré par .python-version
|
||||||
|
run: uv python install
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
- name: Synchronise les dépendances sans dévier du verrou
|
||||||
|
run: uv sync --all-groups --frozen
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
- name: Vérifie le formatage
|
||||||
|
run: uv run ruff format --check .
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
- name: Analyse statique
|
||||||
|
run: uv run ruff check --output-format=github .
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
- name: Typage
|
||||||
|
run: uv run mypy app
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
|
||||||
|
test-back:
|
||||||
|
needs: build-back
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
- name: Installe uv
|
||||||
|
uses: astral-sh/setup-uv@v5
|
||||||
|
with:
|
||||||
|
enable-cache: true
|
||||||
|
cache-dependency-glob: apps/backend/uv.lock
|
||||||
|
|
||||||
|
- name : Lancement des tests et génénration du rapport de couverture (Back)
|
||||||
|
run: uv run pytest --cov-fail-under=85 --cov-report=xml
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
- name: Upload coverage
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: backend-coverage
|
||||||
|
path: apps/backend/coverage.xml
|
||||||
|
|
||||||
|
sonarqube:
|
||||||
|
needs: [build-front, build-back, test-front, test-back]
|
||||||
|
name: SonarQube
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- name: Téléchargement du rapport de couverture (Front)
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: frontend-coverage
|
||||||
|
path: apps/frontend/coverage/frontend
|
||||||
|
- name: Téléchargement du rapport de couverture (Back)
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: backend-coverage
|
||||||
|
path: apps/backend
|
||||||
|
- name: SonarQube Scan
|
||||||
|
uses: SonarSource/sonarqube-scan-action@v8
|
||||||
|
env:
|
||||||
|
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||||
@@ -58,6 +58,14 @@ data/raw/*
|
|||||||
monitoring/grafana/data/
|
monitoring/grafana/data/
|
||||||
monitoring/prometheus/data/
|
monitoring/prometheus/data/
|
||||||
|
|
||||||
|
# ML : jeu de donnees, modeles entraines et suivi MLflow local, tous generes/volumineux
|
||||||
|
ml/data/
|
||||||
|
ml/models/*
|
||||||
|
!ml/models/.gitkeep
|
||||||
|
ml/mlruns/
|
||||||
|
ml/mlartifacts/
|
||||||
|
ml/mlflow.db
|
||||||
|
|
||||||
# IDE et OS
|
# IDE et OS
|
||||||
.idea/
|
.idea/
|
||||||
.vscode/
|
.vscode/
|
||||||
|
|||||||
@@ -1,15 +1,17 @@
|
|||||||
BACKEND := apps/backend
|
BACKEND := apps/backend
|
||||||
FRONTEND := apps/frontend
|
FRONTEND := apps/frontend
|
||||||
|
ML := ml
|
||||||
|
|
||||||
.DEFAULT_GOAL := help
|
.DEFAULT_GOAL := help
|
||||||
.PHONY: help install install-backend install-frontend dev dev-backend dev-frontend \
|
.PHONY: help install install-backend install-frontend install-ml dev dev-backend dev-frontend \
|
||||||
lint format typecheck test test-cov test-integration check \
|
lint format typecheck test test-cov test-integration check \
|
||||||
openapi docker-build db-up db-down db-reset db-logs db-psql migrate bootstrap-admin
|
openapi docker-build db-up db-down db-reset db-logs db-psql migrate bootstrap-admin \
|
||||||
|
ml-lint ml-typecheck ml-test ml-check ml-train
|
||||||
|
|
||||||
help: ## Liste les cibles disponibles
|
help: ## Liste les cibles disponibles
|
||||||
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-16s\033[0m %s\n", $$1, $$2}'
|
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-16s\033[0m %s\n", $$1, $$2}'
|
||||||
|
|
||||||
install: install-backend install-frontend ## Installe les dépendances backend et frontend
|
install: install-backend install-frontend install-ml ## Installe les dépendances backend, frontend et ML
|
||||||
|
|
||||||
install-backend: ## Installe les dépendances du backend
|
install-backend: ## Installe les dépendances du backend
|
||||||
cd $(BACKEND) && uv sync --all-groups
|
cd $(BACKEND) && uv sync --all-groups
|
||||||
@@ -17,6 +19,9 @@ install-backend: ## Installe les dépendances du backend
|
|||||||
install-frontend: ## Installe les dépendances du frontend
|
install-frontend: ## Installe les dépendances du frontend
|
||||||
cd $(FRONTEND) && npm ci
|
cd $(FRONTEND) && npm ci
|
||||||
|
|
||||||
|
install-ml: ## Installe les dépendances du pipeline ML
|
||||||
|
cd $(ML) && uv sync --all-groups
|
||||||
|
|
||||||
dev: ## Lance toute la stack (backend + frontend) en rechargement à chaud
|
dev: ## Lance toute la stack (backend + frontend) en rechargement à chaud
|
||||||
@trap 'kill 0' EXIT INT TERM; \
|
@trap 'kill 0' EXIT INT TERM; \
|
||||||
$(MAKE) --no-print-directory dev-backend & \
|
$(MAKE) --no-print-directory dev-backend & \
|
||||||
@@ -55,6 +60,20 @@ check: lint typecheck test ## Chaîne de vérification complète
|
|||||||
openapi: ## Régénère apps/backend/openapi.json depuis les routes déclarées
|
openapi: ## Régénère apps/backend/openapi.json depuis les routes déclarées
|
||||||
cd $(BACKEND) && uv run python -m app.cli export-openapi
|
cd $(BACKEND) && uv run python -m app.cli export-openapi
|
||||||
|
|
||||||
|
ml-lint: ## Analyse statique du pipeline ML
|
||||||
|
cd $(ML) && uv run ruff check .
|
||||||
|
|
||||||
|
ml-typecheck: ## Vérifie le typage du pipeline ML
|
||||||
|
cd $(ML) && uv run mypy enervision_ml tests
|
||||||
|
|
||||||
|
ml-test: ## Exécute les tests du pipeline ML (donnees synthetiques, sans base ni serveur MLflow)
|
||||||
|
cd $(ML) && uv run pytest
|
||||||
|
|
||||||
|
ml-check: ml-lint ml-typecheck ml-test ## Chaîne de vérification complète du pipeline ML
|
||||||
|
|
||||||
|
ml-train: ## Entraine le modele LightGBM. CSV=chemin optionnel, sinon lit ML_DATABASE_URL
|
||||||
|
cd $(ML) && uv run python -m enervision_ml.train $(if $(CSV),--csv $(CSV),)
|
||||||
|
|
||||||
docker-build: ## Construit l'image du backend
|
docker-build: ## Construit l'image du backend
|
||||||
docker build -t enervision-backend:local $(BACKEND)
|
docker build -t enervision-backend:local $(BACKEND)
|
||||||
|
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ Ce que la documentation apporte à chacun : [docs/architecture/00-vue-ensemble.m
|
|||||||
| Infra | Terraform (k3s single-node) | `infra/terraform` | Initialise |
|
| Infra | Terraform (k3s single-node) | `infra/terraform` | Initialise |
|
||||||
| CI/CD | GitHub Actions | `.github/workflows` | Backend en place |
|
| CI/CD | GitHub Actions | `.github/workflows` | Backend en place |
|
||||||
| Monitoring | Prometheus, Grafana, Alertmanager | `monitoring` | A initialiser |
|
| Monitoring | Prometheus, Grafana, Alertmanager | `monitoring` | A initialiser |
|
||||||
|
| ML | LightGBM, MLflow | `ml` | Entrainement initialise |
|
||||||
|
|
||||||
Le backend, la base et l'infrastructure (Terraform/k3s) sont initialises a ce stade. Le frontend
|
Le backend, la base et l'infrastructure (Terraform/k3s) sont initialises a ce stade. Le frontend
|
||||||
sert un tableau de bord sur `/dashboard`, dont les données proviennent de fixtures : les endpoints
|
sert un tableau de bord sur `/dashboard`, dont les données proviennent de fixtures : les endpoints
|
||||||
@@ -53,6 +54,7 @@ L'etat detaille de chaque brique et les vues d'architecture sont dans
|
|||||||
├── infra/terraform/
|
├── infra/terraform/
|
||||||
│ ├── modules/ Modules reutilisables
|
│ ├── modules/ Modules reutilisables
|
||||||
│ └── environments/ Racines Terraform, une par environnement
|
│ └── environments/ Racines Terraform, une par environnement
|
||||||
|
├── ml/ Pipeline d'entrainement LightGBM, suivi MLflow
|
||||||
├── monitoring/
|
├── monitoring/
|
||||||
│ ├── prometheus/ Collecte et regles d'alerte
|
│ ├── prometheus/ Collecte et regles d'alerte
|
||||||
│ ├── grafana/ Provisioning et dashboards
|
│ ├── grafana/ Provisioning et dashboards
|
||||||
|
|||||||
+21
-3
@@ -123,6 +123,11 @@ async def test_repository_reads_back_what_it_wrote(session: AsyncSession) -> Non
|
|||||||
defaut, ce qui garde `make check` jouable sans Docker. Tout autre marqueur doit etre
|
defaut, ce qui garde `make check` jouable sans Docker. Tout autre marqueur doit etre
|
||||||
declare dans `pyproject.toml` : `--strict-markers` refuse les marqueurs inconnus.
|
declare dans `pyproject.toml` : `--strict-markers` refuse les marqueurs inconnus.
|
||||||
|
|
||||||
|
Ces tests ne sont pas pour autant facultatifs : le job `integration` de
|
||||||
|
`.github/workflows/backend.yml` monte un service TimescaleDB, applique les migrations et
|
||||||
|
les joue a chaque poussee. Un test `integration` casse donc la CI comme un autre. En local,
|
||||||
|
`make db-up` puis `make test-integration`.
|
||||||
|
|
||||||
## Couverture
|
## Couverture
|
||||||
|
|
||||||
Les branches sont mesurees, pas seulement les lignes. Le seuil de 85 % ne s'applique
|
Les branches sont mesurees, pas seulement les lignes. Le seuil de 85 % ne s'applique
|
||||||
@@ -142,14 +147,27 @@ uv run pytest tests/api/test_health.py # un seul fichier
|
|||||||
uv run pytest -k readiness # par motif de nom
|
uv run pytest -k readiness # par motif de nom
|
||||||
```
|
```
|
||||||
|
|
||||||
## Trois fichiers à connaître avant de toucher à l'authentification
|
## Quatre fichiers à connaître avant de toucher à l'authentification
|
||||||
|
|
||||||
|
`tests/api/acces.py` porte la classification des routes du contrat, en quatre ensembles :
|
||||||
|
`ROUTES_PUBLIQUES`, `ROUTE_COOKIE`, `ROUTES_SANS_ROLE` et la table `ROLE_MINIMUM`. Ce n'est pas
|
||||||
|
un fichier de test, c'est la référence que les trois autres confrontent au comportement observé.
|
||||||
|
**Toute route ajoutée doit y être classée** : `test_every_declared_route_is_classified` échoue
|
||||||
|
sinon, et échoue aussi sur une entrée qui ne correspond plus à aucune route.
|
||||||
|
|
||||||
`tests/api/test_route_protection.py` interroge réellement chaque route sans identifiant et
|
`tests/api/test_route_protection.py` interroge réellement chaque route sans identifiant et
|
||||||
échoue si l'une d'elles répond autre chose qu'un 401 ou un 403. Il n'inspecte pas l'arbre de
|
échoue si l'une d'elles répond autre chose qu'un 401 ou un 403. Il n'inspecte pas l'arbre de
|
||||||
dépendances : celui-ci n'est accessible que par l'API privée de FastAPI, et surtout une route
|
dépendances : celui-ci n'est accessible que par l'API privée de FastAPI, et surtout une route
|
||||||
peut porter la bonne dépendance tout en répondant quand même. **Rendre une route publique impose
|
peut porter la bonne dépendance tout en répondant quand même. **Rendre une route publique impose
|
||||||
donc de modifier la liste `ROUTES_PUBLIQUES` de ce fichier**, ce qui apparaît en clair dans la
|
donc de modifier `ROUTES_PUBLIQUES` dans `acces.py`**, ce qui apparaît en clair dans la diff
|
||||||
diff d'une pull request.
|
d'une pull request.
|
||||||
|
|
||||||
|
`tests/api/test_matrice_acces.py` croise chaque route gardée avec chacun des trois rôles, dans
|
||||||
|
les deux sens : un rôle insuffisant reçoit un 403 `Droits insuffisants`, un rôle suffisant ne le
|
||||||
|
reçoit jamais. Le second sens est ce qui rend visible une garde posée trop haut, par exemple
|
||||||
|
`AdminDep` sur une route de lecture. La même matrice est rejouée sous `integration` avec de vrais
|
||||||
|
jetons, donc en traversant le décodage du JWT et la relecture du compte en base, que
|
||||||
|
`dependency_overrides` court-circuite.
|
||||||
|
|
||||||
`tests/services/test_auth.py` donne au faux hacheur un **compteur d'appels**. C'est ce qui rend
|
`tests/services/test_auth.py` donne au faux hacheur un **compteur d'appels**. C'est ce qui rend
|
||||||
possibles les deux assertions qui prouvent la conception, et qu'aucune autre forme de test
|
possibles les deux assertions qui prouvent la conception, et qu'aucune autre forme de test
|
||||||
|
|||||||
@@ -171,7 +171,7 @@ UserServiceDep = Annotated[UserService, Depends(get_user_service)]
|
|||||||
|
|
||||||
|
|
||||||
def get_site_service(session: SessionDep) -> SiteService:
|
def get_site_service(session: SessionDep) -> SiteService:
|
||||||
return SiteService(sites=SiteRepository(session))
|
return SiteService(sites=SiteRepository(session), readings=ReadingRepository(session))
|
||||||
|
|
||||||
|
|
||||||
SiteServiceDep = Annotated[SiteService, Depends(get_site_service)]
|
SiteServiceDep = Annotated[SiteService, Depends(get_site_service)]
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ from fastapi import APIRouter, HTTPException, status
|
|||||||
from app.api.deps import LecteurDep, SiteServiceDep
|
from app.api.deps import LecteurDep, SiteServiceDep
|
||||||
from app.api.openapi import REPONSE_VALIDATION, Reponses
|
from app.api.openapi import REPONSE_VALIDATION, Reponses
|
||||||
from app.schemas.errors import ErrorResponse
|
from app.schemas.errors import ErrorResponse
|
||||||
from app.schemas.site import SiteResponse
|
from app.schemas.site import SiteCurrentResponse, SiteResponse
|
||||||
from app.services.site import SiteNotFoundError
|
from app.services.site import SiteNotFoundError
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
@@ -34,3 +34,19 @@ async def get_site(site_id: str, _: LecteurDep, service: SiteServiceDep) -> Site
|
|||||||
status_code=status.HTTP_404_NOT_FOUND, detail="Site introuvable"
|
status_code=status.HTTP_404_NOT_FOUND, detail="Site introuvable"
|
||||||
) from erreur
|
) from erreur
|
||||||
return SiteResponse.model_validate(site)
|
return SiteResponse.model_validate(site)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/{site_id}/current",
|
||||||
|
response_model=SiteCurrentResponse,
|
||||||
|
summary="Dernière mesure d'un site",
|
||||||
|
responses=REPONSES_INTROUVABLE,
|
||||||
|
)
|
||||||
|
async def get_current(site_id: str, _: LecteurDep, service: SiteServiceDep) -> SiteCurrentResponse:
|
||||||
|
try:
|
||||||
|
actuel = await service.current(site_id)
|
||||||
|
except SiteNotFoundError as erreur:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND, detail="Site introuvable"
|
||||||
|
) from erreur
|
||||||
|
return SiteCurrentResponse.model_validate(actuel)
|
||||||
|
|||||||
@@ -1,9 +1,14 @@
|
|||||||
from collections.abc import AsyncIterator
|
from collections.abc import AsyncIterator
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from fastapi import Depends, FastAPI
|
from fastapi import Depends, FastAPI
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html
|
||||||
|
from fastapi.staticfiles import StaticFiles
|
||||||
from prometheus_fastapi_instrumentator import Instrumentator
|
from prometheus_fastapi_instrumentator import Instrumentator
|
||||||
|
from starlette.requests import Request
|
||||||
|
from starlette.responses import HTMLResponse
|
||||||
|
|
||||||
from app.api.errors import register_error_handlers
|
from app.api.errors import register_error_handlers
|
||||||
from app.api.middleware import SecurityHeadersMiddleware
|
from app.api.middleware import SecurityHeadersMiddleware
|
||||||
@@ -18,6 +23,8 @@ logger = get_logger(__name__)
|
|||||||
|
|
||||||
METHODES_AUTORISEES = ["GET", "POST", "PATCH", "PUT", "DELETE", "OPTIONS"]
|
METHODES_AUTORISEES = ["GET", "POST", "PATCH", "PUT", "DELETE", "OPTIONS"]
|
||||||
EN_TETES_AUTORISES = ["Authorization", "Content-Type"]
|
EN_TETES_AUTORISES = ["Authorization", "Content-Type"]
|
||||||
|
STATIC_DIR = Path(__file__).parent / "static"
|
||||||
|
LOGO_URL = "/static/logo-icon.png"
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
@@ -43,11 +50,41 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
|||||||
openapi_tags=TAGS,
|
openapi_tags=TAGS,
|
||||||
debug=resolved.debug,
|
debug=resolved.debug,
|
||||||
lifespan=lifespan,
|
lifespan=lifespan,
|
||||||
docs_url="/docs" if documentee else None,
|
docs_url=None,
|
||||||
redoc_url="/redoc" if documentee else None,
|
redoc_url=None,
|
||||||
openapi_url="/openapi.json" if documentee else None,
|
openapi_url="/openapi.json" if documentee else None,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if documentee:
|
||||||
|
application.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
|
||||||
|
|
||||||
|
# ReDoc supporte nativement `info.x-logo` (extension Redocly) pour afficher un logo
|
||||||
|
# en en-tête ; Swagger UI n'a pas d'equivalent, il ne reprend que le favicon.
|
||||||
|
openapi_original = application.openapi
|
||||||
|
|
||||||
|
def openapi_avec_logo() -> dict[str, object]:
|
||||||
|
schema = openapi_original()
|
||||||
|
schema["info"]["x-logo"] = {"url": LOGO_URL, "altText": "EnerVision"}
|
||||||
|
return schema
|
||||||
|
|
||||||
|
application.openapi = openapi_avec_logo # type: ignore[method-assign]
|
||||||
|
|
||||||
|
@application.get("/docs", include_in_schema=False)
|
||||||
|
async def docs_swagger(_: Request) -> HTMLResponse:
|
||||||
|
return get_swagger_ui_html(
|
||||||
|
openapi_url="/openapi.json",
|
||||||
|
title=f"{application.title} · Swagger UI",
|
||||||
|
swagger_favicon_url=LOGO_URL,
|
||||||
|
)
|
||||||
|
|
||||||
|
@application.get("/redoc", include_in_schema=False)
|
||||||
|
async def docs_redoc(_: Request) -> HTMLResponse:
|
||||||
|
return get_redoc_html(
|
||||||
|
openapi_url="/openapi.json",
|
||||||
|
title=f"{application.title} · ReDoc",
|
||||||
|
redoc_favicon_url=LOGO_URL,
|
||||||
|
)
|
||||||
|
|
||||||
application.add_middleware(SecurityHeadersMiddleware)
|
application.add_middleware(SecurityHeadersMiddleware)
|
||||||
|
|
||||||
if resolved.allowed_origins:
|
if resolved.allowed_origins:
|
||||||
|
|||||||
@@ -13,14 +13,27 @@ class ReadingRepository:
|
|||||||
|
|
||||||
async def latest_by_site(self) -> Sequence[Reading]:
|
async def latest_by_site(self) -> Sequence[Reading]:
|
||||||
# `.distinct(site_id)` compile en `DISTINCT ON (site_id)` sous PostgreSQL : une seule
|
# `.distinct(site_id)` compile en `DISTINCT ON (site_id)` sous PostgreSQL : une seule
|
||||||
# ligne par site, la plus récente grâce à l'ordre composite qui suit.
|
# ligne par site, la plus récente grâce à l'ordre composite qui suit. `reading_id` départage
|
||||||
|
# les égalités de timestamp, que `uq_reading_source` autorise à `source` différente.
|
||||||
requete = (
|
requete = (
|
||||||
select(Reading)
|
select(Reading)
|
||||||
.distinct(Reading.site_id)
|
.distinct(Reading.site_id)
|
||||||
.order_by(Reading.site_id, Reading.timestamp.desc())
|
.order_by(Reading.site_id, Reading.timestamp.desc(), Reading.reading_id.desc())
|
||||||
)
|
)
|
||||||
return (await self._session.execute(requete)).scalars().all()
|
return (await self._session.execute(requete)).scalars().all()
|
||||||
|
|
||||||
|
async def latest_for_site(self, site_id: str) -> Reading | None:
|
||||||
|
# Piège : `uq_reading_source` autorise deux lignes au même `site_id`+`timestamp` quand la
|
||||||
|
# `source` diffère. Sans `reading_id` en départage, le `LIMIT 1` renverrait au hasard.
|
||||||
|
requete = (
|
||||||
|
select(Reading)
|
||||||
|
.where(Reading.site_id == site_id)
|
||||||
|
.order_by(Reading.timestamp.desc(), Reading.reading_id.desc())
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
lecture: Reading | None = await self._session.scalar(requete)
|
||||||
|
return lecture
|
||||||
|
|
||||||
async def list_history(
|
async def list_history(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict
|
from pydantic import BaseModel, ConfigDict
|
||||||
|
|
||||||
|
|
||||||
@@ -10,3 +13,20 @@ class SiteResponse(BaseModel):
|
|||||||
location: str | None
|
location: str | None
|
||||||
capacity_kw: float | None
|
capacity_kw: float | None
|
||||||
status: str | None
|
status: str | None
|
||||||
|
|
||||||
|
|
||||||
|
class SiteCurrentResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
timestamp: datetime | None
|
||||||
|
site_id: str
|
||||||
|
site_type: str
|
||||||
|
consumption_kw: float | None
|
||||||
|
consumption_kwh: float | None
|
||||||
|
voltage_v: float | None
|
||||||
|
current_a: float | None
|
||||||
|
power_factor: float | None
|
||||||
|
temperature_celsius: float | None
|
||||||
|
humidity_percent: float | None
|
||||||
|
null_reasons: list[str]
|
||||||
|
data_quality: Literal["good", "partial", "degraded", "critical"]
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Contrainte : `ck_reading_quality` accepte NULL et quatre valeurs seulement, alors que le contrat
|
||||||
|
# frontend n'a aucune valeur pour l'absence de qualité. `qualite_ou_critique()` replie donc sur
|
||||||
|
# `critical`, la seule des quatre qui n'induise pas une confiance qu'on n'a pas. `QUALITES_CONNUES`
|
||||||
|
# reste exposé pour les appelants qui doivent distinguer un `critical` stocké d'un repli.
|
||||||
|
|
||||||
|
from typing import Literal, get_args
|
||||||
|
|
||||||
|
DataQuality = Literal["good", "partial", "degraded", "critical"]
|
||||||
|
|
||||||
|
QUALITES_CONNUES: frozenset[str] = frozenset(get_args(DataQuality))
|
||||||
|
|
||||||
|
_PAR_VALEUR: dict[str, DataQuality] = {valeur: valeur for valeur in get_args(DataQuality)}
|
||||||
|
|
||||||
|
|
||||||
|
def qualite_ou_critique(valeur: str | None) -> DataQuality:
|
||||||
|
if valeur is None:
|
||||||
|
return "critical"
|
||||||
|
return _PAR_VALEUR.get(valeur, "critical")
|
||||||
@@ -5,12 +5,11 @@ from typing import Literal
|
|||||||
from app.models.energy import Reading, Site
|
from app.models.energy import Reading, Site
|
||||||
from app.repositories.reading import ReadingRepository
|
from app.repositories.reading import ReadingRepository
|
||||||
from app.repositories.site import SiteRepository
|
from app.repositories.site import SiteRepository
|
||||||
|
from app.services.data_quality import qualite_ou_critique
|
||||||
|
|
||||||
CapteurStatus = Literal["ok", "failing"]
|
CapteurStatus = Literal["ok", "failing"]
|
||||||
OverallStatus = Literal["ok", "degraded", "critical"]
|
OverallStatus = Literal["ok", "degraded", "critical"]
|
||||||
|
|
||||||
QUALITES_CONNUES: frozenset[str] = frozenset({"good", "partial", "degraded", "critical"})
|
|
||||||
|
|
||||||
RAISON_VERS_CAPTEUR: dict[str, str] = {
|
RAISON_VERS_CAPTEUR: dict[str, str] = {
|
||||||
"consumption_sensor_failure": "consumption",
|
"consumption_sensor_failure": "consumption",
|
||||||
"electrical_sensor_failure": "electrical",
|
"electrical_sensor_failure": "electrical",
|
||||||
@@ -80,7 +79,7 @@ def _sante_site(site: Site, derniere: Reading | None) -> SanteSite:
|
|||||||
overall="critical",
|
overall="critical",
|
||||||
)
|
)
|
||||||
|
|
||||||
qualite = derniere.data_quality if derniere.data_quality in QUALITES_CONNUES else "critical"
|
qualite = qualite_ou_critique(derniere.data_quality)
|
||||||
overall = _overall_depuis_qualite(qualite)
|
overall = _overall_depuis_qualite(qualite)
|
||||||
|
|
||||||
if overall == "critical":
|
if overall == "critical":
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
from collections.abc import Sequence
|
from collections.abc import Sequence
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
from app.models.energy import Site
|
from app.models.energy import Site
|
||||||
|
from app.repositories.reading import ReadingRepository
|
||||||
from app.repositories.site import SiteRepository
|
from app.repositories.site import SiteRepository
|
||||||
|
from app.services.data_quality import DataQuality, qualite_ou_critique
|
||||||
|
|
||||||
|
|
||||||
class SiteError(Exception):
|
class SiteError(Exception):
|
||||||
@@ -12,9 +16,26 @@ class SiteNotFoundError(SiteError):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class SiteCurrentReading:
|
||||||
|
timestamp: datetime | None
|
||||||
|
site_id: str
|
||||||
|
site_type: str
|
||||||
|
consumption_kw: float | None
|
||||||
|
consumption_kwh: float | None
|
||||||
|
voltage_v: float | None
|
||||||
|
current_a: float | None
|
||||||
|
power_factor: float | None
|
||||||
|
temperature_celsius: float | None
|
||||||
|
humidity_percent: float | None
|
||||||
|
null_reasons: list[str]
|
||||||
|
data_quality: DataQuality
|
||||||
|
|
||||||
|
|
||||||
class SiteService:
|
class SiteService:
|
||||||
def __init__(self, *, sites: SiteRepository) -> None:
|
def __init__(self, *, sites: SiteRepository, readings: ReadingRepository) -> None:
|
||||||
self._sites = sites
|
self._sites = sites
|
||||||
|
self._readings = readings
|
||||||
|
|
||||||
async def list_all(self) -> Sequence[Site]:
|
async def list_all(self) -> Sequence[Site]:
|
||||||
return await self._sites.list_all()
|
return await self._sites.list_all()
|
||||||
@@ -24,3 +45,38 @@ class SiteService:
|
|||||||
if site is None:
|
if site is None:
|
||||||
raise SiteNotFoundError(site_id)
|
raise SiteNotFoundError(site_id)
|
||||||
return site
|
return site
|
||||||
|
|
||||||
|
async def current(self, site_id: str) -> SiteCurrentReading:
|
||||||
|
site = await self.get_by_id(site_id)
|
||||||
|
derniere = await self._readings.latest_for_site(site_id)
|
||||||
|
|
||||||
|
if derniere is None:
|
||||||
|
return SiteCurrentReading(
|
||||||
|
timestamp=None,
|
||||||
|
site_id=site.site_id,
|
||||||
|
site_type=site.site_type,
|
||||||
|
consumption_kw=None,
|
||||||
|
consumption_kwh=None,
|
||||||
|
voltage_v=None,
|
||||||
|
current_a=None,
|
||||||
|
power_factor=None,
|
||||||
|
temperature_celsius=None,
|
||||||
|
humidity_percent=None,
|
||||||
|
null_reasons=[],
|
||||||
|
data_quality="critical",
|
||||||
|
)
|
||||||
|
|
||||||
|
return SiteCurrentReading(
|
||||||
|
timestamp=derniere.timestamp,
|
||||||
|
site_id=site.site_id,
|
||||||
|
site_type=site.site_type,
|
||||||
|
consumption_kw=derniere.consumption_kw,
|
||||||
|
consumption_kwh=derniere.consumption_kwh,
|
||||||
|
voltage_v=derniere.voltage_v,
|
||||||
|
current_a=derniere.current_a,
|
||||||
|
power_factor=derniere.power_factor,
|
||||||
|
temperature_celsius=derniere.temperature_celsius,
|
||||||
|
humidity_percent=derniere.humidity_percent,
|
||||||
|
null_reasons=derniere.null_reasons or [],
|
||||||
|
data_quality=qualite_ou_critique(derniere.data_quality),
|
||||||
|
)
|
||||||
|
|||||||
@@ -1,14 +1,10 @@
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime
|
||||||
from typing import Literal
|
|
||||||
|
|
||||||
from app.models.energy import Reading, Site
|
from app.models.energy import Reading, Site
|
||||||
from app.repositories.reading import ReadingRepository
|
from app.repositories.reading import ReadingRepository
|
||||||
from app.repositories.site import SiteRepository
|
from app.repositories.site import SiteRepository
|
||||||
|
from app.services.data_quality import QUALITES_CONNUES, DataQuality, qualite_ou_critique
|
||||||
DataQuality = Literal["good", "partial", "degraded", "critical"]
|
|
||||||
|
|
||||||
QUALITES_CONNUES: frozenset[str] = frozenset({"good", "partial", "degraded", "critical"})
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
@dataclass(frozen=True, slots=True)
|
||||||
@@ -58,13 +54,10 @@ class StatsService:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def _resume_site(site: Site, derniere: Reading | None) -> SiteConsumption:
|
def _resume_site(site: Site, derniere: Reading | None) -> SiteConsumption:
|
||||||
capacite = site.capacity_kw or 0
|
capacite = site.capacity_kw or 0
|
||||||
# Piège : `data_quality` est nul dès qu'un site n'a jamais reçu de lecture, ou que le
|
|
||||||
# producteur n'a pas su la qualifier. Le contrat frontend n'a pas de valeur pour ce cas,
|
|
||||||
# `critical` est la seule des quatre qui n'induit pas une confiance qu'on n'a pas.
|
|
||||||
qualite: DataQuality = "critical"
|
qualite: DataQuality = "critical"
|
||||||
consommation = None
|
consommation = None
|
||||||
if derniere is not None and derniere.data_quality in QUALITES_CONNUES:
|
if derniere is not None and derniere.data_quality in QUALITES_CONNUES:
|
||||||
qualite = derniere.data_quality # type: ignore[assignment]
|
qualite = qualite_ou_critique(derniere.data_quality)
|
||||||
consommation = derniere.consumption_kw
|
consommation = derniere.consumption_kw
|
||||||
|
|
||||||
charge = (
|
charge = (
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
File diff suppressed because it is too large
Load Diff
+226
-1
@@ -4,7 +4,11 @@
|
|||||||
"title": "EnerVision API",
|
"title": "EnerVision API",
|
||||||
"summary": "Collecte, analyse et restitution de séries temporelles énergétiques.",
|
"summary": "Collecte, analyse et restitution de séries temporelles énergétiques.",
|
||||||
"description": "\nToutes les routes sont préfixées par `/api/v1`.\n\n**Authentification.** Le jeton d'accès se présente dans l'en-tête `Authorization: Bearer ...`.\nLe jeton de rafraîchissement est un cookie `HttpOnly` que le code client ne voit jamais : il\nsuffit d'émettre les requêtes avec les identifiants de session. `POST /auth/refresh` rend un\nnouveau jeton d'accès et fait tourner le cookie.\n\n**Rôles.** `lecteur`, puis `operateur`, puis `admin`. Chaque rôle couvre les droits du\nprécédent.\n\n**Erreurs.** Le corps porte toujours une clé `detail`. Un `403` dont le `detail` vaut\n`password_change_required` n'est pas un refus de droits : il exige le changement du mot de passe\nprovisoire avant toute autre action.\n\nLe parcours de session complet est décrit dans\n`docs/architecture/31-contrat-authentification.md`.\n",
|
"description": "\nToutes les routes sont préfixées par `/api/v1`.\n\n**Authentification.** Le jeton d'accès se présente dans l'en-tête `Authorization: Bearer ...`.\nLe jeton de rafraîchissement est un cookie `HttpOnly` que le code client ne voit jamais : il\nsuffit d'émettre les requêtes avec les identifiants de session. `POST /auth/refresh` rend un\nnouveau jeton d'accès et fait tourner le cookie.\n\n**Rôles.** `lecteur`, puis `operateur`, puis `admin`. Chaque rôle couvre les droits du\nprécédent.\n\n**Erreurs.** Le corps porte toujours une clé `detail`. Un `403` dont le `detail` vaut\n`password_change_required` n'est pas un refus de droits : il exige le changement du mot de passe\nprovisoire avant toute autre action.\n\nLe parcours de session complet est décrit dans\n`docs/architecture/31-contrat-authentification.md`.\n",
|
||||||
"version": "0.1.0"
|
"version": "0.1.0",
|
||||||
|
"x-logo": {
|
||||||
|
"url": "/static/logo-icon.png",
|
||||||
|
"altText": "EnerVision"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"paths": {
|
"paths": {
|
||||||
"/api/v1/health/live": {
|
"/api/v1/health/live": {
|
||||||
@@ -1111,6 +1115,93 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"/api/v1/sites/{site_id}/current": {
|
||||||
|
"get": {
|
||||||
|
"tags": [
|
||||||
|
"sites"
|
||||||
|
],
|
||||||
|
"summary": "Dernière mesure d'un site",
|
||||||
|
"operationId": "get_current_api_v1_sites__site_id__current_get",
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"Jeton d'accès": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"name": "site_id",
|
||||||
|
"in": "path",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "Site Id"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "Successful Response",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/SiteCurrentResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas renvoyée au client.",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/InternalErrorResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"401": {
|
||||||
|
"description": "Jeton absent, illisible, périmé, ou rendu caduc par un changement de rôle ou une désactivation. L'en-tête `WWW-Authenticate` porte la cause dans `error=`.",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/ErrorResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"403": {
|
||||||
|
"description": "Mot de passe provisoire à changer (`detail` vaut `password_change_required`).",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/ErrorResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"422": {
|
||||||
|
"description": "Corps invalide. Le détail nomme le champ fautif et le type d'erreur, jamais la valeur envoyée.",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/ValidationErrorResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"404": {
|
||||||
|
"description": "Aucun site ne porte cet identifiant.",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/ErrorResponse"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"/api/v1/alerts": {
|
"/api/v1/alerts": {
|
||||||
"get": {
|
"get": {
|
||||||
"tags": [
|
"tags": [
|
||||||
@@ -2293,6 +2384,140 @@
|
|||||||
],
|
],
|
||||||
"title": "SensorStatusResponse"
|
"title": "SensorStatusResponse"
|
||||||
},
|
},
|
||||||
|
"SiteCurrentResponse": {
|
||||||
|
"properties": {
|
||||||
|
"timestamp": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "string",
|
||||||
|
"format": "date-time"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Timestamp"
|
||||||
|
},
|
||||||
|
"site_id": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "Site Id"
|
||||||
|
},
|
||||||
|
"site_type": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "Site Type"
|
||||||
|
},
|
||||||
|
"consumption_kw": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Consumption Kw"
|
||||||
|
},
|
||||||
|
"consumption_kwh": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Consumption Kwh"
|
||||||
|
},
|
||||||
|
"voltage_v": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Voltage V"
|
||||||
|
},
|
||||||
|
"current_a": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Current A"
|
||||||
|
},
|
||||||
|
"power_factor": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Power Factor"
|
||||||
|
},
|
||||||
|
"temperature_celsius": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Temperature Celsius"
|
||||||
|
},
|
||||||
|
"humidity_percent": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Humidity Percent"
|
||||||
|
},
|
||||||
|
"null_reasons": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": "array",
|
||||||
|
"title": "Null Reasons"
|
||||||
|
},
|
||||||
|
"data_quality": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": [
|
||||||
|
"good",
|
||||||
|
"partial",
|
||||||
|
"degraded",
|
||||||
|
"critical"
|
||||||
|
],
|
||||||
|
"title": "Data Quality"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"timestamp",
|
||||||
|
"site_id",
|
||||||
|
"site_type",
|
||||||
|
"consumption_kw",
|
||||||
|
"consumption_kwh",
|
||||||
|
"voltage_v",
|
||||||
|
"current_a",
|
||||||
|
"power_factor",
|
||||||
|
"temperature_celsius",
|
||||||
|
"humidity_percent",
|
||||||
|
"null_reasons",
|
||||||
|
"data_quality"
|
||||||
|
],
|
||||||
|
"title": "SiteCurrentResponse"
|
||||||
|
},
|
||||||
"SiteResponse": {
|
"SiteResponse": {
|
||||||
"properties": {
|
"properties": {
|
||||||
"site_id": {
|
"site_id": {
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
# Pourquoi : classification unique des routes du contrat, lue par test_route_protection.py,
|
||||||
|
# test_openapi.py et test_matrice_acces.py. Trois listes séparées dérivaient auparavant chacune
|
||||||
|
# de leur côté, et deux entrées de ROUTES_A_ROLE ne correspondaient plus à aucune route sans que
|
||||||
|
# rien ne le signale.
|
||||||
|
# Piège : les trois ensembles doivent rester disjoints et couvrir tout le schéma. C'est
|
||||||
|
# `test_every_declared_route_is_classified` qui le vérifie, pas la relecture.
|
||||||
|
|
||||||
|
from typing import Final
|
||||||
|
|
||||||
|
from app.core.roles import Role
|
||||||
|
|
||||||
|
Route = tuple[str, str]
|
||||||
|
|
||||||
|
ROUTES_PUBLIQUES: Final[frozenset[Route]] = frozenset(
|
||||||
|
{
|
||||||
|
("GET", "/api/v1/health/live"),
|
||||||
|
("GET", "/api/v1/health/ready"),
|
||||||
|
("POST", "/api/v1/auth/login"),
|
||||||
|
# Sans cookie, la déconnexion ne fait rien et répond 204 : elle est idempotente.
|
||||||
|
("POST", "/api/v1/auth/logout"),
|
||||||
|
("POST", "/api/v1/auth/forgot-password"),
|
||||||
|
# Protégée par le jeton dans le corps de la requête, pas par un `Principal` : aucune
|
||||||
|
# authentification préalable ne s'applique, c'est la validité du jeton qui tranche.
|
||||||
|
("POST", "/api/v1/auth/reset-password"),
|
||||||
|
# Même raison : lecture seule, protégée par le jeton passé en paramètre, pas par un
|
||||||
|
# `Principal`. Le jeton est un secret de 256 bits, non brute-forçable.
|
||||||
|
("GET", "/api/v1/auth/reset-password/validate"),
|
||||||
|
("GET", "/metrics"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
# Le cookie opaque porte seul l'autorisation : sans lui la route rend 401, mais aucun `Principal`
|
||||||
|
# n'est construit et `require_role` n'entre jamais en jeu.
|
||||||
|
ROUTE_COOKIE: Final[frozenset[Route]] = frozenset({("POST", "/api/v1/auth/refresh")})
|
||||||
|
|
||||||
|
# Authentifiées par `CurrentPrincipalDep` nu, donc hors de `require_role` et, avec lui, hors du
|
||||||
|
# refus `password_change_required`. Volontaire pour `/auth/password`, qui est la sortie de l'état
|
||||||
|
# provisoire ; subi pour `/auth/logout-all`, cf. test_matrice_acces.py.
|
||||||
|
ROUTES_SANS_ROLE: Final[frozenset[Route]] = frozenset(
|
||||||
|
{
|
||||||
|
("GET", "/api/v1/auth/me"),
|
||||||
|
("POST", "/api/v1/auth/password"),
|
||||||
|
("POST", "/api/v1/auth/logout-all"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
ROLE_MINIMUM: Final[dict[Route, Role]] = {
|
||||||
|
("GET", "/api/v1/sites"): Role.LECTEUR,
|
||||||
|
("GET", "/api/v1/sites/{site_id}"): Role.LECTEUR,
|
||||||
|
("GET", "/api/v1/sites/{site_id}/current"): Role.LECTEUR,
|
||||||
|
("GET", "/api/v1/alerts"): Role.LECTEUR,
|
||||||
|
("GET", "/api/v1/recommendations"): Role.LECTEUR,
|
||||||
|
("GET", "/api/v1/recommendations/{recommendation_id}"): Role.LECTEUR,
|
||||||
|
("GET", "/api/v1/stats/summary"): Role.LECTEUR,
|
||||||
|
("GET", "/api/v1/readings"): Role.LECTEUR,
|
||||||
|
("GET", "/api/v1/sensors/status"): Role.ADMIN,
|
||||||
|
("GET", "/api/v1/users"): Role.ADMIN,
|
||||||
|
("POST", "/api/v1/users"): Role.ADMIN,
|
||||||
|
("PATCH", "/api/v1/users/{user_id}"): Role.ADMIN,
|
||||||
|
("POST", "/api/v1/users/{user_id}/password-reset"): Role.ADMIN,
|
||||||
|
}
|
||||||
|
|
||||||
|
# Piège : `{recommendation_id}` est typé `int` et `{user_id}` est un UUID. Une substitution
|
||||||
|
# uniforme par une chaîne quelconque rendrait 422 avant d'atteindre la garde de rôle, et le test
|
||||||
|
# passerait en prouvant autre chose que ce qu'il annonce.
|
||||||
|
SUBSTITUTIONS: Final[dict[str, str]] = {
|
||||||
|
"{user_id}": "00000000-0000-0000-0000-000000000000",
|
||||||
|
"{site_id}": "site-absent-du-jeu-de-donnees",
|
||||||
|
"{recommendation_id}": "999999999",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def chemin_concret(chemin: str) -> str:
|
||||||
|
for gabarit, valeur in SUBSTITUTIONS.items():
|
||||||
|
chemin = chemin.replace(gabarit, valeur)
|
||||||
|
return chemin
|
||||||
|
|
||||||
|
|
||||||
|
def routes_du_schema(schema: dict[str, object]) -> list[Route]:
|
||||||
|
chemins: dict[str, dict[str, object]] = schema["paths"] # type: ignore[assignment]
|
||||||
|
return [
|
||||||
|
(methode.upper(), chemin)
|
||||||
|
for chemin, operations in chemins.items()
|
||||||
|
for methode in operations
|
||||||
|
if methode.upper() in {"GET", "POST", "PATCH", "PUT", "DELETE"}
|
||||||
|
]
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
# Pourquoi : la matrice rôle x route sur les routes réelles. `test_authorization.py` la joue déjà,
|
||||||
|
# mais contre une route jetable montée par une fixture, ce qui ne dit rien du niveau effectivement
|
||||||
|
# posé sur `/sites` ou `/users`. `ROLE_MINIMUM` (tests/api/acces.py) est la référence, et ce
|
||||||
|
# fichier est ce qui la confronte au comportement observé.
|
||||||
|
# Piège : l'assertion porte sur le refus de la garde, pas sur un 200. Un rôle suffisant peut
|
||||||
|
# légitimement recevoir 404 ou 422 selon les données ; ce qui compte est qu'il ne reçoive pas le
|
||||||
|
# 403 `Droits insuffisants`. Sans cette nuance, le test dépendrait du contenu de la base.
|
||||||
|
# Les tests `integration` en fin de fichier rejouent la même matrice avec de vrais jetons, donc en
|
||||||
|
# traversant le décodage du JWT et la relecture du compte, ce que l'override court-circuite.
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from collections.abc import AsyncIterator, Callable, Iterator
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from httpx import AsyncClient, Response
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
from app.api.deps import get_current_principal
|
||||||
|
from app.core.hashing import build_hasher
|
||||||
|
from app.core.principal import Principal
|
||||||
|
from app.core.roles import AccountKind, Role, has_at_least
|
||||||
|
from app.db.session import get_session, get_session_factory
|
||||||
|
from app.repositories.user import UserRepository
|
||||||
|
from tests.api.acces import ROLE_MINIMUM, chemin_concret
|
||||||
|
|
||||||
|
ROLES = [Role.LECTEUR, Role.OPERATEUR, Role.ADMIN]
|
||||||
|
IDS_DE_ROLE = ["lecteur", "operateur", "admin"]
|
||||||
|
REFUS_DE_DROITS = "Droits insuffisants"
|
||||||
|
REFUS_DE_MOT_DE_PASSE = "password_change_required"
|
||||||
|
MOT_DE_PASSE = "un-mot-de-passe-de-recette"
|
||||||
|
|
||||||
|
|
||||||
|
# `FakeSession` de tests/factories.py rend un unique objet pour les trois formes d'appel, ce qui
|
||||||
|
# suffit à un test d'endpoint ciblé mais pas à balayer 13 routes qui interrogent chacune la base
|
||||||
|
# à sa façon. Ce double rend un résultat vide quelle que soit la forme demandée, pour que la
|
||||||
|
# réponse observée vienne de la garde de rôle et jamais d'un double mal ajusté.
|
||||||
|
class ResultatVide:
|
||||||
|
def scalars(self) -> ResultatVide:
|
||||||
|
return self
|
||||||
|
|
||||||
|
def all(self) -> list[object]:
|
||||||
|
return []
|
||||||
|
|
||||||
|
def first(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def one_or_none(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def scalar_one_or_none(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def mappings(self) -> ResultatVide:
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __iter__(self) -> Iterator[object]:
|
||||||
|
return iter(())
|
||||||
|
|
||||||
|
|
||||||
|
class SessionMuette:
|
||||||
|
async def scalar(self, *_: object, **__: object) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def execute(self, *_: object, **__: object) -> ResultatVide:
|
||||||
|
return ResultatVide()
|
||||||
|
|
||||||
|
async def scalars(self, *_: object, **__: object) -> ResultatVide:
|
||||||
|
return ResultatVide()
|
||||||
|
|
||||||
|
async def get(self, *_: object, **__: object) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def flush(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def commit(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def rollback(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def add(self, *_: object, **__: object) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def base_muette(app: FastAPI) -> None:
|
||||||
|
async def override() -> AsyncIterator[SessionMuette]:
|
||||||
|
yield SessionMuette()
|
||||||
|
|
||||||
|
app.dependency_overrides[get_session] = override
|
||||||
|
|
||||||
|
|
||||||
|
def principal(role: Role, *, must_change_password: bool = False) -> Principal:
|
||||||
|
return Principal(
|
||||||
|
id=uuid.uuid4(),
|
||||||
|
email=f"matrice-{role.value}@enervision.fr",
|
||||||
|
role=role,
|
||||||
|
kind=AccountKind.HUMAIN,
|
||||||
|
must_change_password=must_change_password,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def connecte(app: FastAPI) -> Iterator[Callable[[Principal], None]]:
|
||||||
|
def installe(acteur: Principal) -> None:
|
||||||
|
app.dependency_overrides[get_current_principal] = lambda: acteur
|
||||||
|
|
||||||
|
yield installe
|
||||||
|
app.dependency_overrides.pop(get_current_principal, None)
|
||||||
|
|
||||||
|
|
||||||
|
async def appelle(client: AsyncClient, methode: str, chemin: str, **kwargs: object) -> Response:
|
||||||
|
return await client.request(methode, chemin_concret(chemin), json={}, **kwargs) # type: ignore[arg-type]
|
||||||
|
|
||||||
|
|
||||||
|
def motif_du_refus(response: Response) -> str | None:
|
||||||
|
if response.status_code != 403:
|
||||||
|
return None
|
||||||
|
detail = response.json().get("detail")
|
||||||
|
return detail if isinstance(detail, str) else None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("role", ROLES, ids=IDS_DE_ROLE)
|
||||||
|
async def test_a_role_below_the_minimum_is_refused_on_every_guarded_route(
|
||||||
|
connecte: Callable[[Principal], None],
|
||||||
|
client: AsyncClient,
|
||||||
|
base_muette: None,
|
||||||
|
role: Role,
|
||||||
|
) -> None:
|
||||||
|
connecte(principal(role))
|
||||||
|
laissees_passer: list[tuple[str, str, int]] = []
|
||||||
|
|
||||||
|
for (methode, chemin), minimum in ROLE_MINIMUM.items():
|
||||||
|
if has_at_least(role, minimum):
|
||||||
|
continue
|
||||||
|
response = await appelle(client, methode, chemin)
|
||||||
|
if motif_du_refus(response) != REFUS_DE_DROITS:
|
||||||
|
laissees_passer.append((methode, chemin, response.status_code))
|
||||||
|
|
||||||
|
assert laissees_passer == []
|
||||||
|
|
||||||
|
|
||||||
|
# Le pendant du test précédent : sans lui, une garde posée trop haut, par exemple `AdminDep` sur
|
||||||
|
# `/sites`, ne ferait échouer aucun test du dépôt.
|
||||||
|
@pytest.mark.parametrize("role", ROLES, ids=IDS_DE_ROLE)
|
||||||
|
async def test_a_role_at_or_above_the_minimum_is_never_refused_by_the_guard(
|
||||||
|
connecte: Callable[[Principal], None],
|
||||||
|
client: AsyncClient,
|
||||||
|
base_muette: None,
|
||||||
|
role: Role,
|
||||||
|
) -> None:
|
||||||
|
connecte(principal(role))
|
||||||
|
refusees: list[tuple[str, str]] = []
|
||||||
|
|
||||||
|
for (methode, chemin), minimum in ROLE_MINIMUM.items():
|
||||||
|
if not has_at_least(role, minimum):
|
||||||
|
continue
|
||||||
|
response = await appelle(client, methode, chemin)
|
||||||
|
if motif_du_refus(response) == REFUS_DE_DROITS:
|
||||||
|
refusees.append((methode, chemin))
|
||||||
|
|
||||||
|
assert refusees == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_a_pending_password_change_is_refused_on_every_guarded_route(
|
||||||
|
connecte: Callable[[Principal], None],
|
||||||
|
client: AsyncClient,
|
||||||
|
base_muette: None,
|
||||||
|
) -> None:
|
||||||
|
connecte(principal(Role.ADMIN, must_change_password=True))
|
||||||
|
laissees_passer: list[tuple[str, str, int]] = []
|
||||||
|
|
||||||
|
for methode, chemin in ROLE_MINIMUM:
|
||||||
|
response = await appelle(client, methode, chemin)
|
||||||
|
if motif_du_refus(response) != REFUS_DE_MOT_DE_PASSE:
|
||||||
|
laissees_passer.append((methode, chemin, response.status_code))
|
||||||
|
|
||||||
|
assert laissees_passer == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
async def comptes_par_role() -> AsyncIterator[dict[Role, str]]:
|
||||||
|
marque = uuid.uuid4().hex[:12]
|
||||||
|
hacheur = build_hasher(time_cost=1, memory_cost_kib=8192, parallelism=1, max_concurrency=2)
|
||||||
|
empreinte = await hacheur.hash(MOT_DE_PASSE)
|
||||||
|
adresses = {role: f"matrice-{marque}-{role.value}@enervision.fr" for role in ROLES}
|
||||||
|
|
||||||
|
async with get_session_factory()() as session:
|
||||||
|
depot = UserRepository(session)
|
||||||
|
for role, email in adresses.items():
|
||||||
|
await depot.create(email=email, password_hash=empreinte, role=role)
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
yield adresses
|
||||||
|
|
||||||
|
async with get_session_factory()() as session:
|
||||||
|
await session.execute(
|
||||||
|
text("delete from app_user where email like :motif"), {"motif": f"matrice-{marque}-%"}
|
||||||
|
)
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
async def authentifie(client: AsyncClient, email: str) -> dict[str, str]:
|
||||||
|
reponse = await client.post(
|
||||||
|
"/api/v1/auth/login", json={"email": email, "password": MOT_DE_PASSE}
|
||||||
|
)
|
||||||
|
assert reponse.status_code == 200, reponse.text
|
||||||
|
return {"Authorization": f"Bearer {reponse.json()['access_token']}"}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.integration
|
||||||
|
@pytest.mark.parametrize("role", ROLES, ids=IDS_DE_ROLE)
|
||||||
|
async def test_a_real_token_reaches_exactly_the_routes_of_its_rank(
|
||||||
|
comptes_par_role: dict[Role, str], client: AsyncClient, role: Role
|
||||||
|
) -> None:
|
||||||
|
entetes = await authentifie(client, comptes_par_role[role])
|
||||||
|
ecarts: list[tuple[str, str, int, str]] = []
|
||||||
|
|
||||||
|
for (methode, chemin), minimum in ROLE_MINIMUM.items():
|
||||||
|
response = await appelle(client, methode, chemin, headers=entetes)
|
||||||
|
refuse = motif_du_refus(response) == REFUS_DE_DROITS
|
||||||
|
if refuse is has_at_least(role, minimum):
|
||||||
|
ecarts.append((methode, chemin, response.status_code, response.text[:120]))
|
||||||
|
|
||||||
|
assert ecarts == []
|
||||||
|
|
||||||
|
|
||||||
|
# Contrainte : `operateur` n'ouvre aujourd'hui aucune route de plus que `lecteur`, faute d'écriture
|
||||||
|
# métier dans l'API. Figer l'égalité rend la régression visible le jour où une route d'opérateur
|
||||||
|
# arrive sans que `ROLE_MINIMUM` soit mis à jour.
|
||||||
|
@pytest.mark.integration
|
||||||
|
async def test_the_operator_rank_opens_nothing_more_than_the_reader_rank(
|
||||||
|
comptes_par_role: dict[Role, str], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
lecteur = await authentifie(client, comptes_par_role[Role.LECTEUR])
|
||||||
|
operateur = await authentifie(client, comptes_par_role[Role.OPERATEUR])
|
||||||
|
divergences: list[tuple[str, str]] = []
|
||||||
|
|
||||||
|
for methode, chemin in ROLE_MINIMUM:
|
||||||
|
cote_lecteur = await appelle(client, methode, chemin, headers=lecteur)
|
||||||
|
cote_operateur = await appelle(client, methode, chemin, headers=operateur)
|
||||||
|
if cote_lecteur.status_code != cote_operateur.status_code:
|
||||||
|
divergences.append((methode, chemin))
|
||||||
|
|
||||||
|
assert divergences == []
|
||||||
|
|
||||||
|
|
||||||
|
# Piège : `/auth/logout-all` prend un `CurrentPrincipalDep` nu, donc elle échappe au gate
|
||||||
|
# `must_change_password` que seul `require_role` applique. Comportement figé ici, pas corrigé.
|
||||||
|
@pytest.mark.integration
|
||||||
|
async def test_a_temporary_password_blocks_the_business_routes_but_not_logout_all(
|
||||||
|
client: AsyncClient,
|
||||||
|
) -> None:
|
||||||
|
marque = uuid.uuid4().hex[:12]
|
||||||
|
email = f"matrice-{marque}-provisoire@enervision.fr"
|
||||||
|
hacheur = build_hasher(time_cost=1, memory_cost_kib=8192, parallelism=1, max_concurrency=2)
|
||||||
|
empreinte = await hacheur.hash(MOT_DE_PASSE)
|
||||||
|
|
||||||
|
async with get_session_factory()() as session:
|
||||||
|
await UserRepository(session).create(
|
||||||
|
email=email, password_hash=empreinte, role=Role.ADMIN, must_change_password=True
|
||||||
|
)
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
try:
|
||||||
|
entetes = await authentifie(client, email)
|
||||||
|
sites = await client.get("/api/v1/sites", headers=entetes)
|
||||||
|
identite = await client.get("/api/v1/auth/me", headers=entetes)
|
||||||
|
fermeture = await client.post("/api/v1/auth/logout-all", headers=entetes)
|
||||||
|
|
||||||
|
assert motif_du_refus(sites) == REFUS_DE_MOT_DE_PASSE
|
||||||
|
assert identite.status_code == 200
|
||||||
|
assert fermeture.status_code == 204
|
||||||
|
finally:
|
||||||
|
async with get_session_factory()() as session:
|
||||||
|
await session.execute(text("delete from app_user where email = :e"), {"e": email})
|
||||||
|
await session.commit()
|
||||||
@@ -8,6 +8,7 @@ from typing import Any
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from app import cli
|
from app import cli
|
||||||
|
from tests.api.acces import ROLE_MINIMUM
|
||||||
|
|
||||||
METHODES = {"get", "post", "patch", "put", "delete"}
|
METHODES = {"get", "post", "patch", "put", "delete"}
|
||||||
|
|
||||||
@@ -24,20 +25,11 @@ ORIGINE_VERIFIEE = {
|
|||||||
|
|
||||||
# Toute route derrière `require_role` (LecteurDep, OperateurDep, AdminDep) peut rendre 403 pour
|
# Toute route derrière `require_role` (LecteurDep, OperateurDep, AdminDep) peut rendre 403 pour
|
||||||
# `password_change_required`, pas seulement les routes `admin`.
|
# `password_change_required`, pas seulement les routes `admin`.
|
||||||
ROUTES_A_ROLE = {
|
# Piège : cette liste était recopiée ici, et deux de ses entrées portaient `{id}` là où le contrat
|
||||||
("GET", "/api/v1/users"),
|
# expose `{user_id}`. Elles ne correspondaient donc à aucune opération, et le test ci-dessous
|
||||||
("POST", "/api/v1/users"),
|
# passait au vert sans rien vérifier sur ces deux routes. Elle est maintenant dérivée, et
|
||||||
("PATCH", "/api/v1/users/{id}"),
|
# `test_every_declared_route_is_classified` interdit l'entrée morte.
|
||||||
("POST", "/api/v1/users/{id}/password-reset"),
|
ROUTES_A_ROLE = frozenset(ROLE_MINIMUM)
|
||||||
("GET", "/api/v1/sites"),
|
|
||||||
("GET", "/api/v1/sites/{site_id}"),
|
|
||||||
("GET", "/api/v1/alerts"),
|
|
||||||
("GET", "/api/v1/recommendations"),
|
|
||||||
("GET", "/api/v1/recommendations/{recommendation_id}"),
|
|
||||||
("GET", "/api/v1/stats/summary"),
|
|
||||||
("GET", "/api/v1/readings"),
|
|
||||||
("GET", "/api/v1/sensors/status"),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
@pytest.fixture(scope="module")
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Ce test est le garde-fou de l'autorisation : rendre une route publique oblige à modifier
|
# Ce test est le garde-fou de l'autorisation : rendre une route publique oblige à modifier
|
||||||
# `ROUTES_PUBLIQUES` ci-dessous, ce qui apparaît en clair dans la diff d'une pull request et
|
# `ROUTES_PUBLIQUES` dans `tests/api/acces.py`, ce qui apparaît en clair dans la diff d'une pull
|
||||||
# demande une justification au relecteur.
|
# request et demande une justification au relecteur.
|
||||||
# Pourquoi : il interroge réellement chaque route sans jeton au lieu d'inspecter l'arbre de
|
# Pourquoi : il interroge réellement chaque route sans jeton au lieu d'inspecter l'arbre de
|
||||||
# dépendances. L'arbre n'est accessible que par l'API privée de FastAPI, et surtout une route
|
# dépendances. L'arbre n'est accessible que par l'API privée de FastAPI, et surtout une route
|
||||||
# peut porter la bonne dépendance tout en répondant quand même.
|
# peut porter la bonne dépendance tout en répondant quand même.
|
||||||
@@ -11,58 +11,64 @@ import pytest
|
|||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from httpx import AsyncClient
|
from httpx import AsyncClient
|
||||||
|
|
||||||
ROUTES_PUBLIQUES = frozenset(
|
from tests.api.acces import (
|
||||||
{
|
ROLE_MINIMUM,
|
||||||
("GET", "/api/v1/health/live"),
|
ROUTE_COOKIE,
|
||||||
("GET", "/api/v1/health/ready"),
|
ROUTES_PUBLIQUES,
|
||||||
("POST", "/api/v1/auth/login"),
|
ROUTES_SANS_ROLE,
|
||||||
# Sans cookie, la déconnexion ne fait rien et répond 204 : elle est idempotente.
|
Route,
|
||||||
("POST", "/api/v1/auth/logout"),
|
chemin_concret,
|
||||||
("POST", "/api/v1/auth/forgot-password"),
|
routes_du_schema,
|
||||||
# Protégée par le jeton dans le corps de la requête, pas par un `Principal` : aucune
|
|
||||||
# authentification préalable ne s'applique, c'est la validité du jeton qui tranche.
|
|
||||||
("POST", "/api/v1/auth/reset-password"),
|
|
||||||
# Même raison : lecture seule, protégée par le jeton passé en paramètre, pas par un
|
|
||||||
# `Principal`. Le jeton est un secret de 256 bits, non brute-forçable.
|
|
||||||
("GET", "/api/v1/auth/reset-password/validate"),
|
|
||||||
("GET", "/metrics"),
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
VALEURS_DE_SUBSTITUTION = "00000000-0000-0000-0000-000000000000"
|
|
||||||
STATUTS_DE_REFUS = {401, 403}
|
STATUTS_DE_REFUS = {401, 403}
|
||||||
|
HORS_SCHEMA = {("GET", "/metrics")}
|
||||||
|
|
||||||
|
|
||||||
def routes_declarees(app: FastAPI) -> list[tuple[str, str]]:
|
def routes_declarees(app: FastAPI) -> list[Route]:
|
||||||
schema: dict[str, Any] = app.openapi()
|
schema: dict[str, Any] = app.openapi()
|
||||||
return [
|
return routes_du_schema(schema)
|
||||||
(methode.upper(), chemin)
|
|
||||||
for chemin, operations in schema["paths"].items()
|
|
||||||
for methode in operations
|
|
||||||
if methode.upper() in {"GET", "POST", "PATCH", "PUT", "DELETE"}
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def routes_protegees(app: FastAPI) -> list[tuple[str, str]]:
|
def routes_protegees(app: FastAPI) -> list[Route]:
|
||||||
return [route for route in routes_declarees(app) if route not in ROUTES_PUBLIQUES]
|
return [route for route in routes_declarees(app) if route not in ROUTES_PUBLIQUES]
|
||||||
|
|
||||||
|
|
||||||
def test_the_public_allow_list_has_no_stale_entry(app: FastAPI) -> None:
|
def test_the_public_allow_list_has_no_stale_entry(app: FastAPI) -> None:
|
||||||
declarees = set(routes_declarees(app)) | {("GET", "/metrics")}
|
declarees = set(routes_declarees(app)) | HORS_SCHEMA
|
||||||
|
|
||||||
inconnues = ROUTES_PUBLIQUES - declarees
|
inconnues = ROUTES_PUBLIQUES - declarees
|
||||||
|
|
||||||
assert inconnues == set()
|
assert inconnues == set()
|
||||||
|
|
||||||
|
|
||||||
|
# Sans lui, une route ajoutée sans être classée n'est vue par aucun test de rôle : elle hérite
|
||||||
|
# du seul contrôle anonyme, et une garde posée au mauvais niveau passe inaperçue.
|
||||||
|
def test_every_declared_route_is_classified(app: FastAPI) -> None:
|
||||||
|
classees = ROUTES_PUBLIQUES | ROUTE_COOKIE | ROUTES_SANS_ROLE | set(ROLE_MINIMUM)
|
||||||
|
|
||||||
|
non_classees = set(routes_declarees(app)) - classees
|
||||||
|
fantomes = classees - set(routes_declarees(app)) - HORS_SCHEMA
|
||||||
|
|
||||||
|
assert non_classees == set(), "classer la route dans tests/api/acces.py"
|
||||||
|
assert fantomes == set(), "entrée morte : la route n'existe plus sous ce chemin"
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_four_classes_of_routes_stay_disjoint() -> None:
|
||||||
|
classes = [ROUTES_PUBLIQUES, ROUTE_COOKIE, ROUTES_SANS_ROLE, frozenset(ROLE_MINIMUM)]
|
||||||
|
|
||||||
|
for rang, classe in enumerate(classes):
|
||||||
|
for autre in classes[rang + 1 :]:
|
||||||
|
assert classe & autre == frozenset()
|
||||||
|
|
||||||
|
|
||||||
async def test_every_route_rejects_an_anonymous_caller_unless_explicitly_public(
|
async def test_every_route_rejects_an_anonymous_caller_unless_explicitly_public(
|
||||||
app: FastAPI, client: AsyncClient
|
app: FastAPI, client: AsyncClient
|
||||||
) -> None:
|
) -> None:
|
||||||
ouvertes: list[tuple[str, str, int]] = []
|
ouvertes: list[tuple[str, str, int]] = []
|
||||||
|
|
||||||
for methode, chemin in routes_protegees(app):
|
for methode, chemin in routes_protegees(app):
|
||||||
concret = chemin.replace("{user_id}", VALEURS_DE_SUBSTITUTION)
|
response = await client.request(methode, chemin_concret(chemin), json={})
|
||||||
response = await client.request(methode, concret, json={})
|
|
||||||
if response.status_code not in STATUTS_DE_REFUS:
|
if response.status_code not in STATUTS_DE_REFUS:
|
||||||
ouvertes.append((methode, chemin, response.status_code))
|
ouvertes.append((methode, chemin, response.status_code))
|
||||||
|
|
||||||
@@ -81,3 +87,19 @@ async def test_the_declared_routes_are_actually_reachable(app: FastAPI) -> None:
|
|||||||
)
|
)
|
||||||
def test_the_health_probes_stay_public(app: FastAPI, chemin: str) -> None:
|
def test_the_health_probes_stay_public(app: FastAPI, chemin: str) -> None:
|
||||||
assert ("GET", chemin) in ROUTES_PUBLIQUES
|
assert ("GET", chemin) in ROUTES_PUBLIQUES
|
||||||
|
|
||||||
|
|
||||||
|
# Piège : ni les routes `include_in_schema=False` (/docs, /redoc) ni un `Mount` Starlette
|
||||||
|
# (/static) n'apparaissent dans `app.openapi()["paths"]`. `routes_declarees()` ne les voit
|
||||||
|
# donc jamais, et elles échapperaient silencieusement au garde-fou ci-dessus.
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"chemin",
|
||||||
|
["/docs", "/redoc", "/static/logo-icon.png"],
|
||||||
|
ids=["swagger_ui", "redoc", "logo_statique"],
|
||||||
|
)
|
||||||
|
async def test_the_documentation_routes_are_public_by_design(
|
||||||
|
app: FastAPI, client: AsyncClient, chemin: str
|
||||||
|
) -> None:
|
||||||
|
response = await client.get(chemin)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
from collections.abc import Callable, Iterator
|
from collections.abc import Callable, Iterator
|
||||||
|
from datetime import UTC, datetime
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@@ -9,7 +10,9 @@ from app.api.deps import get_current_principal, get_site_service
|
|||||||
from app.core.principal import Principal
|
from app.core.principal import Principal
|
||||||
from app.core.roles import AccountKind, Role
|
from app.core.roles import AccountKind, Role
|
||||||
from app.models.energy import Site
|
from app.models.energy import Site
|
||||||
from app.services.site import SiteNotFoundError
|
from app.services.site import SiteCurrentReading, SiteNotFoundError
|
||||||
|
|
||||||
|
TIMESTAMP = datetime(2026, 9, 16, 12, 0, tzinfo=UTC)
|
||||||
|
|
||||||
|
|
||||||
def principal(role: Role = Role.LECTEUR) -> Principal:
|
def principal(role: Role = Role.LECTEUR) -> Principal:
|
||||||
@@ -33,10 +36,28 @@ def site(site_id: str = "site-1") -> Site:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def lecture_actuelle(site_id: str = "site-1") -> SiteCurrentReading:
|
||||||
|
return SiteCurrentReading(
|
||||||
|
timestamp=TIMESTAMP,
|
||||||
|
site_id=site_id,
|
||||||
|
site_type="industriel",
|
||||||
|
consumption_kw=87.34,
|
||||||
|
consumption_kwh=87.34,
|
||||||
|
voltage_v=401.2,
|
||||||
|
current_a=132.5,
|
||||||
|
power_factor=0.923,
|
||||||
|
temperature_celsius=22.1,
|
||||||
|
humidity_percent=58.4,
|
||||||
|
null_reasons=[],
|
||||||
|
data_quality="good",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class FauxService:
|
class FauxService:
|
||||||
def __init__(self, erreur: Exception | None = None) -> None:
|
def __init__(self, erreur: Exception | None = None) -> None:
|
||||||
self._erreur = erreur
|
self._erreur = erreur
|
||||||
self.site = site()
|
self.site = site()
|
||||||
|
self.actuel = lecture_actuelle()
|
||||||
|
|
||||||
async def list_all(self) -> list[Site]:
|
async def list_all(self) -> list[Site]:
|
||||||
return [self.site]
|
return [self.site]
|
||||||
@@ -46,6 +67,11 @@ class FauxService:
|
|||||||
raise self._erreur
|
raise self._erreur
|
||||||
return self.site
|
return self.site
|
||||||
|
|
||||||
|
async def current(self, site_id: str) -> SiteCurrentReading:
|
||||||
|
if self._erreur is not None:
|
||||||
|
raise self._erreur
|
||||||
|
return self.actuel
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def lecteur_connecte(app: FastAPI) -> Iterator[None]:
|
def lecteur_connecte(app: FastAPI) -> Iterator[None]:
|
||||||
@@ -109,6 +135,30 @@ async def test_get_site_returns_404_for_an_unknown_site(
|
|||||||
assert response.status_code == 404
|
assert response.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
async def test_get_current_returns_the_latest_reading(
|
||||||
|
servi: Callable[..., FauxService], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
servi()
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/sites/site-1/current")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
corps = response.json()
|
||||||
|
assert corps["site_id"] == "site-1"
|
||||||
|
assert corps["data_quality"] == "good"
|
||||||
|
assert corps["consumption_kw"] == 87.34
|
||||||
|
|
||||||
|
|
||||||
|
async def test_get_current_returns_404_for_an_unknown_site(
|
||||||
|
servi: Callable[..., FauxService], client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
servi(SiteNotFoundError("site-inconnu"))
|
||||||
|
|
||||||
|
response = await client.get("/api/v1/sites/site-inconnu/current")
|
||||||
|
|
||||||
|
assert response.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
async def test_list_sites_reaches_the_repository_through_the_session(
|
async def test_list_sites_reaches_the_repository_through_the_session(
|
||||||
lecteur_connecte: None, fake_session: Callable[..., None], client: AsyncClient
|
lecteur_connecte: None, fake_session: Callable[..., None], client: AsyncClient
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|||||||
@@ -88,6 +88,73 @@ async def test_latest_by_site_returns_one_row_per_site(session: AsyncSession) ->
|
|||||||
assert identifiants == {premier, second}
|
assert identifiants == {premier, second}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_latest_by_site_breaks_a_timestamp_tie_on_the_last_written_reading(
|
||||||
|
session: AsyncSession,
|
||||||
|
) -> None:
|
||||||
|
site = await creer_site(session)
|
||||||
|
depot = ReadingRepository(session)
|
||||||
|
horodatage = datetime(2026, 9, 15, tzinfo=UTC)
|
||||||
|
await creer_lecture(
|
||||||
|
session, site_id=site.site_id, timestamp=horodatage, source="api_history", consumption_kw=10
|
||||||
|
)
|
||||||
|
derniere = await creer_lecture(
|
||||||
|
session, site_id=site.site_id, timestamp=horodatage, source="api_current", consumption_kw=42
|
||||||
|
)
|
||||||
|
|
||||||
|
resultats = await depot.latest_by_site()
|
||||||
|
retenues = [r.reading_id for r in resultats if r.site_id == site.site_id]
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert retenues == [derniere.reading_id]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_latest_for_site_returns_the_most_recent_reading(session: AsyncSession) -> None:
|
||||||
|
site = await creer_site(session)
|
||||||
|
depot = ReadingRepository(session)
|
||||||
|
await creer_lecture(session, site_id=site.site_id, timestamp=datetime(2026, 9, 1, tzinfo=UTC))
|
||||||
|
recente = await creer_lecture(
|
||||||
|
session, site_id=site.site_id, timestamp=datetime(2026, 9, 15, tzinfo=UTC)
|
||||||
|
)
|
||||||
|
|
||||||
|
trouvee = await depot.latest_for_site(site.site_id)
|
||||||
|
reading_id = trouvee.reading_id if trouvee else None
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert reading_id == recente.reading_id
|
||||||
|
|
||||||
|
|
||||||
|
async def test_latest_for_site_breaks_a_timestamp_tie_on_the_last_written_reading(
|
||||||
|
session: AsyncSession,
|
||||||
|
) -> None:
|
||||||
|
site = await creer_site(session)
|
||||||
|
depot = ReadingRepository(session)
|
||||||
|
horodatage = datetime(2026, 9, 15, tzinfo=UTC)
|
||||||
|
await creer_lecture(session, site_id=site.site_id, timestamp=horodatage, source="api_history")
|
||||||
|
derniere = await creer_lecture(
|
||||||
|
session, site_id=site.site_id, timestamp=horodatage, source="api_current"
|
||||||
|
)
|
||||||
|
|
||||||
|
trouvee = await depot.latest_for_site(site.site_id)
|
||||||
|
reading_id = trouvee.reading_id if trouvee else None
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert reading_id == derniere.reading_id
|
||||||
|
|
||||||
|
|
||||||
|
async def test_latest_for_site_ignores_the_readings_of_the_other_sites(
|
||||||
|
session: AsyncSession,
|
||||||
|
) -> None:
|
||||||
|
sans_lecture = await creer_site(session)
|
||||||
|
autre = await creer_site(session)
|
||||||
|
depot = ReadingRepository(session)
|
||||||
|
await creer_lecture(session, site_id=autre.site_id)
|
||||||
|
|
||||||
|
trouvee = await depot.latest_for_site(sans_lecture.site_id)
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
assert trouvee is None
|
||||||
|
|
||||||
|
|
||||||
async def test_list_history_orders_the_readings_by_timestamp_descending(
|
async def test_list_history_orders_the_readings_by_timestamp_descending(
|
||||||
session: AsyncSession,
|
session: AsyncSession,
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from app.models.energy import Site
|
from app.models.energy import Site
|
||||||
from app.services.site import SiteNotFoundError, SiteService
|
from app.services.site import SiteNotFoundError, SiteService
|
||||||
|
|
||||||
|
TIMESTAMP = datetime(2026, 9, 16, 12, 0, tzinfo=UTC)
|
||||||
|
|
||||||
|
|
||||||
def site(site_id: str = "site-1") -> Site:
|
def site(site_id: str = "site-1") -> Site:
|
||||||
return Site(
|
return Site(
|
||||||
@@ -15,6 +20,21 @@ def site(site_id: str = "site-1") -> Site:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class FauxLecture:
|
||||||
|
site_id: str
|
||||||
|
timestamp: datetime = TIMESTAMP
|
||||||
|
consumption_kw: float | None = 87.34
|
||||||
|
consumption_kwh: float | None = 87.34
|
||||||
|
voltage_v: float | None = 401.2
|
||||||
|
current_a: float | None = 132.5
|
||||||
|
power_factor: float | None = 0.923
|
||||||
|
temperature_celsius: float | None = 22.1
|
||||||
|
humidity_percent: float | None = 58.4
|
||||||
|
null_reasons: list[str] | None = field(default_factory=list)
|
||||||
|
data_quality: str | None = "good"
|
||||||
|
|
||||||
|
|
||||||
class FakeRepository:
|
class FakeRepository:
|
||||||
def __init__(self, sites: list[Site]) -> None:
|
def __init__(self, sites: list[Site]) -> None:
|
||||||
self._sites = sites
|
self._sites = sites
|
||||||
@@ -26,24 +46,77 @@ class FakeRepository:
|
|||||||
return next((s for s in self._sites if s.site_id == site_id), None)
|
return next((s for s in self._sites if s.site_id == site_id), None)
|
||||||
|
|
||||||
|
|
||||||
async def test_list_all_returns_the_repository_sites() -> None:
|
class FauxDepotLectures:
|
||||||
service = SiteService(sites=FakeRepository([site("a"), site("b")]))
|
def __init__(self, lectures: dict[str, FauxLecture]) -> None:
|
||||||
|
self._lectures = lectures
|
||||||
|
|
||||||
sites = await service.list_all()
|
async def latest_for_site(self, site_id: str) -> FauxLecture | None:
|
||||||
|
return self._lectures.get(site_id)
|
||||||
|
|
||||||
|
|
||||||
|
def service(sites: list[Site], lectures: dict[str, FauxLecture] | None = None) -> SiteService:
|
||||||
|
return SiteService(
|
||||||
|
sites=FakeRepository(sites), # type: ignore[arg-type]
|
||||||
|
readings=FauxDepotLectures(lectures or {}), # type: ignore[arg-type]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_all_returns_the_repository_sites() -> None:
|
||||||
|
svc = service([site("a"), site("b")])
|
||||||
|
|
||||||
|
sites = await svc.list_all()
|
||||||
|
|
||||||
assert [s.site_id for s in sites] == ["a", "b"]
|
assert [s.site_id for s in sites] == ["a", "b"]
|
||||||
|
|
||||||
|
|
||||||
async def test_get_by_id_returns_the_matching_site() -> None:
|
async def test_get_by_id_returns_the_matching_site() -> None:
|
||||||
service = SiteService(sites=FakeRepository([site("a")]))
|
svc = service([site("a")])
|
||||||
|
|
||||||
trouve = await service.get_by_id("a")
|
trouve = await svc.get_by_id("a")
|
||||||
|
|
||||||
assert trouve.site_id == "a"
|
assert trouve.site_id == "a"
|
||||||
|
|
||||||
|
|
||||||
async def test_get_by_id_raises_when_the_site_is_unknown() -> None:
|
async def test_get_by_id_raises_when_the_site_is_unknown() -> None:
|
||||||
service = SiteService(sites=FakeRepository([]))
|
svc = service([])
|
||||||
|
|
||||||
with pytest.raises(SiteNotFoundError):
|
with pytest.raises(SiteNotFoundError):
|
||||||
await service.get_by_id("inconnu")
|
await svc.get_by_id("inconnu")
|
||||||
|
|
||||||
|
|
||||||
|
async def test_current_raises_when_the_site_is_unknown() -> None:
|
||||||
|
svc = service([])
|
||||||
|
|
||||||
|
with pytest.raises(SiteNotFoundError):
|
||||||
|
await svc.current("inconnu")
|
||||||
|
|
||||||
|
|
||||||
|
async def test_current_returns_every_field_as_null_when_the_site_has_no_reading() -> None:
|
||||||
|
svc = service([site("a")])
|
||||||
|
|
||||||
|
actuel = await svc.current("a")
|
||||||
|
|
||||||
|
assert actuel.timestamp is None
|
||||||
|
assert actuel.consumption_kw is None
|
||||||
|
assert actuel.data_quality == "critical"
|
||||||
|
assert actuel.null_reasons == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_current_copies_every_field_from_the_latest_reading() -> None:
|
||||||
|
svc = service([site("a")], {"a": FauxLecture(site_id="a")})
|
||||||
|
|
||||||
|
actuel = await svc.current("a")
|
||||||
|
|
||||||
|
assert actuel.timestamp == TIMESTAMP
|
||||||
|
assert actuel.site_type == "industriel"
|
||||||
|
assert actuel.consumption_kw == 87.34
|
||||||
|
assert actuel.voltage_v == 401.2
|
||||||
|
assert actuel.data_quality == "good"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_current_treats_an_unknown_data_quality_as_critical() -> None:
|
||||||
|
svc = service([site("a")], {"a": FauxLecture(site_id="a", data_quality=None)})
|
||||||
|
|
||||||
|
actuel = await svc.current("a")
|
||||||
|
|
||||||
|
assert actuel.data_quality == "critical"
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# Piège : le logo est committé indépendamment à deux endroits (`app/static/`, servi par
|
||||||
|
# `/docs`/`/redoc`, et `apps/frontend/public/`, servi au front) faute d'étape de build partagée.
|
||||||
|
# Sans ce test, une mise à jour d'un seul des deux fichiers dérive silencieusement : rien en CI
|
||||||
|
# ne le détecte.
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
BACKEND_LOGO = Path(__file__).parent.parent / "app" / "static" / "logo-icon.png"
|
||||||
|
FRONTEND_LOGO = Path(__file__).parent.parent.parent / "frontend" / "public" / "logo-icon.png"
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_backend_logo_stays_in_sync_with_the_frontend_one() -> None:
|
||||||
|
assert BACKEND_LOGO.read_bytes() == FRONTEND_LOGO.read_bytes()
|
||||||
@@ -76,6 +76,13 @@ Points à vérifier après toute regénération :
|
|||||||
côté backend. Le `docker-compose.yml` n'a aucun service frontend.
|
côté backend. Le `docker-compose.yml` n'a aucun service frontend.
|
||||||
4. Ajouter le `Dockerfile` multi-stage (build Angular puis service statique nginx).
|
4. Ajouter le `Dockerfile` multi-stage (build Angular puis service statique nginx).
|
||||||
|
|
||||||
|
## Design système
|
||||||
|
|
||||||
|
Tokens (couleurs, typo, espacements) et composants partagés (`ev-button`, `ev-card`,
|
||||||
|
`ev-alert`, `ev-badge`) sont documentés dans
|
||||||
|
[`docs/architecture/32-design-systeme-frontend.md`](../../docs/architecture/32-design-systeme-frontend.md).
|
||||||
|
Toute nouvelle page doit les réutiliser plutôt que définir ses propres valeurs.
|
||||||
|
|
||||||
## Additional Resources
|
## Additional Resources
|
||||||
|
|
||||||
For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.
|
For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.
|
||||||
|
|||||||
@@ -86,15 +86,6 @@
|
|||||||
"text-summary",
|
"text-summary",
|
||||||
"lcov",
|
"lcov",
|
||||||
"html"
|
"html"
|
||||||
],
|
|
||||||
"reporters": [
|
|
||||||
"default",
|
|
||||||
[
|
|
||||||
"junit",
|
|
||||||
{
|
|
||||||
"outputFile": "test-results/junit.xml"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 57 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
@@ -0,0 +1,18 @@
|
|||||||
|
sonar.projectKey=ProjetPiscine_EnerVision
|
||||||
|
sonar.organization=groupe3-ener-vision
|
||||||
|
sonar.sourceEncoding=UTF-8
|
||||||
|
|
||||||
|
# Dossier contenant le code source
|
||||||
|
sonar.sources=apps/frontend/src,apps/backend/app
|
||||||
|
sonar.tests=apps/backend/tests
|
||||||
|
|
||||||
|
# Liste des fichiers et dossiers à exclure de l'analyse
|
||||||
|
# Liste des fichiers et dossiers à exclure de l'analyse
|
||||||
|
sonar.exclusions=**/node_modules/**,**/dist/**,**/*.spec.js,**/*.test.js,github,db,ml,docker-compose.yml,**/**/Dockerfile,**/**/proxy.conf.json,**/**/package.json,**/**/angular.json
|
||||||
|
|
||||||
|
# Chemin vers le rapport de couverture de code
|
||||||
|
# Fichier généré par Vitest
|
||||||
|
# Chemin vers le rapport de couverture de code
|
||||||
|
# Fichier généré par Vitest
|
||||||
|
sonar.javascript.lcov.reportPaths=apps/frontend/coverage/frontend/lcov.info
|
||||||
|
sonar.python.coverage.reportPaths=apps/backend/cov.info
|
||||||
@@ -12,4 +12,15 @@ export const routes: Routes = [
|
|||||||
canActivate: [authGuard],
|
canActivate: [authGuard],
|
||||||
loadComponent: () => import('./features/dashboard/dashboard').then(m => m.Dashboard),
|
loadComponent: () => import('./features/dashboard/dashboard').then(m => m.Dashboard),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'sites',
|
||||||
|
canActivate: [authGuard],
|
||||||
|
loadComponent: () => import('./features/sites/site-list/site-list').then(m => m.SiteList),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'sites/:siteId',
|
||||||
|
canActivate: [authGuard],
|
||||||
|
loadComponent: () =>
|
||||||
|
import('./features/sites/site-detail/site-detail').then((m) => m.SiteDetail),
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
|
||||||
|
import { ReadingsService } from './readings.service';
|
||||||
|
import { environment } from '../../../environments/environment';
|
||||||
|
|
||||||
|
describe('ReadingsService', () => {
|
||||||
|
let service: ReadingsService;
|
||||||
|
let httpMock: HttpTestingController;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [provideHttpClient(), provideHttpClientTesting()],
|
||||||
|
});
|
||||||
|
service = TestBed.inject(ReadingsService);
|
||||||
|
httpMock = TestBed.inject(HttpTestingController);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => httpMock.verify());
|
||||||
|
|
||||||
|
it("demande l'historique du site avec la fenêtre temporelle donnée", () => {
|
||||||
|
let result: unknown;
|
||||||
|
service
|
||||||
|
.getHistory('SITE001', '2026-09-16T00:00:00Z', '2026-09-17T00:00:00Z')
|
||||||
|
.subscribe((r) => (result = r));
|
||||||
|
|
||||||
|
const req = httpMock.expectOne(
|
||||||
|
(r) => r.url === `${environment.apiUrl}/readings` && r.method === 'GET',
|
||||||
|
);
|
||||||
|
expect(req.request.params.get('site_id')).toBe('SITE001');
|
||||||
|
expect(req.request.params.get('start')).toBe('2026-09-16T00:00:00Z');
|
||||||
|
expect(req.request.params.get('end')).toBe('2026-09-17T00:00:00Z');
|
||||||
|
|
||||||
|
req.flush([{ reading_id: 1, site_id: 'SITE001', consumption_kw: 12.5 }]);
|
||||||
|
|
||||||
|
expect((result as unknown[]).length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ne pose pas de paramètres start/end quand ils sont omis', () => {
|
||||||
|
service.getHistory('SITE001').subscribe();
|
||||||
|
|
||||||
|
const req = httpMock.expectOne(
|
||||||
|
(r) => r.url === `${environment.apiUrl}/readings` && r.method === 'GET',
|
||||||
|
);
|
||||||
|
expect(req.request.params.has('start')).toBe(false);
|
||||||
|
expect(req.request.params.has('end')).toBe(false);
|
||||||
|
|
||||||
|
req.flush([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { Service, inject } from '@angular/core';
|
||||||
|
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||||
|
import { environment } from '../../../environments/environment';
|
||||||
|
import { Reading } from '../../shared/models/reading.model';
|
||||||
|
|
||||||
|
@Service()
|
||||||
|
export class ReadingsService {
|
||||||
|
private http = inject(HttpClient);
|
||||||
|
|
||||||
|
getHistory(siteId: string, start?: string, end?: string) {
|
||||||
|
let params = new HttpParams().set('site_id', siteId);
|
||||||
|
if (start) {
|
||||||
|
params = params.set('start', start);
|
||||||
|
}
|
||||||
|
if (end) {
|
||||||
|
params = params.set('end', end);
|
||||||
|
}
|
||||||
|
return this.http.get<Reading[]>(`${environment.apiUrl}/readings`, { params });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
|
||||||
|
import { SitesService } from './sites.service';
|
||||||
|
import { environment } from '../../../environments/environment';
|
||||||
|
|
||||||
|
describe('SitesService', () => {
|
||||||
|
let service: SitesService;
|
||||||
|
let httpMock: HttpTestingController;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [provideHttpClient(), provideHttpClientTesting()],
|
||||||
|
});
|
||||||
|
service = TestBed.inject(SitesService);
|
||||||
|
httpMock = TestBed.inject(HttpTestingController);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => httpMock.verify());
|
||||||
|
|
||||||
|
it('appelle le bon endpoint et retourne la liste des sites', () => {
|
||||||
|
let result: unknown;
|
||||||
|
service.getSites().subscribe((r) => (result = r));
|
||||||
|
|
||||||
|
const req = httpMock.expectOne(`${environment.apiUrl}/sites`);
|
||||||
|
expect(req.request.method).toBe('GET');
|
||||||
|
|
||||||
|
req.flush([
|
||||||
|
{
|
||||||
|
site_id: 'SITE001',
|
||||||
|
site_name: 'Site 1',
|
||||||
|
site_type: 'industriel',
|
||||||
|
location: 'Nantes',
|
||||||
|
capacity_kw: 500,
|
||||||
|
status: 'actif',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect((result as { site_id: string }[])[0].site_id).toBe('SITE001');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('appelle le bon endpoint et retourne un site', () => {
|
||||||
|
let result: unknown;
|
||||||
|
service.getSite('SITE001').subscribe((r) => (result = r));
|
||||||
|
|
||||||
|
const req = httpMock.expectOne(`${environment.apiUrl}/sites/SITE001`);
|
||||||
|
expect(req.request.method).toBe('GET');
|
||||||
|
|
||||||
|
req.flush({
|
||||||
|
site_id: 'SITE001',
|
||||||
|
site_name: 'Site 1',
|
||||||
|
site_type: 'industriel',
|
||||||
|
location: 'Nantes',
|
||||||
|
capacity_kw: 500,
|
||||||
|
status: 'actif',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect((result as { site_id: string }).site_id).toBe('SITE001');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('appelle le bon endpoint et retourne la mesure courante du site', () => {
|
||||||
|
let result: unknown;
|
||||||
|
service.getCurrent('SITE001').subscribe((r) => (result = r));
|
||||||
|
|
||||||
|
const req = httpMock.expectOne(`${environment.apiUrl}/sites/SITE001/current`);
|
||||||
|
expect(req.request.method).toBe('GET');
|
||||||
|
|
||||||
|
req.flush({
|
||||||
|
timestamp: '2026-09-17T10:00:00Z',
|
||||||
|
site_id: 'SITE001',
|
||||||
|
site_type: 'industriel',
|
||||||
|
consumption_kw: 120,
|
||||||
|
consumption_kwh: null,
|
||||||
|
voltage_v: null,
|
||||||
|
current_a: null,
|
||||||
|
power_factor: null,
|
||||||
|
temperature_celsius: 22,
|
||||||
|
humidity_percent: 55,
|
||||||
|
null_reasons: ['electrical_sensor_failure'],
|
||||||
|
data_quality: 'partial',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect((result as { null_reasons: string[] }).null_reasons).toEqual([
|
||||||
|
'electrical_sensor_failure',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { Service, inject } from '@angular/core';
|
||||||
|
import { HttpClient } from '@angular/common/http';
|
||||||
|
import { environment } from '../../../environments/environment';
|
||||||
|
import { Site } from '../../shared/models/site.model';
|
||||||
|
import { SiteCurrent } from '../../shared/models/site-current.model';
|
||||||
|
|
||||||
|
@Service()
|
||||||
|
export class SitesService {
|
||||||
|
private http = inject(HttpClient);
|
||||||
|
|
||||||
|
getSites() {
|
||||||
|
return this.http.get<Site[]>(`${environment.apiUrl}/sites`);
|
||||||
|
}
|
||||||
|
|
||||||
|
getSite(siteId: string) {
|
||||||
|
return this.http.get<Site>(`${environment.apiUrl}/sites/${siteId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
getCurrent(siteId: string) {
|
||||||
|
return this.http.get<SiteCurrent>(`${environment.apiUrl}/sites/${siteId}/current`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,31 +1,38 @@
|
|||||||
<div class="auth-page">
|
<div class="auth-page">
|
||||||
<form class="auth-card" [formGroup]="form" (ngSubmit)="onSubmit()">
|
<form class="auth-card-wrapper" [formGroup]="form" (ngSubmit)="onSubmit()">
|
||||||
<h1>Nouveau mot de passe</h1>
|
<ev-card>
|
||||||
<p class="auth-subtitle">Votre mot de passe est provisoire, vous devez le modifier avant de continuer</p>
|
<ev-brand class="auth-brand" />
|
||||||
|
<h1>Nouveau mot de passe</h1>
|
||||||
|
<p class="auth-subtitle">
|
||||||
|
Votre mot de passe est provisoire, vous devez le modifier avant de continuer
|
||||||
|
</p>
|
||||||
|
|
||||||
<label for="current_password">Mot de passe actuel</label>
|
<label class="form-label" for="current_password">Mot de passe actuel</label>
|
||||||
<input
|
<input
|
||||||
id="current_password"
|
id="current_password"
|
||||||
type="password"
|
class="form-input"
|
||||||
formControlName="current_password"
|
type="password"
|
||||||
autocomplete="current-password"
|
formControlName="current_password"
|
||||||
/>
|
autocomplete="current-password"
|
||||||
|
/>
|
||||||
|
|
||||||
<label for="new_password">Nouveau mot de passe</label>
|
<label class="form-label" for="new_password">Nouveau mot de passe</label>
|
||||||
<input
|
<input
|
||||||
id="new_password"
|
id="new_password"
|
||||||
type="password"
|
class="form-input"
|
||||||
formControlName="new_password"
|
type="password"
|
||||||
autocomplete="new-password"
|
formControlName="new_password"
|
||||||
/>
|
autocomplete="new-password"
|
||||||
<span class="auth-hint">{{ passwordHint }}</span>
|
/>
|
||||||
|
<span class="form-hint">{{ passwordHint }}</span>
|
||||||
|
|
||||||
@if (errorMessage()) {
|
@if (errorMessage()) {
|
||||||
<p class="auth-error">{{ errorMessage() }}</p>
|
<ev-alert severity="danger">{{ errorMessage() }}</ev-alert>
|
||||||
}
|
}
|
||||||
|
|
||||||
<button type="submit" [disabled]="form.invalid || isLoading()">
|
<ev-button type="submit" [disabled]="form.invalid || isLoading()">
|
||||||
{{ isLoading() ? 'Modification...' : 'Valider' }}
|
{{ isLoading() ? 'Modification...' : 'Valider' }}
|
||||||
</button>
|
</ev-button>
|
||||||
|
</ev-card>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,88 +0,0 @@
|
|||||||
:host {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
min-height: 100vh;
|
|
||||||
background: #f3f4f6;
|
|
||||||
font-family: 'Segoe UI', system-ui, sans-serif;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-card {
|
|
||||||
background: #ffffff;
|
|
||||||
border: 1px solid #e5e7eb;
|
|
||||||
border-radius: 12px;
|
|
||||||
padding: 2.5rem;
|
|
||||||
width: 100%;
|
|
||||||
max-width: 360px;
|
|
||||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
|
|
||||||
h1 {
|
|
||||||
margin: 0;
|
|
||||||
font-size: 1.5rem;
|
|
||||||
font-weight: 700;
|
|
||||||
color: #1f2937;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-subtitle {
|
|
||||||
margin: 0.25rem 0 1.5rem;
|
|
||||||
color: #6b7280;
|
|
||||||
font-size: 0.9rem;
|
|
||||||
line-height: 1.4;
|
|
||||||
}
|
|
||||||
|
|
||||||
label {
|
|
||||||
font-size: 0.85rem;
|
|
||||||
font-weight: 600;
|
|
||||||
color: #374151;
|
|
||||||
margin-bottom: 0.35rem;
|
|
||||||
margin-top: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
input {
|
|
||||||
padding: 0.6rem 0.75rem;
|
|
||||||
border: 1px solid #d1d5db;
|
|
||||||
border-radius: 8px;
|
|
||||||
font-size: 0.95rem;
|
|
||||||
|
|
||||||
&:focus {
|
|
||||||
outline: none;
|
|
||||||
border-color: #3b82f6;
|
|
||||||
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
button {
|
|
||||||
margin-top: 1.5rem;
|
|
||||||
padding: 0.7rem;
|
|
||||||
background: #3b82f6;
|
|
||||||
color: #fff;
|
|
||||||
border: none;
|
|
||||||
border-radius: 8px;
|
|
||||||
font-size: 0.95rem;
|
|
||||||
font-weight: 600;
|
|
||||||
cursor: pointer;
|
|
||||||
|
|
||||||
&:disabled {
|
|
||||||
background: #9ca3af;
|
|
||||||
cursor: not-allowed;
|
|
||||||
}
|
|
||||||
|
|
||||||
&:not(:disabled):hover {
|
|
||||||
background: #2563eb;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-hint {
|
|
||||||
font-size: 0.75rem;
|
|
||||||
color: #9ca3af;
|
|
||||||
margin-top: 0.25rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-error {
|
|
||||||
margin: 0.75rem 0 0;
|
|
||||||
color: #dc2626;
|
|
||||||
font-size: 0.85rem;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ describe('ChangePassword', () => {
|
|||||||
fixture.detectChanges(); // rend le bloc @if (errorMessage())
|
fixture.detectChanges(); // rend le bloc @if (errorMessage())
|
||||||
|
|
||||||
expect(component.errorMessage()).toContain('incorrect');
|
expect(component.errorMessage()).toContain('incorrect');
|
||||||
const errorEl = fixture.nativeElement.querySelector('.auth-error');
|
const errorEl = fixture.nativeElement.querySelector('.ev-alert');
|
||||||
expect(errorEl?.textContent).toContain('incorrect');
|
expect(errorEl?.textContent).toContain('incorrect');
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -73,7 +73,7 @@ describe('ChangePassword', () => {
|
|||||||
|
|
||||||
const button = fixture.nativeElement.querySelector('button[type="submit"]');
|
const button = fixture.nativeElement.querySelector('button[type="submit"]');
|
||||||
expect(button.disabled).toBe(true);
|
expect(button.disabled).toBe(true);
|
||||||
expect(fixture.nativeElement.querySelector('.auth-error')).toBeNull();
|
expect(fixture.nativeElement.querySelector('.ev-alert')).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('déclenche onSubmit via la soumission réelle du formulaire (ngSubmit)', () => {
|
it('déclenche onSubmit via la soumission réelle du formulaire (ngSubmit)', () => {
|
||||||
|
|||||||
@@ -2,12 +2,16 @@ import { Component, inject, signal } from '@angular/core';
|
|||||||
import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';
|
import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';
|
||||||
import { Router } from '@angular/router';
|
import { Router } from '@angular/router';
|
||||||
import { AuthService } from '../../../core/services/auth.service';
|
import { AuthService } from '../../../core/services/auth.service';
|
||||||
|
import { Button } from '../../../shared/components/ui/button/button';
|
||||||
|
import { Card } from '../../../shared/components/ui/card/card';
|
||||||
|
import { Alert } from '../../../shared/components/ui/alert/alert';
|
||||||
|
import { Brand } from '../../../shared/components/ui/brand/brand';
|
||||||
import { passwordValidators, PASSWORD_HINT } from '../../../shared/validators/password.validator';
|
import { passwordValidators, PASSWORD_HINT } from '../../../shared/validators/password.validator';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-change-password',
|
selector: 'app-change-password',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [ReactiveFormsModule],
|
imports: [ReactiveFormsModule, Button, Card, Alert, Brand],
|
||||||
templateUrl: './change-password.html',
|
templateUrl: './change-password.html',
|
||||||
styleUrl: './change-password.scss',
|
styleUrl: './change-password.scss',
|
||||||
})
|
})
|
||||||
@@ -36,7 +40,9 @@ export class ChangePassword {
|
|||||||
},
|
},
|
||||||
error: () => {
|
error: () => {
|
||||||
this.isLoading.set(false);
|
this.isLoading.set(false);
|
||||||
this.errorMessage.set(`Mot de passe actuel incorrect, ou nouveau mot de passe invalide (${this.passwordHint}).`);
|
this.errorMessage.set(
|
||||||
|
`Mot de passe actuel incorrect, ou nouveau mot de passe invalide (${this.passwordHint}).`,
|
||||||
|
);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,38 +1,43 @@
|
|||||||
<div class="auth-page">
|
<div class="auth-page">
|
||||||
<form class="auth-card" [formGroup]="form" (ngSubmit)="onSubmit()">
|
<form class="auth-card-wrapper" [formGroup]="form" (ngSubmit)="onSubmit()">
|
||||||
<h1>Connexion</h1>
|
<ev-card>
|
||||||
<p class="auth-subtitle">Accédez à votre espace EnerVision</p>
|
<ev-brand class="auth-brand" />
|
||||||
|
<h1>Connexion</h1>
|
||||||
|
<p class="auth-subtitle">Accédez à votre espace EnerVision</p>
|
||||||
|
|
||||||
<label for="email">Email</label>
|
<label class="form-label" for="email">Email</label>
|
||||||
<input
|
<input
|
||||||
id="email"
|
id="email"
|
||||||
type="email"
|
class="form-input"
|
||||||
formControlName="email"
|
type="email"
|
||||||
autocomplete="username"
|
formControlName="email"
|
||||||
placeholder="vous@enervision.fr"
|
autocomplete="username"
|
||||||
/>
|
placeholder="vous@enervision.fr"
|
||||||
|
/>
|
||||||
|
|
||||||
<label for="password">Mot de passe</label>
|
<label class="form-label" for="password">Mot de passe</label>
|
||||||
<input
|
<input
|
||||||
id="password"
|
id="password"
|
||||||
type="password"
|
class="form-input"
|
||||||
formControlName="password"
|
type="password"
|
||||||
autocomplete="current-password"
|
formControlName="password"
|
||||||
/>
|
autocomplete="current-password"
|
||||||
|
/>
|
||||||
|
|
||||||
@if (errorMessage()) {
|
@if (errorMessage()) {
|
||||||
<p class="auth-error">
|
<ev-alert severity="danger">
|
||||||
{{ errorMessage() }}
|
{{ errorMessage() }}
|
||||||
@if (retryAfterSeconds(); as seconds) {
|
@if (retryAfterSeconds(); as seconds) {
|
||||||
(réessayez dans {{ seconds }}s)
|
(réessayez dans {{ seconds }}s)
|
||||||
}
|
}
|
||||||
</p>
|
</ev-alert>
|
||||||
}
|
}
|
||||||
|
|
||||||
<button type="submit" [disabled]="form.invalid || isLoading()">
|
<ev-button type="submit" [disabled]="form.invalid || isLoading()">
|
||||||
{{ isLoading() ? 'Connexion...' : 'Se connecter' }}
|
{{ isLoading() ? 'Connexion...' : 'Se connecter' }}
|
||||||
</button>
|
</ev-button>
|
||||||
|
|
||||||
<p class="auth-link"><a routerLink="/forgot-password">Mot de passe oublié ?</a></p>
|
<p class="auth-link"><a routerLink="/forgot-password">Mot de passe oublié ?</a></p>
|
||||||
|
</ev-card>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,85 +1,3 @@
|
|||||||
:host {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
min-height: 100vh;
|
|
||||||
background: #f3f4f6;
|
|
||||||
font-family: 'Segoe UI', system-ui, sans-serif;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-card {
|
|
||||||
background: #ffffff;
|
|
||||||
border: 1px solid #e5e7eb;
|
|
||||||
border-radius: 12px;
|
|
||||||
padding: 2.5rem;
|
|
||||||
width: 100%;
|
|
||||||
max-width: 360px;
|
|
||||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
|
|
||||||
h1 {
|
|
||||||
margin: 0;
|
|
||||||
font-size: 1.5rem;
|
|
||||||
font-weight: 700;
|
|
||||||
color: #1f2937;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-subtitle {
|
|
||||||
margin: 0.25rem 0 1.5rem;
|
|
||||||
color: #6b7280;
|
|
||||||
font-size: 0.9rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
label {
|
|
||||||
font-size: 0.85rem;
|
|
||||||
font-weight: 600;
|
|
||||||
color: #374151;
|
|
||||||
margin-bottom: 0.35rem;
|
|
||||||
margin-top: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
input {
|
|
||||||
padding: 0.6rem 0.75rem;
|
|
||||||
border: 1px solid #d1d5db;
|
|
||||||
border-radius: 8px;
|
|
||||||
font-size: 0.95rem;
|
|
||||||
|
|
||||||
&:focus {
|
|
||||||
outline: none;
|
|
||||||
border-color: #3b82f6;
|
|
||||||
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
button {
|
|
||||||
margin-top: 1.5rem;
|
|
||||||
padding: 0.7rem;
|
|
||||||
background: #3b82f6;
|
|
||||||
color: #fff;
|
|
||||||
border: none;
|
|
||||||
border-radius: 8px;
|
|
||||||
font-size: 0.95rem;
|
|
||||||
font-weight: 600;
|
|
||||||
cursor: pointer;
|
|
||||||
|
|
||||||
&:disabled {
|
|
||||||
background: #9ca3af;
|
|
||||||
cursor: not-allowed;
|
|
||||||
}
|
|
||||||
|
|
||||||
&:not(:disabled):hover {
|
|
||||||
background: #2563eb;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-error {
|
|
||||||
margin: 0.75rem 0 0;
|
|
||||||
color: #dc2626;
|
|
||||||
font-size: 0.85rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.auth-link {
|
.auth-link {
|
||||||
margin-top: 1rem;
|
margin-top: 1rem;
|
||||||
font-size: 0.85rem;
|
font-size: 0.85rem;
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ describe('Login', () => {
|
|||||||
fixture.detectChanges(); // rend le bloc @if (errorMessage()) du template
|
fixture.detectChanges(); // rend le bloc @if (errorMessage()) du template
|
||||||
|
|
||||||
expect(component.errorMessage()).toBe('Email ou mot de passe incorrect.');
|
expect(component.errorMessage()).toBe('Email ou mot de passe incorrect.');
|
||||||
const errorEl = fixture.nativeElement.querySelector('.auth-error');
|
const errorEl = fixture.nativeElement.querySelector('.ev-alert');
|
||||||
expect(errorEl?.textContent).toContain('Email ou mot de passe incorrect.');
|
expect(errorEl?.textContent).toContain('Email ou mot de passe incorrect.');
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -96,7 +96,7 @@ describe('Login', () => {
|
|||||||
fixture.detectChanges(); // rend aussi le sous-bloc @if (retryAfterSeconds(); as seconds)
|
fixture.detectChanges(); // rend aussi le sous-bloc @if (retryAfterSeconds(); as seconds)
|
||||||
|
|
||||||
expect(component.retryAfterSeconds()).toBe(30);
|
expect(component.retryAfterSeconds()).toBe(30);
|
||||||
const errorEl = fixture.nativeElement.querySelector('.auth-error');
|
const errorEl = fixture.nativeElement.querySelector('.ev-alert');
|
||||||
expect(errorEl?.textContent).toContain('30s');
|
expect(errorEl?.textContent).toContain('30s');
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -114,7 +114,7 @@ describe('Login', () => {
|
|||||||
|
|
||||||
const button = fixture.nativeElement.querySelector('button[type="submit"]');
|
const button = fixture.nativeElement.querySelector('button[type="submit"]');
|
||||||
expect(button.disabled).toBe(true);
|
expect(button.disabled).toBe(true);
|
||||||
expect(fixture.nativeElement.querySelector('.auth-error')).toBeNull();
|
expect(fixture.nativeElement.querySelector('.ev-alert')).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('déclenche onSubmit via la soumission réelle du formulaire (ngSubmit)', () => {
|
it('déclenche onSubmit via la soumission réelle du formulaire (ngSubmit)', () => {
|
||||||
|
|||||||
@@ -3,12 +3,19 @@ import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';
|
|||||||
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
||||||
import { HttpErrorResponse } from '@angular/common/http';
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
import { AuthService } from '../../../core/services/auth.service';
|
import { AuthService } from '../../../core/services/auth.service';
|
||||||
import { MESSAGE_LIEN_RESET_INVALIDE, MOTIF_LIEN_RESET_INVALIDE } from '../../../shared/models/auth-redirect-reason';
|
import { Button } from '../../../shared/components/ui/button/button';
|
||||||
|
import { Card } from '../../../shared/components/ui/card/card';
|
||||||
|
import { Alert } from '../../../shared/components/ui/alert/alert';
|
||||||
|
import { Brand } from '../../../shared/components/ui/brand/brand';
|
||||||
|
import {
|
||||||
|
MESSAGE_LIEN_RESET_INVALIDE,
|
||||||
|
MOTIF_LIEN_RESET_INVALIDE,
|
||||||
|
} from '../../../shared/models/auth-redirect-reason';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-login',
|
selector: 'app-login',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [ReactiveFormsModule, RouterLink],
|
imports: [ReactiveFormsModule, RouterLink, Button, Card, Alert, Brand],
|
||||||
templateUrl: './login.html',
|
templateUrl: './login.html',
|
||||||
styleUrl: './login.scss',
|
styleUrl: './login.scss',
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,19 +1,33 @@
|
|||||||
<div class="dashboard">
|
<div class="dashboard">
|
||||||
<header class="dashboard__header">
|
<header class="dashboard__header">
|
||||||
<div>
|
<div class="dashboard__brand">
|
||||||
<h1>Vue d'ensemble</h1>
|
<a routerLink="/dashboard" class="ev-brand-link">
|
||||||
<p class="dashboard__subtitle">Consommation instantanée du parc</p>
|
<ev-brand class="dashboard__logo" />
|
||||||
|
</a>
|
||||||
|
<div>
|
||||||
|
<h1>Vue d'ensemble</h1>
|
||||||
|
<p class="dashboard__subtitle">Consommation instantanée du parc</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="dashboard__actions">
|
||||||
|
<a routerLink="/sites" class="ev-link">Voir les sites</a>
|
||||||
|
<ev-button
|
||||||
|
class="logout-button"
|
||||||
|
variant="secondary"
|
||||||
|
[fullWidth]="false"
|
||||||
|
(click)="onLogout()"
|
||||||
|
>Déconnexion</ev-button
|
||||||
|
>
|
||||||
</div>
|
</div>
|
||||||
<button type="button" class="logout-button" (click)="onLogout()">Déconnexion</button>
|
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
@if (error(); as message) {
|
@if (error(); as message) {
|
||||||
<p class="banner-error" role="alert">{{ message }}</p>
|
<ev-alert severity="danger" class="banner-error">{{ message }}</ev-alert>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (stats(); as s) {
|
@if (stats(); as s) {
|
||||||
<section class="overview">
|
<section class="overview">
|
||||||
<div class="card card--gauge">
|
<ev-card class="card card--gauge">
|
||||||
<span class="card__label">Consommation vs capacité</span>
|
<span class="card__label">Consommation vs capacité</span>
|
||||||
<app-consumption-gauge
|
<app-consumption-gauge
|
||||||
[consumption]="s.total_consumption_kw"
|
[consumption]="s.total_consumption_kw"
|
||||||
@@ -23,20 +37,20 @@
|
|||||||
>{{ s.total_consumption_kw | number: '1.0-1' }} /
|
>{{ s.total_consumption_kw | number: '1.0-1' }} /
|
||||||
{{ s.total_capacity_kw | number }} kW</span
|
{{ s.total_capacity_kw | number }} kW</span
|
||||||
>
|
>
|
||||||
</div>
|
</ev-card>
|
||||||
|
|
||||||
<div class="card">
|
<ev-card class="card">
|
||||||
<span class="card__label">Charge moyenne du parc</span>
|
<span class="card__label">Charge moyenne du parc</span>
|
||||||
<span class="card__value">{{ s.average_load_percent }} %</span>
|
<span class="card__value">{{ s.average_load_percent }} %</span>
|
||||||
<div class="progress-bar">
|
<div class="progress-bar">
|
||||||
<div class="progress-bar__fill" [style.width.%]="s.average_load_percent"></div>
|
<div class="progress-bar__fill" [style.width.%]="s.average_load_percent"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</ev-card>
|
||||||
|
|
||||||
<div class="card">
|
<ev-card class="card">
|
||||||
<span class="card__label">Sites suivis</span>
|
<span class="card__label">Sites suivis</span>
|
||||||
<span class="card__value">{{ s.total_sites }}</span>
|
<span class="card__value">{{ s.total_sites }}</span>
|
||||||
</div>
|
</ev-card>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="chart-section">
|
<section class="chart-section">
|
||||||
@@ -50,8 +64,8 @@
|
|||||||
<h2>Alertes actives</h2>
|
<h2>Alertes actives</h2>
|
||||||
<ul class="alerts-list">
|
<ul class="alerts-list">
|
||||||
@for (alert of alerts(); track alert.alert_id) {
|
@for (alert of alerts(); track alert.alert_id) {
|
||||||
<li class="alert-item" [class]="'alert-item--' + alert.severity">
|
<li class="alert-item">
|
||||||
<span class="alert-item__badge">{{ alert.severity }}</span>
|
<ev-badge [tone]="badgeToneForSeverity(alert.severity)">{{ alert.severity }}</ev-badge>
|
||||||
<span class="alert-item__message">{{ alert.message }}</span>
|
<span class="alert-item__message">{{ alert.message }}</span>
|
||||||
</li>
|
</li>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,23 +1,22 @@
|
|||||||
:host {
|
:host {
|
||||||
--color-good: #2e7d32;
|
|
||||||
--color-partial: #f9a825;
|
|
||||||
--color-degraded: #ef6c00;
|
|
||||||
--color-critical: #c62828;
|
|
||||||
--color-bg-card: #ffffff;
|
|
||||||
--color-border: #e5e7eb;
|
|
||||||
--color-text-muted: #6b7280;
|
|
||||||
--radius: 10px;
|
|
||||||
|
|
||||||
display: block;
|
display: block;
|
||||||
font-family: 'Segoe UI', system-ui, sans-serif;
|
color: var(--color-text);
|
||||||
color: #1f2937;
|
padding: 2.5rem 2rem;
|
||||||
padding: 2rem;
|
|
||||||
max-width: 1100px;
|
max-width: 1100px;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
.dashboard__header {
|
.dashboard__header {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: space-between;
|
||||||
margin-bottom: 2rem;
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dashboard__brand {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.85rem;
|
||||||
|
|
||||||
h1 {
|
h1 {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
@@ -26,11 +25,21 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.dashboard__logo {
|
||||||
|
font-size: 1.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
.dashboard__subtitle {
|
.dashboard__subtitle {
|
||||||
margin: 0.25rem 0 0;
|
margin: 0.25rem 0 0;
|
||||||
color: var(--color-text-muted);
|
color: var(--color-text-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.dashboard__actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
h2 {
|
h2 {
|
||||||
font-size: 1.1rem;
|
font-size: 1.1rem;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
@@ -38,13 +47,8 @@ h2 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.banner-error {
|
.banner-error {
|
||||||
|
display: block;
|
||||||
margin: 0 0 1.5rem;
|
margin: 0 0 1.5rem;
|
||||||
padding: 0.75rem 1rem;
|
|
||||||
border: 1px solid var(--color-critical);
|
|
||||||
border-left-width: 4px;
|
|
||||||
border-radius: var(--radius);
|
|
||||||
background: #fdecea;
|
|
||||||
color: var(--color-critical);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.overview {
|
.overview {
|
||||||
@@ -55,14 +59,8 @@ h2 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.card {
|
.card {
|
||||||
background: var(--color-bg-card);
|
|
||||||
border: 1px solid var(--color-border);
|
|
||||||
border-radius: var(--radius);
|
|
||||||
padding: 1.25rem;
|
padding: 1.25rem;
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 0.35rem;
|
gap: 0.35rem;
|
||||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.card--gauge {
|
.card--gauge {
|
||||||
@@ -84,16 +82,16 @@ h2 {
|
|||||||
|
|
||||||
.progress-bar {
|
.progress-bar {
|
||||||
height: 6px;
|
height: 6px;
|
||||||
background: #e5e7eb;
|
background: var(--color-border-light);
|
||||||
border-radius: 999px;
|
border-radius: var(--radius-pill);
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
margin-top: 0.25rem;
|
margin-top: 0.25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.progress-bar__fill {
|
.progress-bar__fill {
|
||||||
height: 100%;
|
height: 100%;
|
||||||
background: #3b82f6;
|
background: var(--color-primary);
|
||||||
border-radius: 999px;
|
border-radius: var(--radius-pill);
|
||||||
transition: width 0.3s ease;
|
transition: width 0.3s ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,59 +113,11 @@ h2 {
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 0.75rem;
|
gap: 0.75rem;
|
||||||
padding: 0.7rem 1rem;
|
padding: 0.7rem 1rem;
|
||||||
border-radius: var(--radius);
|
border-radius: var(--radius-md);
|
||||||
background: #fef2f2;
|
background: var(--color-danger-bg);
|
||||||
border: 1px solid #fecaca;
|
border: 1px solid var(--color-danger-border);
|
||||||
}
|
|
||||||
|
|
||||||
.alert-item__badge {
|
|
||||||
font-size: 0.7rem;
|
|
||||||
font-weight: 700;
|
|
||||||
text-transform: uppercase;
|
|
||||||
padding: 0.2rem 0.55rem;
|
|
||||||
border-radius: 999px;
|
|
||||||
color: #fff;
|
|
||||||
background: var(--color-critical);
|
|
||||||
flex-shrink: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.alert-item--high .alert-item__badge {
|
|
||||||
background: var(--color-degraded);
|
|
||||||
}
|
|
||||||
.alert-item--medium .alert-item__badge {
|
|
||||||
background: var(--color-partial);
|
|
||||||
}
|
|
||||||
.alert-item--low .alert-item__badge {
|
|
||||||
background: var(--color-good);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.alert-item__message {
|
.alert-item__message {
|
||||||
font-size: 0.9rem;
|
font-size: 0.9rem;
|
||||||
}
|
}
|
||||||
.dashboard__header {
|
|
||||||
display: flex;
|
|
||||||
align-items: flex-start;
|
|
||||||
justify-content: space-between;
|
|
||||||
margin-bottom: 2rem;
|
|
||||||
|
|
||||||
h1 {
|
|
||||||
margin: 0;
|
|
||||||
font-size: 1.75rem;
|
|
||||||
font-weight: 700;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.logout-button {
|
|
||||||
padding: 0.5rem 1rem;
|
|
||||||
background: #ffffff;
|
|
||||||
border: 1px solid #d1d5db;
|
|
||||||
border-radius: 8px;
|
|
||||||
font-size: 0.85rem;
|
|
||||||
font-weight: 600;
|
|
||||||
color: #374151;
|
|
||||||
cursor: pointer;
|
|
||||||
|
|
||||||
&:hover {
|
|
||||||
background: #f3f4f6;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ 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 {AuthService} from '../../core/services/auth.service';
|
import {AuthService} from '../../core/services/auth.service';
|
||||||
import {Router} from '@angular/router';
|
import {Router, provideRouter} from '@angular/router';
|
||||||
|
|
||||||
vi.mock('chart.js', () => {
|
vi.mock('chart.js', () => {
|
||||||
class ChartMock {
|
class ChartMock {
|
||||||
@@ -29,6 +29,7 @@ describe('Dashboard', () => {
|
|||||||
providers: [
|
providers: [
|
||||||
{ provide: StatsService, useValue: statsMock },
|
{ provide: StatsService, useValue: statsMock },
|
||||||
{ provide: AlertsService, useValue: alertsMock },
|
{ provide: AlertsService, useValue: alertsMock },
|
||||||
|
provideRouter([]),
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -60,6 +61,7 @@ describe('Dashboard', () => {
|
|||||||
providers: [
|
providers: [
|
||||||
{ provide: StatsService, useValue: statsMock },
|
{ provide: StatsService, useValue: statsMock },
|
||||||
{ provide: AlertsService, useValue: alertsMock },
|
{ provide: AlertsService, useValue: alertsMock },
|
||||||
|
provideRouter([]),
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -86,6 +88,7 @@ describe('Dashboard', () => {
|
|||||||
providers: [
|
providers: [
|
||||||
{ provide: StatsService, useValue: statsMock },
|
{ provide: StatsService, useValue: statsMock },
|
||||||
{ provide: AlertsService, useValue: alertsMock },
|
{ provide: AlertsService, useValue: alertsMock },
|
||||||
|
provideRouter([]),
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -99,7 +102,6 @@ describe('Dashboard', () => {
|
|||||||
const statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
const statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
||||||
const alertsMock = { getAlerts: vi.fn().mockReturnValue(of([])) };
|
const alertsMock = { getAlerts: vi.fn().mockReturnValue(of([])) };
|
||||||
const authMock = { logout: vi.fn().mockReturnValue(of(undefined)), clearSession: vi.fn() };
|
const authMock = { logout: vi.fn().mockReturnValue(of(undefined)), clearSession: vi.fn() };
|
||||||
const routerMock = { navigate: vi.fn() };
|
|
||||||
|
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
imports: [Dashboard],
|
imports: [Dashboard],
|
||||||
@@ -107,18 +109,21 @@ describe('Dashboard', () => {
|
|||||||
{ provide: StatsService, useValue: statsMock },
|
{ provide: StatsService, useValue: statsMock },
|
||||||
{ provide: AlertsService, useValue: alertsMock },
|
{ provide: AlertsService, useValue: alertsMock },
|
||||||
{ provide: AuthService, useValue: authMock },
|
{ provide: AuthService, useValue: authMock },
|
||||||
{ provide: Router, useValue: routerMock },
|
provideRouter([]),
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(Dashboard);
|
const fixture = TestBed.createComponent(Dashboard);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const router = TestBed.inject(Router);
|
||||||
|
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||||
|
|
||||||
const button = fixture.nativeElement.querySelector('.logout-button');
|
const button = fixture.nativeElement.querySelector('.logout-button');
|
||||||
button.click();
|
button.click();
|
||||||
|
|
||||||
expect(authMock.logout).toHaveBeenCalled();
|
expect(authMock.logout).toHaveBeenCalled();
|
||||||
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
|
expect(navigateSpy).toHaveBeenCalledWith(['/login']);
|
||||||
});
|
});
|
||||||
it('déconnecte localement et redirige vers /login même si logout échoue côté réseau', () => {
|
it('déconnecte localement et redirige vers /login même si logout échoue côté réseau', () => {
|
||||||
const statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
const statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
||||||
@@ -127,25 +132,51 @@ describe('Dashboard', () => {
|
|||||||
logout: vi.fn().mockReturnValue(throwError(() => new Error('réseau indisponible'))),
|
logout: vi.fn().mockReturnValue(throwError(() => new Error('réseau indisponible'))),
|
||||||
clearSession: vi.fn(),
|
clearSession: vi.fn(),
|
||||||
};
|
};
|
||||||
const routerMock = { navigate: vi.fn() };
|
|
||||||
|
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
imports: [Dashboard],
|
imports: [Dashboard],
|
||||||
providers: [
|
providers: [
|
||||||
{ provide: StatsService, useValue: statsMock },
|
{ provide: StatsService, useValue: statsMock },
|
||||||
{ provide: AlertsService, useValue: alertsMock },
|
{ provide: AlertsService, useValue: alertsMock },
|
||||||
{ provide: AuthService, useValue: authMock },
|
{ provide: AuthService, useValue: authMock },
|
||||||
{ provide: Router, useValue: routerMock },
|
provideRouter([]),
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(Dashboard);
|
const fixture = TestBed.createComponent(Dashboard);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const router = TestBed.inject(Router);
|
||||||
|
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||||
|
|
||||||
const button = fixture.nativeElement.querySelector('.logout-button');
|
const button = fixture.nativeElement.querySelector('.logout-button');
|
||||||
button.click();
|
button.click();
|
||||||
|
|
||||||
expect(authMock.clearSession).toHaveBeenCalled();
|
expect(authMock.clearSession).toHaveBeenCalled();
|
||||||
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
|
expect(navigateSpy).toHaveBeenCalledWith(['/login']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('distingue le ton des sévérités high et critical', () => {
|
||||||
|
const statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
||||||
|
const alertsMock = { getAlerts: vi.fn().mockReturnValue(of([])) };
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [Dashboard],
|
||||||
|
providers: [
|
||||||
|
{ provide: StatsService, useValue: statsMock },
|
||||||
|
{ provide: AlertsService, useValue: alertsMock },
|
||||||
|
provideRouter([]),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(Dashboard);
|
||||||
|
const dashboard = fixture.componentInstance;
|
||||||
|
|
||||||
|
expect(dashboard.badgeToneForSeverity('low')).toBe('success');
|
||||||
|
expect(dashboard.badgeToneForSeverity('medium')).toBe('warning');
|
||||||
|
expect(dashboard.badgeToneForSeverity('high')).toBe('danger');
|
||||||
|
expect(dashboard.badgeToneForSeverity('critical')).toBe('critical');
|
||||||
|
expect(dashboard.badgeToneForSeverity('high')).not.toBe(
|
||||||
|
dashboard.badgeToneForSeverity('critical'),
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,23 +2,45 @@ import { Component, OnInit, inject, signal, DestroyRef } from '@angular/core';
|
|||||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
import { timer, switchMap, catchError, EMPTY, Observable } from 'rxjs';
|
import { timer, switchMap, catchError, EMPTY, Observable } from 'rxjs';
|
||||||
import { DecimalPipe } from '@angular/common';
|
import { DecimalPipe } from '@angular/common';
|
||||||
import { Router } from '@angular/router';
|
import { Router, RouterLink } from '@angular/router';
|
||||||
import { StatsService } from '../../core/services/stats.service';
|
import { StatsService } from '../../core/services/stats.service';
|
||||||
import { ConsumptionGauge } from '../../shared/components/consumption-gauge/consumption-gauge';
|
import { ConsumptionGauge } from '../../shared/components/consumption-gauge/consumption-gauge';
|
||||||
import { SiteLoadChart } from '../../shared/components/site-load-chart/site-load-chart';
|
import { SiteLoadChart } from '../../shared/components/site-load-chart/site-load-chart';
|
||||||
import { AlertsService } from '../../core/services/alerts.service';
|
import { AlertsService } from '../../core/services/alerts.service';
|
||||||
import { AuthService } from '../../core/services/auth.service';
|
import { AuthService } from '../../core/services/auth.service';
|
||||||
import { StatsSummary } from '../../shared/models/stats.model';
|
import { StatsSummary } from '../../shared/models/stats.model';
|
||||||
import { Alert } from '../../shared/models/alert.model';
|
import { Alert, AlertSeverity } from '../../shared/models/alert.model';
|
||||||
|
import { Card } from '../../shared/components/ui/card/card';
|
||||||
|
import { Alert as EvAlert } from '../../shared/components/ui/alert/alert';
|
||||||
|
import { Badge, BadgeTone } from '../../shared/components/ui/badge/badge';
|
||||||
|
import { Brand } from '../../shared/components/ui/brand/brand';
|
||||||
|
import { Button } from '../../shared/components/ui/button/button';
|
||||||
|
|
||||||
const REFRESH_INTERVAL_MS = 10000;
|
const REFRESH_INTERVAL_MS = 10000;
|
||||||
const UNAVAILABLE_MESSAGE =
|
const UNAVAILABLE_MESSAGE =
|
||||||
'Données indisponibles, les valeurs affichées datent du dernier relevé.';
|
'Données indisponibles, les valeurs affichées datent du dernier relevé.';
|
||||||
|
|
||||||
|
const TON_PAR_SEVERITE: Record<AlertSeverity, BadgeTone> = {
|
||||||
|
low: 'success',
|
||||||
|
medium: 'warning',
|
||||||
|
high: 'danger',
|
||||||
|
critical: 'critical',
|
||||||
|
};
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-dashboard',
|
selector: 'app-dashboard',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [DecimalPipe, ConsumptionGauge, SiteLoadChart],
|
imports: [
|
||||||
|
DecimalPipe,
|
||||||
|
RouterLink,
|
||||||
|
ConsumptionGauge,
|
||||||
|
SiteLoadChart,
|
||||||
|
Card,
|
||||||
|
EvAlert,
|
||||||
|
Badge,
|
||||||
|
Brand,
|
||||||
|
Button,
|
||||||
|
],
|
||||||
templateUrl: './dashboard.html',
|
templateUrl: './dashboard.html',
|
||||||
styleUrl: './dashboard.scss',
|
styleUrl: './dashboard.scss',
|
||||||
})
|
})
|
||||||
@@ -54,6 +76,10 @@ export class Dashboard implements OnInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
badgeToneForSeverity(severity: AlertSeverity): BadgeTone {
|
||||||
|
return TON_PAR_SEVERITE[severity];
|
||||||
|
}
|
||||||
|
|
||||||
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,85 @@
|
|||||||
|
<div class="site-detail">
|
||||||
|
<nav class="ev-breadcrumb">
|
||||||
|
<a routerLink="/dashboard">Tableau de bord</a>
|
||||||
|
<span>/</span>
|
||||||
|
<a routerLink="/sites">Sites</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<header class="site-detail__header">
|
||||||
|
<a routerLink="/dashboard" class="ev-brand-link">
|
||||||
|
<ev-brand class="site-detail__logo" />
|
||||||
|
</a>
|
||||||
|
<div>
|
||||||
|
<h1>{{ site()?.site_name ?? siteId() }}</h1>
|
||||||
|
@if (site(); as s) {
|
||||||
|
<p class="site-detail__subtitle">
|
||||||
|
{{ s.site_type }} · {{ s.location || 'Localisation inconnue' }}
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="site-detail__badges">
|
||||||
|
@if (site(); as s) {
|
||||||
|
<ev-badge [tone]="badgeToneForStatus(s.status)">{{ s.status ?? '-' }}</ev-badge>
|
||||||
|
}
|
||||||
|
@if (hasMeasurement() && qualityLabel(); as label) {
|
||||||
|
<ev-badge [tone]="qualityTone()">{{ label }}</ev-badge>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
@if (error(); as message) {
|
||||||
|
<ev-alert severity="danger" class="banner-error">{{ message }}</ev-alert>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (site(); as s) {
|
||||||
|
@if (hasMeasurement()) {
|
||||||
|
<section class="overview">
|
||||||
|
<ev-card class="card card--gauge">
|
||||||
|
<span class="card__label">Consommation vs capacité</span>
|
||||||
|
@let consumption = consumptionKw();
|
||||||
|
@if (consumption !== null) {
|
||||||
|
<app-consumption-gauge [consumption]="consumption" [capacity]="s.capacity_kw ?? 0" />
|
||||||
|
<span class="card__value">
|
||||||
|
{{ consumptionLabel() }} / {{ s.capacity_kw ?? '-' }} kW
|
||||||
|
</span>
|
||||||
|
} @else {
|
||||||
|
<p class="card__unavailable">
|
||||||
|
Consommation indisponible
|
||||||
|
<span class="metric__reason">({{ consumptionReason() }})</span>
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
</ev-card>
|
||||||
|
|
||||||
|
<ev-card class="metrics-card">
|
||||||
|
<span class="card__label">Mesure instantanée</span>
|
||||||
|
<dl class="metrics-grid">
|
||||||
|
@for (metric of metrics(); track metric.key) {
|
||||||
|
<div class="metric">
|
||||||
|
<dt>{{ metric.label }}</dt>
|
||||||
|
@if (metric.value !== null) {
|
||||||
|
<dd>{{ metric.value }}</dd>
|
||||||
|
} @else {
|
||||||
|
<dd class="metric__unavailable">
|
||||||
|
Indisponible
|
||||||
|
<span class="metric__reason">({{ metric.reason }})</span>
|
||||||
|
</dd>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
</ev-card>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@if (history().length > 0) {
|
||||||
|
<section class="chart-section">
|
||||||
|
<h2>Historique de consommation</h2>
|
||||||
|
<app-reading-history-chart [readings]="history()" />
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
} @else {
|
||||||
|
<ev-alert severity="warning" class="banner-empty">{{ noMeasurementMessage }}</ev-alert>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
<a routerLink="/sites" class="ev-link">Retour aux sites</a>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
color: var(--color-text);
|
||||||
|
padding: 2.5rem 2rem;
|
||||||
|
max-width: 1100px;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-detail__header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.85rem;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.75rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-detail__logo {
|
||||||
|
font-size: 1.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-detail__subtitle {
|
||||||
|
margin: 0.25rem 0 0;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-detail__badges {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
margin-left: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.banner-error {
|
||||||
|
display: block;
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.banner-empty {
|
||||||
|
display: block;
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.overview {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
|
||||||
|
gap: 1rem;
|
||||||
|
margin-bottom: 2.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
padding: 1.25rem;
|
||||||
|
gap: 0.35rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card--gauge {
|
||||||
|
align-items: center;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card__label {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card__value {
|
||||||
|
font-size: 1.6rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card__unavailable {
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metrics-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, 1fr);
|
||||||
|
gap: 0.75rem 1.5rem;
|
||||||
|
margin: 0.5rem 0 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric {
|
||||||
|
dt {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
dd {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.05rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric__unavailable {
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
font-weight: 400;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric__reason {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
h2 {
|
||||||
|
font-size: 1.1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
margin: 0 0 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chart-section {
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { ActivatedRoute, convertToParamMap, provideRouter } from '@angular/router';
|
||||||
|
import { vi } from 'vitest';
|
||||||
|
import { BehaviorSubject, of, throwError } from 'rxjs';
|
||||||
|
import { SiteDetail } from './site-detail';
|
||||||
|
import { SitesService } from '../../../core/services/sites.service';
|
||||||
|
import { ReadingsService } from '../../../core/services/readings.service';
|
||||||
|
|
||||||
|
const SITE = {
|
||||||
|
site_id: 'SITE001',
|
||||||
|
site_name: 'Site 1',
|
||||||
|
site_type: 'industriel',
|
||||||
|
location: 'Nantes',
|
||||||
|
capacity_kw: 500,
|
||||||
|
status: 'actif',
|
||||||
|
};
|
||||||
|
|
||||||
|
const CURRENT_COMPLET = {
|
||||||
|
timestamp: '2026-09-17T10:00:00Z',
|
||||||
|
site_id: 'SITE001',
|
||||||
|
site_type: 'industriel',
|
||||||
|
consumption_kw: 120,
|
||||||
|
consumption_kwh: null,
|
||||||
|
voltage_v: 230,
|
||||||
|
current_a: 12,
|
||||||
|
power_factor: 0.95,
|
||||||
|
temperature_celsius: 22,
|
||||||
|
humidity_percent: 55,
|
||||||
|
null_reasons: [] as string[],
|
||||||
|
data_quality: 'good' as const,
|
||||||
|
};
|
||||||
|
|
||||||
|
const SANS_MESURE = {
|
||||||
|
...CURRENT_COMPLET,
|
||||||
|
timestamp: null,
|
||||||
|
consumption_kw: null,
|
||||||
|
voltage_v: null,
|
||||||
|
current_a: null,
|
||||||
|
power_factor: null,
|
||||||
|
temperature_celsius: null,
|
||||||
|
humidity_percent: null,
|
||||||
|
data_quality: 'critical' as const,
|
||||||
|
};
|
||||||
|
|
||||||
|
const LECTURE = {
|
||||||
|
reading_id: 1,
|
||||||
|
site_id: 'SITE001',
|
||||||
|
timestamp: '2026-09-17T09:00:00Z',
|
||||||
|
source: 'api_history' as const,
|
||||||
|
consumption_kw: 118,
|
||||||
|
consumption_kwh: null,
|
||||||
|
consumption_euros: null,
|
||||||
|
voltage_v: 230,
|
||||||
|
current_a: 12,
|
||||||
|
power_factor: 0.95,
|
||||||
|
temperature_celsius: 22,
|
||||||
|
humidity_percent: 55,
|
||||||
|
solar_irradiance_wm2: null,
|
||||||
|
is_working_hours: true,
|
||||||
|
data_quality: 'good' as const,
|
||||||
|
null_reasons: null,
|
||||||
|
imputed_values: null,
|
||||||
|
imputation_method: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
function setup(
|
||||||
|
siteId: string,
|
||||||
|
sitesMock: Partial<SitesService>,
|
||||||
|
readingsMock: Partial<ReadingsService>,
|
||||||
|
) {
|
||||||
|
const paramMap = new BehaviorSubject(convertToParamMap({ siteId }));
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [SiteDetail],
|
||||||
|
providers: [
|
||||||
|
provideRouter([]),
|
||||||
|
{ provide: ActivatedRoute, useValue: { paramMap } },
|
||||||
|
{ provide: SitesService, useValue: sitesMock },
|
||||||
|
{ provide: ReadingsService, useValue: readingsMock },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
return { fixture: TestBed.createComponent(SiteDetail), paramMap };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('SiteDetail', () => {
|
||||||
|
it('charge le site, la mesure courante et son historique au démarrage', () => {
|
||||||
|
const { fixture } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{
|
||||||
|
getSite: vi.fn().mockReturnValue(of(SITE)),
|
||||||
|
getCurrent: vi.fn().mockReturnValue(of(CURRENT_COMPLET)),
|
||||||
|
},
|
||||||
|
{ getHistory: vi.fn().mockReturnValue(of([LECTURE])) },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.site()?.site_id).toBe('SITE001');
|
||||||
|
expect(fixture.componentInstance.current()?.consumption_kw).toBe(120);
|
||||||
|
expect(fixture.componentInstance.history().length).toBe(1);
|
||||||
|
expect(fixture.componentInstance.error()).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("signale l'indisponibilité quand un des appels échoue", () => {
|
||||||
|
const { fixture } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{
|
||||||
|
getSite: vi.fn().mockReturnValue(throwError(() => new Error('nope'))),
|
||||||
|
getCurrent: vi.fn().mockReturnValue(of(CURRENT_COMPLET)),
|
||||||
|
},
|
||||||
|
{ getHistory: vi.fn().mockReturnValue(of([])) },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.error()).not.toBeNull();
|
||||||
|
expect(fixture.componentInstance.site()).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('efface les données du site précédent quand le chargement du suivant échoue', () => {
|
||||||
|
const getSite = vi
|
||||||
|
.fn()
|
||||||
|
.mockReturnValueOnce(of(SITE))
|
||||||
|
.mockReturnValueOnce(throwError(() => new Error('404')));
|
||||||
|
const { fixture, paramMap } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{ getSite, getCurrent: vi.fn().mockReturnValue(of(CURRENT_COMPLET)) },
|
||||||
|
{ getHistory: vi.fn().mockReturnValue(of([LECTURE])) },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(fixture.componentInstance.site()?.site_id).toBe('SITE001');
|
||||||
|
|
||||||
|
paramMap.next(convertToParamMap({ siteId: 'SITE002' }));
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.error()).not.toBeNull();
|
||||||
|
expect(fixture.componentInstance.site()).toBeNull();
|
||||||
|
expect(fixture.componentInstance.current()).toBeNull();
|
||||||
|
expect(fixture.componentInstance.history()).toEqual([]);
|
||||||
|
expect(fixture.nativeElement.textContent).not.toContain('Site 1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('interroge le site et sa mesure courante en parallèle', () => {
|
||||||
|
const getSite = vi.fn().mockReturnValue(of(SITE));
|
||||||
|
const getCurrent = vi.fn().mockReturnValue(of(CURRENT_COMPLET));
|
||||||
|
const { fixture } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{ getSite, getCurrent },
|
||||||
|
{ getHistory: vi.fn().mockReturnValue(of([])) },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(getSite).toHaveBeenCalledWith('SITE001');
|
||||||
|
expect(getCurrent).toHaveBeenCalledWith('SITE001');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('signale la panne du capteur de consommation au lieu de tracer une jauge à zéro', () => {
|
||||||
|
const sansConsommation = {
|
||||||
|
...CURRENT_COMPLET,
|
||||||
|
consumption_kw: null,
|
||||||
|
null_reasons: ['consumption_sensor_failure'],
|
||||||
|
data_quality: 'partial' as const,
|
||||||
|
};
|
||||||
|
const { fixture } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{
|
||||||
|
getSite: vi.fn().mockReturnValue(of(SITE)),
|
||||||
|
getCurrent: vi.fn().mockReturnValue(of(sansConsommation)),
|
||||||
|
},
|
||||||
|
{ getHistory: vi.fn().mockReturnValue(of([LECTURE])) },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.consumptionKw()).toBeNull();
|
||||||
|
expect(fixture.componentInstance.consumptionReason()).toBe('capteur de consommation en panne');
|
||||||
|
expect(fixture.nativeElement.querySelector('app-consumption-gauge')).toBeNull();
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('Consommation indisponible');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('trace la jauge pour une consommation nulle réellement mesurée', () => {
|
||||||
|
const { fixture } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{
|
||||||
|
getSite: vi.fn().mockReturnValue(of(SITE)),
|
||||||
|
getCurrent: vi.fn().mockReturnValue(of({ ...CURRENT_COMPLET, consumption_kw: 0 })),
|
||||||
|
},
|
||||||
|
{ getHistory: vi.fn().mockReturnValue(of([LECTURE])) },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.consumptionLabel()).toBe('0.0 kW');
|
||||||
|
expect(fixture.nativeElement.querySelector('app-consumption-gauge')).not.toBeNull();
|
||||||
|
expect(fixture.nativeElement.textContent).not.toContain('Consommation indisponible');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('affiche explicitement les champs null avec leur raison plutôt que de les masquer', () => {
|
||||||
|
const partielle = {
|
||||||
|
...CURRENT_COMPLET,
|
||||||
|
voltage_v: null,
|
||||||
|
current_a: null,
|
||||||
|
power_factor: null,
|
||||||
|
null_reasons: ['electrical_sensor_failure'],
|
||||||
|
data_quality: 'partial' as const,
|
||||||
|
};
|
||||||
|
const { fixture } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{
|
||||||
|
getSite: vi.fn().mockReturnValue(of(SITE)),
|
||||||
|
getCurrent: vi.fn().mockReturnValue(of(partielle)),
|
||||||
|
},
|
||||||
|
{ getHistory: vi.fn().mockReturnValue(of([LECTURE])) },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const tension = fixture.componentInstance.metrics().find((m) => m.key === 'voltage_v');
|
||||||
|
expect(tension?.value).toBeNull();
|
||||||
|
expect(tension?.reason).toBe('capteur électrique en panne');
|
||||||
|
|
||||||
|
const texte = fixture.nativeElement.textContent;
|
||||||
|
expect(texte).toContain('Indisponible');
|
||||||
|
expect(texte).toContain('capteur électrique en panne');
|
||||||
|
expect(texte).toContain('Données partielles');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('recharge les données quand le paramètre de route siteId change', () => {
|
||||||
|
const getSite = vi.fn().mockReturnValue(of(SITE));
|
||||||
|
const { fixture, paramMap } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{ getSite, getCurrent: vi.fn().mockReturnValue(of(CURRENT_COMPLET)) },
|
||||||
|
{ getHistory: vi.fn().mockReturnValue(of([])) },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
paramMap.next(convertToParamMap({ siteId: 'SITE002' }));
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(getSite).toHaveBeenCalledWith('SITE002');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ancre la fenêtre d'historique sur la dernière mesure connue plutôt que sur l'horloge", () => {
|
||||||
|
const getHistory = vi.fn().mockReturnValue(of([]));
|
||||||
|
const { fixture } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{
|
||||||
|
getSite: vi.fn().mockReturnValue(of(SITE)),
|
||||||
|
getCurrent: vi.fn().mockReturnValue(of(CURRENT_COMPLET)),
|
||||||
|
},
|
||||||
|
{ getHistory },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(getHistory).toHaveBeenCalledWith(
|
||||||
|
'SITE001',
|
||||||
|
'2026-09-16T10:00:00.000Z',
|
||||||
|
'2026-09-17T10:00:00Z',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("annonce l'absence de mesure sans interroger l'historique quand timestamp est null", () => {
|
||||||
|
const getHistory = vi.fn().mockReturnValue(of([]));
|
||||||
|
const { fixture } = setup(
|
||||||
|
'SITE001',
|
||||||
|
{
|
||||||
|
getSite: vi.fn().mockReturnValue(of(SITE)),
|
||||||
|
getCurrent: vi.fn().mockReturnValue(of(SANS_MESURE)),
|
||||||
|
},
|
||||||
|
{ getHistory },
|
||||||
|
);
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(getHistory).not.toHaveBeenCalled();
|
||||||
|
expect(fixture.componentInstance.hasMeasurement()).toBe(false);
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('Aucune mesure remontée pour ce site.');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
import { Component, DestroyRef, computed, inject, signal } from '@angular/core';
|
||||||
|
import { takeUntilDestroyed, toObservable, toSignal } from '@angular/core/rxjs-interop';
|
||||||
|
import { ActivatedRoute, RouterLink } from '@angular/router';
|
||||||
|
import { catchError, EMPTY, filter, forkJoin, map, Observable, of, switchMap } from 'rxjs';
|
||||||
|
import { SitesService } from '../../../core/services/sites.service';
|
||||||
|
import { ReadingsService } from '../../../core/services/readings.service';
|
||||||
|
import { Site } from '../../../shared/models/site.model';
|
||||||
|
import { Reading, ReadingDataQuality } from '../../../shared/models/reading.model';
|
||||||
|
import { SiteCurrent } from '../../../shared/models/site-current.model';
|
||||||
|
import { Card } from '../../../shared/components/ui/card/card';
|
||||||
|
import { Alert } from '../../../shared/components/ui/alert/alert';
|
||||||
|
import { Badge, BadgeTone } from '../../../shared/components/ui/badge/badge';
|
||||||
|
import { Brand } from '../../../shared/components/ui/brand/brand';
|
||||||
|
import { ConsumptionGauge } from '../../../shared/components/consumption-gauge/consumption-gauge';
|
||||||
|
import { ReadingHistoryChart } from '../../../shared/components/reading-history-chart/reading-history-chart';
|
||||||
|
|
||||||
|
const UNAVAILABLE_MESSAGE = 'Détail du site indisponible, réessayez plus tard.';
|
||||||
|
const NO_MEASUREMENT_MESSAGE = 'Aucune mesure remontée pour ce site.';
|
||||||
|
const HISTORY_WINDOW_MS = 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
const TON_PAR_STATUT: Record<string, BadgeTone> = {
|
||||||
|
actif: 'success',
|
||||||
|
maintenance: 'warning',
|
||||||
|
hors_service: 'danger',
|
||||||
|
};
|
||||||
|
|
||||||
|
const TON_PAR_QUALITE: Record<ReadingDataQuality, BadgeTone> = {
|
||||||
|
good: 'success',
|
||||||
|
partial: 'warning',
|
||||||
|
degraded: 'danger',
|
||||||
|
critical: 'critical',
|
||||||
|
};
|
||||||
|
|
||||||
|
const LIBELLE_PAR_QUALITE: Record<ReadingDataQuality, string> = {
|
||||||
|
good: 'Données complètes',
|
||||||
|
partial: 'Données partielles',
|
||||||
|
degraded: 'Données dégradées',
|
||||||
|
critical: 'Données critiques',
|
||||||
|
};
|
||||||
|
|
||||||
|
type MetricKey =
|
||||||
|
| 'consumption_kw'
|
||||||
|
| 'voltage_v'
|
||||||
|
| 'current_a'
|
||||||
|
| 'power_factor'
|
||||||
|
| 'temperature_celsius'
|
||||||
|
| 'humidity_percent';
|
||||||
|
|
||||||
|
interface MetricDef {
|
||||||
|
key: MetricKey;
|
||||||
|
label: string;
|
||||||
|
format: (value: number) => string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const CONSUMPTION_DEF: MetricDef = {
|
||||||
|
key: 'consumption_kw',
|
||||||
|
label: 'Consommation',
|
||||||
|
format: (v) => `${v.toFixed(1)} kW`,
|
||||||
|
};
|
||||||
|
|
||||||
|
const METRIC_DEFS: MetricDef[] = [
|
||||||
|
CONSUMPTION_DEF,
|
||||||
|
{ key: 'voltage_v', label: 'Tension', format: (v) => `${v.toFixed(1)} V` },
|
||||||
|
{ key: 'current_a', label: 'Courant', format: (v) => `${v.toFixed(1)} A` },
|
||||||
|
{ key: 'power_factor', label: 'Cos φ', format: (v) => v.toFixed(2) },
|
||||||
|
{ key: 'temperature_celsius', label: 'Température', format: (v) => `${v.toFixed(1)} °C` },
|
||||||
|
{ key: 'humidity_percent', label: 'Humidité', format: (v) => `${v.toFixed(0)} %` },
|
||||||
|
];
|
||||||
|
|
||||||
|
// Contrainte : miroir de RAISON_VERS_CAPTEUR et CHAMPS_PAR_CAPTEUR (backend, services/sensor.py) ;
|
||||||
|
// `null_reasons` porte le code de panne du capteur, jamais le nom du champ resté vide.
|
||||||
|
const RAISONS_PAR_CHAMP: Record<MetricKey, string[]> = {
|
||||||
|
consumption_kw: ['consumption_sensor_failure', 'network_loss'],
|
||||||
|
voltage_v: ['electrical_sensor_failure', 'network_loss'],
|
||||||
|
current_a: ['electrical_sensor_failure', 'network_loss'],
|
||||||
|
power_factor: ['electrical_sensor_failure', 'network_loss'],
|
||||||
|
temperature_celsius: ['temperature_sensor_failure', 'network_loss'],
|
||||||
|
humidity_percent: ['humidity_sensor_failure', 'network_loss'],
|
||||||
|
};
|
||||||
|
|
||||||
|
const LIBELLE_PAR_RAISON: Record<string, string> = {
|
||||||
|
consumption_sensor_failure: 'capteur de consommation en panne',
|
||||||
|
electrical_sensor_failure: 'capteur électrique en panne',
|
||||||
|
temperature_sensor_failure: 'capteur de température en panne',
|
||||||
|
humidity_sensor_failure: "capteur d'humidité en panne",
|
||||||
|
network_loss: 'perte réseau',
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface MetricView {
|
||||||
|
key: MetricKey;
|
||||||
|
label: string;
|
||||||
|
value: string | null;
|
||||||
|
reason: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-site-detail',
|
||||||
|
standalone: true,
|
||||||
|
imports: [RouterLink, Card, Alert, Badge, Brand, ConsumptionGauge, ReadingHistoryChart],
|
||||||
|
templateUrl: './site-detail.html',
|
||||||
|
styleUrl: './site-detail.scss',
|
||||||
|
})
|
||||||
|
export class SiteDetail {
|
||||||
|
private route = inject(ActivatedRoute);
|
||||||
|
private sitesService = inject(SitesService);
|
||||||
|
private readingsService = inject(ReadingsService);
|
||||||
|
private destroyRef = inject(DestroyRef);
|
||||||
|
|
||||||
|
readonly noMeasurementMessage = NO_MEASUREMENT_MESSAGE;
|
||||||
|
|
||||||
|
siteId = toSignal(this.route.paramMap.pipe(map((params) => params.get('siteId') ?? '')));
|
||||||
|
|
||||||
|
site = signal<Site | null>(null);
|
||||||
|
current = signal<SiteCurrent | null>(null);
|
||||||
|
history = signal<Reading[]>([]);
|
||||||
|
error = signal<string | null>(null);
|
||||||
|
|
||||||
|
hasMeasurement = computed(() => this.current()?.timestamp != null);
|
||||||
|
|
||||||
|
consumptionKw = computed(() => this.current()?.consumption_kw ?? null);
|
||||||
|
|
||||||
|
consumptionLabel = computed(() => {
|
||||||
|
const kw = this.consumptionKw();
|
||||||
|
return kw != null ? CONSUMPTION_DEF.format(kw) : null;
|
||||||
|
});
|
||||||
|
|
||||||
|
consumptionReason = computed(() => this.reasonFor('consumption_kw', this.current()));
|
||||||
|
|
||||||
|
qualityLabel = computed(() => {
|
||||||
|
const quality = this.current()?.data_quality;
|
||||||
|
return quality ? LIBELLE_PAR_QUALITE[quality] : null;
|
||||||
|
});
|
||||||
|
|
||||||
|
qualityTone = computed<BadgeTone>(() => {
|
||||||
|
const quality = this.current()?.data_quality;
|
||||||
|
return quality ? TON_PAR_QUALITE[quality] : 'neutral';
|
||||||
|
});
|
||||||
|
|
||||||
|
metrics = computed<MetricView[]>(() => {
|
||||||
|
const current = this.current();
|
||||||
|
return METRIC_DEFS.map((def) => {
|
||||||
|
const valeur = current ? current[def.key] : null;
|
||||||
|
return {
|
||||||
|
key: def.key,
|
||||||
|
label: def.label,
|
||||||
|
value: valeur != null ? def.format(valeur) : null,
|
||||||
|
reason: valeur == null ? this.reasonFor(def.key, current) : '',
|
||||||
|
};
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
toObservable(this.siteId)
|
||||||
|
.pipe(
|
||||||
|
filter((siteId): siteId is string => !!siteId),
|
||||||
|
// Piège : switchMap sur le flux externe annule le chargement en cours dès qu'un
|
||||||
|
// nouveau siteId arrive, sinon une réponse en retard peut écraser le site affiché.
|
||||||
|
switchMap((siteId) => this.load(siteId)),
|
||||||
|
takeUntilDestroyed(this.destroyRef),
|
||||||
|
)
|
||||||
|
.subscribe((result) => {
|
||||||
|
this.error.set(null);
|
||||||
|
this.site.set(result.site);
|
||||||
|
this.current.set(result.current);
|
||||||
|
this.history.set(result.history);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
badgeToneForStatus(status: string | null): BadgeTone {
|
||||||
|
return status ? (TON_PAR_STATUT[status] ?? 'neutral') : 'neutral';
|
||||||
|
}
|
||||||
|
|
||||||
|
private load(siteId: string) {
|
||||||
|
return forkJoin({
|
||||||
|
site: this.sitesService.getSite(siteId),
|
||||||
|
current: this.sitesService.getCurrent(siteId),
|
||||||
|
}).pipe(
|
||||||
|
switchMap(({ site, current }) =>
|
||||||
|
this.loadHistory(siteId, current).pipe(map((history) => ({ site, current, history }))),
|
||||||
|
),
|
||||||
|
catchError(() => this.reportUnavailable()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private loadHistory(siteId: string, current: SiteCurrent): Observable<Reading[]> {
|
||||||
|
// Piège : le jeu de données s'arrête bien avant « maintenant » ; ancrer la fenêtre sur la
|
||||||
|
// dernière mesure connue plutôt que sur l'horloge évite un historique systématiquement vide.
|
||||||
|
const end = current.timestamp;
|
||||||
|
if (end === null) {
|
||||||
|
return of([]);
|
||||||
|
}
|
||||||
|
const start = new Date(new Date(end).getTime() - HISTORY_WINDOW_MS).toISOString();
|
||||||
|
return this.readingsService.getHistory(siteId, start, end);
|
||||||
|
}
|
||||||
|
|
||||||
|
private reasonFor(field: MetricKey, current: SiteCurrent | null): string {
|
||||||
|
const raisons = RAISONS_PAR_CHAMP[field];
|
||||||
|
const trouvees = (current?.null_reasons ?? [])
|
||||||
|
.filter((raison) => raisons.includes(raison))
|
||||||
|
.map((raison) => LIBELLE_PAR_RAISON[raison] ?? raison);
|
||||||
|
return trouvees.length > 0 ? trouvees.join(', ') : 'cause inconnue';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Piège : vider les signaux avec l'erreur, sinon la page garde le site précédemment chargé
|
||||||
|
// sous le bandeau et laisse lire les chiffres de A en croyant regarder B.
|
||||||
|
private reportUnavailable(): Observable<never> {
|
||||||
|
this.error.set(UNAVAILABLE_MESSAGE);
|
||||||
|
this.site.set(null);
|
||||||
|
this.current.set(null);
|
||||||
|
this.history.set([]);
|
||||||
|
return EMPTY;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
<div class="site-list">
|
||||||
|
<nav class="ev-breadcrumb">
|
||||||
|
<a routerLink="/dashboard">Tableau de bord</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<header class="site-list__header">
|
||||||
|
<a routerLink="/dashboard" class="ev-brand-link">
|
||||||
|
<ev-brand class="site-list__logo" />
|
||||||
|
</a>
|
||||||
|
<div>
|
||||||
|
<h1>Sites</h1>
|
||||||
|
<p class="site-list__subtitle">Vue d'ensemble du parc suivi</p>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
@if (error(); as message) {
|
||||||
|
<ev-alert severity="danger" class="banner-error">{{ message }}</ev-alert>
|
||||||
|
}
|
||||||
|
|
||||||
|
<ev-card class="table-card">
|
||||||
|
<table class="sites-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Nom</th>
|
||||||
|
<th>Type</th>
|
||||||
|
<th>Localisation</th>
|
||||||
|
<th>Capacité (kW)</th>
|
||||||
|
<th>Statut</th>
|
||||||
|
<th></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@for (site of sites(); track site.site_id) {
|
||||||
|
<tr>
|
||||||
|
<td>{{ site.site_name }}</td>
|
||||||
|
<td>{{ site.site_type }}</td>
|
||||||
|
<td>{{ site.location || '-' }}</td>
|
||||||
|
<td>{{ site.capacity_kw ?? '-' }}</td>
|
||||||
|
<td><ev-badge [tone]="badgeToneForStatus(site.status)">{{ site.status ?? '-' }}</ev-badge></td>
|
||||||
|
<td><a [routerLink]="['/sites', site.site_id]" class="ev-link">Détail</a></td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</ev-card>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
color: var(--color-text);
|
||||||
|
padding: 2.5rem 2rem;
|
||||||
|
max-width: 1100px;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-list__header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.85rem;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.75rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-list__logo {
|
||||||
|
font-size: 1.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-list__subtitle {
|
||||||
|
margin: 0.25rem 0 0;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.banner-error {
|
||||||
|
display: block;
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-card {
|
||||||
|
padding: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sites-table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
|
||||||
|
th,
|
||||||
|
td {
|
||||||
|
padding: 0.85rem 1.25rem;
|
||||||
|
text-align: left;
|
||||||
|
border-bottom: 1px solid var(--color-border-light);
|
||||||
|
}
|
||||||
|
|
||||||
|
th {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
tr:last-child td {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideRouter } from '@angular/router';
|
||||||
|
import { vi } from 'vitest';
|
||||||
|
import { of, throwError } from 'rxjs';
|
||||||
|
import { SiteList } from './site-list';
|
||||||
|
import { SitesService } from '../../../core/services/sites.service';
|
||||||
|
|
||||||
|
describe('SiteList', () => {
|
||||||
|
it('charge et affiche les sites au démarrage', () => {
|
||||||
|
const sitesMock = {
|
||||||
|
getSites: vi.fn().mockReturnValue(
|
||||||
|
of([
|
||||||
|
{
|
||||||
|
site_id: 'SITE001',
|
||||||
|
site_name: 'Site 1',
|
||||||
|
site_type: 'industriel',
|
||||||
|
location: 'Nantes',
|
||||||
|
capacity_kw: 500,
|
||||||
|
status: 'actif',
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [SiteList],
|
||||||
|
providers: [{ provide: SitesService, useValue: sitesMock }, provideRouter([])],
|
||||||
|
});
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(SiteList);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(sitesMock.getSites).toHaveBeenCalled();
|
||||||
|
expect(fixture.componentInstance.sites().length).toBe(1);
|
||||||
|
expect(fixture.componentInstance.error()).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("signale l'indisponibilité quand le chargement échoue", () => {
|
||||||
|
const sitesMock = { getSites: vi.fn().mockReturnValue(throwError(() => new Error('nope'))) };
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [SiteList],
|
||||||
|
providers: [{ provide: SitesService, useValue: sitesMock }, provideRouter([])],
|
||||||
|
});
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(SiteList);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.error()).not.toBeNull();
|
||||||
|
expect(fixture.componentInstance.sites().length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('affiche un tiret pour les champs nullables', () => {
|
||||||
|
const sitesMock = {
|
||||||
|
getSites: vi.fn().mockReturnValue(
|
||||||
|
of([
|
||||||
|
{
|
||||||
|
site_id: 'SITE002',
|
||||||
|
site_name: 'Site 2',
|
||||||
|
site_type: 'bureau',
|
||||||
|
location: null,
|
||||||
|
capacity_kw: null,
|
||||||
|
status: null,
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [SiteList],
|
||||||
|
providers: [{ provide: SitesService, useValue: sitesMock }, provideRouter([])],
|
||||||
|
});
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(SiteList);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const cells = fixture.nativeElement.querySelectorAll('td');
|
||||||
|
expect(cells[2].textContent.trim()).toBe('-');
|
||||||
|
expect(cells[3].textContent.trim()).toBe('-');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { Component, OnInit, inject, signal } from '@angular/core';
|
||||||
|
import { RouterLink } from '@angular/router';
|
||||||
|
import { catchError, EMPTY, Observable } from 'rxjs';
|
||||||
|
import { SitesService } from '../../../core/services/sites.service';
|
||||||
|
import { Site } from '../../../shared/models/site.model';
|
||||||
|
import { Card } from '../../../shared/components/ui/card/card';
|
||||||
|
import { Alert } from '../../../shared/components/ui/alert/alert';
|
||||||
|
import { Badge, BadgeTone } from '../../../shared/components/ui/badge/badge';
|
||||||
|
import { Brand } from '../../../shared/components/ui/brand/brand';
|
||||||
|
|
||||||
|
const UNAVAILABLE_MESSAGE = 'Liste des sites indisponible, réessayez plus tard.';
|
||||||
|
|
||||||
|
const TON_PAR_STATUT: Record<string, BadgeTone> = {
|
||||||
|
actif: 'success',
|
||||||
|
maintenance: 'warning',
|
||||||
|
hors_service: 'danger',
|
||||||
|
};
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-site-list',
|
||||||
|
standalone: true,
|
||||||
|
imports: [RouterLink, Card, Alert, Badge, Brand],
|
||||||
|
templateUrl: './site-list.html',
|
||||||
|
styleUrl: './site-list.scss',
|
||||||
|
})
|
||||||
|
export class SiteList implements OnInit {
|
||||||
|
private sitesService = inject(SitesService);
|
||||||
|
|
||||||
|
sites = signal<Site[]>([]);
|
||||||
|
error = signal<string | null>(null);
|
||||||
|
|
||||||
|
ngOnInit(): void {
|
||||||
|
this.sitesService
|
||||||
|
.getSites()
|
||||||
|
.pipe(catchError(() => this.reportUnavailable()))
|
||||||
|
.subscribe((sites) => this.sites.set(sites));
|
||||||
|
}
|
||||||
|
|
||||||
|
badgeToneForStatus(status: string | null): BadgeTone {
|
||||||
|
return status ? (TON_PAR_STATUT[status] ?? 'neutral') : 'neutral';
|
||||||
|
}
|
||||||
|
|
||||||
|
private reportUnavailable(): Observable<never> {
|
||||||
|
this.error.set(UNAVAILABLE_MESSAGE);
|
||||||
|
return EMPTY;
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
@@ -0,0 +1 @@
|
|||||||
|
<canvas #canvas></canvas>
|
||||||
+4
@@ -0,0 +1,4 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
height: 260px;
|
||||||
|
}
|
||||||
+101
@@ -0,0 +1,101 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { vi } from 'vitest';
|
||||||
|
import { Chart } from 'chart.js';
|
||||||
|
import { ReadingHistoryChart } from './reading-history-chart';
|
||||||
|
|
||||||
|
vi.mock('chart.js', () => {
|
||||||
|
class ChartMock {
|
||||||
|
static instances: ChartMock[] = [];
|
||||||
|
static register = vi.fn();
|
||||||
|
update = vi.fn();
|
||||||
|
destroy = vi.fn();
|
||||||
|
data: { labels?: unknown[]; datasets: Record<string, unknown>[] } = { datasets: [{}] };
|
||||||
|
constructor(_canvas: unknown, config?: { data?: ChartMock['data'] }) {
|
||||||
|
if (config?.data) {
|
||||||
|
this.data = config.data;
|
||||||
|
}
|
||||||
|
ChartMock.instances.push(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { Chart: ChartMock, registerables: [] };
|
||||||
|
});
|
||||||
|
|
||||||
|
type ChartDouble = {
|
||||||
|
destroy: ReturnType<typeof vi.fn>;
|
||||||
|
data: { labels?: unknown[]; datasets: Record<string, unknown>[] };
|
||||||
|
};
|
||||||
|
|
||||||
|
function lastChart(): ChartDouble | undefined {
|
||||||
|
return (Chart as unknown as { instances: ChartDouble[] }).instances.at(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const READING = {
|
||||||
|
reading_id: 1,
|
||||||
|
site_id: 'S1',
|
||||||
|
timestamp: '2026-09-17T10:00:00Z',
|
||||||
|
source: 'api_history' as const,
|
||||||
|
consumption_kw: 42,
|
||||||
|
consumption_kwh: null,
|
||||||
|
consumption_euros: null,
|
||||||
|
voltage_v: null,
|
||||||
|
current_a: null,
|
||||||
|
power_factor: null,
|
||||||
|
temperature_celsius: null,
|
||||||
|
humidity_percent: null,
|
||||||
|
solar_irradiance_wm2: null,
|
||||||
|
is_working_hours: null,
|
||||||
|
data_quality: 'good' as const,
|
||||||
|
null_reasons: null,
|
||||||
|
imputed_values: null,
|
||||||
|
imputation_method: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('ReadingHistoryChart', () => {
|
||||||
|
it('se crée sans erreur avec une liste de lectures valide', () => {
|
||||||
|
TestBed.configureTestingModule({ imports: [ReadingHistoryChart] });
|
||||||
|
const fixture = TestBed.createComponent(ReadingHistoryChart);
|
||||||
|
fixture.componentRef.setInput('readings', [READING]);
|
||||||
|
expect(() => fixture.detectChanges()).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('met à jour le graphique quand les lectures changent après initialisation', () => {
|
||||||
|
TestBed.configureTestingModule({ imports: [ReadingHistoryChart] });
|
||||||
|
const fixture = TestBed.createComponent(ReadingHistoryChart);
|
||||||
|
fixture.componentRef.setInput('readings', [READING]);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
fixture.componentRef.setInput('readings', [
|
||||||
|
{ ...READING, reading_id: 2, consumption_kw: 60, data_quality: 'critical' as const },
|
||||||
|
]);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(() => fixture.detectChanges()).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("trace du plus ancien au plus récent, quel que soit l'ordre reçu de l'API", () => {
|
||||||
|
TestBed.configureTestingModule({ imports: [ReadingHistoryChart] });
|
||||||
|
const fixture = TestBed.createComponent(ReadingHistoryChart);
|
||||||
|
// L'API trie en timestamp décroissant : le composant doit rétablir la chronologie.
|
||||||
|
fixture.componentRef.setInput('readings', [
|
||||||
|
{ ...READING, reading_id: 2, timestamp: '2026-09-17T11:00:00Z', consumption_kw: 60 },
|
||||||
|
{ ...READING, reading_id: 1, timestamp: '2026-09-17T10:00:00Z', consumption_kw: 42 },
|
||||||
|
]);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const chart = lastChart();
|
||||||
|
expect(chart?.data.labels).toEqual(['2026-09-17T10:00:00Z', '2026-09-17T11:00:00Z']);
|
||||||
|
expect(chart?.data.datasets[0]['data']).toEqual([42, 60]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('détruit le graphique quand le composant est détruit', () => {
|
||||||
|
TestBed.configureTestingModule({ imports: [ReadingHistoryChart] });
|
||||||
|
const fixture = TestBed.createComponent(ReadingHistoryChart);
|
||||||
|
fixture.componentRef.setInput('readings', [READING]);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const chart = lastChart();
|
||||||
|
fixture.destroy();
|
||||||
|
|
||||||
|
expect(chart?.destroy).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
+95
@@ -0,0 +1,95 @@
|
|||||||
|
import {
|
||||||
|
Component,
|
||||||
|
ElementRef,
|
||||||
|
ViewChild,
|
||||||
|
input,
|
||||||
|
effect,
|
||||||
|
AfterViewInit,
|
||||||
|
OnDestroy,
|
||||||
|
} from '@angular/core';
|
||||||
|
import { Chart, registerables } from 'chart.js';
|
||||||
|
import { Reading, ReadingDataQuality } from '../../models/reading.model';
|
||||||
|
|
||||||
|
Chart.register(...registerables);
|
||||||
|
|
||||||
|
const QUALITY_COLORS: Record<ReadingDataQuality, string> = {
|
||||||
|
good: '#3b82f6',
|
||||||
|
partial: '#f9a825',
|
||||||
|
degraded: '#ef6c00',
|
||||||
|
critical: '#c62828',
|
||||||
|
};
|
||||||
|
const UNKNOWN_QUALITY_COLOR = '#9ca3af';
|
||||||
|
|
||||||
|
interface ChartSeries {
|
||||||
|
labels: string[];
|
||||||
|
values: number[];
|
||||||
|
colors: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Piège : l'API renvoie les lectures du plus récent au plus ancien (ReadingRepository.list_history
|
||||||
|
// trie en timestamp desc) ; sans ce tri l'axe des abscisses se lirait à rebours.
|
||||||
|
function toSeries(readings: Reading[]): ChartSeries {
|
||||||
|
const ordered = [...readings].sort((a, b) => Date.parse(a.timestamp) - Date.parse(b.timestamp));
|
||||||
|
return {
|
||||||
|
labels: ordered.map((r) => r.timestamp),
|
||||||
|
values: ordered.map((r) => r.consumption_kw ?? 0),
|
||||||
|
colors: ordered.map((r) =>
|
||||||
|
r.data_quality ? QUALITY_COLORS[r.data_quality] : UNKNOWN_QUALITY_COLOR,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-reading-history-chart',
|
||||||
|
standalone: true,
|
||||||
|
templateUrl: './reading-history-chart.html',
|
||||||
|
styleUrl: './reading-history-chart.scss',
|
||||||
|
})
|
||||||
|
export class ReadingHistoryChart implements AfterViewInit, OnDestroy {
|
||||||
|
readings = input.required<Reading[]>();
|
||||||
|
|
||||||
|
@ViewChild('canvas') private canvasRef!: ElementRef<HTMLCanvasElement>;
|
||||||
|
private chart?: Chart<'line'>;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
effect(() => {
|
||||||
|
const series = toSeries(this.readings());
|
||||||
|
if (this.chart) {
|
||||||
|
this.chart.data.labels = series.labels;
|
||||||
|
this.chart.data.datasets[0].data = series.values;
|
||||||
|
this.chart.data.datasets[0].pointBackgroundColor = series.colors;
|
||||||
|
this.chart.update('none');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
ngAfterViewInit(): void {
|
||||||
|
const series = toSeries(this.readings());
|
||||||
|
this.chart = new Chart(this.canvasRef.nativeElement, {
|
||||||
|
type: 'line',
|
||||||
|
data: {
|
||||||
|
labels: series.labels,
|
||||||
|
datasets: [
|
||||||
|
{
|
||||||
|
data: series.values,
|
||||||
|
borderColor: '#3b82f6',
|
||||||
|
pointBackgroundColor: series.colors,
|
||||||
|
tension: 0.25,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
responsive: true,
|
||||||
|
maintainAspectRatio: false,
|
||||||
|
plugins: { legend: { display: false } },
|
||||||
|
scales: {
|
||||||
|
y: { beginAtZero: true, title: { display: true, text: 'Consommation (kW)' } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnDestroy(): void {
|
||||||
|
this.chart?.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<ng-content></ng-content>
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
border: 1px solid transparent;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
:host.ev-alert--success {
|
||||||
|
background: var(--color-success-bg);
|
||||||
|
border-color: var(--color-success);
|
||||||
|
color: var(--color-success);
|
||||||
|
}
|
||||||
|
|
||||||
|
:host.ev-alert--warning {
|
||||||
|
background: var(--color-warning-bg);
|
||||||
|
border-color: var(--color-warning);
|
||||||
|
color: var(--color-warning-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
:host.ev-alert--danger {
|
||||||
|
background: var(--color-danger-bg);
|
||||||
|
border-color: var(--color-danger-border);
|
||||||
|
color: var(--color-danger);
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { Component } from '@angular/core';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { Alert } from './alert';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
standalone: true,
|
||||||
|
imports: [Alert],
|
||||||
|
template: `<ev-alert severity="success">C'est fait</ev-alert>`,
|
||||||
|
})
|
||||||
|
class AlertHost {}
|
||||||
|
|
||||||
|
describe('Alert', () => {
|
||||||
|
it('applique la classe danger par défaut', async () => {
|
||||||
|
await TestBed.configureTestingModule({ imports: [Alert] }).compileComponents();
|
||||||
|
const fixture = TestBed.createComponent(Alert);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.nativeElement.classList).toContain('ev-alert--danger');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('applique la sévérité demandée et projette le contenu', async () => {
|
||||||
|
await TestBed.configureTestingModule({ imports: [AlertHost] }).compileComponents();
|
||||||
|
const fixture = TestBed.createComponent(AlertHost);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const el = fixture.nativeElement.querySelector('.ev-alert');
|
||||||
|
expect(el.classList).toContain('ev-alert--success');
|
||||||
|
expect(el.textContent).toContain("C'est fait");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { Component, HostBinding, input } from '@angular/core';
|
||||||
|
|
||||||
|
export type AlertSeverity = 'success' | 'warning' | 'danger';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'ev-alert',
|
||||||
|
standalone: true,
|
||||||
|
templateUrl: './alert.html',
|
||||||
|
styleUrl: './alert.scss',
|
||||||
|
})
|
||||||
|
export class Alert {
|
||||||
|
severity = input<AlertSeverity>('danger');
|
||||||
|
|
||||||
|
@HostBinding('class')
|
||||||
|
get hostClass(): string {
|
||||||
|
return `ev-alert ev-alert--${this.severity()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
@HostBinding('attr.role')
|
||||||
|
readonly role = 'alert';
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<span class="ev-badge" [class]="'ev-badge--' + tone()">
|
||||||
|
<ng-content></ng-content>
|
||||||
|
</span>
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
:host {
|
||||||
|
display: inline-flex;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-badge {
|
||||||
|
display: inline-block;
|
||||||
|
font-size: 0.7rem;
|
||||||
|
font-weight: 700;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
padding: 0.2rem 0.55rem;
|
||||||
|
border-radius: var(--radius-pill);
|
||||||
|
color: var(--color-text-inverse);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-badge--success {
|
||||||
|
background: var(--color-success);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-badge--warning {
|
||||||
|
background: var(--color-warning);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-badge--danger {
|
||||||
|
background: var(--color-danger);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-badge--critical {
|
||||||
|
background: var(--color-critical);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-badge--neutral {
|
||||||
|
background: var(--color-text-muted);
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { Component } from '@angular/core';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { Badge } from './badge';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
standalone: true,
|
||||||
|
imports: [Badge],
|
||||||
|
template: `<ev-badge tone="danger">critique</ev-badge>`,
|
||||||
|
})
|
||||||
|
class BadgeHost {}
|
||||||
|
|
||||||
|
describe('Badge', () => {
|
||||||
|
it('applique le ton neutral par défaut', async () => {
|
||||||
|
await TestBed.configureTestingModule({ imports: [Badge] }).compileComponents();
|
||||||
|
const fixture = TestBed.createComponent(Badge);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.nativeElement.querySelector('.ev-badge').classList).toContain('ev-badge--neutral');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('applique le ton demandé et projette le contenu', async () => {
|
||||||
|
await TestBed.configureTestingModule({ imports: [BadgeHost] }).compileComponents();
|
||||||
|
const fixture = TestBed.createComponent(BadgeHost);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const el = fixture.nativeElement.querySelector('.ev-badge');
|
||||||
|
expect(el.classList).toContain('ev-badge--danger');
|
||||||
|
expect(el.textContent).toContain('critique');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { Component, input } from '@angular/core';
|
||||||
|
|
||||||
|
export type BadgeTone = 'success' | 'warning' | 'danger' | 'critical' | 'neutral';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'ev-badge',
|
||||||
|
standalone: true,
|
||||||
|
templateUrl: './badge.html',
|
||||||
|
styleUrl: './badge.scss',
|
||||||
|
})
|
||||||
|
export class Badge {
|
||||||
|
tone = input<BadgeTone>('neutral');
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
<img src="/logo-icon.png" alt="" class="ev-brand__icon" />
|
||||||
|
<span class="ev-brand__name">EnerVision</span>
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
:host {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.45em;
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--color-text);
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-brand__icon {
|
||||||
|
height: 1.3em;
|
||||||
|
width: auto;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-brand__name {
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { Brand } from './brand';
|
||||||
|
|
||||||
|
describe('Brand', () => {
|
||||||
|
it("affiche l'icône et le nom EnerVision", async () => {
|
||||||
|
await TestBed.configureTestingModule({ imports: [Brand] }).compileComponents();
|
||||||
|
const fixture = TestBed.createComponent(Brand);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const icon = fixture.nativeElement.querySelector('img.ev-brand__icon');
|
||||||
|
expect(icon).toBeTruthy();
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('EnerVision');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { Component } from '@angular/core';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'ev-brand',
|
||||||
|
standalone: true,
|
||||||
|
templateUrl: './brand.html',
|
||||||
|
styleUrl: './brand.scss',
|
||||||
|
})
|
||||||
|
export class Brand {}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
<button
|
||||||
|
[type]="type()"
|
||||||
|
class="ev-button"
|
||||||
|
[class]="'ev-button--' + variant()"
|
||||||
|
[class.ev-button--inline]="!fullWidth()"
|
||||||
|
[disabled]="disabled()"
|
||||||
|
>
|
||||||
|
<ng-content></ng-content>
|
||||||
|
</button>
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
.ev-button {
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.7rem;
|
||||||
|
border: none;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
font-size: 0.95rem;
|
||||||
|
font-weight: 600;
|
||||||
|
font-family: var(--font-family);
|
||||||
|
cursor: pointer;
|
||||||
|
|
||||||
|
&:disabled {
|
||||||
|
cursor: not-allowed;
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
&.ev-button--inline {
|
||||||
|
width: auto;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-button--primary {
|
||||||
|
background: var(--color-primary);
|
||||||
|
color: var(--color-text-inverse);
|
||||||
|
|
||||||
|
&:disabled {
|
||||||
|
background: var(--color-disabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
&:not(:disabled):hover {
|
||||||
|
background: var(--color-primary-hover);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-button--secondary {
|
||||||
|
background: var(--color-surface);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
color: var(--color-label);
|
||||||
|
|
||||||
|
&:not(:disabled):hover {
|
||||||
|
background: var(--color-bg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-button--danger {
|
||||||
|
background: var(--color-danger);
|
||||||
|
color: var(--color-text-inverse);
|
||||||
|
|
||||||
|
&:disabled {
|
||||||
|
background: var(--color-disabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
&:not(:disabled):hover {
|
||||||
|
background: var(--color-danger-hover);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { Component } from '@angular/core';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { Button } from './button';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
standalone: true,
|
||||||
|
imports: [Button],
|
||||||
|
template: `<ev-button>Valider</ev-button>`,
|
||||||
|
})
|
||||||
|
class ButtonHost {}
|
||||||
|
|
||||||
|
describe('Button', () => {
|
||||||
|
beforeEach(async () => {
|
||||||
|
await TestBed.configureTestingModule({ imports: [Button] }).compileComponents();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('applique la classe de la variante primary par défaut', () => {
|
||||||
|
const fixture = TestBed.createComponent(Button);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const button = fixture.nativeElement.querySelector('button');
|
||||||
|
expect(button.classList).toContain('ev-button--primary');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('applique la classe de la variante demandée', () => {
|
||||||
|
const fixture = TestBed.createComponent(Button);
|
||||||
|
fixture.componentRef.setInput('variant', 'danger');
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const button = fixture.nativeElement.querySelector('button');
|
||||||
|
expect(button.classList).toContain('ev-button--danger');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('désactive le bouton natif quand disabled est vrai', () => {
|
||||||
|
const fixture = TestBed.createComponent(Button);
|
||||||
|
fixture.componentRef.setInput('disabled', true);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const button = fixture.nativeElement.querySelector('button');
|
||||||
|
expect(button.disabled).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('projette le contenu', async () => {
|
||||||
|
await TestBed.configureTestingModule({ imports: [ButtonHost] }).compileComponents();
|
||||||
|
const fixture = TestBed.createComponent(ButtonHost);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.nativeElement.querySelector('button').textContent).toContain('Valider');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { Component, input } from '@angular/core';
|
||||||
|
|
||||||
|
export type ButtonVariant = 'primary' | 'secondary' | 'danger';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'ev-button',
|
||||||
|
standalone: true,
|
||||||
|
templateUrl: './button.html',
|
||||||
|
styleUrl: './button.scss',
|
||||||
|
})
|
||||||
|
export class Button {
|
||||||
|
variant = input<ButtonVariant>('primary');
|
||||||
|
type = input<'button' | 'submit'>('button');
|
||||||
|
disabled = input(false);
|
||||||
|
fullWidth = input(true);
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<ng-content></ng-content>
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
:host {
|
||||||
|
background: var(--color-surface);
|
||||||
|
border: 1px solid var(--color-border-light);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
padding: var(--space-5);
|
||||||
|
box-shadow: var(--shadow-card);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { Component } from '@angular/core';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { Card } from './card';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
standalone: true,
|
||||||
|
imports: [Card],
|
||||||
|
template: `<ev-card><p>Contenu</p></ev-card>`,
|
||||||
|
})
|
||||||
|
class CardHost {}
|
||||||
|
|
||||||
|
describe('Card', () => {
|
||||||
|
it('projette son contenu', async () => {
|
||||||
|
await TestBed.configureTestingModule({ imports: [CardHost] }).compileComponents();
|
||||||
|
const fixture = TestBed.createComponent(CardHost);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const card = fixture.nativeElement.querySelector('ev-card');
|
||||||
|
expect(card).toBeTruthy();
|
||||||
|
expect(card.textContent).toContain('Contenu');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { Component } from '@angular/core';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'ev-card',
|
||||||
|
standalone: true,
|
||||||
|
templateUrl: './card.html',
|
||||||
|
styleUrl: './card.scss',
|
||||||
|
})
|
||||||
|
export class Card {}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
export type ReadingSource = 'csv' | 'api_current' | 'api_history';
|
||||||
|
export type ReadingDataQuality = 'good' | 'partial' | 'degraded' | 'critical';
|
||||||
|
|
||||||
|
export interface Reading {
|
||||||
|
reading_id: number;
|
||||||
|
site_id: string;
|
||||||
|
timestamp: string;
|
||||||
|
source: ReadingSource;
|
||||||
|
consumption_kw: number | null;
|
||||||
|
consumption_kwh: number | null;
|
||||||
|
consumption_euros: string | null;
|
||||||
|
voltage_v: number | null;
|
||||||
|
current_a: number | null;
|
||||||
|
power_factor: number | null;
|
||||||
|
temperature_celsius: number | null;
|
||||||
|
humidity_percent: number | null;
|
||||||
|
solar_irradiance_wm2: number | null;
|
||||||
|
is_working_hours: boolean | null;
|
||||||
|
data_quality: ReadingDataQuality | null;
|
||||||
|
null_reasons: string[] | null;
|
||||||
|
imputed_values: Record<string, unknown> | null;
|
||||||
|
imputation_method: string | null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { ReadingDataQuality } from './reading.model';
|
||||||
|
|
||||||
|
export interface SiteCurrent {
|
||||||
|
timestamp: string | null;
|
||||||
|
site_id: string;
|
||||||
|
site_type: string;
|
||||||
|
consumption_kw: number | null;
|
||||||
|
consumption_kwh: number | null;
|
||||||
|
voltage_v: number | null;
|
||||||
|
current_a: number | null;
|
||||||
|
power_factor: number | null;
|
||||||
|
temperature_celsius: number | null;
|
||||||
|
humidity_percent: number | null;
|
||||||
|
null_reasons: string[];
|
||||||
|
data_quality: ReadingDataQuality;
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
export interface Site {
|
||||||
|
site_id: string;
|
||||||
|
site_name: string;
|
||||||
|
site_type: string;
|
||||||
|
location: string | null;
|
||||||
|
capacity_kw: number | null;
|
||||||
|
status: string | null;
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
export const environment = {
|
export const environment = {
|
||||||
production: false,
|
production: false,
|
||||||
apiUrl: '/api/v1',
|
apiUrl: '/api/v1',
|
||||||
useMockFixtures: true, // a passer a false une fois le backend prêt
|
useMockFixtures: false,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,10 +2,10 @@
|
|||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<title>Frontend</title>
|
<title>EnerVision</title>
|
||||||
<base href="/" />
|
<base href="/" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
<link rel="icon" type="image/x-icon" href="favicon.ico" />
|
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<app-root></app-root>
|
<app-root></app-root>
|
||||||
|
|||||||
@@ -1 +1,11 @@
|
|||||||
/* You can add global styles to this file, and also import other style files */
|
@use 'styles/tokens';
|
||||||
|
@use 'styles/forms';
|
||||||
|
@use 'styles/auth-page';
|
||||||
|
@use 'styles/links';
|
||||||
|
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
font-family: var(--font-family);
|
||||||
|
color: var(--color-text);
|
||||||
|
background: var(--color-bg);
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
.auth-page {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-height: 100vh;
|
||||||
|
padding: var(--space-4);
|
||||||
|
box-sizing: border-box;
|
||||||
|
background:
|
||||||
|
radial-gradient(circle at 15% 10%, var(--color-primary-light) 0%, transparent 45%),
|
||||||
|
radial-gradient(circle at 85% 90%, var(--color-primary-light) 0%, transparent 40%),
|
||||||
|
var(--color-bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-card-wrapper {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 420px;
|
||||||
|
|
||||||
|
ev-card {
|
||||||
|
padding: 3rem 2.5rem;
|
||||||
|
box-shadow:
|
||||||
|
0 20px 25px -5px rgba(0, 0, 0, 0.06),
|
||||||
|
0 8px 10px -6px rgba(0, 0, 0, 0.04);
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-brand {
|
||||||
|
justify-content: center;
|
||||||
|
width: 100%;
|
||||||
|
font-size: 2.1rem;
|
||||||
|
margin-bottom: 1.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.85rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--color-text);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-subtitle {
|
||||||
|
margin: 0.4rem 0 2rem;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
font-size: 0.95rem;
|
||||||
|
line-height: 1.4;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
ev-alert {
|
||||||
|
display: block;
|
||||||
|
margin-top: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
ev-button {
|
||||||
|
display: block;
|
||||||
|
margin-top: 1.75rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
.form-label {
|
||||||
|
display: block;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--color-label);
|
||||||
|
margin-bottom: var(--space-1);
|
||||||
|
margin-top: var(--space-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-input {
|
||||||
|
width: 100%;
|
||||||
|
padding: var(--space-2) 0.75rem;
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
font-size: 0.95rem;
|
||||||
|
font-family: var(--font-family);
|
||||||
|
box-sizing: border-box;
|
||||||
|
|
||||||
|
&:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--color-primary);
|
||||||
|
box-shadow: 0 0 0 3px rgba(22, 163, 74, 0.15);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-hint {
|
||||||
|
display: block;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
color: var(--color-disabled);
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
.ev-link {
|
||||||
|
color: var(--color-primary);
|
||||||
|
font-weight: 600;
|
||||||
|
text-decoration: none;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-breadcrumb {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.4rem;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
margin-bottom: 1.25rem;
|
||||||
|
|
||||||
|
a {
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
text-decoration: none;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
color: var(--color-primary);
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.ev-brand-link {
|
||||||
|
display: inline-flex;
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
:root {
|
||||||
|
// Marque (dérivé du logo : vert feuille/éclair, halo)
|
||||||
|
--color-primary: #16a34a;
|
||||||
|
--color-primary-hover: #15803d;
|
||||||
|
--color-primary-light: #dcfce7;
|
||||||
|
|
||||||
|
// Neutres (texte, bordures, fonds)
|
||||||
|
--color-text: #1f2937;
|
||||||
|
--color-text-muted: #6b7280;
|
||||||
|
--color-label: #374151;
|
||||||
|
--color-border: #d1d5db;
|
||||||
|
--color-border-light: #e5e7eb;
|
||||||
|
--color-bg: #f3f4f6;
|
||||||
|
--color-surface: #ffffff;
|
||||||
|
--color-disabled: #9ca3af;
|
||||||
|
|
||||||
|
// Sémantique (statuts, alertes)
|
||||||
|
--color-success: #16a34a;
|
||||||
|
--color-success-bg: #dcfce7;
|
||||||
|
--color-warning: #f9a825;
|
||||||
|
--color-warning-bg: #fef9e7;
|
||||||
|
--color-danger: #dc2626;
|
||||||
|
--color-danger-hover: #b91c1c;
|
||||||
|
--color-danger-bg: #fef2f2;
|
||||||
|
--color-danger-border: #fecaca;
|
||||||
|
--color-critical: #b91c1c;
|
||||||
|
--color-warning-text: #92400e;
|
||||||
|
--color-text-inverse: #ffffff;
|
||||||
|
|
||||||
|
// Typo, rayons, ombre
|
||||||
|
--font-family: 'Segoe UI', system-ui, sans-serif;
|
||||||
|
--radius-sm: 8px;
|
||||||
|
--radius-md: 12px;
|
||||||
|
--radius-pill: 999px;
|
||||||
|
--shadow-card: 0 1px 3px rgba(0, 0, 0, 0.06);
|
||||||
|
|
||||||
|
// Espacements
|
||||||
|
--space-1: 0.35rem;
|
||||||
|
--space-2: 0.6rem;
|
||||||
|
--space-3: 1rem;
|
||||||
|
--space-4: 1.5rem;
|
||||||
|
--space-5: 2.5rem;
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
coverage: {
|
||||||
|
provider: 'v8',
|
||||||
|
reporter: ['text', 'lcov'],
|
||||||
|
reportsDirectory: './coverage',
|
||||||
|
include: ['src/**/*.{ts,tsx,js,jsx}'],
|
||||||
|
exclude: [
|
||||||
|
'**/*.spec.*',
|
||||||
|
'**/*.test.*',
|
||||||
|
'**/node_modules/**',
|
||||||
|
'**/dist/**',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
# 0005 - Modèle de prédiction de consommation : LightGBM
|
||||||
|
|
||||||
|
- Statut : accepté
|
||||||
|
- Date : 2026-09-17
|
||||||
|
|
||||||
|
## Contexte
|
||||||
|
|
||||||
|
Le schéma `prediction` contraint déjà la forme de la solution (deux cibles de régression,
|
||||||
|
`consumption_kw` instantané et `consumption_kwh` sur `period_minutes`, un statut
|
||||||
|
`insufficient_data` à détecter explicitement), mais aucun modèle n'était choisi. Trois
|
||||||
|
contraintes non négociables cadrent le choix, discutées dans l'issue #89 :
|
||||||
|
|
||||||
|
1. **EC06** (grille de notation individuelle) exige un modèle **entraîné, versionné avec
|
||||||
|
MLflow**, exposé via un endpoint fonctionnel, avec **surveillance du drift** en production.
|
||||||
|
2. **Aucun GPU dédié** : l'infra tourne on-premise sur une VM à 4 CPU / 8 Gio RAM (ou
|
||||||
|
`Standard_B2s`/`B2ms` côté Azure, 2 vCPU max) — Azure Machine Learning est de toute façon
|
||||||
|
bloqué par la politique Azure du projet.
|
||||||
|
3. **Délai serré** : le jalon J3 arrive à échéance le lendemain de la décision, J4 concentre déjà
|
||||||
|
26 issues sur 4 jours. Un modèle long à mettre en œuvre retarde la chaîne complète (service de
|
||||||
|
scoring #37, moteur de recommandations #38, tests ML #44/#45, tous bloqués par ce choix).
|
||||||
|
|
||||||
|
Le jeu de données est déjà disponible (`all_sites_combined.csv`, fourni par le formateur) : 7
|
||||||
|
sites, 2 ans au pas horaire (~17 500 lignes/site), avec `temperature_celsius`,
|
||||||
|
`humidity_percent`, `solar_irradiance_wm2` en régresseurs exogènes et des features calendaires
|
||||||
|
déjà dérivées.
|
||||||
|
|
||||||
|
## Options comparées
|
||||||
|
|
||||||
|
| Critère | Prophet | LightGBM/XGBoost | NeuralProphet | SARIMA | Holt-Winters | Mistral (LLM) |
|
||||||
|
|---|---|---|---|---|---|---|
|
||||||
|
| Saisonnalités multiples (jour/semaine/an) | Oui, nativement | Oui, via features engineered | Oui, nativement, + autorégression | Une seule, lourd à régler (SARIMAX) | Une seule, aucune | Non conçu pour ça |
|
||||||
|
| Régresseurs exogènes | Oui, mais doivent être connus dans le futur au moment de la prédiction | Oui, via lags/moyennes glissantes sur le passé | Oui, natif | Difficile en multivarié | Aucun support | Contexte de prompt seulement, non appris |
|
||||||
|
| Coût de calcul (VM sans GPU) | Faible | Faible | Élevé (deep learning) | Faible | Faible | Élevé à prohibitif |
|
||||||
|
| Versionnable MLflow | Oui, nativement | Oui, nativement | Pas de support direct | Oui, générique | Pas de support direct | Rien à versionner (pas un modèle entraîné) |
|
||||||
|
| Granularité | Un modèle par site (ou par site × métrique) | Un seul modèle global sur tous les sites | Un par site | Un par site | Un par site | — |
|
||||||
|
| Effort avant l'échéance | Faible | Moyen (feature engineering) | Élevé | Moyen à élevé | Faible en soi | Élevé, ou factice |
|
||||||
|
|
||||||
|
## Décision
|
||||||
|
|
||||||
|
**LightGBM, un seul modèle global** couvrant tous les sites, plutôt qu'un modèle par site
|
||||||
|
(Prophet) ou par famille de site. Cible : `consumption_kwh`, avec `period_minutes` comme feature
|
||||||
|
d'entrée plutôt que comme étape d'agrégation post-prédiction. Suivi et versioning via **MLflow**
|
||||||
|
(tracking + registre de modèles), sur le magasin local par défaut dans un premier temps —
|
||||||
|
l'hébergement sur l'infra k3s reste une question ouverte, non bloquante pour démarrer.
|
||||||
|
|
||||||
|
Raisons retenues, au-delà du tableau ci-dessus :
|
||||||
|
|
||||||
|
- **Un modèle global plutôt qu'un modèle par site** évite la fragilité des sites les moins
|
||||||
|
fournis en historique : ils bénéficient de ce qu'apprennent les autres sites, ce qu'un Prophet
|
||||||
|
par site ne permet pas.
|
||||||
|
- **Aucune dépendance à une prévision météo future.** Prophet exige que ses régresseurs
|
||||||
|
(`add_regressor`) soient connus au moment prédit ; `temperature_celsius`,
|
||||||
|
`humidity_percent` et `solar_irradiance_wm2` sont des mesures passées, pas des prévisions, et
|
||||||
|
aucune source de prévision météo n'existe dans le projet. LightGBM s'en sort avec des features
|
||||||
|
de lag/moyenne glissante calculées sur l'historique déjà présent dans `reading`, cf.
|
||||||
|
`ml/enervision_ml/features.py` — un choix qui vaut aussi bien à l'entraînement qu'au futur
|
||||||
|
scoring.
|
||||||
|
- **Apprentissage direct sur `consumption_kwh`** avec `period_minutes` en feature, sans étape
|
||||||
|
d'agrégation intermédiaire que la sortie continue de Prophet aurait demandée.
|
||||||
|
- **Coût de calcul compatible avec l'infra on-premise sans GPU.**
|
||||||
|
|
||||||
|
Débat complet, comparatif détaillé et décision finale : issue #89 (Johan, phyri0s,
|
||||||
|
ValentinDeFaria), actée en réunion d'équipe du 2026-09-17 et validée par l'ensemble de l'équipe.
|
||||||
|
|
||||||
|
## Conséquences
|
||||||
|
|
||||||
|
- Le pipeline d'entraînement (`ml/`, ce commit) lit `reading` + `site` par connexion PostgreSQL
|
||||||
|
directe et construit ses features par lags/moyennes glissantes plutôt que par régresseurs
|
||||||
|
contemporains, cf. `docs/ML-START.md`.
|
||||||
|
- Le rôle PostgreSQL dédié `enervision_ml` (lecture seule sur `reading`/`site`) n'est pas encore
|
||||||
|
provisionné : dette déjà assumée par l'ADR 0003 pour les comptes ETL/ML, `ML_DATABASE_URL`
|
||||||
|
pointe pour l'instant vers la même base que le backend applicatif en développement.
|
||||||
|
- Le service de scoring (#37), le moteur de recommandations (#38) et les tests de dérive
|
||||||
|
(#44/#45) restent à construire ; ils consommeront le même module `enervision_ml.features`, qui
|
||||||
|
doit rester strictement identique entre entraînement et scoring pour éviter un train/serve skew
|
||||||
|
silencieux.
|
||||||
|
- La surveillance de drift exigée par EC06 n'est pas encore implémentée : ce ticket ne livre que
|
||||||
|
l'entraînement et son suivi MLflow (paramètres, métriques, artefact modèle), pas le monitoring
|
||||||
|
en production.
|
||||||
|
- L'hébergement de MLflow sur l'infra k3s reste une question ouverte ; le magasin SQLite local
|
||||||
|
(`ml/mlflow.db`, ignoré par git) suffit pour l'instant à comparer des runs sur un poste.
|
||||||
|
|
||||||
|
## Alternatives écartées
|
||||||
|
|
||||||
|
- **Prophet** : proposition initiale, écartée après débat pour les raisons ci-dessus (modèle par
|
||||||
|
site, dépendance à une météo future indisponible, agrégation kWh en post-traitement). Reste un
|
||||||
|
candidat solide si un jour le projet doit produire une décomposition tendance/saisonnalité
|
||||||
|
explicable pour un usage différent.
|
||||||
|
- **Mistral (LLM)** : aucun produit dédié aux séries temporelles ; interroger un LLM généraliste
|
||||||
|
ne constitue pas un modèle entraîné et versionnable au sens MLflow, et le fine-tuning est hors
|
||||||
|
budget de calcul et hors délai.
|
||||||
|
- **SARIMA** : ne gère pas nativement plusieurs régresseurs exogènes ; réglage (p,d,q,P,D,Q) plus
|
||||||
|
long que le délai disponible.
|
||||||
|
- **NeuralProphet** : fait tout ce que fait Prophet et apprend en plus des motifs autorégressifs,
|
||||||
|
mais coûte plus cher en calcul (pas de GPU disponible) et n'a pas d'outil MLflow direct — piste
|
||||||
|
d'évolution possible, non engageante à ce stade.
|
||||||
|
- **Holt-Winters** : écarté d'entrée, pas seulement différé — aucun support de régresseurs
|
||||||
|
exogènes, alors que la météo et l'irradiance sont nécessaires ici.
|
||||||
|
- **CatBoost** : même famille que LightGBM, gère nativement les colonnes catégorielles (comme
|
||||||
|
`site_type`) sans encodage manuel. Non rejeté, différé : candidat à comparer si LightGBM
|
||||||
|
plafonne en précision.
|
||||||
@@ -77,6 +77,7 @@ collecteur ne vient le lire.
|
|||||||
| Backend | FastAPI, Python 3.14 | `apps/backend` | `En cours` | Factory, configuration, journalisation, 2 sondes de santé, `/metrics`, contrat OpenAPI versionné, routes `sites`, `alerts`, `recommendations`, `stats/summary` et `readings` en lecture (endpoints → services → repositories → models) |
|
| Backend | FastAPI, Python 3.14 | `apps/backend` | `En cours` | Factory, configuration, journalisation, 2 sondes de santé, `/metrics`, contrat OpenAPI versionné, routes `sites`, `alerts`, `recommendations`, `stats/summary` et `readings` en lecture (endpoints → services → repositories → models) |
|
||||||
| Frontend | Angular 22, Node 24 | `apps/frontend` | `En cours` | Tableau de bord sur route `/dashboard`, deux services HTTP, graphiques Chart.js, données servies par des fixtures |
|
| Frontend | Angular 22, Node 24 | `apps/frontend` | `En cours` | Tableau de bord sur route `/dashboard`, deux services HTTP, graphiques Chart.js, données servies par des fixtures |
|
||||||
| Base | PostgreSQL 17 + TimescaleDB | `db` | `Fait` | Bootstrap de l'extension, base de test, chaîne Alembic. Schéma applicatif créé (`site`, `dataset`, `reading` en hypertable, `prediction`, `alert`, `recommendation`) |
|
| Base | PostgreSQL 17 + TimescaleDB | `db` | `Fait` | Bootstrap de l'extension, base de test, chaîne Alembic. Schéma applicatif créé (`site`, `dataset`, `reading` en hypertable, `prediction`, `alert`, `recommendation`) |
|
||||||
|
| ML | LightGBM, MLflow | `ml` | `En cours` | Pipeline d'entraînement (features par lags/moyennes glissantes, baseline de persistance saisonnière, suivi MLflow local), voir [ADR 0005](../adr/0005-modele-prediction-lightgbm.md) et [ML-START.md](../../ML-START.md). Scoring, endpoint et surveillance de dérive pas encore construits |
|
||||||
| Infra | Terraform, k3s single-node | `infra/terraform` | `En cours` | Module d'installation du cluster. Jamais appliqué, aucune ressource Kubernetes déclarée |
|
| Infra | Terraform, k3s single-node | `infra/terraform` | `En cours` | Module d'installation du cluster. Jamais appliqué, aucune ressource Kubernetes déclarée |
|
||||||
| Monitoring | Prometheus, Grafana, Alertmanager | `monitoring` | `Cible` | Rien, hors le `/metrics` exposé par l'API |
|
| Monitoring | Prometheus, Grafana, Alertmanager | `monitoring` | `Cible` | Rien, hors le `/metrics` exposé par l'API |
|
||||||
| ETL | Apache Airflow | `etl/airflow` | `Cible` | Rien |
|
| ETL | Apache Airflow | `etl/airflow` | `Cible` | Rien |
|
||||||
|
|||||||
@@ -142,6 +142,7 @@ Deux fichiers d'environnement, deux usages : `.env` à la racine alimente `docke
|
|||||||
| POST | `/api/v1/users/{id}/password-reset` | Réinitialise et ferme les sessions. `admin` | 401, 403, 404, 422, 500 |
|
| POST | `/api/v1/users/{id}/password-reset` | Réinitialise et ferme les sessions. `admin` | 401, 403, 404, 422, 500 |
|
||||||
| GET | `/api/v1/sites` | Liste les sites. `lecteur` | 401, 403, 500 |
|
| GET | `/api/v1/sites` | Liste les sites. `lecteur` | 401, 403, 500 |
|
||||||
| GET | `/api/v1/sites/{site_id}` | Décrit un site. `lecteur` | 401, 403, 404, 422, 500 |
|
| GET | `/api/v1/sites/{site_id}` | Décrit un site. `lecteur` | 401, 403, 404, 422, 500 |
|
||||||
|
| GET | `/api/v1/sites/{site_id}/current` | Dernière mesure d'un site. `lecteur` | 401, 403, 404, 422, 500 |
|
||||||
| GET | `/api/v1/alerts` | Liste les alertes, filtrable par `site_id` et `severity`. `lecteur` | 401, 403, 422, 500 |
|
| GET | `/api/v1/alerts` | Liste les alertes, filtrable par `site_id` et `severity`. `lecteur` | 401, 403, 422, 500 |
|
||||||
| GET | `/api/v1/recommendations` | Liste les recommandations. `lecteur` | 401, 403, 500 |
|
| GET | `/api/v1/recommendations` | Liste les recommandations. `lecteur` | 401, 403, 500 |
|
||||||
| GET | `/api/v1/recommendations/{recommendation_id}` | Décrit une recommandation. `lecteur` | 401, 403, 404, 422, 500 |
|
| GET | `/api/v1/recommendations/{recommendation_id}` | Décrit une recommandation. `lecteur` | 401, 403, 404, 422, 500 |
|
||||||
@@ -154,10 +155,12 @@ Deux fichiers d'environnement, deux usages : `.env` à la racine alimente `docke
|
|||||||
Les codes de la dernière colonne sont ceux que le schéma **déclare**, et le fichier
|
Les codes de la dernière colonne sont ceux que le schéma **déclare**, et le fichier
|
||||||
`openapi.json` versionné interdit qu'ils divergent de ce que les routes rendent.
|
`openapi.json` versionné interdit qu'ils divergent de ce que les routes rendent.
|
||||||
|
|
||||||
**Quatre routes seulement sont publiques** : les deux sondes, `/auth/login` et `/auth/logout`.
|
**Sept routes du contrat sont publiques** : les deux sondes, `/auth/login`, `/auth/logout`,
|
||||||
|
`/auth/forgot-password` et les deux routes de réinitialisation, qui portent leur autorisation dans
|
||||||
|
le jeton à usage unique plutôt que dans un `Principal`.
|
||||||
`tests/api/test_route_protection.py` interroge réellement chaque autre route sans identifiant et
|
`tests/api/test_route_protection.py` interroge réellement chaque autre route sans identifiant et
|
||||||
échoue si l'une d'elles répond autre chose qu'un 401 ou un 403. Rendre une route publique impose
|
échoue si l'une d'elles répond autre chose qu'un 401 ou un 403. Rendre une route publique impose
|
||||||
donc de modifier la liste dans ce fichier de test.
|
donc de modifier `ROUTES_PUBLIQUES` dans `tests/api/acces.py`.
|
||||||
|
|
||||||
`GET /sites` et `GET /sites/{site_id}` sont la première route métier, et le gabarit repris pour
|
`GET /sites` et `GET /sites/{site_id}` sont la première route métier, et le gabarit repris pour
|
||||||
`GET /alerts` puis pour les suivantes (`dataset`, `prediction`) : les quatre couches
|
`GET /alerts` puis pour les suivantes (`dataset`, `prediction`) : les quatre couches
|
||||||
@@ -171,7 +174,11 @@ et `GET /recommendations/{recommendation_id}` reprennent le même gabarit à la
|
|||||||
elle remonte à un site par sa seule `alert_id`, `alert` n'étant pas encore exposée. `GET
|
elle remonte à un site par sa seule `alert_id`, `alert` n'étant pas encore exposée. `GET
|
||||||
/stats/summary` et `GET /sensors/status` agrègent chacune deux repositories (`SiteRepository`,
|
/stats/summary` et `GET /sensors/status` agrègent chacune deux repositories (`SiteRepository`,
|
||||||
`ReadingRepository`) dans un service dédié plutôt que d'exposer une table : elles n'entrent donc
|
`ReadingRepository`) dans un service dédié plutôt que d'exposer une table : elles n'entrent donc
|
||||||
pas dans ce gabarit route-par-table. Le contrat détaillé pour le frontend est dans
|
pas dans ce gabarit route-par-table. `GET /sites/{site_id}/current` reste sur le gabarit `sites`,
|
||||||
|
mais `SiteService` gagne la même seconde dépendance (`ReadingRepository`) pour restituer la
|
||||||
|
dernière `Reading` du site : un site connu sans lecture rend `200` avec tous les champs de mesure
|
||||||
|
à `null` et `data_quality="critical"`, seul un `site_id` absent de la base rend `404`. Le contrat
|
||||||
|
détaillé pour le frontend est dans
|
||||||
[31-contrat-authentification.md](31-contrat-authentification.md).
|
[31-contrat-authentification.md](31-contrat-authentification.md).
|
||||||
|
|
||||||
`GET /readings` reprend le même gabarit mais s'en écarte sur un point : `reading` est l'hypertable,
|
`GET /readings` reprend le même gabarit mais s'en écarte sur un point : `reading` est l'hypertable,
|
||||||
@@ -268,11 +275,16 @@ Checklist pour toute nouvelle route sur le gabarit `sites`/`alerts`/`recommendat
|
|||||||
au niveau de l'`include_router()` du routeur, `REPONSE_VALIDATION` et les codes locaux
|
au niveau de l'`include_router()` du routeur, `REPONSE_VALIDATION` et les codes locaux
|
||||||
(404, 409, ...) directement sur l'endpoint qui les rend.
|
(404, 409, ...) directement sur l'endpoint qui les rend.
|
||||||
2. Décrire son tag dans `TAGS`.
|
2. Décrire son tag dans `TAGS`.
|
||||||
3. Si elle passe par `require_role` (`LecteurDep`/`OperateurDep`/`AdminDep`), l'ajouter à
|
3. **La classer dans `tests/api/acces.py`** : `ROLE_MINIMUM` avec son rôle minimum si elle passe
|
||||||
`ROUTES_A_ROLE` dans `tests/api/test_openapi.py`. Si elle passe par `require_trusted_origin`,
|
par `require_role` (`LecteurDep`/`OperateurDep`/`AdminDep`), `ROUTES_SANS_ROLE` si elle se
|
||||||
l'ajouter à `ORIGINE_VERIFIEE`. **Ces deux listes sont maintenues à la main, pas dérivées** :
|
contente de `CurrentPrincipalDep`, `ROUTES_PUBLIQUES` si elle est ouverte. L'oubli n'est plus
|
||||||
une route oubliée n'y est pas détectée automatiquement.
|
silencieux : `test_every_declared_route_is_classified` échoue sur une route non classée comme
|
||||||
4. `make openapi`, puis `uv run pytest tests/api/test_openapi.py`.
|
sur une entrée qui ne correspond plus à aucune route. `ROUTES_A_ROLE` de `test_openapi.py` en
|
||||||
|
est dérivée, et `test_matrice_acces.py` vérifie le niveau réellement monté.
|
||||||
|
4. Si elle passe par `require_trusted_origin`, l'ajouter à `ORIGINE_VERIFIEE` dans
|
||||||
|
`tests/api/test_openapi.py`. **Cette liste-là reste maintenue à la main.**
|
||||||
|
5. `make openapi`, puis `uv run pytest tests/api/test_openapi.py tests/api/test_route_protection.py
|
||||||
|
tests/api/test_matrice_acces.py`.
|
||||||
|
|
||||||
## Sécurité
|
## Sécurité
|
||||||
|
|
||||||
@@ -323,9 +335,14 @@ Le reste, par ordre de surface :
|
|||||||
|
|
||||||
Conventions, gabarits et arborescence : [`apps/backend/TESTING.md`](../../apps/backend/TESTING.md).
|
Conventions, gabarits et arborescence : [`apps/backend/TESTING.md`](../../apps/backend/TESTING.md).
|
||||||
|
|
||||||
Trois fichiers méritent d'être connus avant de toucher à l'authentification :
|
Quatre fichiers méritent d'être connus avant de toucher à l'authentification :
|
||||||
|
|
||||||
|
- `tests/api/acces.py` : la classification des routes, `ROUTES_PUBLIQUES` et `ROLE_MINIMUM` en
|
||||||
|
tête. Ce n'est pas un test, c'est la référence que les deux suivants confrontent au
|
||||||
|
comportement observé.
|
||||||
- `tests/api/test_route_protection.py` : le garde-fou de l'autorisation, décrit plus haut.
|
- `tests/api/test_route_protection.py` : le garde-fou de l'autorisation, décrit plus haut.
|
||||||
|
- `tests/api/test_matrice_acces.py` : chaque route gardée croisée avec chacun des trois rôles,
|
||||||
|
dans les deux sens, puis rejouée sous `integration` avec de vrais jetons.
|
||||||
- `tests/services/test_auth.py` : le faux hacheur y porte un compteur d'appels, ce qui permet les
|
- `tests/services/test_auth.py` : le faux hacheur y porte un compteur d'appels, ce qui permet les
|
||||||
deux assertions qui prouvent le design, à savoir un appel quand l'adresse est inconnue et zéro
|
deux assertions qui prouvent le design, à savoir un appel quand l'adresse est inconnue et zéro
|
||||||
appel quand la limite est atteinte.
|
appel quand la limite est atteinte.
|
||||||
|
|||||||
@@ -16,6 +16,10 @@ Ce qui est en place :
|
|||||||
- `core/services` porte `StatsService` et `AlertsService`, `core/interceptors` l'intercepteur de
|
- `core/services` porte `StatsService` et `AlertsService`, `core/interceptors` l'intercepteur de
|
||||||
fixtures, `features/dashboard` la page, `shared/components` la jauge de consommation et le
|
fixtures, `features/dashboard` la page, `shared/components` la jauge de consommation et le
|
||||||
graphique de charge par site, tous deux construits sur Chart.js.
|
graphique de charge par site, tous deux construits sur Chart.js.
|
||||||
|
- Un système de design partagé (`shared/components/ui/` : `ev-button`, `ev-card`, `ev-alert`,
|
||||||
|
`ev-badge`, `ev-brand`, tokens CSS dans `styles/_tokens.scss`) que toute nouvelle page doit
|
||||||
|
réutiliser plutôt que redéfinir ses propres styles. Détail :
|
||||||
|
[32-design-systeme-frontend.md](32-design-systeme-frontend.md).
|
||||||
- L'état vit dans des signaux, sans bibliothèque dédiée.
|
- L'état vit dans des signaux, sans bibliothèque dédiée.
|
||||||
- Vitest via le builder `@angular/build:unit-test`, couverture activée, sept fichiers de test.
|
- Vitest via le builder `@angular/build:unit-test`, couverture activée, sept fichiers de test.
|
||||||
- Prettier configuré, parser `angular` pour les gabarits HTML.
|
- Prettier configuré, parser `angular` pour les gabarits HTML.
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
# Design système frontend
|
||||||
|
|
||||||
|
Ce que toute nouvelle page ou tout nouveau composant Angular doit réutiliser, plutôt que
|
||||||
|
redéfinir ses propres couleurs, rayons ou espacements en dur. Contexte : issue
|
||||||
|
[#91](https://github.com/ineszang/ProjetPiscine_EnerVision/issues/91), née d'une incohérence
|
||||||
|
visuelle accumulée page après page (aucun jeton partagé n'existait avant ce chantier).
|
||||||
|
|
||||||
|
## Tokens
|
||||||
|
|
||||||
|
Déclarés en CSS custom properties dans `apps/frontend/src/styles/_tokens.scss`, importés une
|
||||||
|
seule fois dans `src/styles.scss`. Disponibles partout sans import supplémentaire.
|
||||||
|
|
||||||
|
| Variable | Rôle |
|
||||||
|
|---|---|
|
||||||
|
| `--color-primary`, `--color-primary-hover`, `--color-primary-light` | Couleur de marque (vert, dérivé du logo), actions principales |
|
||||||
|
| `--color-text`, `--color-text-muted`, `--color-label` | Hiérarchie de texte (titres, texte secondaire, labels de formulaire) |
|
||||||
|
| `--color-border`, `--color-border-light` | Bordures d'inputs et de cartes |
|
||||||
|
| `--color-bg`, `--color-surface` | Fond de page vs fond des cartes/panneaux |
|
||||||
|
| `--color-disabled` | Éléments désactivés |
|
||||||
|
| `--color-success` / `-bg`, `--color-warning` / `-bg` / `-text`, `--color-danger` / `-hover` / `-bg` / `-border`, `--color-critical` | États sémantiques (alertes, badges) |
|
||||||
|
| `--color-text-inverse` | Texte sur fond coloré plein (boutons/badges) |
|
||||||
|
| `--font-family` | Police unique de l'application |
|
||||||
|
| `--radius-sm`, `--radius-md`, `--radius-pill` | Rayons de bordure (input/bouton, carte, pastille) |
|
||||||
|
| `--shadow-card` | Ombre portée des cartes |
|
||||||
|
| `--space-1` à `--space-5` | Échelle d'espacement (0.35rem à 2.5rem) |
|
||||||
|
|
||||||
|
Les classes de formulaire partagées (`.form-label`, `.form-input`, `.form-hint`) sont dans
|
||||||
|
`apps/frontend/src/styles/_forms.scss`, importées globalement de la même façon. Elles
|
||||||
|
s'appliquent directement à des `<label>`/`<input>` natifs liés par `formControlName` : pas de
|
||||||
|
composant `ControlValueAccessor` dédié, le gain n'en vaut pas la complexité pour des formulaires
|
||||||
|
aussi simples que ceux de ce projet. Les erreurs de formulaire, elles, s'affichent via
|
||||||
|
`<ev-alert severity="danger">`, pas une classe dédiée.
|
||||||
|
|
||||||
|
La classe `.auth-page` (`apps/frontend/src/styles/_auth-page.scss`, importée globalement) porte
|
||||||
|
le fond dégradé et le centrage commun aux pages d'authentification (`login`, `change-password`,
|
||||||
|
et à terme `forgot-password`/`reset-password`) : elle enveloppe la carte, pas de duplication du
|
||||||
|
fond par page.
|
||||||
|
|
||||||
|
Les classes de navigation partagées (`.ev-link`, `.ev-breadcrumb`, `.ev-brand-link`) sont dans
|
||||||
|
`apps/frontend/src/styles/_links.scss`, importées globalement. Convention pour toute page de la
|
||||||
|
zone authentifiée (derrière `authGuard`) : le logo (`<ev-brand>`) est enveloppé dans
|
||||||
|
`<a routerLink="/dashboard" class="ev-brand-link">` pour ramener au tableau de bord en un clic,
|
||||||
|
et un `<nav class="ev-breadcrumb">` liste le chemin de retour vers les pages parentes quand la
|
||||||
|
page n'est pas à la racine (voir `site-list`/`site-detail-placeholder` pour l'exemple).
|
||||||
|
|
||||||
|
## Composants partagés
|
||||||
|
|
||||||
|
Dans `apps/frontend/src/app/shared/components/ui/`, chacun standalone, à importer directement
|
||||||
|
dans le tableau `imports` du composant qui l'utilise.
|
||||||
|
|
||||||
|
- **`<ev-button>`** (`button/`) : `variant` (`primary` / `secondary` / `danger`, défaut
|
||||||
|
`primary`), `type` (`button` / `submit`, défaut `button`), `disabled`, `fullWidth` (défaut
|
||||||
|
`true` ; passer `false` pour un bouton qui ne doit pas occuper toute la largeur de son
|
||||||
|
conteneur, ex. une action isolée dans un en-tête).
|
||||||
|
```html
|
||||||
|
<ev-button type="submit" [disabled]="form.invalid">Valider</ev-button>
|
||||||
|
<ev-button variant="secondary" [fullWidth]="false">Déconnexion</ev-button>
|
||||||
|
```
|
||||||
|
- **`<ev-card>`** (`card/`) : conteneur à padding/rayon/ombre standard, sans input, tout est le
|
||||||
|
contenu projeté (`<ng-content>`). Le style vit sur `:host` : une classe externe passée par le
|
||||||
|
parent (`<ev-card class="ma-classe">`) se combine avec le style du composant sans le masquer.
|
||||||
|
```html
|
||||||
|
<ev-card><h1>Titre</h1></ev-card>
|
||||||
|
```
|
||||||
|
- **`<ev-alert>`** (`alert/`) : `severity` (`success` / `warning` / `danger`, défaut `danger`),
|
||||||
|
`role="alert"` posé automatiquement. Même principe de style sur `:host`.
|
||||||
|
```html
|
||||||
|
<ev-alert severity="danger">Erreur : {{ message }}</ev-alert>
|
||||||
|
```
|
||||||
|
- **`<ev-badge>`** (`badge/`) : `tone` (`success` / `warning` / `danger` / `critical` /
|
||||||
|
`neutral`, défaut `neutral`), pastille à bord arrondi pour un statut court. `danger` et
|
||||||
|
`critical` sont deux rouges distincts (`--color-danger` vs `--color-critical`, plus sombre) :
|
||||||
|
une sévérité `critical` ne doit pas se confondre visuellement avec une `high`.
|
||||||
|
```html
|
||||||
|
<ev-badge tone="danger">critique</ev-badge>
|
||||||
|
```
|
||||||
|
- **`<ev-brand>`** (`brand/`) : lockup icône + « EnerVision », sans input. La taille se pilote
|
||||||
|
entièrement via `font-size` (l'icône et le texte sont exprimés en `em`, donc ils grossissent
|
||||||
|
ensemble en gardant le même écart proportionnel) : une page l'agrandit simplement avec
|
||||||
|
`ev-brand { font-size: 2.1rem; }`. Ne pas recomposer icône + texte en une seule image bitmap :
|
||||||
|
un essai en ce sens (recadrage pixel de l'asset source) a produit un rendu bruité et un espacement
|
||||||
|
figé, impossible à ajuster proprement.
|
||||||
|
```html
|
||||||
|
<ev-brand />
|
||||||
|
```
|
||||||
|
|
||||||
|
## Logo
|
||||||
|
|
||||||
|
L'icône seule (sans le mot-symbole), recadrée depuis l'asset source du projet, vit à deux
|
||||||
|
endroits qui doivent rester synchronisés si le logo change un jour :
|
||||||
|
`apps/frontend/public/logo-icon.png` (utilisée par `<ev-brand>`) et
|
||||||
|
`apps/backend/app/static/logo-icon.png` (référencée par `/docs`, favicon Swagger, et `/redoc` via
|
||||||
|
l'extension `x-logo` du schéma OpenAPI, voir `app/main.py`). Le mot-symbole « EnerVision » n'est
|
||||||
|
jamais une image : c'est le texte du composant `<ev-brand>`, en police système.
|
||||||
|
|
||||||
|
Le favicon `apps/frontend/public/favicon.ico` est généré depuis la même icône (multi-tailles
|
||||||
|
16 à 256px).
|
||||||
|
|
||||||
|
## Règle pour toute nouvelle page
|
||||||
|
|
||||||
|
Utiliser les tokens et les composants ci-dessus plutôt que des valeurs en dur (couleurs
|
||||||
|
hexadécimales, rayons, espacements). Étendre ce document si un nouveau composant partagé est
|
||||||
|
créé.
|
||||||
@@ -13,6 +13,7 @@ contredisent, c'est l'ADR qui fait foi et la vue qui est en retard.
|
|||||||
| [20-backend.md](20-backend.md) | Couches FastAPI, séquence de démarrage, routes, configuration, contrat OpenAPI |
|
| [20-backend.md](20-backend.md) | Couches FastAPI, séquence de démarrage, routes, configuration, contrat OpenAPI |
|
||||||
| [30-frontend.md](30-frontend.md) | Angular, arborescence cible, flux HTTP |
|
| [30-frontend.md](30-frontend.md) | Angular, arborescence cible, flux HTTP |
|
||||||
| [31-contrat-authentification.md](31-contrat-authentification.md) | Ce que le frontend doit savoir pour coder la connexion |
|
| [31-contrat-authentification.md](31-contrat-authentification.md) | Ce que le frontend doit savoir pour coder la connexion |
|
||||||
|
| [32-design-systeme-frontend.md](32-design-systeme-frontend.md) | Tokens CSS, composants `ev-*` partagés, règle anti-couleur-en-dur |
|
||||||
| [40-data.md](40-data.md) | Frontières `db/` et `alembic/`, cycle de vie d'une mesure, modèle |
|
| [40-data.md](40-data.md) | Frontières `db/` et `alembic/`, cycle de vie d'une mesure, modèle |
|
||||||
|
|
||||||
L'observabilité et la CI/CD n'ont pas de document propre : ce sont des sections des documents
|
L'observabilité et la CI/CD n'ont pas de document propre : ce sont des sections des documents
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user