Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
692ec436a5 | ||
|
|
a3d32a6fb1 | ||
|
|
63ee79cf32 | ||
|
|
76fa90dfcb | ||
|
|
e13096c62a | ||
|
|
3fb907d6f6 | ||
|
|
c7490d01b3 | ||
|
|
523b623dc1 | ||
|
|
61e031fc16 | ||
|
|
781644b28e | ||
|
|
1654e4dd81 | ||
|
|
e50921c907 | ||
|
|
56f7211f0b | ||
|
|
c83fd889b8 | ||
|
|
cf22b2ae55 | ||
|
|
12c5cf87ad | ||
|
|
7b076171d2 | ||
|
|
ad149db0cb | ||
|
|
50dcb4de32 | ||
|
|
d25e544db6 | ||
|
|
22ff1d93f4 | ||
|
|
d632af57b8 | ||
|
|
fabd073aaf | ||
|
|
31a9cb109f | ||
|
|
50dddf952b | ||
|
|
fc6600aeaf | ||
|
|
1325a75e9a | ||
|
|
16a0cc4d3b | ||
|
|
5e7cb005ac | ||
|
|
3347fa5bdb | ||
|
|
da481d7485 | ||
|
|
344f82fcdd | ||
|
|
6c1f86b4ce |
@@ -1,18 +1,36 @@
|
||||
BACKEND := apps/backend
|
||||
FRONTEND := apps/frontend
|
||||
|
||||
.DEFAULT_GOAL := help
|
||||
.PHONY: help install dev lint format typecheck test test-cov test-integration check \
|
||||
docker-build db-up db-down db-reset db-logs db-psql migrate bootstrap-admin
|
||||
.PHONY: help install install-backend install-frontend dev dev-backend dev-frontend \
|
||||
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
|
||||
|
||||
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}'
|
||||
|
||||
install: ## Installe les dépendances du backend
|
||||
install: install-backend install-frontend ## Installe les dépendances backend et frontend
|
||||
|
||||
install-backend: ## Installe les dépendances du backend
|
||||
cd $(BACKEND) && uv sync --all-groups
|
||||
|
||||
dev: ## Lance l'API en rechargement à chaud
|
||||
install-frontend: ## Installe les dépendances du frontend
|
||||
cd $(FRONTEND) && npm ci
|
||||
|
||||
dev: ## Lance toute la stack (backend + frontend) en rechargement à chaud
|
||||
@trap 'kill 0' EXIT INT TERM; \
|
||||
$(MAKE) --no-print-directory dev-backend & \
|
||||
$(MAKE) --no-print-directory dev-frontend & \
|
||||
wait
|
||||
|
||||
dev-backend: ## Lance l'API seule en rechargement à chaud
|
||||
@echo "backend -> http://localhost:8000 (docs sur /docs)"
|
||||
cd $(BACKEND) && uv run uvicorn app.main:create_app --factory --reload --host 0.0.0.0 --port 8000
|
||||
|
||||
dev-frontend: ## Lance le frontend seul en rechargement à chaud
|
||||
@echo "frontend -> http://localhost:4200"
|
||||
cd $(FRONTEND) && npm start
|
||||
|
||||
lint: ## Analyse statique du backend
|
||||
cd $(BACKEND) && uv run ruff check .
|
||||
|
||||
@@ -34,6 +52,9 @@ test-integration: ## Exécute les tests exigeant une base joignable
|
||||
|
||||
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
|
||||
cd $(BACKEND) && uv run python -m app.cli export-openapi
|
||||
|
||||
docker-build: ## Construit l'image du backend
|
||||
docker build -t enervision-backend:local $(BACKEND)
|
||||
|
||||
|
||||
@@ -63,16 +63,17 @@ L'etat detaille de chaque brique et les vues d'architecture sont dans
|
||||
|
||||
## Demarrage
|
||||
|
||||
Prerequis : uv, Docker. Le poste doit disposer de Python 3.14, que `uv` installe seul.
|
||||
Prerequis : uv, Docker, Node 24 LTS (npm fourni). Le poste doit disposer de Python 3.14, que
|
||||
`uv` installe seul.
|
||||
|
||||
```bash
|
||||
cp .env.example .env # variables de docker-compose
|
||||
cp apps/backend/.env.example apps/backend/.env # variables du backend hors conteneur
|
||||
|
||||
make db-up # PostgreSQL + TimescaleDB, publie sur le port 5433
|
||||
make install # dependances du backend
|
||||
make install # dependances du backend et du frontend
|
||||
make migrate # applique les migrations Alembic
|
||||
make dev # API sur http://localhost:8000, docs sur /docs
|
||||
make dev # backend sur http://localhost:8000 (docs sur /docs), frontend sur http://localhost:4200
|
||||
make check # lint + typage + tests
|
||||
```
|
||||
|
||||
@@ -83,9 +84,11 @@ Deux fichiers d'environnement, deux usages : `.env` a la racine alimente `docker
|
||||
5432, souvent deja pris par une autre base.
|
||||
|
||||
La boucle de developpement est `make db-up` puis `make dev` : seule la base tourne en
|
||||
conteneur. Le service `backend` du `docker-compose.yml` sert la stack complete et la recette,
|
||||
et n'embarque pas le source, donc toute modification y demande un
|
||||
`docker compose up -d --build backend`.
|
||||
conteneur, le backend et le frontend tournent tous les deux sur le poste, lances ensemble par
|
||||
`make dev` (logs entrelaces dans le meme terminal, Ctrl+C arrete les deux). `make dev-backend`
|
||||
et `make dev-frontend` restent disponibles pour lancer un seul des deux. Le service `backend`
|
||||
du `docker-compose.yml` sert la stack complete et la recette, et n'embarque pas le source, donc
|
||||
toute modification y demande un `docker compose up -d --build backend`.
|
||||
|
||||
Verifier que la base repond et que l'extension est chargee :
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ de demarrer sans elles.
|
||||
## Commandes
|
||||
|
||||
Depuis la racine du monorepo, via le `Makefile` : `make install`, `make dev`, `make lint`,
|
||||
`make format`, `make typecheck`, `make test`, `make check`, `make docker-build`.
|
||||
`make format`, `make typecheck`, `make test`, `make check`, `make openapi`, `make docker-build`.
|
||||
|
||||
Directement depuis ce dossier :
|
||||
|
||||
@@ -39,8 +39,12 @@ uv run ruff format . # format
|
||||
uv run mypy app # typage strict
|
||||
uv run pytest # tests + couverture
|
||||
uv run pytest -m integration # tests exigeant une base joignable
|
||||
uv run python -m app.cli export-openapi # régénère openapi.json
|
||||
```
|
||||
|
||||
`openapi.json` est versionné : `tests/api/test_openapi.py` échoue si le fichier ne correspond
|
||||
plus aux routes déclarées. Toute PR qui change une route le régénère dans le même commit.
|
||||
|
||||
Les conventions de tests, les gabarits et le detail des marqueurs sont dans
|
||||
[`TESTING.md`](TESTING.md).
|
||||
|
||||
@@ -103,6 +107,10 @@ Le sens de dependance est unique : `endpoints` vers `services` vers `repositorie
|
||||
| `/api/v1/users` | Liste et crée des comptes | `admin` |
|
||||
| `/api/v1/users/{id}` | Change le rôle ou l'activation | `admin` |
|
||||
| `/api/v1/users/{id}/password-reset` | Réinitialise et ferme les sessions | `admin` |
|
||||
| `/api/v1/sites` | Liste les sites | `lecteur` |
|
||||
| `/api/v1/sites/{site_id}` | Décrit un site | `lecteur` |
|
||||
| `/api/v1/recommendations` | Liste les recommandations | `lecteur` |
|
||||
| `/api/v1/recommendations/{recommendation_id}` | Décrit une recommandation | `lecteur` |
|
||||
| `/metrics` | Métriques au format Prometheus | jeton si `APP_METRICS_TOKEN` |
|
||||
| `/docs`, `/openapi.json` | Documentation, fermée en `staging` et `prod` | public sinon |
|
||||
|
||||
|
||||
@@ -21,11 +21,19 @@ from app.core.roles import AccountKind, Role, has_at_least
|
||||
from app.core.security import TokenExpiredError, TokenInvalidError, TokenPolicy
|
||||
from app.core.security import decode_access_token as decode_token
|
||||
from app.db.session import get_session
|
||||
from app.repositories.alert import AlertRepository
|
||||
from app.repositories.audit_log import AuditLogRepository
|
||||
from app.repositories.login_attempt import LoginAttemptRepository
|
||||
from app.repositories.reading import ReadingRepository
|
||||
from app.repositories.recommendation import RecommendationRepository
|
||||
from app.repositories.refresh_token import RefreshTokenRepository
|
||||
from app.repositories.site import SiteRepository
|
||||
from app.repositories.user import UserRepository
|
||||
from app.services.alert import AlertService
|
||||
from app.services.auth import AuthService, LoginPolicy
|
||||
from app.services.recommendation import RecommendationService
|
||||
from app.services.site import SiteService
|
||||
from app.services.stats import StatsService
|
||||
from app.services.user import UserService
|
||||
|
||||
SessionDep = Annotated[AsyncSession, Depends(get_session)]
|
||||
@@ -131,6 +139,34 @@ def get_user_service(
|
||||
UserServiceDep = Annotated[UserService, Depends(get_user_service)]
|
||||
|
||||
|
||||
def get_site_service(session: SessionDep) -> SiteService:
|
||||
return SiteService(sites=SiteRepository(session))
|
||||
|
||||
|
||||
SiteServiceDep = Annotated[SiteService, Depends(get_site_service)]
|
||||
|
||||
|
||||
def get_alert_service(session: SessionDep) -> AlertService:
|
||||
return AlertService(alerts=AlertRepository(session))
|
||||
|
||||
|
||||
AlertServiceDep = Annotated[AlertService, Depends(get_alert_service)]
|
||||
|
||||
|
||||
def get_recommendation_service(session: SessionDep) -> RecommendationService:
|
||||
return RecommendationService(recommendations=RecommendationRepository(session))
|
||||
|
||||
|
||||
RecommendationServiceDep = Annotated[RecommendationService, Depends(get_recommendation_service)]
|
||||
|
||||
|
||||
def get_stats_service(session: SessionDep) -> StatsService:
|
||||
return StatsService(sites=SiteRepository(session), readings=ReadingRepository(session))
|
||||
|
||||
|
||||
StatsServiceDep = Annotated[StatsService, Depends(get_stats_service)]
|
||||
|
||||
|
||||
async def get_current_principal(
|
||||
credentials: CredentialsDep,
|
||||
session: SessionDep,
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
# Piège : `cookie_de_rafraichissement` est purement documentaire, d'où son `auto_error=False`.
|
||||
# Avec la valeur par défaut, FastAPI répondrait 403 avant d'atteindre `lit_le_cookie()`, et
|
||||
# `/auth/refresh` cesserait de rendre le 401 que le frontend attend.
|
||||
|
||||
from typing import Any, Final
|
||||
|
||||
from fastapi.security import APIKeyCookie
|
||||
|
||||
from app.core.config import REFRESH_COOKIE_DEFAUT
|
||||
from app.schemas.errors import ErrorResponse, InternalErrorResponse, ValidationErrorResponse
|
||||
|
||||
Reponses = dict[int | str, dict[str, Any]]
|
||||
|
||||
SUMMARY: Final = "Collecte, analyse et restitution de séries temporelles énergétiques."
|
||||
|
||||
DESCRIPTION: Final = """
|
||||
Toutes les routes sont préfixées par `/api/v1`.
|
||||
|
||||
**Authentification.** Le jeton d'accès se présente dans l'en-tête `Authorization: Bearer ...`.
|
||||
Le jeton de rafraîchissement est un cookie `HttpOnly` que le code client ne voit jamais : il
|
||||
suffit d'émettre les requêtes avec les identifiants de session. `POST /auth/refresh` rend un
|
||||
nouveau jeton d'accès et fait tourner le cookie.
|
||||
|
||||
**Rôles.** `lecteur`, puis `operateur`, puis `admin`. Chaque rôle couvre les droits du
|
||||
précédent.
|
||||
|
||||
**Erreurs.** Le corps porte toujours une clé `detail`. Un `403` dont le `detail` vaut
|
||||
`password_change_required` n'est pas un refus de droits : il exige le changement du mot de passe
|
||||
provisoire avant toute autre action.
|
||||
|
||||
Le parcours de session complet est décrit dans
|
||||
`docs/architecture/31-contrat-authentification.md`.
|
||||
"""
|
||||
|
||||
TAGS: Final[list[dict[str, Any]]] = [
|
||||
{
|
||||
"name": "health",
|
||||
"description": (
|
||||
"Sondes d'infrastructure, publiques. `live` prouve que le processus répond, `ready` "
|
||||
"que la base répond et que l'extension TimescaleDB est chargée."
|
||||
),
|
||||
},
|
||||
{
|
||||
"name": "auth",
|
||||
"description": (
|
||||
"Ouverture, rotation et fermeture de session, et changement de son propre mot de passe."
|
||||
),
|
||||
},
|
||||
{
|
||||
"name": "users",
|
||||
"description": "Administration des comptes. Réservé au rôle `admin`.",
|
||||
},
|
||||
{
|
||||
"name": "sites",
|
||||
"description": "Consultation du parc de sites. Accessible à partir du rôle `lecteur`.",
|
||||
},
|
||||
{
|
||||
"name": "alerts",
|
||||
"description": "Consultation des alertes de consommation. Accessible à partir du rôle "
|
||||
"`lecteur`.",
|
||||
},
|
||||
{
|
||||
"name": "recommendations",
|
||||
"description": (
|
||||
"Consultation des recommandations issues des alertes. Accessible à partir du rôle "
|
||||
"`lecteur`."
|
||||
),
|
||||
},
|
||||
{
|
||||
"name": "stats",
|
||||
"description": "Statistiques agrégées de consommation. Accessible à partir du rôle "
|
||||
"`lecteur`.",
|
||||
},
|
||||
]
|
||||
|
||||
cookie_de_rafraichissement = APIKeyCookie(
|
||||
name=REFRESH_COOKIE_DEFAUT,
|
||||
scheme_name="Cookie de rafraîchissement",
|
||||
description=(
|
||||
"Cookie `HttpOnly` posé par `/auth/login` et tourné par `/auth/refresh`. Il prend le "
|
||||
"préfixe `__Secure-` dès que l'API tourne derrière TLS, et n'est émis que vers "
|
||||
"`/api/v1/auth`."
|
||||
),
|
||||
auto_error=False,
|
||||
)
|
||||
|
||||
# Le 422 n'est déclaré que sur les routes qui acceptent un corps ou un paramètre : ailleurs,
|
||||
# aucune validation ne peut échouer et l'annoncer serait faux.
|
||||
REPONSE_VALIDATION: Final[Reponses] = {
|
||||
422: {
|
||||
"model": ValidationErrorResponse,
|
||||
"description": (
|
||||
"Corps invalide. Le détail nomme le champ fautif et le type d'erreur, jamais la "
|
||||
"valeur envoyée."
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
REPONSE_SERVEUR: Final[Reponses] = {
|
||||
500: {
|
||||
"model": InternalErrorResponse,
|
||||
"description": (
|
||||
"Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas "
|
||||
"renvoyée au client."
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
REPONSE_INDISPONIBLE: Final[Reponses] = {
|
||||
503: {
|
||||
"model": ErrorResponse,
|
||||
"description": "Base injoignable, ou extension TimescaleDB absente de la base.",
|
||||
},
|
||||
}
|
||||
|
||||
REPONSES_AUTHENTIFIEES: Final[Reponses] = {
|
||||
401: {
|
||||
"model": ErrorResponse,
|
||||
"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=`."
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
REPONSES_ADMIN: Final[Reponses] = {
|
||||
**REPONSES_AUTHENTIFIEES,
|
||||
403: {
|
||||
"model": ErrorResponse,
|
||||
"description": (
|
||||
"Droits insuffisants, ou mot de passe provisoire à changer quand `detail` vaut "
|
||||
"`password_change_required`."
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
# `lecteur` est le rôle minimum : `require_role` n'y refuse jamais un 403 pour droits
|
||||
# insuffisants, seulement pour le mot de passe provisoire.
|
||||
REPONSES_LECTEUR: Final[Reponses] = {
|
||||
**REPONSES_AUTHENTIFIEES,
|
||||
403: {
|
||||
"model": ErrorResponse,
|
||||
"description": (
|
||||
"Mot de passe provisoire à changer (`detail` vaut `password_change_required`)."
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
REPONSE_ORIGINE_REFUSEE: Final[Reponses] = {
|
||||
403: {
|
||||
"model": ErrorResponse,
|
||||
"description": "Origine non autorisée (protection CSRF de `require_trusted_origin`).",
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api.deps import AlertServiceDep, LecteurDep
|
||||
from app.api.openapi import REPONSE_VALIDATION
|
||||
from app.schemas.alert import AlertResponse, AlertSeverity
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=list[AlertResponse],
|
||||
summary="Liste les alertes",
|
||||
responses=REPONSE_VALIDATION,
|
||||
)
|
||||
async def list_alerts(
|
||||
_: LecteurDep,
|
||||
service: AlertServiceDep,
|
||||
site_id: str | None = None,
|
||||
severity: AlertSeverity | None = None,
|
||||
) -> list[AlertResponse]:
|
||||
alertes = await service.list_all(site_id=site_id, severity=severity)
|
||||
return [AlertResponse.model_validate(alerte) for alerte in alertes]
|
||||
@@ -11,6 +11,13 @@ from app.api.deps import (
|
||||
get_client_ip,
|
||||
require_trusted_origin,
|
||||
)
|
||||
from app.api.openapi import (
|
||||
REPONSE_ORIGINE_REFUSEE,
|
||||
REPONSE_VALIDATION,
|
||||
REPONSES_AUTHENTIFIEES,
|
||||
Reponses,
|
||||
cookie_de_rafraichissement,
|
||||
)
|
||||
from app.core.cookies import RefreshCookie, cookie_name
|
||||
from app.core.logging import get_logger
|
||||
from app.schemas.auth import (
|
||||
@@ -19,6 +26,7 @@ from app.schemas.auth import (
|
||||
PrincipalResponse,
|
||||
TokenResponse,
|
||||
)
|
||||
from app.schemas.errors import ErrorResponse
|
||||
from app.services.auth import (
|
||||
AuthenticatedSession,
|
||||
InvalidCredentialsError,
|
||||
@@ -32,6 +40,51 @@ logger = get_logger(__name__)
|
||||
DETAIL_IDENTIFIANTS = "Identifiants invalides"
|
||||
DETAIL_SESSION = "Session invalide"
|
||||
|
||||
REPONSES_LOGIN: Reponses = {
|
||||
**REPONSE_VALIDATION,
|
||||
401: {
|
||||
"model": ErrorResponse,
|
||||
"description": (
|
||||
"Identifiants faux, compte inconnu ou compte désactivé. Le message est le même dans "
|
||||
"les trois cas, et n'apprend donc rien sur l'existence du compte."
|
||||
),
|
||||
},
|
||||
429: {
|
||||
"model": ErrorResponse,
|
||||
"description": "Trop de tentatives sur cette fenêtre glissante.",
|
||||
"headers": {
|
||||
"Retry-After": {
|
||||
"description": "Secondes à attendre avant une nouvelle tentative.",
|
||||
"schema": {"type": "integer"},
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
REPONSES_REFRESH: Reponses = {
|
||||
**REPONSE_ORIGINE_REFUSEE,
|
||||
401: {
|
||||
"model": ErrorResponse,
|
||||
"description": (
|
||||
"Cookie absent, session expirée, révoquée, ou jeton déjà tourné. Dans ce dernier cas "
|
||||
"toute la famille de sessions est révoquée et le cookie est effacé avec la réponse."
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
REPONSES_LOGOUT: Reponses = {**REPONSE_ORIGINE_REFUSEE}
|
||||
|
||||
REPONSES_LOGOUT_ALL: Reponses = {**REPONSES_AUTHENTIFIEES, **REPONSE_ORIGINE_REFUSEE}
|
||||
|
||||
REPONSES_MOT_DE_PASSE: Reponses = {
|
||||
**REPONSE_VALIDATION,
|
||||
**REPONSE_ORIGINE_REFUSEE,
|
||||
401: {
|
||||
"model": ErrorResponse,
|
||||
"description": "Jeton d'accès invalide, ou mot de passe courant faux.",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def repond(
|
||||
response: Response, settings: SettingsDep, session: AuthenticatedSession
|
||||
@@ -61,7 +114,12 @@ def lit_le_cookie(request: Request, settings: SettingsDep) -> str:
|
||||
return secret
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenResponse, summary="Ouvre une session")
|
||||
@router.post(
|
||||
"/login",
|
||||
response_model=TokenResponse,
|
||||
summary="Ouvre une session",
|
||||
responses=REPONSES_LOGIN,
|
||||
)
|
||||
async def login(
|
||||
payload: LoginRequest,
|
||||
request: Request,
|
||||
@@ -98,7 +156,8 @@ async def login(
|
||||
"/refresh",
|
||||
response_model=TokenResponse,
|
||||
summary="Fait tourner la session",
|
||||
dependencies=[Depends(require_trusted_origin)],
|
||||
dependencies=[Depends(require_trusted_origin), Depends(cookie_de_rafraichissement)],
|
||||
responses=REPONSES_REFRESH,
|
||||
)
|
||||
async def refresh(
|
||||
request: Request,
|
||||
@@ -133,7 +192,8 @@ async def refresh(
|
||||
"/logout",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
summary="Ferme la session courante",
|
||||
dependencies=[Depends(require_trusted_origin)],
|
||||
dependencies=[Depends(require_trusted_origin), Depends(cookie_de_rafraichissement)],
|
||||
responses=REPONSES_LOGOUT,
|
||||
)
|
||||
async def logout(
|
||||
request: Request, response: Response, settings: SettingsDep, service: AuthServiceDep
|
||||
@@ -150,6 +210,7 @@ async def logout(
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
summary="Ferme toutes les sessions du compte",
|
||||
dependencies=[Depends(require_trusted_origin)],
|
||||
responses=REPONSES_LOGOUT_ALL,
|
||||
)
|
||||
async def logout_all(
|
||||
principal: CurrentPrincipalDep,
|
||||
@@ -163,7 +224,12 @@ async def logout_all(
|
||||
response.delete_cookie(**RefreshCookie.expired(settings).as_deletion_kwargs())
|
||||
|
||||
|
||||
@router.get("/me", response_model=PrincipalResponse, summary="Décrit le compte connecté")
|
||||
@router.get(
|
||||
"/me",
|
||||
response_model=PrincipalResponse,
|
||||
summary="Décrit le compte connecté",
|
||||
responses=REPONSES_AUTHENTIFIEES,
|
||||
)
|
||||
async def me(principal: CurrentPrincipalDep) -> PrincipalResponse:
|
||||
return PrincipalResponse.from_principal(principal)
|
||||
|
||||
@@ -173,6 +239,7 @@ async def me(principal: CurrentPrincipalDep) -> PrincipalResponse:
|
||||
response_model=TokenResponse,
|
||||
summary="Change son propre mot de passe",
|
||||
dependencies=[Depends(require_trusted_origin)],
|
||||
responses=REPONSES_MOT_DE_PASSE,
|
||||
)
|
||||
async def change_password(
|
||||
payload: PasswordChangeRequest,
|
||||
|
||||
@@ -3,16 +3,17 @@ from sqlalchemy import text
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from app.api.deps import SessionDep, SettingsDep
|
||||
from app.api.openapi import REPONSE_INDISPONIBLE
|
||||
from app.core.logging import get_logger
|
||||
from app.schemas.health import LivenessStatus, ReadinessStatus
|
||||
|
||||
logger = get_logger(__name__)
|
||||
router = APIRouter(tags=["health"])
|
||||
router = APIRouter()
|
||||
|
||||
TIMESCALEDB_VERSION = text("SELECT extversion FROM pg_extension WHERE extname = 'timescaledb'")
|
||||
|
||||
|
||||
@router.get("/live", summary="Sonde de vivacite")
|
||||
@router.get("/live", summary="Sonde de vivacité")
|
||||
async def liveness(settings: SettingsDep) -> LivenessStatus:
|
||||
return LivenessStatus(
|
||||
status="ok",
|
||||
@@ -22,11 +23,13 @@ async def liveness(settings: SettingsDep) -> LivenessStatus:
|
||||
)
|
||||
|
||||
|
||||
@router.get("/ready", summary="Sonde de disponibilite")
|
||||
@router.get("/ready", summary="Sonde de disponibilité", responses=REPONSE_INDISPONIBLE)
|
||||
async def readiness(session: SessionDep) -> ReadinessStatus:
|
||||
try:
|
||||
version: str | None = await session.scalar(TIMESCALEDB_VERSION)
|
||||
except SQLAlchemyError, OSError:
|
||||
# `# fmt: skip` contourne un bug de ruff format 0.16.7 : il retire les parenthèses de ce
|
||||
# `except` à deux types, ce qui produit une syntaxe invalide (`except A, B:`).
|
||||
except (SQLAlchemyError, OSError): # fmt: skip
|
||||
logger.exception("Base de données injoignable")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
|
||||
from app.api.deps import LecteurDep, RecommendationServiceDep
|
||||
from app.api.openapi import REPONSE_VALIDATION, Reponses
|
||||
from app.schemas.errors import ErrorResponse
|
||||
from app.schemas.recommendation import RecommendationResponse
|
||||
from app.services.recommendation import RecommendationNotFoundError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
REPONSES_INTROUVABLE: Reponses = {
|
||||
**REPONSE_VALIDATION,
|
||||
404: {"model": ErrorResponse, "description": "Aucune recommandation ne porte cet identifiant."},
|
||||
}
|
||||
|
||||
|
||||
@router.get("", response_model=list[RecommendationResponse], summary="Liste les recommandations")
|
||||
async def list_recommendations(
|
||||
_: LecteurDep, service: RecommendationServiceDep
|
||||
) -> list[RecommendationResponse]:
|
||||
recommendations = await service.list_all()
|
||||
return [RecommendationResponse.model_validate(r) for r in recommendations]
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{recommendation_id}",
|
||||
response_model=RecommendationResponse,
|
||||
summary="Décrit une recommandation",
|
||||
responses=REPONSES_INTROUVABLE,
|
||||
)
|
||||
async def get_recommendation(
|
||||
recommendation_id: int, _: LecteurDep, service: RecommendationServiceDep
|
||||
) -> RecommendationResponse:
|
||||
try:
|
||||
recommendation = await service.get_by_id(recommendation_id)
|
||||
except RecommendationNotFoundError as erreur:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="Recommandation introuvable"
|
||||
) from erreur
|
||||
return RecommendationResponse.model_validate(recommendation)
|
||||
@@ -0,0 +1,36 @@
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
|
||||
from app.api.deps import LecteurDep, SiteServiceDep
|
||||
from app.api.openapi import REPONSE_VALIDATION, Reponses
|
||||
from app.schemas.errors import ErrorResponse
|
||||
from app.schemas.site import SiteResponse
|
||||
from app.services.site import SiteNotFoundError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
REPONSES_INTROUVABLE: Reponses = {
|
||||
**REPONSE_VALIDATION,
|
||||
404: {"model": ErrorResponse, "description": "Aucun site ne porte cet identifiant."},
|
||||
}
|
||||
|
||||
|
||||
@router.get("", response_model=list[SiteResponse], summary="Liste les sites")
|
||||
async def list_sites(_: LecteurDep, service: SiteServiceDep) -> list[SiteResponse]:
|
||||
sites = await service.list_all()
|
||||
return [SiteResponse.model_validate(site) for site in sites]
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{site_id}",
|
||||
response_model=SiteResponse,
|
||||
summary="Décrit un site",
|
||||
responses=REPONSES_INTROUVABLE,
|
||||
)
|
||||
async def get_site(site_id: str, _: LecteurDep, service: SiteServiceDep) -> SiteResponse:
|
||||
try:
|
||||
site = await service.get_by_id(site_id)
|
||||
except SiteNotFoundError as erreur:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="Site introuvable"
|
||||
) from erreur
|
||||
return SiteResponse.model_validate(site)
|
||||
@@ -0,0 +1,16 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api.deps import LecteurDep, StatsServiceDep
|
||||
from app.schemas.stats import StatsSummaryResponse
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get(
|
||||
"/summary",
|
||||
response_model=StatsSummaryResponse,
|
||||
summary="Résume la consommation instantanée du parc",
|
||||
)
|
||||
async def get_summary(_: LecteurDep, service: StatsServiceDep) -> StatsSummaryResponse:
|
||||
resume = await service.summary()
|
||||
return StatsSummaryResponse.model_validate(resume)
|
||||
@@ -3,7 +3,9 @@ from uuid import UUID
|
||||
from fastapi import APIRouter, HTTPException, Response, status
|
||||
|
||||
from app.api.deps import AdminDep, UserServiceDep
|
||||
from app.api.openapi import REPONSE_VALIDATION, Reponses
|
||||
from app.core.logging import get_logger
|
||||
from app.schemas.errors import ErrorResponse
|
||||
from app.schemas.user import (
|
||||
TemporaryPasswordResponse,
|
||||
UserCreateRequest,
|
||||
@@ -15,6 +17,28 @@ from app.services.user import EmailAlreadyUsedError, LastAdminError, UserNotFoun
|
||||
router = APIRouter()
|
||||
logger = get_logger(__name__)
|
||||
|
||||
REPONSES_CREATION: Reponses = {
|
||||
**REPONSE_VALIDATION,
|
||||
409: {"model": ErrorResponse, "description": "Adresse déjà portée par un autre compte."},
|
||||
}
|
||||
|
||||
REPONSES_INTROUVABLE: Reponses = {
|
||||
**REPONSE_VALIDATION,
|
||||
404: {"model": ErrorResponse, "description": "Aucun compte ne porte cet identifiant."},
|
||||
}
|
||||
|
||||
REPONSES_MODIFICATION: Reponses = {
|
||||
**REPONSES_INTROUVABLE,
|
||||
400: {"model": ErrorResponse, "description": "Corps vide, aucune modification demandée."},
|
||||
409: {
|
||||
"model": ErrorResponse,
|
||||
"description": (
|
||||
"L'opération laisserait la plateforme sans administrateur actif, qu'il s'agisse de "
|
||||
"rétrograder le dernier ou de le désactiver."
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("", response_model=list[UserResponse], summary="Liste les comptes")
|
||||
async def list_users(_: AdminDep, service: UserServiceDep) -> list[UserResponse]:
|
||||
@@ -27,6 +51,7 @@ async def list_users(_: AdminDep, service: UserServiceDep) -> list[UserResponse]
|
||||
response_model=TemporaryPasswordResponse,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Crée un compte avec un mot de passe provisoire",
|
||||
responses=REPONSES_CREATION,
|
||||
)
|
||||
async def create_user(
|
||||
payload: UserCreateRequest,
|
||||
@@ -55,7 +80,12 @@ async def create_user(
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/{user_id}", response_model=UserResponse, summary="Change le rôle ou l'activation")
|
||||
@router.patch(
|
||||
"/{user_id}",
|
||||
response_model=UserResponse,
|
||||
summary="Change le rôle ou l'activation",
|
||||
responses=REPONSES_MODIFICATION,
|
||||
)
|
||||
async def update_user(
|
||||
user_id: UUID,
|
||||
payload: UserUpdateRequest,
|
||||
@@ -92,6 +122,7 @@ async def update_user(
|
||||
"/{user_id}/password-reset",
|
||||
response_model=TemporaryPasswordResponse,
|
||||
summary="Réinitialise le mot de passe et ferme les sessions",
|
||||
responses=REPONSES_INTROUVABLE,
|
||||
)
|
||||
async def reset_password(
|
||||
user_id: UUID, acteur: AdminDep, service: UserServiceDep, response: Response
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api.v1.endpoints import auth, health, users
|
||||
from app.api.openapi import REPONSE_SERVEUR, REPONSES_ADMIN, REPONSES_LECTEUR
|
||||
from app.api.v1.endpoints import alerts, auth, health, recommendations, sites, stats, users
|
||||
|
||||
api_router = APIRouter()
|
||||
api_router = APIRouter(responses=REPONSE_SERVEUR)
|
||||
api_router.include_router(health.router, prefix="/health", tags=["health"])
|
||||
api_router.include_router(auth.router, prefix="/auth", tags=["auth"])
|
||||
api_router.include_router(users.router, prefix="/users", tags=["users"])
|
||||
api_router.include_router(users.router, prefix="/users", tags=["users"], responses=REPONSES_ADMIN)
|
||||
api_router.include_router(sites.router, prefix="/sites", tags=["sites"], responses=REPONSES_LECTEUR)
|
||||
api_router.include_router(
|
||||
alerts.router, prefix="/alerts", tags=["alerts"], responses=REPONSES_LECTEUR
|
||||
)
|
||||
api_router.include_router(
|
||||
recommendations.router,
|
||||
prefix="/recommendations",
|
||||
tags=["recommendations"],
|
||||
responses=REPONSES_LECTEUR,
|
||||
)
|
||||
api_router.include_router(stats.router, prefix="/stats", tags=["stats"], responses=REPONSES_LECTEUR)
|
||||
|
||||
@@ -7,18 +7,25 @@
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import secrets
|
||||
import sys
|
||||
from getpass import getpass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from pydantic import SecretStr
|
||||
|
||||
from app.core.config import Settings, get_settings
|
||||
from app.core.hashing import build_hasher
|
||||
from app.core.roles import Role
|
||||
from app.db.session import get_session_factory
|
||||
from app.main import create_app
|
||||
from app.repositories.user import UserRepository
|
||||
|
||||
LONGUEUR_MOT_DE_PASSE_GENERE = 24
|
||||
LONGUEUR_MINIMALE = 12
|
||||
CHEMIN_CONTRAT = Path(__file__).resolve().parent.parent / "openapi.json"
|
||||
|
||||
|
||||
async def create_admin(
|
||||
@@ -55,6 +62,35 @@ async def create_admin(
|
||||
)
|
||||
|
||||
|
||||
# Piège : le schéma ne doit dépendre ni du `.env` du poste ni des variables `APP_*`, sinon le
|
||||
# fichier versionné changerait de machine en machine et le test de dérive deviendrait un oracle
|
||||
# de configuration locale. Tout ce qui atteint le schéma est donc posé ici, `_env_file` compris.
|
||||
def settings_du_contrat() -> Settings:
|
||||
return Settings(
|
||||
_env_file=None,
|
||||
name="EnerVision API",
|
||||
version="0.1.0",
|
||||
env="local",
|
||||
api_prefix="/api/v1",
|
||||
secret_key=SecretStr("contrat-openapi-sans-effet-sur-le-schema"),
|
||||
database_url="postgresql+asyncpg://openapi:contrat@localhost:5432/enervision",
|
||||
)
|
||||
|
||||
|
||||
def schema_du_contrat() -> dict[str, Any]:
|
||||
schema: dict[str, Any] = create_app(settings_du_contrat()).openapi()
|
||||
return schema
|
||||
|
||||
|
||||
def rend_le_contrat() -> str:
|
||||
return json.dumps(schema_du_contrat(), indent=2, ensure_ascii=False) + "\n"
|
||||
|
||||
|
||||
def export_openapi(destination: Path) -> str:
|
||||
destination.write_text(rend_le_contrat(), encoding="utf-8")
|
||||
return f"Contrat OpenAPI écrit dans {destination}"
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(prog="python -m app.cli", description="Outils EnerVision")
|
||||
sous_commandes = parser.add_subparsers(dest="commande", required=True)
|
||||
@@ -67,6 +103,11 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
admin.add_argument(
|
||||
"--force", action="store_true", help="Crée le compte même si un administrateur existe"
|
||||
)
|
||||
|
||||
contrat = sous_commandes.add_parser(
|
||||
"export-openapi", help="Écrit le contrat OpenAPI sur disque"
|
||||
)
|
||||
contrat.add_argument("--output", default=str(CHEMIN_CONTRAT))
|
||||
return parser
|
||||
|
||||
|
||||
@@ -86,6 +127,11 @@ def read_password(*, generate: bool) -> str:
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
arguments = build_parser().parse_args(argv)
|
||||
|
||||
if arguments.commande == "export-openapi":
|
||||
print(export_openapi(Path(arguments.output)))
|
||||
return 0
|
||||
|
||||
mot_de_passe = read_password(generate=arguments.generate)
|
||||
|
||||
succes, message = asyncio.run(
|
||||
|
||||
@@ -8,6 +8,7 @@ Environment = Literal["local", "dev", "staging", "prod"]
|
||||
SameSite = Literal["lax", "strict", "none"]
|
||||
|
||||
SECRET_KEY_MIN_LENGTH = 32
|
||||
REFRESH_COOKIE_DEFAUT = "ev_refresh"
|
||||
SENTINELLES_INTERDITES = frozenset(
|
||||
{"change_me", "changeme", "secret", "secret-de-test", "changez-moi", "todo"}
|
||||
)
|
||||
@@ -38,7 +39,7 @@ class Settings(BaseSettings):
|
||||
access_token_ttl_seconds: int = Field(default=900, ge=60, le=3600)
|
||||
refresh_token_ttl_seconds: int = Field(default=604800, ge=3600, le=2592000)
|
||||
|
||||
refresh_cookie_name: str = "ev_refresh"
|
||||
refresh_cookie_name: str = REFRESH_COOKIE_DEFAUT
|
||||
cookie_path: str = "/api/v1/auth"
|
||||
cookie_samesite: SameSite = "strict"
|
||||
cookie_secure: bool | None = None
|
||||
|
||||
@@ -7,6 +7,7 @@ from prometheus_fastapi_instrumentator import Instrumentator
|
||||
|
||||
from app.api.errors import register_error_handlers
|
||||
from app.api.middleware import SecurityHeadersMiddleware
|
||||
from app.api.openapi import DESCRIPTION, SUMMARY, TAGS
|
||||
from app.api.security import require_metrics_token
|
||||
from app.api.v1.router import api_router
|
||||
from app.core.config import Settings, get_settings
|
||||
@@ -37,6 +38,9 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
application = FastAPI(
|
||||
title=resolved.name,
|
||||
version=resolved.version,
|
||||
summary=SUMMARY,
|
||||
description=DESCRIPTION,
|
||||
openapi_tags=TAGS,
|
||||
debug=resolved.debug,
|
||||
lifespan=lifespan,
|
||||
docs_url="/docs" if documentee else None,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
from collections.abc import Sequence
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.energy import Alert
|
||||
|
||||
|
||||
class AlertRepository:
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self._session = session
|
||||
|
||||
async def list_all(
|
||||
self, *, site_id: str | None = None, severity: str | None = None
|
||||
) -> Sequence[Alert]:
|
||||
requete = select(Alert).order_by(Alert.timestamp.desc(), Alert.alert_id.desc())
|
||||
if site_id is not None:
|
||||
requete = requete.where(Alert.site_id == site_id)
|
||||
if severity is not None:
|
||||
requete = requete.where(Alert.severity == severity)
|
||||
return (await self._session.scalars(requete)).all()
|
||||
@@ -0,0 +1,21 @@
|
||||
from collections.abc import Sequence
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.energy import Reading
|
||||
|
||||
|
||||
class ReadingRepository:
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self._session = session
|
||||
|
||||
async def latest_by_site(self) -> Sequence[Reading]:
|
||||
# `.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.
|
||||
requete = (
|
||||
select(Reading)
|
||||
.distinct(Reading.site_id)
|
||||
.order_by(Reading.site_id, Reading.timestamp.desc())
|
||||
)
|
||||
return (await self._session.execute(requete)).scalars().all()
|
||||
@@ -0,0 +1,22 @@
|
||||
from collections.abc import Sequence
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.energy import Recommendation
|
||||
|
||||
|
||||
class RecommendationRepository:
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self._session = session
|
||||
|
||||
async def list_all(self) -> Sequence[Recommendation]:
|
||||
requete = select(Recommendation).order_by(Recommendation.recommendation_id)
|
||||
return (await self._session.scalars(requete)).all()
|
||||
|
||||
async def get_by_id(self, recommendation_id: int) -> Recommendation | None:
|
||||
requete = select(Recommendation).where(
|
||||
Recommendation.recommendation_id == recommendation_id
|
||||
)
|
||||
recommendation: Recommendation | None = await self._session.scalar(requete)
|
||||
return recommendation
|
||||
@@ -0,0 +1,20 @@
|
||||
from collections.abc import Sequence
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.energy import Site
|
||||
|
||||
|
||||
class SiteRepository:
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self._session = session
|
||||
|
||||
async def list_all(self) -> Sequence[Site]:
|
||||
requete = select(Site).order_by(Site.site_id)
|
||||
return (await self._session.scalars(requete)).all()
|
||||
|
||||
async def get_by_id(self, site_id: str) -> Site | None:
|
||||
requete = select(Site).where(Site.site_id == site_id)
|
||||
site: Site | None = await self._session.scalar(requete)
|
||||
return site
|
||||
@@ -0,0 +1,34 @@
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
|
||||
class AlertType(StrEnum):
|
||||
SPIKE = "spike"
|
||||
THRESHOLD = "threshold"
|
||||
ANOMALY = "anomaly"
|
||||
OUTAGE = "outage"
|
||||
SENSOR = "sensor"
|
||||
|
||||
|
||||
class AlertSeverity(StrEnum):
|
||||
LOW = "low"
|
||||
MEDIUM = "medium"
|
||||
HIGH = "high"
|
||||
CRITICAL = "critical"
|
||||
|
||||
|
||||
class AlertResponse(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
alert_id: int
|
||||
site_id: str
|
||||
timestamp: datetime
|
||||
type: AlertType
|
||||
severity: AlertSeverity
|
||||
message: str
|
||||
value: float | None
|
||||
threshold: float | None
|
||||
metric: str | None
|
||||
prediction_id: int | None
|
||||
@@ -0,0 +1,23 @@
|
||||
# Piège : ces modèles ne décrivent rien, ils publient. Ce sont eux que Swagger montre, donc ils
|
||||
# doivent suivre `validation_error_handler()` et `unhandled_error_handler()` d'`app/api/errors.py`
|
||||
# à la lettre. Un champ renommé là-bas sans l'être ici rend la documentation fausse en silence.
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class ErrorResponse(BaseModel):
|
||||
detail: str
|
||||
|
||||
|
||||
class FieldError(BaseModel):
|
||||
champ: str
|
||||
type: str
|
||||
|
||||
|
||||
class ValidationErrorResponse(BaseModel):
|
||||
detail: list[FieldError]
|
||||
|
||||
|
||||
class InternalErrorResponse(BaseModel):
|
||||
detail: str
|
||||
correlation: str
|
||||
@@ -0,0 +1,14 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
|
||||
class RecommendationResponse(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
recommendation_id: int
|
||||
alert_id: int
|
||||
action: str
|
||||
explanation: str
|
||||
rule_reference: str
|
||||
created_at: datetime
|
||||
@@ -0,0 +1,12 @@
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
|
||||
class SiteResponse(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
site_id: str
|
||||
site_name: str
|
||||
site_type: str
|
||||
location: str | None
|
||||
capacity_kw: float | None
|
||||
status: str | None
|
||||
@@ -0,0 +1,26 @@
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
|
||||
class SiteSummaryResponse(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
site_id: str
|
||||
site_name: str
|
||||
current_consumption_kw: float | None
|
||||
capacity_kw: float
|
||||
load_percent: float | None
|
||||
data_quality: Literal["good", "partial", "degraded", "critical"]
|
||||
|
||||
|
||||
class StatsSummaryResponse(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
timestamp: datetime
|
||||
total_sites: int
|
||||
total_consumption_kw: float
|
||||
total_capacity_kw: float
|
||||
average_load_percent: float
|
||||
sites: list[SiteSummaryResponse]
|
||||
@@ -0,0 +1,14 @@
|
||||
from collections.abc import Sequence
|
||||
|
||||
from app.models.energy import Alert
|
||||
from app.repositories.alert import AlertRepository
|
||||
|
||||
|
||||
class AlertService:
|
||||
def __init__(self, *, alerts: AlertRepository) -> None:
|
||||
self._alerts = alerts
|
||||
|
||||
async def list_all(
|
||||
self, *, site_id: str | None = None, severity: str | None = None
|
||||
) -> Sequence[Alert]:
|
||||
return await self._alerts.list_all(site_id=site_id, severity=severity)
|
||||
@@ -0,0 +1,26 @@
|
||||
from collections.abc import Sequence
|
||||
|
||||
from app.models.energy import Recommendation
|
||||
from app.repositories.recommendation import RecommendationRepository
|
||||
|
||||
|
||||
class RecommendationError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class RecommendationNotFoundError(RecommendationError):
|
||||
pass
|
||||
|
||||
|
||||
class RecommendationService:
|
||||
def __init__(self, *, recommendations: RecommendationRepository) -> None:
|
||||
self._recommendations = recommendations
|
||||
|
||||
async def list_all(self) -> Sequence[Recommendation]:
|
||||
return await self._recommendations.list_all()
|
||||
|
||||
async def get_by_id(self, recommendation_id: int) -> Recommendation:
|
||||
recommendation = await self._recommendations.get_by_id(recommendation_id)
|
||||
if recommendation is None:
|
||||
raise RecommendationNotFoundError(recommendation_id)
|
||||
return recommendation
|
||||
@@ -0,0 +1,26 @@
|
||||
from collections.abc import Sequence
|
||||
|
||||
from app.models.energy import Site
|
||||
from app.repositories.site import SiteRepository
|
||||
|
||||
|
||||
class SiteError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class SiteNotFoundError(SiteError):
|
||||
pass
|
||||
|
||||
|
||||
class SiteService:
|
||||
def __init__(self, *, sites: SiteRepository) -> None:
|
||||
self._sites = sites
|
||||
|
||||
async def list_all(self) -> Sequence[Site]:
|
||||
return await self._sites.list_all()
|
||||
|
||||
async def get_by_id(self, site_id: str) -> Site:
|
||||
site = await self._sites.get_by_id(site_id)
|
||||
if site is None:
|
||||
raise SiteNotFoundError(site_id)
|
||||
return site
|
||||
@@ -0,0 +1,81 @@
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from typing import Literal
|
||||
|
||||
from app.models.energy import Reading, Site
|
||||
from app.repositories.reading import ReadingRepository
|
||||
from app.repositories.site import SiteRepository
|
||||
|
||||
DataQuality = Literal["good", "partial", "degraded", "critical"]
|
||||
|
||||
QUALITES_CONNUES: frozenset[str] = frozenset({"good", "partial", "degraded", "critical"})
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SiteConsumption:
|
||||
site_id: str
|
||||
site_name: str
|
||||
current_consumption_kw: float | None
|
||||
capacity_kw: float
|
||||
load_percent: float | None
|
||||
data_quality: DataQuality
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ConsumptionSummary:
|
||||
timestamp: datetime
|
||||
total_sites: int
|
||||
total_consumption_kw: float
|
||||
total_capacity_kw: float
|
||||
average_load_percent: float
|
||||
sites: list[SiteConsumption]
|
||||
|
||||
|
||||
class StatsService:
|
||||
def __init__(self, sites: SiteRepository, readings: ReadingRepository) -> None:
|
||||
self._sites = sites
|
||||
self._readings = readings
|
||||
|
||||
async def summary(self) -> ConsumptionSummary:
|
||||
sites = await self._sites.list_all()
|
||||
dernieres = {lecture.site_id: lecture for lecture in await self._readings.latest_by_site()}
|
||||
|
||||
resumes = [self._resume_site(site, dernieres.get(site.site_id)) for site in sites]
|
||||
consommation_totale = sum(r.current_consumption_kw or 0 for r in resumes)
|
||||
capacite_totale = sum(r.capacity_kw for r in resumes)
|
||||
|
||||
return ConsumptionSummary(
|
||||
timestamp=datetime.now(UTC),
|
||||
total_sites=len(resumes),
|
||||
total_consumption_kw=consommation_totale,
|
||||
total_capacity_kw=capacite_totale,
|
||||
average_load_percent=(
|
||||
consommation_totale / capacite_totale * 100 if capacite_totale > 0 else 0
|
||||
),
|
||||
sites=resumes,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _resume_site(site: Site, derniere: Reading | None) -> SiteConsumption:
|
||||
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"
|
||||
consommation = None
|
||||
if derniere is not None and derniere.data_quality in QUALITES_CONNUES:
|
||||
qualite = derniere.data_quality # type: ignore[assignment]
|
||||
consommation = derniere.consumption_kw
|
||||
|
||||
charge = (
|
||||
consommation / capacite * 100 if consommation is not None and capacite > 0 else None
|
||||
)
|
||||
|
||||
return SiteConsumption(
|
||||
site_id=site.site_id,
|
||||
site_name=site.site_name,
|
||||
current_consumption_kw=consommation,
|
||||
capacity_kw=capacite,
|
||||
load_percent=charge,
|
||||
data_quality=qualite,
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,137 @@
|
||||
from collections.abc import Callable, Iterator
|
||||
from datetime import UTC, datetime
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from httpx import AsyncClient
|
||||
|
||||
from app.api.deps import get_alert_service, get_current_principal
|
||||
from app.core.principal import Principal
|
||||
from app.core.roles import AccountKind, Role
|
||||
from app.models.energy import Alert
|
||||
from app.schemas.alert import AlertSeverity
|
||||
|
||||
|
||||
def principal(role: Role = Role.LECTEUR) -> Principal:
|
||||
return Principal(
|
||||
id=uuid4(),
|
||||
email=f"{role.value}@enervision.fr",
|
||||
role=role,
|
||||
kind=AccountKind.HUMAIN,
|
||||
must_change_password=False,
|
||||
)
|
||||
|
||||
|
||||
def alert(alert_id: int = 1, site_id: str = "site-1", severity: str = "high") -> Alert:
|
||||
return Alert(
|
||||
alert_id=alert_id,
|
||||
source_alert_id=f"ALR-{alert_id}",
|
||||
site_id=site_id,
|
||||
source="enervision",
|
||||
timestamp=datetime(2026, 9, 16, tzinfo=UTC),
|
||||
type="threshold",
|
||||
severity=severity,
|
||||
message="Dépassement du seuil configuré",
|
||||
value=812.5,
|
||||
threshold=720.0,
|
||||
metric="consumption_kw",
|
||||
prediction_id=None,
|
||||
raw_data={},
|
||||
)
|
||||
|
||||
|
||||
class FauxService:
|
||||
def __init__(self) -> None:
|
||||
self.alert = alert()
|
||||
self.appels: list[tuple[str | None, str | None]] = []
|
||||
|
||||
async def list_all(
|
||||
self, *, site_id: str | None = None, severity: str | None = None
|
||||
) -> list[Alert]:
|
||||
self.appels.append((site_id, severity))
|
||||
return [self.alert]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def lecteur_connecte(app: FastAPI) -> Iterator[None]:
|
||||
app.dependency_overrides[get_current_principal] = lambda: principal()
|
||||
yield
|
||||
app.dependency_overrides.pop(get_current_principal, None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def servi(app: FastAPI, lecteur_connecte: None) -> Iterator[Callable[[], FauxService]]:
|
||||
def installe() -> FauxService:
|
||||
service = FauxService()
|
||||
app.dependency_overrides[get_alert_service] = lambda: service
|
||||
return service
|
||||
|
||||
yield installe
|
||||
app.dependency_overrides.pop(get_alert_service, None)
|
||||
|
||||
|
||||
async def test_list_alerts_returns_the_alerts(
|
||||
servi: Callable[[], FauxService], client: AsyncClient
|
||||
) -> None:
|
||||
servi()
|
||||
|
||||
response = await client.get("/api/v1/alerts")
|
||||
|
||||
assert response.status_code == 200
|
||||
corps = response.json()
|
||||
assert corps == [
|
||||
{
|
||||
"alert_id": 1,
|
||||
"site_id": "site-1",
|
||||
"timestamp": "2026-09-16T00:00:00Z",
|
||||
"type": "threshold",
|
||||
"severity": "high",
|
||||
"message": "Dépassement du seuil configuré",
|
||||
"value": 812.5,
|
||||
"threshold": 720.0,
|
||||
"metric": "consumption_kw",
|
||||
"prediction_id": None,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
async def test_list_alerts_transmits_the_site_id_filter(
|
||||
servi: Callable[[], FauxService], client: AsyncClient
|
||||
) -> None:
|
||||
service = servi()
|
||||
|
||||
await client.get("/api/v1/alerts?site_id=site-1")
|
||||
|
||||
assert service.appels == [("site-1", None)]
|
||||
|
||||
|
||||
async def test_list_alerts_transmits_the_severity_filter(
|
||||
servi: Callable[[], FauxService], client: AsyncClient
|
||||
) -> None:
|
||||
service = servi()
|
||||
|
||||
await client.get("/api/v1/alerts?severity=critical")
|
||||
|
||||
assert service.appels == [(None, AlertSeverity.CRITICAL)]
|
||||
|
||||
|
||||
async def test_list_alerts_returns_422_for_an_unknown_severity(
|
||||
servi: Callable[[], FauxService], client: AsyncClient
|
||||
) -> None:
|
||||
servi()
|
||||
|
||||
response = await client.get("/api/v1/alerts?severity=invalide")
|
||||
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
async def test_list_alerts_returns_an_empty_list_when_there_is_nothing(
|
||||
lecteur_connecte: None, fake_session: Callable[..., None], client: AsyncClient
|
||||
) -> None:
|
||||
fake_session(result=[])
|
||||
|
||||
response = await client.get("/api/v1/alerts")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == []
|
||||
@@ -0,0 +1,123 @@
|
||||
# Pourquoi : `openapi.json` est versionné, donc une route qui change son contrat public le montre
|
||||
# dans la diff d'une pull request. `test_the_committed_contract_matches_the_generated_one` est ce
|
||||
# qui empêche le fichier de dériver du code sans que personne ne le voie.
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from app import cli
|
||||
|
||||
METHODES = {"get", "post", "patch", "put", "delete"}
|
||||
|
||||
# `/auth/logout` lit le cookie mais ne le réclame pas : sans session elle répond 204, et un 401
|
||||
# documenté y serait faux.
|
||||
SANS_REFUS = {("POST", "/api/v1/auth/logout")}
|
||||
|
||||
ORIGINE_VERIFIEE = {
|
||||
("POST", "/api/v1/auth/refresh"),
|
||||
("POST", "/api/v1/auth/logout"),
|
||||
("POST", "/api/v1/auth/logout-all"),
|
||||
("POST", "/api/v1/auth/password"),
|
||||
}
|
||||
|
||||
# Toute route derrière `require_role` (LecteurDep, OperateurDep, AdminDep) peut rendre 403 pour
|
||||
# `password_change_required`, pas seulement les routes `admin`.
|
||||
ROUTES_A_ROLE = {
|
||||
("GET", "/api/v1/users"),
|
||||
("POST", "/api/v1/users"),
|
||||
("PATCH", "/api/v1/users/{id}"),
|
||||
("POST", "/api/v1/users/{id}/password-reset"),
|
||||
("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"),
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def schema() -> dict[str, Any]:
|
||||
return cli.schema_du_contrat()
|
||||
|
||||
|
||||
def operations(schema: dict[str, Any]) -> list[tuple[str, str, dict[str, Any]]]:
|
||||
return [
|
||||
(methode.upper(), chemin, operation)
|
||||
for chemin, operations_du_chemin in schema["paths"].items()
|
||||
for methode, operation in operations_du_chemin.items()
|
||||
if methode in METHODES
|
||||
]
|
||||
|
||||
|
||||
def test_the_committed_contract_matches_the_generated_one(schema: dict[str, Any]) -> None:
|
||||
publie = json.loads(cli.CHEMIN_CONTRAT.read_text(encoding="utf-8"))
|
||||
|
||||
assert publie == schema, "lancer `make openapi` et versionner le fichier obtenu"
|
||||
|
||||
|
||||
def test_every_route_demanding_an_identity_says_how_it_refuses(schema: dict[str, Any]) -> None:
|
||||
muettes = [
|
||||
(methode, chemin)
|
||||
for methode, chemin, operation in operations(schema)
|
||||
if operation.get("security")
|
||||
and (methode, chemin) not in SANS_REFUS
|
||||
and "401" not in operation["responses"]
|
||||
]
|
||||
|
||||
assert muettes == []
|
||||
|
||||
|
||||
def test_every_role_guarded_route_documents_the_role_refusal(schema: dict[str, Any]) -> None:
|
||||
sans_403 = [
|
||||
(methode, chemin)
|
||||
for methode, chemin, operation in operations(schema)
|
||||
if (methode, chemin) in ROUTES_A_ROLE and "403" not in operation["responses"]
|
||||
]
|
||||
|
||||
assert sans_403 == []
|
||||
|
||||
|
||||
def test_every_origin_checked_route_documents_the_csrf_refusal(schema: dict[str, Any]) -> None:
|
||||
sans_403 = [
|
||||
(methode, chemin)
|
||||
for methode, chemin, operation in operations(schema)
|
||||
if (methode, chemin) in ORIGINE_VERIFIEE and "403" not in operation["responses"]
|
||||
]
|
||||
|
||||
assert sans_403 == []
|
||||
|
||||
|
||||
def test_the_validation_model_matches_what_the_handler_returns(schema: dict[str, Any]) -> None:
|
||||
modeles = {
|
||||
operation["responses"]["422"]["content"]["application/json"]["schema"]["$ref"]
|
||||
for _, _, operation in operations(schema)
|
||||
if "422" in operation["responses"]
|
||||
}
|
||||
|
||||
assert modeles == {"#/components/schemas/ValidationErrorResponse"}
|
||||
assert "HTTPValidationError" not in schema["components"]["schemas"]
|
||||
|
||||
|
||||
def test_the_rate_limit_documents_the_delay_header(schema: dict[str, Any]) -> None:
|
||||
trop_de_tentatives = schema["paths"]["/api/v1/auth/login"]["post"]["responses"]["429"]
|
||||
|
||||
assert "Retry-After" in trop_de_tentatives["headers"]
|
||||
|
||||
|
||||
def test_the_refresh_cookie_appears_in_the_security_schemes(schema: dict[str, Any]) -> None:
|
||||
schemes = schema["components"]["securitySchemes"]
|
||||
|
||||
assert schemes["Cookie de rafraîchissement"]["in"] == "cookie"
|
||||
assert schemes["Cookie de rafraîchissement"]["name"] == "ev_refresh"
|
||||
|
||||
|
||||
def test_each_tag_used_by_a_route_is_described(schema: dict[str, Any]) -> None:
|
||||
decrits = {tag["name"] for tag in schema["tags"]}
|
||||
|
||||
for methode, chemin, operation in operations(schema):
|
||||
poses = operation.get("tags", [])
|
||||
assert len(poses) == len(set(poses)), f"tag en double sur {methode} {chemin}"
|
||||
assert set(poses) <= decrits, f"tag non décrit sur {methode} {chemin}"
|
||||
@@ -0,0 +1,144 @@
|
||||
from collections.abc import Callable, Iterator
|
||||
from datetime import UTC, datetime
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from httpx import AsyncClient
|
||||
|
||||
from app.api.deps import get_current_principal, get_recommendation_service
|
||||
from app.core.principal import Principal
|
||||
from app.core.roles import AccountKind, Role
|
||||
from app.models.energy import Recommendation
|
||||
from app.services.recommendation import RecommendationNotFoundError
|
||||
|
||||
MOMENT = datetime(2024, 1, 1, tzinfo=UTC)
|
||||
|
||||
|
||||
def principal(role: Role = Role.LECTEUR) -> Principal:
|
||||
return Principal(
|
||||
id=uuid4(),
|
||||
email=f"{role.value}@enervision.fr",
|
||||
role=role,
|
||||
kind=AccountKind.HUMAIN,
|
||||
must_change_password=False,
|
||||
)
|
||||
|
||||
|
||||
def recommendation(recommendation_id: int = 1) -> Recommendation:
|
||||
return Recommendation(
|
||||
recommendation_id=recommendation_id,
|
||||
alert_id=1,
|
||||
action="Vérifier la consommation",
|
||||
explanation="Pic détecté",
|
||||
rule_reference="spike-v1",
|
||||
created_at=MOMENT,
|
||||
)
|
||||
|
||||
|
||||
class FauxService:
|
||||
def __init__(self, erreur: Exception | None = None) -> None:
|
||||
self._erreur = erreur
|
||||
self.recommendation = recommendation()
|
||||
|
||||
async def list_all(self) -> list[Recommendation]:
|
||||
return [self.recommendation]
|
||||
|
||||
async def get_by_id(self, recommendation_id: int) -> Recommendation:
|
||||
if self._erreur is not None:
|
||||
raise self._erreur
|
||||
return self.recommendation
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def lecteur_connecte(app: FastAPI) -> Iterator[None]:
|
||||
app.dependency_overrides[get_current_principal] = lambda: principal()
|
||||
yield
|
||||
app.dependency_overrides.pop(get_current_principal, None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def servi(
|
||||
app: FastAPI, lecteur_connecte: None
|
||||
) -> Iterator[Callable[[Exception | None], FauxService]]:
|
||||
def installe(erreur: Exception | None = None) -> FauxService:
|
||||
service = FauxService(erreur)
|
||||
app.dependency_overrides[get_recommendation_service] = lambda: service
|
||||
return service
|
||||
|
||||
yield installe
|
||||
app.dependency_overrides.pop(get_recommendation_service, None)
|
||||
|
||||
|
||||
async def test_list_recommendations_returns_the_recommendations(
|
||||
servi: Callable[..., FauxService], client: AsyncClient
|
||||
) -> None:
|
||||
servi()
|
||||
|
||||
response = await client.get("/api/v1/recommendations")
|
||||
|
||||
assert response.status_code == 200
|
||||
corps = response.json()
|
||||
assert corps == [
|
||||
{
|
||||
"recommendation_id": 1,
|
||||
"alert_id": 1,
|
||||
"action": "Vérifier la consommation",
|
||||
"explanation": "Pic détecté",
|
||||
"rule_reference": "spike-v1",
|
||||
"created_at": "2024-01-01T00:00:00Z",
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
async def test_get_recommendation_returns_the_matching_recommendation(
|
||||
servi: Callable[..., FauxService], client: AsyncClient
|
||||
) -> None:
|
||||
servi()
|
||||
|
||||
response = await client.get("/api/v1/recommendations/1")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["recommendation_id"] == 1
|
||||
|
||||
|
||||
async def test_get_recommendation_returns_404_for_an_unknown_recommendation(
|
||||
servi: Callable[..., FauxService], client: AsyncClient
|
||||
) -> None:
|
||||
servi(RecommendationNotFoundError(404))
|
||||
|
||||
response = await client.get("/api/v1/recommendations/404")
|
||||
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
async def test_list_recommendations_reaches_the_repository_through_the_session(
|
||||
lecteur_connecte: None, fake_session: Callable[..., None], client: AsyncClient
|
||||
) -> None:
|
||||
fake_session(result=[recommendation(1), recommendation(2)])
|
||||
|
||||
response = await client.get("/api/v1/recommendations")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert [r["recommendation_id"] for r in response.json()] == [1, 2]
|
||||
|
||||
|
||||
async def test_get_recommendation_reaches_the_repository_through_the_session(
|
||||
lecteur_connecte: None, fake_session: Callable[..., None], client: AsyncClient
|
||||
) -> None:
|
||||
fake_session(result=recommendation(1))
|
||||
|
||||
response = await client.get("/api/v1/recommendations/1")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["recommendation_id"] == 1
|
||||
|
||||
|
||||
async def test_get_recommendation_returns_404_when_the_session_finds_nothing(
|
||||
lecteur_connecte: None, fake_session: Callable[..., None], client: AsyncClient
|
||||
) -> None:
|
||||
fake_session(result=None)
|
||||
|
||||
response = await client.get("/api/v1/recommendations/404")
|
||||
|
||||
assert response.status_code == 404
|
||||
@@ -0,0 +1,141 @@
|
||||
from collections.abc import Callable, Iterator
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from httpx import AsyncClient
|
||||
|
||||
from app.api.deps import get_current_principal, get_site_service
|
||||
from app.core.principal import Principal
|
||||
from app.core.roles import AccountKind, Role
|
||||
from app.models.energy import Site
|
||||
from app.services.site import SiteNotFoundError
|
||||
|
||||
|
||||
def principal(role: Role = Role.LECTEUR) -> Principal:
|
||||
return Principal(
|
||||
id=uuid4(),
|
||||
email=f"{role.value}@enervision.fr",
|
||||
role=role,
|
||||
kind=AccountKind.HUMAIN,
|
||||
must_change_password=False,
|
||||
)
|
||||
|
||||
|
||||
def site(site_id: str = "site-1") -> Site:
|
||||
return Site(
|
||||
site_id=site_id,
|
||||
site_name="Site de test",
|
||||
site_type="industriel",
|
||||
location="Toulouse",
|
||||
capacity_kw=42.0,
|
||||
status="actif",
|
||||
)
|
||||
|
||||
|
||||
class FauxService:
|
||||
def __init__(self, erreur: Exception | None = None) -> None:
|
||||
self._erreur = erreur
|
||||
self.site = site()
|
||||
|
||||
async def list_all(self) -> list[Site]:
|
||||
return [self.site]
|
||||
|
||||
async def get_by_id(self, site_id: str) -> Site:
|
||||
if self._erreur is not None:
|
||||
raise self._erreur
|
||||
return self.site
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def lecteur_connecte(app: FastAPI) -> Iterator[None]:
|
||||
app.dependency_overrides[get_current_principal] = lambda: principal()
|
||||
yield
|
||||
app.dependency_overrides.pop(get_current_principal, None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def servi(
|
||||
app: FastAPI, lecteur_connecte: None
|
||||
) -> Iterator[Callable[[Exception | None], FauxService]]:
|
||||
def installe(erreur: Exception | None = None) -> FauxService:
|
||||
service = FauxService(erreur)
|
||||
app.dependency_overrides[get_site_service] = lambda: service
|
||||
return service
|
||||
|
||||
yield installe
|
||||
app.dependency_overrides.pop(get_site_service, None)
|
||||
|
||||
|
||||
async def test_list_sites_returns_the_sites(
|
||||
servi: Callable[..., FauxService], client: AsyncClient
|
||||
) -> None:
|
||||
servi()
|
||||
|
||||
response = await client.get("/api/v1/sites")
|
||||
|
||||
assert response.status_code == 200
|
||||
corps = response.json()
|
||||
assert corps == [
|
||||
{
|
||||
"site_id": "site-1",
|
||||
"site_name": "Site de test",
|
||||
"site_type": "industriel",
|
||||
"location": "Toulouse",
|
||||
"capacity_kw": 42.0,
|
||||
"status": "actif",
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
async def test_get_site_returns_the_matching_site(
|
||||
servi: Callable[..., FauxService], client: AsyncClient
|
||||
) -> None:
|
||||
servi()
|
||||
|
||||
response = await client.get("/api/v1/sites/site-1")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["site_id"] == "site-1"
|
||||
|
||||
|
||||
async def test_get_site_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")
|
||||
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
async def test_list_sites_reaches_the_repository_through_the_session(
|
||||
lecteur_connecte: None, fake_session: Callable[..., None], client: AsyncClient
|
||||
) -> None:
|
||||
fake_session(result=[site("a"), site("b")])
|
||||
|
||||
response = await client.get("/api/v1/sites")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert [s["site_id"] for s in response.json()] == ["a", "b"]
|
||||
|
||||
|
||||
async def test_get_site_reaches_the_repository_through_the_session(
|
||||
lecteur_connecte: None, fake_session: Callable[..., None], client: AsyncClient
|
||||
) -> None:
|
||||
fake_session(result=site("a"))
|
||||
|
||||
response = await client.get("/api/v1/sites/a")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["site_id"] == "a"
|
||||
|
||||
|
||||
async def test_get_site_returns_404_when_the_session_finds_nothing(
|
||||
lecteur_connecte: None, fake_session: Callable[..., None], client: AsyncClient
|
||||
) -> None:
|
||||
fake_session(result=None)
|
||||
|
||||
response = await client.get("/api/v1/sites/inconnu")
|
||||
|
||||
assert response.status_code == 404
|
||||
@@ -0,0 +1,73 @@
|
||||
from collections.abc import Callable, Iterator
|
||||
from datetime import UTC, datetime
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from httpx import AsyncClient
|
||||
|
||||
from app.api.deps import get_current_principal, get_stats_service
|
||||
from app.core.principal import Principal
|
||||
from app.core.roles import AccountKind, Role
|
||||
from app.services.stats import ConsumptionSummary, SiteConsumption
|
||||
|
||||
|
||||
def principal(role: Role = Role.LECTEUR) -> Principal:
|
||||
return Principal(
|
||||
id=uuid4(),
|
||||
email=f"{role.value}@enervision.fr",
|
||||
role=role,
|
||||
kind=AccountKind.HUMAIN,
|
||||
must_change_password=False,
|
||||
)
|
||||
|
||||
|
||||
class FauxService:
|
||||
def __init__(self) -> None:
|
||||
self.resume = ConsumptionSummary(
|
||||
timestamp=datetime.now(UTC),
|
||||
total_sites=1,
|
||||
total_consumption_kw=87.34,
|
||||
total_capacity_kw=200,
|
||||
average_load_percent=43.7,
|
||||
sites=[
|
||||
SiteConsumption(
|
||||
site_id="SITE001",
|
||||
site_name="Bureau Paris La Défense",
|
||||
current_consumption_kw=87.34,
|
||||
capacity_kw=200,
|
||||
load_percent=43.7,
|
||||
data_quality="good",
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
async def summary(self) -> ConsumptionSummary:
|
||||
return self.resume
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def servi(app: FastAPI) -> Iterator[Callable[[], FauxService]]:
|
||||
def installe() -> FauxService:
|
||||
service = FauxService()
|
||||
app.dependency_overrides[get_stats_service] = lambda: service
|
||||
app.dependency_overrides[get_current_principal] = lambda: principal()
|
||||
return service
|
||||
|
||||
yield installe
|
||||
app.dependency_overrides.pop(get_stats_service, None)
|
||||
app.dependency_overrides.pop(get_current_principal, None)
|
||||
|
||||
|
||||
async def test_get_summary_returns_the_service_result(
|
||||
servi: Callable[[], FauxService], client: AsyncClient
|
||||
) -> None:
|
||||
servi()
|
||||
|
||||
response = await client.get("/api/v1/stats/summary")
|
||||
|
||||
assert response.status_code == 200
|
||||
corps = response.json()
|
||||
assert corps["total_sites"] == 1
|
||||
assert corps["sites"][0]["site_id"] == "SITE001"
|
||||
assert corps["sites"][0]["data_quality"] == "good"
|
||||
@@ -1,3 +1,4 @@
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
from app.core.config import Settings
|
||||
@@ -12,6 +13,16 @@ SETTINGS_DE_TEST: dict[str, Any] = {
|
||||
}
|
||||
|
||||
|
||||
class FakeScalars:
|
||||
"""Resultat factice pour `.scalars()` : `.all()` renvoie les lignes fournies."""
|
||||
|
||||
def __init__(self, rows: Sequence[object]) -> None:
|
||||
self._rows = rows
|
||||
|
||||
def all(self) -> Sequence[object]:
|
||||
return self._rows
|
||||
|
||||
|
||||
class FakeSession:
|
||||
"""Session factice : renvoie `result`, ou leve `failure` si elle est fournie."""
|
||||
|
||||
@@ -25,6 +36,9 @@ class FakeSession:
|
||||
async def execute(self, *_: object, **__: object) -> object:
|
||||
return self._repondre()
|
||||
|
||||
async def scalars(self, *_: object, **__: object) -> FakeScalars:
|
||||
return FakeScalars(self._repondre() or [])
|
||||
|
||||
def _repondre(self) -> object:
|
||||
if self._failure is not None:
|
||||
raise self._failure
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.energy import Alert
|
||||
from app.repositories.alert import AlertRepository
|
||||
from app.schemas.alert import AlertSeverity
|
||||
from tests.repositories.test_site import creer as creer_site
|
||||
from tests.repositories.test_site import identifiant as identifiant_site
|
||||
|
||||
pytestmark = pytest.mark.integration
|
||||
|
||||
|
||||
async def creer_alerte(session: AsyncSession, *, site_id: str, **overrides: object) -> Alert:
|
||||
alerte = Alert(
|
||||
source_alert_id=overrides.get("source_alert_id", f"ALR-{uuid.uuid4().hex[:12]}"),
|
||||
site_id=site_id,
|
||||
source=overrides.get("source", "enervision"),
|
||||
timestamp=overrides.get("timestamp", datetime(2026, 9, 16, tzinfo=UTC)),
|
||||
type=overrides.get("type", "threshold"),
|
||||
severity=overrides.get("severity", "high"),
|
||||
message=overrides.get("message", "Dépassement du seuil configuré"),
|
||||
value=overrides.get("value", 812.5),
|
||||
threshold=overrides.get("threshold", 720.0),
|
||||
metric=overrides.get("metric", "consumption_kw"),
|
||||
prediction_id=overrides.get("prediction_id"),
|
||||
raw_data=overrides.get("raw_data", {}),
|
||||
)
|
||||
session.add(alerte)
|
||||
await session.flush()
|
||||
return alerte
|
||||
|
||||
|
||||
async def test_list_all_returns_the_alerts_sorted_by_timestamp_descending(
|
||||
session: AsyncSession,
|
||||
) -> None:
|
||||
site = await creer_site(session)
|
||||
depot = AlertRepository(session)
|
||||
ancienne = await creer_alerte(
|
||||
session, site_id=site.site_id, timestamp=datetime(2026, 9, 1, tzinfo=UTC)
|
||||
)
|
||||
recente = await creer_alerte(
|
||||
session, site_id=site.site_id, timestamp=datetime(2026, 9, 15, tzinfo=UTC)
|
||||
)
|
||||
|
||||
alertes = await depot.list_all()
|
||||
identifiants = [
|
||||
a.alert_id for a in alertes if a.alert_id in (ancienne.alert_id, recente.alert_id)
|
||||
]
|
||||
await session.rollback()
|
||||
|
||||
assert identifiants == [recente.alert_id, ancienne.alert_id]
|
||||
|
||||
|
||||
async def test_list_all_filters_by_site_id(session: AsyncSession) -> None:
|
||||
premier = await creer_site(session)
|
||||
second = await creer_site(session)
|
||||
depot = AlertRepository(session)
|
||||
voulue = await creer_alerte(session, site_id=premier.site_id)
|
||||
await creer_alerte(session, site_id=second.site_id)
|
||||
|
||||
alertes = await depot.list_all(site_id=premier.site_id)
|
||||
identifiants = [a.alert_id for a in alertes]
|
||||
await session.rollback()
|
||||
|
||||
assert identifiants == [voulue.alert_id]
|
||||
|
||||
|
||||
async def test_list_all_filters_by_severity(session: AsyncSession) -> None:
|
||||
site = await creer_site(session)
|
||||
depot = AlertRepository(session)
|
||||
voulue = await creer_alerte(session, site_id=site.site_id, severity="critical")
|
||||
await creer_alerte(session, site_id=site.site_id, severity="low")
|
||||
|
||||
alertes = await depot.list_all(severity=AlertSeverity.CRITICAL)
|
||||
identifiants = [a.alert_id for a in alertes]
|
||||
await session.rollback()
|
||||
|
||||
assert identifiants == [voulue.alert_id]
|
||||
|
||||
|
||||
async def test_list_all_returns_an_empty_list_when_there_is_nothing(
|
||||
session: AsyncSession,
|
||||
) -> None:
|
||||
depot = AlertRepository(session)
|
||||
|
||||
alertes = await depot.list_all(site_id=identifiant_site())
|
||||
|
||||
assert list(alertes) == []
|
||||
@@ -0,0 +1,72 @@
|
||||
import uuid
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.energy import Reading, Site
|
||||
from app.repositories.reading import ReadingRepository
|
||||
|
||||
pytestmark = pytest.mark.integration
|
||||
|
||||
|
||||
def identifiant() -> str:
|
||||
return f"SITE-{uuid.uuid4().hex[:8]}"
|
||||
|
||||
|
||||
def lecture(site_id: str, *, timestamp: datetime, consumption_kw: float) -> Reading:
|
||||
return Reading(
|
||||
site_id=site_id,
|
||||
timestamp=timestamp,
|
||||
source="api_current",
|
||||
consumption_kw=consumption_kw,
|
||||
data_quality="good",
|
||||
raw_data={},
|
||||
)
|
||||
|
||||
|
||||
async def test_latest_by_site_keeps_only_the_most_recent_reading(session: AsyncSession) -> None:
|
||||
site_id = identifiant()
|
||||
maintenant = datetime.now(UTC)
|
||||
session.add(Site(site_id=site_id, site_name="Site", site_type="bureau", capacity_kw=100))
|
||||
await session.flush()
|
||||
session.add_all(
|
||||
[
|
||||
lecture(site_id, timestamp=maintenant - timedelta(hours=1), consumption_kw=10),
|
||||
lecture(site_id, timestamp=maintenant, consumption_kw=42),
|
||||
]
|
||||
)
|
||||
await session.flush()
|
||||
depot = ReadingRepository(session)
|
||||
|
||||
resultats = await depot.latest_by_site()
|
||||
consommations = [r.consumption_kw for r in resultats if r.site_id == site_id]
|
||||
await session.rollback()
|
||||
|
||||
assert consommations == [42]
|
||||
|
||||
|
||||
async def test_latest_by_site_returns_one_row_per_site(session: AsyncSession) -> None:
|
||||
premier, second = identifiant(), identifiant()
|
||||
maintenant = datetime.now(UTC)
|
||||
session.add_all(
|
||||
[
|
||||
Site(site_id=premier, site_name="A", site_type="bureau", capacity_kw=100),
|
||||
Site(site_id=second, site_name="B", site_type="bureau", capacity_kw=200),
|
||||
]
|
||||
)
|
||||
await session.flush()
|
||||
session.add_all(
|
||||
[
|
||||
lecture(premier, timestamp=maintenant, consumption_kw=10),
|
||||
lecture(second, timestamp=maintenant, consumption_kw=20),
|
||||
]
|
||||
)
|
||||
await session.flush()
|
||||
depot = ReadingRepository(session)
|
||||
|
||||
resultats = await depot.latest_by_site()
|
||||
identifiants = {r.site_id for r in resultats if r.site_id in (premier, second)}
|
||||
await session.rollback()
|
||||
|
||||
assert identifiants == {premier, second}
|
||||
@@ -0,0 +1,85 @@
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.energy import Alert, Recommendation, Site
|
||||
from app.repositories.recommendation import RecommendationRepository
|
||||
|
||||
pytestmark = pytest.mark.integration
|
||||
|
||||
MOMENT = datetime(2024, 1, 1, tzinfo=UTC)
|
||||
|
||||
|
||||
async def creer_site(session: AsyncSession) -> str:
|
||||
site_id = f"TEST-{uuid.uuid4()}"
|
||||
session.add(Site(site_id=site_id, site_name="Site de test", site_type="office"))
|
||||
await session.flush()
|
||||
return site_id
|
||||
|
||||
|
||||
async def creer_alerte(session: AsyncSession) -> int:
|
||||
site_id = await creer_site(session)
|
||||
alerte = Alert(
|
||||
source_alert_id=str(uuid.uuid4()),
|
||||
site_id=site_id,
|
||||
source="api_mock",
|
||||
timestamp=MOMENT,
|
||||
type="spike",
|
||||
severity="high",
|
||||
message="Test",
|
||||
raw_data={},
|
||||
)
|
||||
session.add(alerte)
|
||||
await session.flush()
|
||||
return alerte.alert_id
|
||||
|
||||
|
||||
async def creer(session: AsyncSession, **overrides: object) -> Recommendation:
|
||||
recommendation = Recommendation(
|
||||
alert_id=overrides.get("alert_id") or await creer_alerte(session),
|
||||
action=overrides.get("action", "Vérifier la consommation"),
|
||||
explanation=overrides.get("explanation", "Pic détecté"),
|
||||
rule_reference=overrides.get("rule_reference", f"spike-{uuid.uuid4().hex[:8]}"),
|
||||
)
|
||||
session.add(recommendation)
|
||||
await session.flush()
|
||||
return recommendation
|
||||
|
||||
|
||||
async def test_get_by_id_returns_the_matching_recommendation(session: AsyncSession) -> None:
|
||||
depot = RecommendationRepository(session)
|
||||
cree = await creer(session)
|
||||
|
||||
trouve = await depot.get_by_id(cree.recommendation_id)
|
||||
action = trouve.action if trouve else None
|
||||
await session.rollback()
|
||||
|
||||
assert action == "Vérifier la consommation"
|
||||
|
||||
|
||||
async def test_get_by_id_returns_nothing_for_an_unknown_identifier(
|
||||
session: AsyncSession,
|
||||
) -> None:
|
||||
trouve = await RecommendationRepository(session).get_by_id(0)
|
||||
|
||||
assert trouve is None
|
||||
|
||||
|
||||
async def test_list_all_returns_the_recommendations_sorted_by_identifier(
|
||||
session: AsyncSession,
|
||||
) -> None:
|
||||
depot = RecommendationRepository(session)
|
||||
premiere = await creer(session)
|
||||
seconde = await creer(session)
|
||||
|
||||
recommendations = await depot.list_all()
|
||||
identifiants = [
|
||||
r.recommendation_id
|
||||
for r in recommendations
|
||||
if r.recommendation_id in (premiere.recommendation_id, seconde.recommendation_id)
|
||||
]
|
||||
await session.rollback()
|
||||
|
||||
assert identifiants == sorted(identifiants)
|
||||
@@ -0,0 +1,59 @@
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.energy import Site
|
||||
from app.repositories.site import SiteRepository
|
||||
|
||||
pytestmark = pytest.mark.integration
|
||||
|
||||
|
||||
def identifiant() -> str:
|
||||
return f"site-{uuid.uuid4().hex[:12]}"
|
||||
|
||||
|
||||
async def creer(session: AsyncSession, **overrides: object) -> Site:
|
||||
site = Site(
|
||||
site_id=overrides.get("site_id", identifiant()),
|
||||
site_name=overrides.get("site_name", "Site de test"),
|
||||
site_type=overrides.get("site_type", "industriel"),
|
||||
location=overrides.get("location", "Toulouse"),
|
||||
capacity_kw=overrides.get("capacity_kw", 42.0),
|
||||
status=overrides.get("status", "actif"),
|
||||
)
|
||||
session.add(site)
|
||||
await session.flush()
|
||||
return site
|
||||
|
||||
|
||||
async def test_get_by_id_returns_the_matching_site(session: AsyncSession) -> None:
|
||||
depot = SiteRepository(session)
|
||||
cree = await creer(session)
|
||||
|
||||
trouve = await depot.get_by_id(cree.site_id)
|
||||
nom = trouve.site_name if trouve else None
|
||||
await session.rollback()
|
||||
|
||||
assert nom == "Site de test"
|
||||
|
||||
|
||||
async def test_get_by_id_returns_nothing_for_an_unknown_identifier(
|
||||
session: AsyncSession,
|
||||
) -> None:
|
||||
trouve = await SiteRepository(session).get_by_id(identifiant())
|
||||
|
||||
assert trouve is None
|
||||
|
||||
|
||||
async def test_list_all_returns_the_sites_sorted_by_identifier(session: AsyncSession) -> None:
|
||||
depot = SiteRepository(session)
|
||||
premier, second = sorted([f"zz-{identifiant()}", f"aa-{identifiant()}"])
|
||||
await creer(session, site_id=second)
|
||||
await creer(session, site_id=premier)
|
||||
|
||||
sites = await depot.list_all()
|
||||
identifiants = [site.site_id for site in sites if site.site_id in (premier, second)]
|
||||
await session.rollback()
|
||||
|
||||
assert identifiants == [premier, second]
|
||||
@@ -0,0 +1,55 @@
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from app.models.energy import Alert
|
||||
from app.services.alert import AlertService
|
||||
|
||||
|
||||
def alert(
|
||||
alert_id: int = 1,
|
||||
site_id: str = "site-1",
|
||||
severity: str = "high",
|
||||
) -> Alert:
|
||||
return Alert(
|
||||
alert_id=alert_id,
|
||||
source_alert_id=f"ALR-{alert_id}",
|
||||
site_id=site_id,
|
||||
source="enervision",
|
||||
timestamp=datetime(2026, 9, 16, tzinfo=UTC),
|
||||
type="threshold",
|
||||
severity=severity,
|
||||
message="Dépassement du seuil configuré",
|
||||
value=812.5,
|
||||
threshold=720.0,
|
||||
metric="consumption_kw",
|
||||
prediction_id=None,
|
||||
raw_data={},
|
||||
)
|
||||
|
||||
|
||||
class FakeRepository:
|
||||
def __init__(self, alerts: list[Alert]) -> None:
|
||||
self._alerts = alerts
|
||||
self.appels: list[tuple[str | None, str | None]] = []
|
||||
|
||||
async def list_all(
|
||||
self, *, site_id: str | None = None, severity: str | None = None
|
||||
) -> list[Alert]:
|
||||
self.appels.append((site_id, severity))
|
||||
return self._alerts
|
||||
|
||||
|
||||
async def test_list_all_returns_the_repository_alerts() -> None:
|
||||
service = AlertService(alerts=FakeRepository([alert(1), alert(2)]))
|
||||
|
||||
alertes = await service.list_all()
|
||||
|
||||
assert [a.alert_id for a in alertes] == [1, 2]
|
||||
|
||||
|
||||
async def test_list_all_relays_the_filters_to_the_repository() -> None:
|
||||
depot = FakeRepository([])
|
||||
service = AlertService(alerts=depot)
|
||||
|
||||
await service.list_all(site_id="site-1", severity="critical")
|
||||
|
||||
assert depot.appels == [("site-1", "critical")]
|
||||
@@ -0,0 +1,55 @@
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models.energy import Recommendation
|
||||
from app.services.recommendation import RecommendationNotFoundError, RecommendationService
|
||||
|
||||
|
||||
def recommendation(recommendation_id: int = 1) -> Recommendation:
|
||||
return Recommendation(
|
||||
recommendation_id=recommendation_id,
|
||||
alert_id=1,
|
||||
action="Vérifier la consommation",
|
||||
explanation="Pic détecté",
|
||||
rule_reference="spike-v1",
|
||||
created_at=datetime(2024, 1, 1, tzinfo=UTC),
|
||||
)
|
||||
|
||||
|
||||
class FakeRepository:
|
||||
def __init__(self, recommendations: list[Recommendation]) -> None:
|
||||
self._recommendations = recommendations
|
||||
|
||||
async def list_all(self) -> list[Recommendation]:
|
||||
return self._recommendations
|
||||
|
||||
async def get_by_id(self, recommendation_id: int) -> Recommendation | None:
|
||||
return next(
|
||||
(r for r in self._recommendations if r.recommendation_id == recommendation_id), None
|
||||
)
|
||||
|
||||
|
||||
async def test_list_all_returns_the_repository_recommendations() -> None:
|
||||
service = RecommendationService(
|
||||
recommendations=FakeRepository([recommendation(1), recommendation(2)])
|
||||
)
|
||||
|
||||
recommendations = await service.list_all()
|
||||
|
||||
assert [r.recommendation_id for r in recommendations] == [1, 2]
|
||||
|
||||
|
||||
async def test_get_by_id_returns_the_matching_recommendation() -> None:
|
||||
service = RecommendationService(recommendations=FakeRepository([recommendation(1)]))
|
||||
|
||||
trouve = await service.get_by_id(1)
|
||||
|
||||
assert trouve.recommendation_id == 1
|
||||
|
||||
|
||||
async def test_get_by_id_raises_when_the_recommendation_is_unknown() -> None:
|
||||
service = RecommendationService(recommendations=FakeRepository([]))
|
||||
|
||||
with pytest.raises(RecommendationNotFoundError):
|
||||
await service.get_by_id(404)
|
||||
@@ -0,0 +1,49 @@
|
||||
import pytest
|
||||
|
||||
from app.models.energy import Site
|
||||
from app.services.site import SiteNotFoundError, SiteService
|
||||
|
||||
|
||||
def site(site_id: str = "site-1") -> Site:
|
||||
return Site(
|
||||
site_id=site_id,
|
||||
site_name="Site de test",
|
||||
site_type="industriel",
|
||||
location="Toulouse",
|
||||
capacity_kw=42.0,
|
||||
status="actif",
|
||||
)
|
||||
|
||||
|
||||
class FakeRepository:
|
||||
def __init__(self, sites: list[Site]) -> None:
|
||||
self._sites = sites
|
||||
|
||||
async def list_all(self) -> list[Site]:
|
||||
return self._sites
|
||||
|
||||
async def get_by_id(self, site_id: str) -> Site | 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:
|
||||
service = SiteService(sites=FakeRepository([site("a"), site("b")]))
|
||||
|
||||
sites = await service.list_all()
|
||||
|
||||
assert [s.site_id for s in sites] == ["a", "b"]
|
||||
|
||||
|
||||
async def test_get_by_id_returns_the_matching_site() -> None:
|
||||
service = SiteService(sites=FakeRepository([site("a")]))
|
||||
|
||||
trouve = await service.get_by_id("a")
|
||||
|
||||
assert trouve.site_id == "a"
|
||||
|
||||
|
||||
async def test_get_by_id_raises_when_the_site_is_unknown() -> None:
|
||||
service = SiteService(sites=FakeRepository([]))
|
||||
|
||||
with pytest.raises(SiteNotFoundError):
|
||||
await service.get_by_id("inconnu")
|
||||
@@ -0,0 +1,107 @@
|
||||
from dataclasses import dataclass
|
||||
|
||||
from app.services.stats import StatsService
|
||||
|
||||
|
||||
@dataclass
|
||||
class FauxSite:
|
||||
site_id: str
|
||||
site_name: str
|
||||
capacity_kw: float | None
|
||||
|
||||
|
||||
@dataclass
|
||||
class FauxLecture:
|
||||
site_id: str
|
||||
consumption_kw: float | None
|
||||
data_quality: str | None
|
||||
|
||||
|
||||
class FauxDepotSites:
|
||||
def __init__(self, sites: list[FauxSite]) -> None:
|
||||
self._sites = sites
|
||||
|
||||
async def list_all(self) -> list[FauxSite]:
|
||||
return self._sites
|
||||
|
||||
|
||||
class FauxDepotLectures:
|
||||
def __init__(self, lectures: list[FauxLecture]) -> None:
|
||||
self._lectures = lectures
|
||||
|
||||
async def latest_by_site(self) -> list[FauxLecture]:
|
||||
return self._lectures
|
||||
|
||||
|
||||
async def test_summary_computes_totals_and_the_average_load() -> None:
|
||||
service = StatsService(
|
||||
sites=FauxDepotSites([FauxSite("A", "Site A", 200), FauxSite("B", "Site B", 800)]), # type: ignore[arg-type]
|
||||
readings=FauxDepotLectures( # type: ignore[arg-type]
|
||||
[
|
||||
FauxLecture("A", 100, "good"),
|
||||
FauxLecture("B", 400, "good"),
|
||||
]
|
||||
),
|
||||
)
|
||||
|
||||
resume = await service.summary()
|
||||
|
||||
assert resume.total_sites == 2
|
||||
assert resume.total_consumption_kw == 500
|
||||
assert resume.total_capacity_kw == 1000
|
||||
assert resume.average_load_percent == 50
|
||||
par_site = {site.site_id: site for site in resume.sites}
|
||||
assert par_site["A"].load_percent == 50
|
||||
assert par_site["B"].load_percent == 50
|
||||
|
||||
|
||||
async def test_summary_treats_a_site_without_any_reading_as_critical() -> None:
|
||||
service = StatsService(
|
||||
sites=FauxDepotSites([FauxSite("A", "Site A", 200)]), # type: ignore[arg-type]
|
||||
readings=FauxDepotLectures([]), # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
resume = await service.summary()
|
||||
|
||||
site = resume.sites[0]
|
||||
assert site.data_quality == "critical"
|
||||
assert site.current_consumption_kw is None
|
||||
assert site.load_percent is None
|
||||
|
||||
|
||||
async def test_summary_treats_a_reading_with_an_unknown_quality_as_critical() -> None:
|
||||
service = StatsService(
|
||||
sites=FauxDepotSites([FauxSite("A", "Site A", 200)]), # type: ignore[arg-type]
|
||||
readings=FauxDepotLectures([FauxLecture("A", 50, None)]), # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
resume = await service.summary()
|
||||
|
||||
site = resume.sites[0]
|
||||
assert site.data_quality == "critical"
|
||||
assert site.current_consumption_kw is None
|
||||
|
||||
|
||||
async def test_summary_exposes_a_missing_capacity_as_zero_without_dividing_by_it() -> None:
|
||||
service = StatsService(
|
||||
sites=FauxDepotSites([FauxSite("A", "Site A", None)]), # type: ignore[arg-type]
|
||||
readings=FauxDepotLectures([FauxLecture("A", 50, "good")]), # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
resume = await service.summary()
|
||||
|
||||
site = resume.sites[0]
|
||||
assert site.capacity_kw == 0
|
||||
assert site.current_consumption_kw == 50
|
||||
assert site.load_percent is None
|
||||
|
||||
|
||||
async def test_summary_returns_zero_average_load_when_no_site_has_a_capacity() -> None:
|
||||
service = StatsService(
|
||||
sites=FauxDepotSites([FauxSite("A", "Site A", None)]), # type: ignore[arg-type]
|
||||
readings=FauxDepotLectures([]), # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
resume = await service.summary()
|
||||
|
||||
assert resume.average_load_percent == 0
|
||||
@@ -1,3 +1,6 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app import cli
|
||||
@@ -55,3 +58,52 @@ def test_read_password_refuses_two_different_entries(monkeypatch: pytest.MonkeyP
|
||||
|
||||
with pytest.raises(SystemExit):
|
||||
cli.read_password(generate=False)
|
||||
|
||||
|
||||
def test_build_parser_reads_the_export_openapi_arguments() -> None:
|
||||
arguments = cli.build_parser().parse_args(
|
||||
["export-openapi", "--output", "ailleurs/contrat.json"]
|
||||
)
|
||||
|
||||
assert arguments.commande == "export-openapi"
|
||||
assert arguments.output == "ailleurs/contrat.json"
|
||||
|
||||
|
||||
def test_build_parser_defaults_the_export_to_the_versioned_contract() -> None:
|
||||
arguments = cli.build_parser().parse_args(["export-openapi"])
|
||||
|
||||
assert arguments.output == str(cli.CHEMIN_CONTRAT)
|
||||
|
||||
|
||||
def test_settings_of_the_contract_ignore_the_local_environment(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setenv("APP_API_PREFIX", "/api/v9")
|
||||
monkeypatch.setenv("APP_NAME", "API du poste de Johan")
|
||||
|
||||
settings = cli.settings_du_contrat()
|
||||
|
||||
assert settings.api_prefix == "/api/v1"
|
||||
assert settings.name == "EnerVision API"
|
||||
|
||||
|
||||
def test_export_openapi_writes_a_readable_schema_where_asked(tmp_path: Path) -> None:
|
||||
destination = tmp_path / "contrat.json"
|
||||
|
||||
cli.export_openapi(destination)
|
||||
|
||||
assert json.loads(destination.read_text(encoding="utf-8"))["openapi"].startswith("3.")
|
||||
|
||||
|
||||
# Piège : `main()` réclamait un mot de passe avant de lire la commande. Sans le branchement,
|
||||
# l'export resterait bloqué sur `getpass` et aucune CI ne pourrait le rejouer.
|
||||
def test_main_exports_the_contract_without_asking_for_a_password(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
destination = tmp_path / "contrat.json"
|
||||
|
||||
code = cli.main(["export-openapi", "--output", str(destination)])
|
||||
|
||||
assert code == 0
|
||||
assert destination.exists()
|
||||
assert str(destination) in capsys.readouterr().out
|
||||
|
||||
@@ -81,7 +81,6 @@
|
||||
"builder": "@angular/build:unit-test",
|
||||
"options": {
|
||||
"coverage": true,
|
||||
"isolate": true,
|
||||
"coverageReporters": [
|
||||
"text-summary",
|
||||
"lcov",
|
||||
|
||||
@@ -1,21 +1,13 @@
|
||||
import {ApplicationConfig, inject, provideAppInitializer, provideBrowserGlobalErrorListeners} from '@angular/core';
|
||||
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { routes } from './app.routes';
|
||||
import { mockApiInterceptor } from './core/interceptors/mock-api-interceptor';
|
||||
import { provideHttpClient, withInterceptors } from '@angular/common/http';
|
||||
import {catchError, firstValueFrom, of} from 'rxjs';
|
||||
import {AuthService} from './core/services/auth.service';
|
||||
import {authInterceptor} from './core/interceptors/auth-interceptor';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
provideBrowserGlobalErrorListeners(),
|
||||
provideRouter(routes),
|
||||
provideHttpClient(withInterceptors([authInterceptor, mockApiInterceptor])),
|
||||
provideAppInitializer(() => {
|
||||
const auth = inject(AuthService);
|
||||
// Un 401 ici est normal : ça veut juste dire qu'il n'y a pas de session.
|
||||
return firstValueFrom(auth.refreshShared().pipe(catchError(() => of(null))));
|
||||
}),
|
||||
provideHttpClient(withInterceptors([mockApiInterceptor])),
|
||||
],
|
||||
};
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
import { Routes } from '@angular/router';
|
||||
import {authGuard} from './core/guards/auth-guard';
|
||||
|
||||
export const routes: Routes = [
|
||||
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
|
||||
{ path: 'login', loadComponent: () => import('./features/auth/login/login').then(m => m.Login) },
|
||||
{ path: 'change-password', loadComponent: () => import('./features/auth/change-password/change-password').then(m => m.ChangePassword) },
|
||||
{
|
||||
path: 'dashboard',
|
||||
canActivate: [authGuard],
|
||||
loadComponent: () => import('./features/dashboard/dashboard').then(m => m.Dashboard),
|
||||
loadComponent: () => import('./features/dashboard/dashboard').then((m) => m.Dashboard),
|
||||
},
|
||||
];
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { Router, ActivatedRouteSnapshot } from '@angular/router';
|
||||
import { vi } from 'vitest';
|
||||
import { authGuard } from './auth-guard';
|
||||
import { AuthService } from '../services/auth.service';
|
||||
|
||||
describe('authGuard', () => {
|
||||
let authMock: { isAuthenticated: ReturnType<typeof vi.fn>; principal: ReturnType<typeof vi.fn> };
|
||||
let routerMock: { navigate: ReturnType<typeof vi.fn> };
|
||||
|
||||
beforeEach(() => {
|
||||
authMock = { isAuthenticated: vi.fn(), principal: vi.fn() };
|
||||
routerMock = { navigate: vi.fn() };
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{ provide: AuthService, useValue: authMock },
|
||||
{ provide: Router, useValue: routerMock },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('redirige vers /login si non authentifié', () => {
|
||||
authMock.isAuthenticated.mockReturnValue(false);
|
||||
|
||||
const result = TestBed.runInInjectionContext(() =>
|
||||
authGuard({ data: {} } as ActivatedRouteSnapshot, {} as any)
|
||||
);
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
|
||||
});
|
||||
|
||||
it('redirige vers /login si le rôle ne correspond pas', () => {
|
||||
authMock.isAuthenticated.mockReturnValue(true);
|
||||
authMock.principal.mockReturnValue({ role: 'lecteur' });
|
||||
|
||||
const result = TestBed.runInInjectionContext(() =>
|
||||
authGuard({ data: { role: 'admin' } } as unknown as ActivatedRouteSnapshot, {} as any)
|
||||
);
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
|
||||
});
|
||||
|
||||
it('autorise si authentifié et rôle correspondant', () => {
|
||||
authMock.isAuthenticated.mockReturnValue(true);
|
||||
authMock.principal.mockReturnValue({ role: 'admin' });
|
||||
|
||||
const result = TestBed.runInInjectionContext(() =>
|
||||
authGuard({ data: { role: 'admin' } } as unknown as ActivatedRouteSnapshot, {} as any)
|
||||
);
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('autorise si authentifié et aucun rôle requis', () => {
|
||||
authMock.isAuthenticated.mockReturnValue(true);
|
||||
authMock.principal.mockReturnValue({ role: 'lecteur' });
|
||||
|
||||
const result = TestBed.runInInjectionContext(() =>
|
||||
authGuard({ data: {} } as ActivatedRouteSnapshot, {} as any)
|
||||
);
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,21 +0,0 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
import { AuthService } from '../services/auth.service';
|
||||
|
||||
export const authGuard: CanActivateFn = (route) => {
|
||||
const auth = inject(AuthService);
|
||||
const router = inject(Router);
|
||||
|
||||
if (!auth.isAuthenticated()) {
|
||||
router.navigate(['/login']);
|
||||
return false;
|
||||
}
|
||||
|
||||
const requiredRole = route.data['role'] as string | undefined;
|
||||
if (requiredRole && auth.principal()?.role !== requiredRole) {
|
||||
router.navigate(['/login']);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
@@ -1,161 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHandlerFn,
|
||||
HttpHeaders,
|
||||
HttpRequest,
|
||||
provideHttpClient,
|
||||
withInterceptors
|
||||
} from '@angular/common/http';
|
||||
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
|
||||
import { Router } from '@angular/router';
|
||||
import { of, throwError } from 'rxjs';
|
||||
import { vi } from 'vitest';
|
||||
import { authInterceptor } from './auth-interceptor';
|
||||
import { AuthService } from '../services/auth.service';
|
||||
|
||||
describe('authInterceptor', () => {
|
||||
let http: HttpClient;
|
||||
let httpMock: HttpTestingController;
|
||||
let authMock: { getAccessToken: ReturnType<typeof vi.fn>; clearSession: ReturnType<typeof vi.fn>; refreshShared: ReturnType<typeof vi.fn> };
|
||||
let routerMock: { navigate: ReturnType<typeof vi.fn> };
|
||||
|
||||
beforeEach(() => {
|
||||
authMock = {
|
||||
getAccessToken: vi.fn().mockReturnValue('fake-token'),
|
||||
clearSession: vi.fn(),
|
||||
refreshShared: vi.fn(),
|
||||
};
|
||||
routerMock = { navigate: vi.fn() };
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(withInterceptors([authInterceptor])),
|
||||
provideHttpClientTesting(),
|
||||
{ provide: AuthService, useValue: authMock },
|
||||
{ provide: Router, useValue: routerMock },
|
||||
],
|
||||
});
|
||||
|
||||
http = TestBed.inject(HttpClient);
|
||||
httpMock = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => httpMock.verify());
|
||||
|
||||
it('ajoute le header Authorization quand un token est disponible', () => {
|
||||
http.get('/api/v1/stats/summary').subscribe();
|
||||
const req = httpMock.expectOne('/api/v1/stats/summary');
|
||||
expect(req.request.headers.get('Authorization')).toBe('Bearer fake-token');
|
||||
req.flush({});
|
||||
});
|
||||
|
||||
it("n'ajoute pas le header Authorization sur /auth/login", () => {
|
||||
http.post('/api/v1/auth/login', {}).subscribe();
|
||||
const req = httpMock.expectOne('/api/v1/auth/login');
|
||||
expect(req.request.headers.has('Authorization')).toBe(false);
|
||||
req.flush({});
|
||||
});
|
||||
|
||||
it('ajoute withCredentials sur les routes /auth/*', () => {
|
||||
http.post('/api/v1/auth/login', {}).subscribe();
|
||||
const req = httpMock.expectOne('/api/v1/auth/login');
|
||||
expect(req.request.withCredentials).toBe(true);
|
||||
req.flush({});
|
||||
});
|
||||
|
||||
it('redirige vers /change-password sur un 403 avec ce detail précis', () => {
|
||||
http.get('/api/v1/dashboard').subscribe({ error: () => {} });
|
||||
const req = httpMock.expectOne('/api/v1/dashboard');
|
||||
req.flush({ detail: 'password_change_required' }, { status: 403, statusText: 'Forbidden' });
|
||||
expect(routerMock.navigate).toHaveBeenCalledWith(['/change-password']);
|
||||
});
|
||||
|
||||
it('ne redirige pas sur un 403 avec un autre detail', () => {
|
||||
http.get('/api/v1/dashboard').subscribe({ error: () => {} });
|
||||
const req = httpMock.expectOne('/api/v1/dashboard');
|
||||
req.flush({ detail: 'Droits insuffisants' }, { status: 403, statusText: 'Forbidden' });
|
||||
expect(routerMock.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('déconnecte et redirige vers /login sur un 401 avec error="invalid_token"', () => {
|
||||
http.get('/api/v1/dashboard').subscribe({ error: () => {} });
|
||||
const req = httpMock.expectOne('/api/v1/dashboard');
|
||||
req.flush(
|
||||
{},
|
||||
{ status: 401, statusText: 'Unauthorized', headers: new HttpHeaders({ 'WWW-Authenticate': 'Bearer error="invalid_token"' }) }
|
||||
);
|
||||
expect(authMock.clearSession).toHaveBeenCalled();
|
||||
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
|
||||
});
|
||||
|
||||
it('déconnecte directement sur un 401 provenant de /auth/refresh, sans tenter de rafraîchir', () => {
|
||||
http.post('/api/v1/auth/refresh', {}).subscribe({ error: () => {} });
|
||||
const req = httpMock.expectOne('/api/v1/auth/refresh');
|
||||
req.flush({}, { status: 401, statusText: 'Unauthorized' });
|
||||
expect(authMock.clearSession).toHaveBeenCalled();
|
||||
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
|
||||
});
|
||||
|
||||
it('rafraîchit puis rejoue la requête sur un 401 avec error="expired"', () => {
|
||||
authMock.refreshShared.mockReturnValue(of({ access_token: 'new-token' }));
|
||||
authMock.getAccessToken.mockReturnValueOnce('old-token').mockReturnValue('new-token');
|
||||
|
||||
let result: unknown;
|
||||
http.get('/api/v1/dashboard').subscribe((r) => (result = r));
|
||||
|
||||
const firstReq = httpMock.expectOne('/api/v1/dashboard');
|
||||
firstReq.flush({}, { status: 401, statusText: 'Unauthorized', headers: new HttpHeaders({ 'WWW-Authenticate': 'Bearer error="expired"' }) });
|
||||
|
||||
const retriedReq = httpMock.expectOne('/api/v1/dashboard');
|
||||
expect(retriedReq.request.headers.get('Authorization')).toBe('Bearer new-token');
|
||||
retriedReq.flush({ ok: true });
|
||||
|
||||
expect(result).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
it('déconnecte si le rafraîchissement échoue après un 401 "expired"', () => {
|
||||
authMock.refreshShared.mockReturnValue(throwError(() => new Error('refresh failed')));
|
||||
|
||||
http.get('/api/v1/dashboard').subscribe({ error: () => {} });
|
||||
const req = httpMock.expectOne('/api/v1/dashboard');
|
||||
req.flush({}, { status: 401, statusText: 'Unauthorized', headers: new HttpHeaders({ 'WWW-Authenticate': 'Bearer error="expired"' }) });
|
||||
|
||||
expect(authMock.clearSession).toHaveBeenCalled();
|
||||
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
|
||||
});
|
||||
|
||||
it("propage l'erreur telle quelle si ce n'est pas une HttpErrorResponse", () => {
|
||||
const req = new HttpRequest('GET', '/api/v1/dashboard');
|
||||
const boom = new Error('erreur inattendue, pas HTTP');
|
||||
const next: HttpHandlerFn = () => throwError(() => boom);
|
||||
|
||||
let captured: unknown;
|
||||
TestBed.runInInjectionContext(() => {
|
||||
authInterceptor(req, next).subscribe({ error: (e) => (captured = e) });
|
||||
});
|
||||
|
||||
expect(captured).toBe(boom);
|
||||
});
|
||||
|
||||
it('propage un 401 sur /auth/login sans tenter de rafraîchir ni déconnecter', () => {
|
||||
http.post('/api/v1/auth/login', {}).subscribe({ error: () => {} });
|
||||
const req = httpMock.expectOne('/api/v1/auth/login');
|
||||
req.flush({}, { status: 401, statusText: 'Unauthorized' });
|
||||
|
||||
expect(authMock.refreshShared).not.toHaveBeenCalled();
|
||||
expect(authMock.clearSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("propage un 401 dont le WWW-Authenticate ne correspond à aucun cas connu", () => {
|
||||
http.get('/api/v1/dashboard').subscribe({ error: () => {} });
|
||||
const req = httpMock.expectOne('/api/v1/dashboard');
|
||||
req.flush(
|
||||
{},
|
||||
{ status: 401, statusText: 'Unauthorized', headers: new HttpHeaders({ 'WWW-Authenticate': 'Bearer error="unknown_case"' }) }
|
||||
);
|
||||
|
||||
expect(authMock.refreshShared).not.toHaveBeenCalled();
|
||||
expect(authMock.clearSession).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,77 +0,0 @@
|
||||
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
|
||||
import { inject } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { Observable, catchError, switchMap, throwError } from 'rxjs';
|
||||
import { AuthService } from '../services/auth.service';
|
||||
import { TokenResponse } from '../../shared/models/auth.model';
|
||||
|
||||
function parseAuthError(response: HttpErrorResponse): string | null {
|
||||
const header = response.headers?.get('WWW-Authenticate') ?? '';
|
||||
const match = header.match(/error="([^"]+)"/);
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
export const authInterceptor: HttpInterceptorFn = (req, next) => {
|
||||
const auth = inject(AuthService);
|
||||
const router = inject(Router);
|
||||
|
||||
const isAuthRoute = req.url.includes('/auth/');
|
||||
let request = isAuthRoute ? req.clone({ withCredentials: true }) : req;
|
||||
|
||||
const token = auth.getAccessToken();
|
||||
if (token && !req.url.endsWith('/auth/login')) {
|
||||
request = request.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
|
||||
}
|
||||
|
||||
return next(request).pipe(
|
||||
catchError((error: unknown) => {
|
||||
if (!(error instanceof HttpErrorResponse)) {
|
||||
return throwError(() => error);
|
||||
}
|
||||
|
||||
if (error.status === 403) {
|
||||
const detail = (error.error as { detail?: string })?.detail;
|
||||
if (detail === 'password_change_required') {
|
||||
router.navigate(['/change-password']);
|
||||
}
|
||||
return throwError(() => error);
|
||||
}
|
||||
|
||||
if (error.status !== 401 || req.url.endsWith('/auth/login')) {
|
||||
return throwError(() => error);
|
||||
}
|
||||
|
||||
if (req.url.endsWith('/auth/refresh')) {
|
||||
auth.clearSession();
|
||||
router.navigate(['/login']);
|
||||
return throwError(() => error);
|
||||
}
|
||||
|
||||
const kind = parseAuthError(error);
|
||||
|
||||
if (kind === 'invalid_token') {
|
||||
auth.clearSession();
|
||||
router.navigate(['/login']);
|
||||
return throwError(() => error);
|
||||
}
|
||||
|
||||
if (kind === 'expired' || kind === 'token_stale') {
|
||||
return (auth.refreshShared() as Observable<TokenResponse>).pipe(
|
||||
switchMap(() => {
|
||||
const retried = request.clone({
|
||||
setHeaders: { Authorization: `Bearer ${auth.getAccessToken()}` },
|
||||
});
|
||||
return next(retried);
|
||||
}),
|
||||
catchError((refreshError) => {
|
||||
auth.clearSession();
|
||||
router.navigate(['/login']);
|
||||
return throwError(() => refreshError);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
};
|
||||
@@ -1,86 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
|
||||
import { AuthService } from './auth.service';
|
||||
import { environment } from '../../../environments/environment';
|
||||
|
||||
describe('AuthService', () => {
|
||||
let service: AuthService;
|
||||
let httpMock: HttpTestingController;
|
||||
|
||||
const tokenResponse = {
|
||||
access_token: 'abc123',
|
||||
token_type: 'bearer',
|
||||
expires_in: 900,
|
||||
principal: {
|
||||
id: '1',
|
||||
email: 'a@a.com',
|
||||
role: 'admin' as const,
|
||||
kind: 'human' as const,
|
||||
must_change_password: false,
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideHttpClient(), provideHttpClientTesting()],
|
||||
});
|
||||
service = TestBed.inject(AuthService);
|
||||
httpMock = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => httpMock.verify());
|
||||
|
||||
it('stocke le token et le principal après un login réussi', () => {
|
||||
service.login({ email: 'a@a.com', password: 'secret' }).subscribe();
|
||||
|
||||
const req = httpMock.expectOne(`${environment.apiUrl}/auth/login`);
|
||||
expect(req.request.withCredentials).toBe(true);
|
||||
req.flush(tokenResponse);
|
||||
|
||||
expect(service.getAccessToken()).toBe('abc123');
|
||||
expect(service.principal()?.email).toBe('a@a.com');
|
||||
expect(service.isAuthenticated()).toBe(true);
|
||||
});
|
||||
|
||||
it('efface la session au logout', () => {
|
||||
service.login({ email: 'a@a.com', password: 'secret' }).subscribe();
|
||||
httpMock.expectOne(`${environment.apiUrl}/auth/login`).flush(tokenResponse);
|
||||
|
||||
service.logout().subscribe();
|
||||
httpMock.expectOne(`${environment.apiUrl}/auth/logout`).flush(null);
|
||||
|
||||
expect(service.getAccessToken()).toBeNull();
|
||||
expect(service.isAuthenticated()).toBe(false);
|
||||
});
|
||||
|
||||
it("ne déclenche qu'un seul appel réseau si refreshShared est appelé plusieurs fois avant la réponse", () => {
|
||||
service.refreshShared().subscribe();
|
||||
service.refreshShared().subscribe();
|
||||
service.refreshShared().subscribe();
|
||||
|
||||
const requests = httpMock.match(`${environment.apiUrl}/auth/refresh`);
|
||||
expect(requests.length).toBe(1);
|
||||
requests[0].flush(tokenResponse);
|
||||
});
|
||||
|
||||
it('met à jour la session après un changement de mot de passe réussi', () => {
|
||||
service.changePassword({ current_password: 'old', new_password: 'new-password-1234' }).subscribe();
|
||||
|
||||
const req = httpMock.expectOne(`${environment.apiUrl}/auth/password`);
|
||||
req.flush(tokenResponse);
|
||||
|
||||
expect(service.getAccessToken()).toBe('abc123');
|
||||
});
|
||||
|
||||
it('récupère le principal courant via /auth/me', () => {
|
||||
let result: unknown;
|
||||
service.me().subscribe((r) => (result = r));
|
||||
|
||||
const req = httpMock.expectOne(`${environment.apiUrl}/auth/me`);
|
||||
expect(req.request.method).toBe('GET');
|
||||
req.flush(tokenResponse.principal);
|
||||
|
||||
expect(result).toEqual(tokenResponse.principal);
|
||||
});
|
||||
});
|
||||
@@ -1,69 +0,0 @@
|
||||
import { Service, signal, computed, inject } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable, tap, finalize, shareReplay } from 'rxjs';
|
||||
import { LoginRequest, PasswordChangeRequest, Principal, TokenResponse } from '../../shared/models/auth.model';
|
||||
import { environment } from '../../../environments/environment';
|
||||
|
||||
@Service()
|
||||
export class AuthService {
|
||||
private http = inject(HttpClient);
|
||||
|
||||
// Jamais de localStorage/sessionStorage/cookie côté JS : juste un signal en
|
||||
// mémoire. Un rechargement de page le perd, c'est voulu par le contrat.
|
||||
private accessTokenSignal = signal<string | null>(null);
|
||||
private principalSignal = signal<Principal | null>(null);
|
||||
|
||||
readonly principal = this.principalSignal.asReadonly();
|
||||
readonly isAuthenticated = computed(() => this.principalSignal() !== null);
|
||||
|
||||
private rotation$?: Observable<TokenResponse>;
|
||||
|
||||
getAccessToken(): string | null {
|
||||
return this.accessTokenSignal();
|
||||
}
|
||||
|
||||
private setSession(response: TokenResponse): void {
|
||||
this.accessTokenSignal.set(response.access_token);
|
||||
this.principalSignal.set(response.principal);
|
||||
}
|
||||
|
||||
clearSession(): void {
|
||||
this.accessTokenSignal.set(null);
|
||||
this.principalSignal.set(null);
|
||||
}
|
||||
|
||||
login(credentials: LoginRequest): Observable<TokenResponse> {
|
||||
return this.http
|
||||
.post<TokenResponse>(`${environment.apiUrl}/auth/login`, credentials, { withCredentials: true })
|
||||
.pipe(tap((response) => this.setSession(response)));
|
||||
}
|
||||
|
||||
// Un seul rafraîchissement en vol à la fois, partagé entre tous les
|
||||
// appelants (sinon le serveur révoque toute la session sur des rotations concurrentes).
|
||||
refreshShared(): Observable<TokenResponse> {
|
||||
this.rotation$ ??= this.http
|
||||
.post<TokenResponse>(`${environment.apiUrl}/auth/refresh`, {}, { withCredentials: true })
|
||||
.pipe(
|
||||
tap((response) => this.setSession(response)),
|
||||
finalize(() => (this.rotation$ = undefined)),
|
||||
shareReplay(1)
|
||||
);
|
||||
return this.rotation$;
|
||||
}
|
||||
|
||||
logout(): Observable<void> {
|
||||
return this.http
|
||||
.post<void>(`${environment.apiUrl}/auth/logout`, {}, { withCredentials: true })
|
||||
.pipe(tap(() => this.clearSession()));
|
||||
}
|
||||
|
||||
changePassword(payload: PasswordChangeRequest): Observable<TokenResponse> {
|
||||
return this.http
|
||||
.post<TokenResponse>(`${environment.apiUrl}/auth/password`, payload, { withCredentials: true })
|
||||
.pipe(tap((response) => this.setSession(response)));
|
||||
}
|
||||
|
||||
me(): Observable<Principal> {
|
||||
return this.http.get<Principal>(`${environment.apiUrl}/auth/me`);
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
<div class="auth-page">
|
||||
<form class="auth-card" [formGroup]="form" (ngSubmit)="onSubmit()">
|
||||
<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>
|
||||
<input
|
||||
id="current_password"
|
||||
type="password"
|
||||
formControlName="current_password"
|
||||
autocomplete="current-password"
|
||||
/>
|
||||
|
||||
<label for="new_password">Nouveau mot de passe</label>
|
||||
<input
|
||||
id="new_password"
|
||||
type="password"
|
||||
formControlName="new_password"
|
||||
autocomplete="new-password"
|
||||
/>
|
||||
<span class="auth-hint">12 à 128 caractères</span>
|
||||
|
||||
@if (errorMessage()) {
|
||||
<p class="auth-error">{{ errorMessage() }}</p>
|
||||
}
|
||||
|
||||
<button type="submit" [disabled]="form.invalid || isLoading()">
|
||||
{{ isLoading() ? 'Modification...' : 'Valider' }}
|
||||
</button>
|
||||
</form>
|
||||
</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;
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { ReactiveFormsModule } from '@angular/forms';
|
||||
import { Router } from '@angular/router';
|
||||
import { of, throwError } from 'rxjs';
|
||||
import { vi } from 'vitest';
|
||||
import { ChangePassword } from './change-password';
|
||||
import { AuthService } from '../../../core/services/auth.service';
|
||||
|
||||
describe('ChangePassword', () => {
|
||||
let authMock: { changePassword: ReturnType<typeof vi.fn> };
|
||||
let routerMock: { navigate: ReturnType<typeof vi.fn> };
|
||||
|
||||
beforeEach(async () => {
|
||||
authMock = { changePassword: vi.fn() };
|
||||
routerMock = { navigate: vi.fn() };
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [ChangePassword, ReactiveFormsModule],
|
||||
providers: [
|
||||
{ provide: AuthService, useValue: authMock },
|
||||
{ provide: Router, useValue: routerMock },
|
||||
],
|
||||
}).compileComponents();
|
||||
});
|
||||
|
||||
it('ne soumet pas si le formulaire est invalide (mot de passe trop court)', () => {
|
||||
const fixture = TestBed.createComponent(ChangePassword);
|
||||
const component = fixture.componentInstance;
|
||||
component.form.setValue({ current_password: 'old', new_password: 'trop-court' });
|
||||
|
||||
component.onSubmit();
|
||||
expect(authMock.changePassword).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirige vers /dashboard après un changement réussi', () => {
|
||||
const fixture = TestBed.createComponent(ChangePassword);
|
||||
const component = fixture.componentInstance;
|
||||
component.form.setValue({ current_password: 'ancien-mot-de-passe', new_password: 'un-nouveau-mot-de-passe-valide' });
|
||||
|
||||
authMock.changePassword.mockReturnValue(of({ principal: { role: 'admin' } }));
|
||||
|
||||
component.onSubmit();
|
||||
expect(routerMock.navigate).toHaveBeenCalledWith(['/dashboard']);
|
||||
});
|
||||
|
||||
it("affiche un message d'erreur si le mot de passe actuel est incorrect", () => {
|
||||
const fixture = TestBed.createComponent(ChangePassword);
|
||||
const component = fixture.componentInstance;
|
||||
component.form.setValue({ current_password: 'mauvais-mot-de-passe', new_password: 'un-nouveau-mot-de-passe-valide' });
|
||||
|
||||
authMock.changePassword.mockReturnValue(throwError(() => new Error('401')));
|
||||
|
||||
component.onSubmit();
|
||||
fixture.detectChanges(); // rend le bloc @if (errorMessage())
|
||||
|
||||
expect(component.errorMessage()).toContain('incorrect');
|
||||
const errorEl = fixture.nativeElement.querySelector('.auth-error');
|
||||
expect(errorEl?.textContent).toContain('incorrect');
|
||||
});
|
||||
|
||||
it('désactive le bouton tant que le formulaire est invalide', () => {
|
||||
const fixture = TestBed.createComponent(ChangePassword);
|
||||
fixture.detectChanges();
|
||||
|
||||
const button = fixture.nativeElement.querySelector('button[type="submit"]');
|
||||
expect(button.disabled).toBe(true);
|
||||
expect(fixture.nativeElement.querySelector('.auth-error')).toBeNull();
|
||||
});
|
||||
|
||||
it('déclenche onSubmit via la soumission réelle du formulaire (ngSubmit)', () => {
|
||||
const fixture = TestBed.createComponent(ChangePassword);
|
||||
const component = fixture.componentInstance;
|
||||
component.form.setValue({ current_password: 'ancien-mot-de-passe', new_password: 'un-nouveau-mot-de-passe-valide' });
|
||||
fixture.detectChanges();
|
||||
|
||||
authMock.changePassword.mockReturnValue(of({ principal: { role: 'admin' } }));
|
||||
|
||||
const form = fixture.nativeElement.querySelector('form');
|
||||
form.dispatchEvent(new Event('submit'));
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(authMock.changePassword).toHaveBeenCalledWith({
|
||||
current_password: 'ancien-mot-de-passe',
|
||||
new_password: 'un-nouveau-mot-de-passe-valide',
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
@@ -1,41 +0,0 @@
|
||||
import { Component, inject, signal } from '@angular/core';
|
||||
import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';
|
||||
import { Router } from '@angular/router';
|
||||
import { AuthService } from '../../../core/services/auth.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-change-password',
|
||||
standalone: true,
|
||||
imports: [ReactiveFormsModule],
|
||||
templateUrl: './change-password.html',
|
||||
styleUrl: './change-password.scss',
|
||||
})
|
||||
export class ChangePassword {
|
||||
private fb = inject(FormBuilder);
|
||||
private auth = inject(AuthService);
|
||||
private router = inject(Router);
|
||||
|
||||
errorMessage = signal<string | null>(null);
|
||||
isLoading = signal(false);
|
||||
|
||||
form = this.fb.nonNullable.group({
|
||||
current_password: ['', Validators.required],
|
||||
new_password: ['', [Validators.required, Validators.minLength(12), Validators.maxLength(128)]],
|
||||
});
|
||||
|
||||
onSubmit(): void {
|
||||
if (this.form.invalid) return;
|
||||
this.isLoading.set(true);
|
||||
this.errorMessage.set(null);
|
||||
|
||||
this.auth.changePassword(this.form.getRawValue()).subscribe({
|
||||
next: (response) => {
|
||||
this.router.navigate(['/dashboard']);
|
||||
},
|
||||
error: () => {
|
||||
this.isLoading.set(false);
|
||||
this.errorMessage.set('Mot de passe actuel incorrect, ou nouveau mot de passe invalide (12 à 128 caractères).');
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
<div class="auth-page">
|
||||
<form class="auth-card" [formGroup]="form" (ngSubmit)="onSubmit()">
|
||||
<h1>Connexion</h1>
|
||||
<p class="auth-subtitle">Accédez à votre espace EnerVision</p>
|
||||
|
||||
<label for="email">Email</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
formControlName="email"
|
||||
autocomplete="username"
|
||||
placeholder="vous@enervision.fr"
|
||||
/>
|
||||
|
||||
<label for="password">Mot de passe</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
formControlName="password"
|
||||
autocomplete="current-password"
|
||||
/>
|
||||
|
||||
@if (errorMessage()) {
|
||||
<p class="auth-error">
|
||||
{{ errorMessage() }}
|
||||
@if (retryAfterSeconds(); as seconds) {
|
||||
(réessayez dans {{ seconds }}s)
|
||||
}
|
||||
</p>
|
||||
}
|
||||
|
||||
<button type="submit" [disabled]="form.invalid || isLoading()">
|
||||
{{ isLoading() ? 'Connexion...' : 'Se connecter' }}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
@@ -1,81 +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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { ReactiveFormsModule } from '@angular/forms';
|
||||
import { Router } from '@angular/router';
|
||||
import { HttpErrorResponse, HttpHeaders } from '@angular/common/http';
|
||||
import { of, throwError } from 'rxjs';
|
||||
import { vi } from 'vitest';
|
||||
import { Login } from './login';
|
||||
import { AuthService } from '../../../core/services/auth.service';
|
||||
|
||||
describe('Login', () => {
|
||||
let authMock: { login: ReturnType<typeof vi.fn> };
|
||||
let routerMock: { navigate: ReturnType<typeof vi.fn> };
|
||||
|
||||
beforeEach(async () => {
|
||||
authMock = { login: vi.fn() };
|
||||
routerMock = { navigate: vi.fn() };
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [Login, ReactiveFormsModule],
|
||||
providers: [
|
||||
{ provide: AuthService, useValue: authMock },
|
||||
{ provide: Router, useValue: routerMock },
|
||||
],
|
||||
}).compileComponents();
|
||||
});
|
||||
|
||||
it('ne soumet pas si le formulaire est invalide', () => {
|
||||
const fixture = TestBed.createComponent(Login);
|
||||
fixture.componentInstance.onSubmit();
|
||||
expect(authMock.login).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirige vers /change-password si must_change_password est vrai', () => {
|
||||
const fixture = TestBed.createComponent(Login);
|
||||
const component = fixture.componentInstance;
|
||||
component.form.setValue({ email: 'a@a.com', password: 'secret' });
|
||||
|
||||
authMock.login.mockReturnValue(of({ principal: { role: 'admin', must_change_password: true } }));
|
||||
|
||||
component.onSubmit();
|
||||
expect(routerMock.navigate).toHaveBeenCalledWith(['/change-password']);
|
||||
});
|
||||
|
||||
it('redirige vers /dashboard si le mot de passe est déjà à jour', () => {
|
||||
const fixture = TestBed.createComponent(Login);
|
||||
const component = fixture.componentInstance;
|
||||
component.form.setValue({ email: 'a@a.com', password: 'secret' });
|
||||
|
||||
authMock.login.mockReturnValue(of({ principal: { role: 'lecteur', must_change_password: false } }));
|
||||
|
||||
component.onSubmit();
|
||||
expect(routerMock.navigate).toHaveBeenCalledWith(['/dashboard']);
|
||||
});
|
||||
|
||||
it('affiche un message générique sur un 401', () => {
|
||||
const fixture = TestBed.createComponent(Login);
|
||||
const component = fixture.componentInstance;
|
||||
component.form.setValue({ email: 'a@a.com', password: 'wrong' });
|
||||
|
||||
authMock.login.mockReturnValue(throwError(() => new HttpErrorResponse({ status: 401 })));
|
||||
|
||||
component.onSubmit();
|
||||
fixture.detectChanges(); // rend le bloc @if (errorMessage()) du template
|
||||
|
||||
expect(component.errorMessage()).toBe('Email ou mot de passe incorrect.');
|
||||
const errorEl = fixture.nativeElement.querySelector('.auth-error');
|
||||
expect(errorEl?.textContent).toContain('Email ou mot de passe incorrect.');
|
||||
});
|
||||
|
||||
it("affiche le délai d'attente sur un 429 avec Retry-After", () => {
|
||||
const fixture = TestBed.createComponent(Login);
|
||||
const component = fixture.componentInstance;
|
||||
component.form.setValue({ email: 'a@a.com', password: 'wrong' });
|
||||
|
||||
authMock.login.mockReturnValue(
|
||||
throwError(() => new HttpErrorResponse({ status: 429, headers: new HttpHeaders({ 'Retry-After': '30' }) }))
|
||||
);
|
||||
|
||||
component.onSubmit();
|
||||
fixture.detectChanges(); // rend aussi le sous-bloc @if (retryAfterSeconds(); as seconds)
|
||||
|
||||
expect(component.retryAfterSeconds()).toBe(30);
|
||||
const errorEl = fixture.nativeElement.querySelector('.auth-error');
|
||||
expect(errorEl?.textContent).toContain('30s');
|
||||
});
|
||||
|
||||
it('désactive le bouton tant que le formulaire est invalide', () => {
|
||||
const fixture = TestBed.createComponent(Login);
|
||||
fixture.detectChanges();
|
||||
|
||||
const button = fixture.nativeElement.querySelector('button[type="submit"]');
|
||||
expect(button.disabled).toBe(true);
|
||||
expect(fixture.nativeElement.querySelector('.auth-error')).toBeNull();
|
||||
});
|
||||
|
||||
it('déclenche onSubmit via la soumission réelle du formulaire (ngSubmit)', () => {
|
||||
const fixture = TestBed.createComponent(Login);
|
||||
const component = fixture.componentInstance;
|
||||
component.form.setValue({ email: 'a@a.com', password: 'secret' });
|
||||
fixture.detectChanges();
|
||||
|
||||
authMock.login.mockReturnValue(of({ principal: { role: 'lecteur', must_change_password: false } }));
|
||||
|
||||
const form = fixture.nativeElement.querySelector('form');
|
||||
form.dispatchEvent(new Event('submit'));
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(authMock.login).toHaveBeenCalledWith({ email: 'a@a.com', password: 'secret' });
|
||||
});
|
||||
});
|
||||
@@ -1,55 +0,0 @@
|
||||
import { Component, inject, signal } from '@angular/core';
|
||||
import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';
|
||||
import { Router } from '@angular/router';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { AuthService } from '../../../core/services/auth.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-login',
|
||||
standalone: true,
|
||||
imports: [ReactiveFormsModule],
|
||||
templateUrl: './login.html',
|
||||
styleUrl: './login.scss',
|
||||
})
|
||||
export class Login {
|
||||
private fb = inject(FormBuilder);
|
||||
private auth = inject(AuthService);
|
||||
private router = inject(Router);
|
||||
|
||||
errorMessage = signal<string | null>(null);
|
||||
retryAfterSeconds = signal<number | null>(null);
|
||||
isLoading = signal(false);
|
||||
|
||||
form = this.fb.nonNullable.group({
|
||||
email: ['', [Validators.required, Validators.email]],
|
||||
password: ['', Validators.required],
|
||||
});
|
||||
|
||||
onSubmit(): void {
|
||||
if (this.form.invalid) return;
|
||||
|
||||
this.isLoading.set(true);
|
||||
this.errorMessage.set(null);
|
||||
this.retryAfterSeconds.set(null);
|
||||
|
||||
this.auth.login(this.form.getRawValue()).subscribe({
|
||||
next: (response) => {
|
||||
if (response.principal.must_change_password) {
|
||||
this.router.navigate(['/change-password']);
|
||||
return;
|
||||
}
|
||||
this.router.navigate(['/dashboard']);
|
||||
},
|
||||
error: (error: HttpErrorResponse) => {
|
||||
this.isLoading.set(false);
|
||||
if (error.status === 429) {
|
||||
const retryAfter = error.headers.get('Retry-After');
|
||||
this.retryAfterSeconds.set(retryAfter ? Number(retryAfter) : null);
|
||||
this.errorMessage.set('Trop de tentatives, réessayez plus tard.');
|
||||
return;
|
||||
}
|
||||
this.errorMessage.set('Email ou mot de passe incorrect.');
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,7 @@
|
||||
<div class="dashboard">
|
||||
<header class="dashboard__header">
|
||||
<div>
|
||||
<h1>Vue d'ensemble</h1>
|
||||
<p class="dashboard__subtitle">Consommation instantanée du parc</p>
|
||||
</div>
|
||||
<button type="button" class="logout-button" (click)="onLogout()">Déconnexion</button>
|
||||
<h1>Vue d'ensemble</h1>
|
||||
<p class="dashboard__subtitle">Consommation instantanée du parc</p>
|
||||
</header>
|
||||
|
||||
@if (error(); as message) {
|
||||
|
||||
@@ -144,30 +144,3 @@ h2 {
|
||||
.alert-item__message {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,8 +4,6 @@ import { of, throwError } from 'rxjs';
|
||||
import { Dashboard } from './dashboard';
|
||||
import { StatsService } from '../../core/services/stats.service';
|
||||
import { AlertsService } from '../../core/services/alerts.service';
|
||||
import {AuthService} from '../../core/services/auth.service';
|
||||
import {Router} from '@angular/router';
|
||||
|
||||
vi.mock('chart.js', () => {
|
||||
class ChartMock {
|
||||
@@ -94,58 +92,4 @@ describe('Dashboard', () => {
|
||||
|
||||
expect(fixture.componentInstance.alerts().length).toBe(0);
|
||||
});
|
||||
|
||||
it('appelle logout et redirige vers /login au clic sur le bouton de déconnexion', () => {
|
||||
const statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
||||
const alertsMock = { getAlerts: vi.fn().mockReturnValue(of([])) };
|
||||
const authMock = { logout: vi.fn().mockReturnValue(of(undefined)), clearSession: vi.fn() };
|
||||
const routerMock = { navigate: vi.fn() };
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [Dashboard],
|
||||
providers: [
|
||||
{ provide: StatsService, useValue: statsMock },
|
||||
{ provide: AlertsService, useValue: alertsMock },
|
||||
{ provide: AuthService, useValue: authMock },
|
||||
{ provide: Router, useValue: routerMock },
|
||||
],
|
||||
});
|
||||
|
||||
const fixture = TestBed.createComponent(Dashboard);
|
||||
fixture.detectChanges();
|
||||
|
||||
const button = fixture.nativeElement.querySelector('.logout-button');
|
||||
button.click();
|
||||
|
||||
expect(authMock.logout).toHaveBeenCalled();
|
||||
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
|
||||
});
|
||||
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 alertsMock = { getAlerts: vi.fn().mockReturnValue(of([])) };
|
||||
const authMock = {
|
||||
logout: vi.fn().mockReturnValue(throwError(() => new Error('réseau indisponible'))),
|
||||
clearSession: vi.fn(),
|
||||
};
|
||||
const routerMock = { navigate: vi.fn() };
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [Dashboard],
|
||||
providers: [
|
||||
{ provide: StatsService, useValue: statsMock },
|
||||
{ provide: AlertsService, useValue: alertsMock },
|
||||
{ provide: AuthService, useValue: authMock },
|
||||
{ provide: Router, useValue: routerMock },
|
||||
],
|
||||
});
|
||||
|
||||
const fixture = TestBed.createComponent(Dashboard);
|
||||
fixture.detectChanges();
|
||||
|
||||
const button = fixture.nativeElement.querySelector('.logout-button');
|
||||
button.click();
|
||||
|
||||
expect(authMock.clearSession).toHaveBeenCalled();
|
||||
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,12 +2,10 @@ import { Component, OnInit, inject, signal, DestroyRef } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { timer, switchMap, catchError, EMPTY, Observable } from 'rxjs';
|
||||
import { DecimalPipe } from '@angular/common';
|
||||
import { Router } from '@angular/router';
|
||||
import { StatsService } from '../../core/services/stats.service';
|
||||
import { ConsumptionGauge } from '../../shared/components/consumption-gauge/consumption-gauge';
|
||||
import { SiteLoadChart } from '../../shared/components/site-load-chart/site-load-chart';
|
||||
import { AlertsService } from '../../core/services/alerts.service';
|
||||
import { AuthService } from '../../core/services/auth.service';
|
||||
import { StatsSummary } from '../../shared/models/stats.model';
|
||||
import { Alert } from '../../shared/models/alert.model';
|
||||
|
||||
@@ -25,8 +23,6 @@ const UNAVAILABLE_MESSAGE =
|
||||
export class Dashboard implements OnInit {
|
||||
private statsService = inject(StatsService);
|
||||
private alertsService = inject(AlertsService);
|
||||
private auth = inject(AuthService);
|
||||
private router = inject(Router);
|
||||
private destroyRef = inject(DestroyRef);
|
||||
|
||||
stats = signal<StatsSummary | null>(null);
|
||||
@@ -54,17 +50,6 @@ export class Dashboard implements OnInit {
|
||||
});
|
||||
}
|
||||
|
||||
onLogout(): void {
|
||||
this.auth.logout().subscribe({
|
||||
next: () => this.router.navigate(['/login']),
|
||||
error: () => {
|
||||
// Même si l'appel réseau échoue, on considère l'utilisateur déconnecté localement.
|
||||
this.auth.clearSession();
|
||||
this.router.navigate(['/login']);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private reportUnavailable(): Observable<never> {
|
||||
this.error.set(UNAVAILABLE_MESSAGE);
|
||||
return EMPTY;
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
export type Role = 'lecteur' | 'operateur' | 'admin';
|
||||
|
||||
export interface LoginRequest {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface PasswordChangeRequest {
|
||||
current_password: string;
|
||||
new_password: string;
|
||||
}
|
||||
|
||||
export interface Principal {
|
||||
id: string;
|
||||
email: string;
|
||||
role: Role;
|
||||
kind: 'human';
|
||||
must_change_password: boolean;
|
||||
}
|
||||
|
||||
export interface TokenResponse {
|
||||
access_token: string;
|
||||
token_type: string;
|
||||
expires_in: number;
|
||||
principal: Principal;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
export const environment = {
|
||||
production: true,
|
||||
apiUrl: '/api/v1',
|
||||
apiUrl: 'http://localhost:8000/api/v1',
|
||||
useMockFixtures: false,
|
||||
};
|
||||
|
||||
@@ -74,9 +74,9 @@ collecteur ne vient le lire.
|
||||
|
||||
| Domaine | Technologie | Emplacement | Statut | Ce qui existe réellement |
|
||||
|---|---|---|---|---|
|
||||
| Backend | FastAPI, Python 3.14 | `apps/backend` | `En cours` | Factory, configuration, journalisation, 2 sondes de santé, `/metrics`. Aucune couche métier |
|
||||
| Backend | FastAPI, Python 3.14 | `apps/backend` | `En cours` | Factory, configuration, journalisation, 2 sondes de santé, `/metrics`, contrat OpenAPI versionné, routes `sites` et `recommendations` 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 |
|
||||
| Base | PostgreSQL 17 + TimescaleDB | `db` | `Fait` | Bootstrap de l'extension, base de test, chaîne Alembic. Aucune table applicative |
|
||||
| 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`) |
|
||||
| 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 |
|
||||
| ETL | Apache Airflow | `etl/airflow` | `Cible` | Rien |
|
||||
|
||||
@@ -35,9 +35,10 @@ flowchart TB
|
||||
| `backend` | Construite depuis `apps/backend` | `depends_on: db, condition: service_healthy`. **N'embarque pas le source** : toute modification impose `docker compose up -d --build backend` |
|
||||
|
||||
**La boucle de développement n'utilise pas le service `backend`.** `make db-up` puis `make dev` :
|
||||
seule la base tourne en conteneur, l'API tourne sur le poste avec le rechargement à chaud. Le
|
||||
service `backend` sert la stack complète et la recette. Les deux occupent le port 8000, ils ne se
|
||||
lancent donc pas ensemble.
|
||||
seule la base tourne en conteneur, l'API et `ng serve` tournent sur le poste avec le rechargement
|
||||
à chaud, lancés ensemble par `make dev` (`make dev-backend`/`make dev-frontend` pour lancer l'un
|
||||
des deux seul). Le service `backend` sert la stack complète et la recette. Les deux occupent le
|
||||
port 8000, ils ne se lancent donc pas ensemble.
|
||||
|
||||
Deux pièges sont documentés en tête du `docker-compose.yml`, ils ne se devinent pas :
|
||||
|
||||
|
||||
@@ -12,11 +12,11 @@ Les quatre couches existent désormais, portées par l'authentification.
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
ep["endpoints<br/>health, auth, users"]
|
||||
ep["endpoints<br/>health, auth, users, sites,<br/>recommendations, stats"]
|
||||
sc["schemas<br/>Pydantic"]
|
||||
sv["services<br/>AuthService, UserService"]
|
||||
rp["repositories<br/>user, refresh_token,<br/>login_attempt, audit_log"]
|
||||
md["models<br/>4 tables"]
|
||||
sv["services<br/>AuthService, UserService,<br/>SiteService, RecommendationService,<br/>StatsService"]
|
||||
rp["repositories<br/>user, refresh_token,<br/>login_attempt, audit_log,<br/>site, recommendation, reading"]
|
||||
md["models<br/>10 tables"]
|
||||
db[("PostgreSQL")]
|
||||
|
||||
ep --> sc
|
||||
@@ -126,29 +126,50 @@ Deux fichiers d'environnement, deux usages : `.env` à la racine alimente `docke
|
||||
|
||||
## Routes exposées
|
||||
|
||||
| Méthode | Chemin | Dans l'OpenAPI | Rôle |
|
||||
| Méthode | Chemin | Rôle | Erreurs déclarées |
|
||||
|---|---|---|---|
|
||||
| GET | `/api/v1/health/live` | oui | Le processus répond. Ne touche pas la base |
|
||||
| GET | `/api/v1/health/ready` | oui | La base répond **et** l'extension TimescaleDB est chargée |
|
||||
| POST | `/api/v1/auth/login` | oui | Ouvre une session. Publique |
|
||||
| POST | `/api/v1/auth/refresh` | oui | Fait tourner la session. Cookie seulement |
|
||||
| POST | `/api/v1/auth/logout` | oui | Ferme la session courante. Idempotente |
|
||||
| POST | `/api/v1/auth/logout-all` | oui | Ferme toutes les sessions du compte |
|
||||
| POST | `/api/v1/auth/password` | oui | Change son propre mot de passe |
|
||||
| GET | `/api/v1/auth/me` | oui | Décrit le compte connecté |
|
||||
| GET | `/api/v1/users` | oui | Liste les comptes. `admin` |
|
||||
| POST | `/api/v1/users` | oui | Crée un compte, rend un mot de passe provisoire. `admin` |
|
||||
| PATCH | `/api/v1/users/{id}` | oui | Change le rôle ou l'activation. `admin` |
|
||||
| POST | `/api/v1/users/{id}/password-reset` | oui | Réinitialise et ferme les sessions. `admin` |
|
||||
| GET | `/metrics` | non | Format Prometheus. Jeton requis si `APP_METRICS_TOKEN` est posé |
|
||||
| GET | `/docs`, `/redoc`, `/openapi.json` | non | Fermés en `staging` et en `prod` |
|
||||
| GET | `/api/v1/health/live` | Le processus répond. Ne touche pas la base | 500 |
|
||||
| GET | `/api/v1/health/ready` | La base répond **et** l'extension TimescaleDB est chargée | 503, 500 |
|
||||
| POST | `/api/v1/auth/login` | Ouvre une session. Publique | 401, 422, 429, 500 |
|
||||
| POST | `/api/v1/auth/refresh` | Fait tourner la session. Cookie seulement | 401, 403, 500 |
|
||||
| POST | `/api/v1/auth/logout` | Ferme la session courante. Idempotente | 403, 500 |
|
||||
| POST | `/api/v1/auth/logout-all` | Ferme toutes les sessions du compte | 401, 403, 500 |
|
||||
| POST | `/api/v1/auth/password` | Change son propre mot de passe | 401, 403, 422, 500 |
|
||||
| GET | `/api/v1/auth/me` | Décrit le compte connecté | 401, 500 |
|
||||
| GET | `/api/v1/users` | Liste les comptes. `admin` | 401, 403, 500 |
|
||||
| POST | `/api/v1/users` | Crée un compte, rend un mot de passe provisoire. `admin` | 401, 403, 409, 422, 500 |
|
||||
| PATCH | `/api/v1/users/{id}` | Change le rôle ou l'activation. `admin` | 400, 401, 403, 404, 409, 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/{site_id}` | Décrit 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/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/stats/summary` | Résume la consommation instantanée du parc. `lecteur` | 401, 403, 500 |
|
||||
| GET | `/metrics` | Format Prometheus, hors du schéma. Jeton requis si `APP_METRICS_TOKEN` est posé | |
|
||||
| GET | `/docs`, `/redoc`, `/openapi.json` | Hors du schéma. Fermés en `staging` et en `prod` | |
|
||||
|
||||
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.
|
||||
|
||||
**Quatre routes seulement sont publiques** : les deux sondes, `/auth/login` et `/auth/logout`.
|
||||
`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
|
||||
donc de modifier la liste dans ce fichier de test.
|
||||
|
||||
Aucune route métier n'existe à ce jour. Le contrat détaillé pour le frontend est dans
|
||||
`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 (`reading`, `dataset`, `prediction`, `recommendation`) : les
|
||||
quatre couches `endpoints → services → repositories → models` y sont toutes présentes, sur des
|
||||
tables déjà créées par la révision Alembic `e6d2026091501`. Elles n'exigent que le rôle `lecteur`,
|
||||
contrairement aux routes d'administration qui exigent `admin`. `SiteRepository` lit par
|
||||
`AsyncSession.scalar()` (une ligne) et `AsyncSession.scalars()` (plusieurs lignes) plutôt que par
|
||||
`execute()`, ce qui la rend testable par la fixture `fake_session` au niveau endpoint sans base
|
||||
réelle. `GET /recommendations` et `GET /recommendations/{recommendation_id}` reprennent le même
|
||||
gabarit à la lettre, `recommendation_id` étant un entier plutôt qu'un texte. Une recommandation ne
|
||||
porte pas `site_id` : elle remonte à un site par sa seule `alert_id`, `alert` n'étant pas encore
|
||||
exposée. `GET /stats/summary` agrège deux repositories (`SiteRepository`, `ReadingRepository`)
|
||||
dans un service dédié plutôt que d'exposer une table : elle n'entre donc pas dans ce gabarit
|
||||
route-par-table. Le contrat détaillé pour le frontend est dans
|
||||
[31-contrat-authentification.md](31-contrat-authentification.md).
|
||||
|
||||
### `/health/ready`
|
||||
@@ -182,6 +203,62 @@ sequenceDiagram
|
||||
end
|
||||
```
|
||||
|
||||
## Contrat OpenAPI
|
||||
|
||||
Statut : `Fait`.
|
||||
|
||||
Le schéma est servi sur `/openapi.json`, `/docs` et `/redoc`, fermés en `staging` et en `prod`.
|
||||
Il est aussi **versionné** dans [`apps/backend/openapi.json`](../../apps/backend/openapi.json) :
|
||||
|
||||
```bash
|
||||
make openapi
|
||||
```
|
||||
|
||||
Pourquoi un fichier en plus de la route. Une route qui change son contrat public le montre alors
|
||||
dans la diff de la pull request, et le frontend dispose d'une référence lisible sans lancer l'API.
|
||||
`tests/api/test_openapi.py` compare le fichier au schéma généré et échoue si l'un bouge sans
|
||||
l'autre ; le fichier vivant sous `apps/backend/`, le filtre de chemins de `backend.yml` le couvre.
|
||||
|
||||
**Le schéma exporté ne dépend pas du poste.** `settings_du_contrat()` pose le nom, la version et
|
||||
le préfixe, et coupe la lecture du `.env`. Sans cela, un `APP_API_PREFIX` local suffirait à faire
|
||||
diverger le fichier d'une machine à l'autre, et le test deviendrait un oracle de configuration
|
||||
plutôt qu'un garde-fou de contrat.
|
||||
|
||||
Trois champs sont volontairement absents d'`info`, parce qu'ils poseraient une décision qui n'est
|
||||
pas prise :
|
||||
|
||||
| Champ | Pourquoi |
|
||||
|---|---|
|
||||
| `servers` | L'URL publique dépend de l'ingress, question ouverte dans [10-infra.md](10-infra.md) |
|
||||
| `license_info` | Aucune licence n'est choisie |
|
||||
| `contact` | Aucun canal de support n'existe |
|
||||
|
||||
Deux schémas de sécurité sont déclarés : `Jeton d'accès` pour le porteur JWT, et
|
||||
`Cookie de rafraîchissement` pour `/auth/refresh` et `/auth/logout`. **Le second est purement
|
||||
documentaire** : son `auto_error=False` garantit qu'il ne décide d'aucun refus. Le passer à vrai
|
||||
ferait répondre 403 avant d'atteindre `lit_le_cookie()`, et `/auth/refresh` cesserait de rendre le
|
||||
401 sur lequel le frontend déclenche sa déconnexion.
|
||||
|
||||
Les modèles de `app/schemas/errors.py` décrivent ce que les gestionnaires renvoient réellement.
|
||||
`ValidationErrorResponse` remplace le `HTTPValidationError` par défaut de FastAPI, dont la clé
|
||||
`loc` n'apparaît dans aucune réponse de cette API : `validation_error_handler()` rend `champ` et
|
||||
`type`. Renommer un champ là-bas sans le faire ici rend la documentation fausse en silence.
|
||||
|
||||
### Ajouter une route métier
|
||||
|
||||
Checklist pour toute nouvelle route sur le gabarit `sites`/`alerts`/`recommendations`/`stats`
|
||||
(`reading`, `dataset`, `prediction`) :
|
||||
|
||||
1. Composer ses `responses=` depuis `app/api/openapi.py` : `REPONSES_LECTEUR`/`REPONSES_ADMIN`
|
||||
au niveau de l'`include_router()` du routeur, `REPONSE_VALIDATION` et les codes locaux
|
||||
(404, 409, ...) directement sur l'endpoint qui les rend.
|
||||
2. Décrire son tag dans `TAGS`.
|
||||
3. Si elle passe par `require_role` (`LecteurDep`/`OperateurDep`/`AdminDep`), l'ajouter à
|
||||
`ROUTES_A_ROLE` dans `tests/api/test_openapi.py`. Si elle passe par `require_trusted_origin`,
|
||||
l'ajouter à `ORIGINE_VERIFIEE`. **Ces deux listes sont maintenues à la main, pas dérivées** :
|
||||
une route oubliée n'y est pas détectée automatiquement.
|
||||
4. `make openapi`, puis `uv run pytest tests/api/test_openapi.py`.
|
||||
|
||||
## Sécurité
|
||||
|
||||
Voir la vue consolidée dans [00-vue-ensemble.md](00-vue-ensemble.md) et les décisions dans les
|
||||
|
||||
@@ -108,8 +108,9 @@ déploiement, en même temps que sera tranchée la question de l'ingress dans
|
||||
le message d'erreur arrive avant toute compilation. Un poste en 22.21 ou en 24.12 ne peut donc ni
|
||||
tester ni construire le frontend.
|
||||
|
||||
Le frontend **n'a pas de cible dans le `Makefile` racine** et **aucun service dans
|
||||
`docker-compose.yml`** : il se pilote uniquement par `npm`, depuis `apps/frontend`. Le port 4200
|
||||
Le frontend a ses cibles dans le `Makefile` racine (`install-frontend`, `dev-frontend`,
|
||||
englobées par `install` et `dev`), mais **aucun service dans `docker-compose.yml`** : en
|
||||
développement il tourne toujours directement via `npm`, depuis `apps/frontend`. Le port 4200
|
||||
n'apparaît dans le compose que comme valeur par défaut d'`APP_CORS_ORIGINS`, côté backend.
|
||||
|
||||
Un `Dockerfile` frontend existe sur la branche `feat/pipeline-cd`, mais il est mono-étage et sans
|
||||
|
||||
@@ -26,7 +26,9 @@ gérer : il suffit d'envoyer les requêtes avec `withCredentials`.
|
||||
| PATCH | `/api/v1/users/{id}` | jeton d'accès, `admin` | `200` `UserResponse` |
|
||||
| POST | `/api/v1/users/{id}/password-reset` | jeton d'accès, `admin` | `200` `TemporaryPasswordResponse` |
|
||||
|
||||
Le schéma exact est dans `/docs` (Swagger), servi en local et en développement.
|
||||
Le schéma exact est dans [`apps/backend/openapi.json`](../../apps/backend/openapi.json),
|
||||
lisible sans lancer l'API, et servi par `/docs` en local et en développement. La table des
|
||||
codes d'erreur ci-dessous reste la référence de comportement, le schéma celle de forme.
|
||||
|
||||
## Charges utiles
|
||||
|
||||
@@ -66,6 +68,7 @@ Le secret de rafraîchissement **n'apparaît jamais** dans le corps de la répon
|
||||
| `401` sur `/auth/refresh` | session révoquée, expirée ou rejouée | **déconnecter** et renvoyer vers la page de connexion |
|
||||
| `403` avec `detail: "password_change_required"` | mot de passe provisoire | rediriger vers l'écran de changement de mot de passe |
|
||||
| `403` avec `detail: "Droits insuffisants"` | rôle trop bas | masquer ou griser l'action, ne pas déconnecter |
|
||||
| `403` sur `/auth/refresh`, `/logout`, `/logout-all`, `/password` | origine hors liste autorisée (voir « Origines autorisées ») | erreur de configuration réseau, pas un cas à gérer par l'utilisateur |
|
||||
| `422` | corps invalide | le détail donne `champ` et `type`, jamais la valeur envoyée |
|
||||
|
||||
## Les quatre règles qui comptent
|
||||
|
||||
@@ -4,12 +4,12 @@ PostgreSQL 17 avec l'extension TimescaleDB. Le choix, ses alternatives et ses co
|
||||
dans l'[ADR 0001](../adr/0001-postgresql-timescaledb.md), qui fait foi. Ce document décrit le
|
||||
système qui en découle.
|
||||
|
||||
## Avertissement
|
||||
## Ce que couvre ce document
|
||||
|
||||
**Aucune table applicative n'existe à ce jour.** `Base.metadata` est vide, `app/models/` ne
|
||||
contient qu'un commentaire, l'unique révision Alembic ne crée aucune table, et aucune hypertable
|
||||
n'a été déclarée. Tout ce qui suit sous le statut `Cible` est une proposition de structure, pas un
|
||||
relevé du code. Le modèle sera arrêté au jalon J2.
|
||||
**Dix tables applicatives existent** : quatre pour l'authentification, six pour les données
|
||||
d'énergie, dont l'hypertable `reading`. Les sections marquées `Fait` relèvent le code. Celles
|
||||
marquées `Cible` décrivent ce qui n'est pas écrit, au premier rang desquelles la chaîne
|
||||
d'ingestion, les agrégats continus, la compression et la rétention.
|
||||
|
||||
## Trois emplacements, trois rôles
|
||||
|
||||
@@ -35,7 +35,7 @@ Statut : `Fait`.
|
||||
- `db/init/100-extensions.sql` crée l'extension `timescaledb`.
|
||||
- `db/init/110-test-database.sql` crée `enervision_test`, dont le nom est attendu en dur par
|
||||
`apps/backend/tests/conftest.py`.
|
||||
- Quatre révisions Alembic. La première, `5353c0e4f094`, **ne crée aucune table** : elle
|
||||
- Cinq révisions Alembic. La première, `5353c0e4f094`, **ne crée aucune table** : elle
|
||||
établit `alembic_version` et refuse de s'appliquer si l'extension manque :
|
||||
|
||||
```sql
|
||||
@@ -48,16 +48,18 @@ Cette garde forme paire avec le 503 de `/api/v1/health/ready`. Un bootstrap saut
|
||||
au démarrage de l'API : ces deux gardes le rendent visible tôt, des deux côtés.
|
||||
|
||||
Les trois suivantes créent les tables de l'authentification, décrites plus bas : `app_user`,
|
||||
puis `login_attempt` et `audit_log`, puis `refresh_token`.
|
||||
puis `login_attempt` et `audit_log`, puis `refresh_token`. La cinquième, `e6d2026091501`, crée
|
||||
les six tables de données décrites en fin de document et déclare l'hypertable `reading`.
|
||||
|
||||
## Cycle de vie d'une mesure
|
||||
|
||||
Statut : `Cible`. Aucun de ces maillons n'existe.
|
||||
Statut : `Cible`, sauf l'hypertable `reading` qui existe. Ni l'ingestion, ni les agrégats
|
||||
continus, ni la compression, ni la rétention ne sont écrits.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
src["Source de mesures"] -.-> ing["Ingestion Airflow"]
|
||||
ing -.-> hy[("Hypertable mesure")]
|
||||
ing -.-> hy[("Hypertable reading")]
|
||||
hy -.-> agg[("Agrégat continu")]
|
||||
hy -.-> comp["Compression"]
|
||||
hy -.-> ret["Rétention"]
|
||||
@@ -133,67 +135,46 @@ donc **pas** une hypertable : une politique de rétention émettrait des `DELETE
|
||||
refuseraient. `login_attempt`, à l'inverse, est faite pour se purger, puisque son volume est
|
||||
piloté par l'attaquant.
|
||||
|
||||
## Modèle métier
|
||||
|
||||
Statut : `Cible`. Les entités ci-dessous sont des **candidates**, à valider en J2. Elles
|
||||
s'appuient sur les gabarits de [`apps/backend/TESTING.md`](../../apps/backend/TESTING.md), qui
|
||||
évoquent déjà un modèle `Site`, un `SiteRepository` et un `ConsumptionService` exposant un
|
||||
`total_kwh(site_id)`.
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
SITE ||--o{ POINT_DE_MESURE : porte
|
||||
POINT_DE_MESURE ||--o{ MESURE : produit
|
||||
|
||||
SITE {
|
||||
int id PK
|
||||
string nom
|
||||
}
|
||||
POINT_DE_MESURE {
|
||||
int id PK
|
||||
int site_id FK
|
||||
string libelle
|
||||
string unite
|
||||
}
|
||||
MESURE {
|
||||
timestamptz horodatage PK
|
||||
int point_id PK
|
||||
double valeur
|
||||
}
|
||||
```
|
||||
|
||||
`MESURE` est la table destinée à devenir une hypertable, partitionnée sur `horodatage`. Sa clé
|
||||
primaire doit inclure la colonne de temps : TimescaleDB l'exige, une clé sur le seul identifiant
|
||||
de point serait refusée.
|
||||
|
||||
## Gabarit de révision créant une hypertable
|
||||
|
||||
Conforme à la règle de l'ADR 0001 : table et hypertable dans la même révision.
|
||||
Conforme à la règle de l'ADR 0001 : table et hypertable dans la même révision. La révision
|
||||
`e6d2026091501` en est l'exemple réel, réduit ici à l'essentiel.
|
||||
|
||||
```python
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"mesure",
|
||||
sa.Column("horodatage", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("point_id", sa.Integer(), sa.ForeignKey("point_de_mesure.id"), nullable=False),
|
||||
sa.Column("valeur", sa.Float(), nullable=False),
|
||||
sa.PrimaryKeyConstraint("horodatage", "point_id"),
|
||||
"reading",
|
||||
sa.Column("reading_id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||
sa.Column("site_id", sa.Text(), nullable=False),
|
||||
sa.Column("timestamp", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.PrimaryKeyConstraint("reading_id", "timestamp"),
|
||||
)
|
||||
op.execute(
|
||||
"SELECT create_hypertable('reading', by_range('timestamp'), "
|
||||
"create_default_indexes => FALSE)"
|
||||
)
|
||||
op.execute("SELECT create_hypertable('mesure', by_range('horodatage'))")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("mesure")
|
||||
op.drop_table("reading")
|
||||
```
|
||||
|
||||
La clé primaire inclut la colonne de temps parce que TimescaleDB l'exige : toute contrainte
|
||||
unique d'une hypertable doit porter la colonne de partitionnement, et une clé sur le seul
|
||||
`reading_id` serait refusée par `create_hypertable`.
|
||||
|
||||
`create_default_indexes => FALSE` écarte l'index que TimescaleDB pose d'office sur la seule
|
||||
colonne de temps : les index déclarés dans la révision le couvrent déjà.
|
||||
|
||||
`drop_table` suffit au retour arrière : supprimer la table supprime l'hypertable et ses partitions.
|
||||
|
||||
## Conventions
|
||||
|
||||
- **Noms au singulier**, en minuscules, sans préfixe de table.
|
||||
- **Noms au singulier**, en minuscules, sans préfixe de table : `app_user`, `reading`.
|
||||
- **Toute colonne de temps en `timestamptz`.** Jamais de `timestamp` nu : une mesure sans fuseau
|
||||
devient ininterprétable dès le premier changement d'heure.
|
||||
- **La colonne de partitionnement s'appelle `horodatage`** et entre dans la clé primaire.
|
||||
- **La colonne de partitionnement entre dans la clé primaire.** Dans `reading` elle s'appelle
|
||||
`timestamp` : c'est un nom de colonne, son type reste `timestamptz`.
|
||||
- **Les politiques de rétention et de compression** vont dans `db/migrations/`, pas dans Alembic :
|
||||
elles ne découlent pas du schéma applicatif.
|
||||
- **Tout modèle doit être importé dans `app/models/__init__.py`**, sans quoi
|
||||
@@ -201,13 +182,12 @@ def downgrade() -> None:
|
||||
|
||||
## Questions ouvertes
|
||||
|
||||
Elles relèvent du jalon J2, « valider le périmètre retenu », et bloquent le modèle définitif.
|
||||
Elles relèvent du jalon J2, « valider le périmètre retenu ». Le schéma est livré : ce qui suit
|
||||
porte sur son exploitation, plus sur sa forme.
|
||||
|
||||
- **Quelles sources de mesures**, et selon quel protocole elles sont collectées.
|
||||
- **Quelle granularité** à l'ingestion : la seconde, la minute, le quart d'heure.
|
||||
- **Quels agrégats continus**, et sur quelles fenêtres.
|
||||
- **Quelle profondeur de rétention** en données brutes, et à partir de quand on compresse.
|
||||
- **Quelles unités** sont manipulées, et si une même table les mélange.
|
||||
- **Multi-tenant ou non** : un site appartient-il à un client, et faut-il cloisonner les lectures.
|
||||
|
||||
## Modélisation détaillée des données
|
||||
@@ -220,12 +200,11 @@ jusqu’aux recommandations proposées à l’utilisateur.
|
||||
### Schéma de données
|
||||
|
||||
Le diagramme ci-dessous présente les tables et leurs relations.
|
||||
Il décrit une structure de conception ; les migrations correspondantes
|
||||
restent à implémenter.
|
||||
La révision `e6d2026091501` les crée.
|
||||
|
||||

|
||||
|
||||
*Figure — Modélisation des données EnerVision.*
|
||||
*Figure : Modélisation des données EnerVision.*
|
||||
|
||||
### Description des tables
|
||||
|
||||
@@ -234,15 +213,15 @@ des données.
|
||||
|
||||
| Table | Rôle | Origine des informations |
|
||||
|---|---|---|
|
||||
| `datasets` | Identifier les jeux historiques, retrouver leurs fichiers et conserver leurs métadonnées | Archive CSV/JSON et informations ajoutées lors de l’import |
|
||||
| `sites` | Regrouper les informations des sites : identifiant, nom, type et caractéristiques disponibles | CSV et API Mock `/api/v1/sites` |
|
||||
| `readings` | Stocker les mesures, leur provenance, leur qualité et les éventuelles valeurs imputées | CSV et API Mock `/current` et `/readings` |
|
||||
| `predictions` | Conserver les prévisions, leur période cible et la référence du modèle utilisé | Traitements ML d’EnerVision |
|
||||
| `alerts` | Enregistrer les alertes, leur type, leur gravité et leur message | API Mock `/alerts` et détections EnerVision |
|
||||
| `recommendations` | Proposer des actions et expliquer la règle qui les motive | Règles métier d’EnerVision |
|
||||
| `dataset` | Identifier les jeux historiques, retrouver leurs fichiers et conserver leurs métadonnées | Archive CSV/JSON et informations ajoutées lors de l’import |
|
||||
| `site` | Regrouper les informations des sites : identifiant, nom, type et caractéristiques disponibles | CSV et API Mock `/api/v1/sites` |
|
||||
| `reading` | Stocker les mesures, leur provenance, leur qualité et les éventuelles valeurs imputées | CSV et API Mock `/current` et `/readings` |
|
||||
| `prediction` | Conserver les prévisions, leur période cible et la référence du modèle utilisé | Traitements ML d’EnerVision |
|
||||
| `alert` | Enregistrer les alertes, leur type, leur gravité et leur message | API Mock `/alerts` et détections EnerVision |
|
||||
| `recommendation` | Proposer des actions et expliquer la règle qui les motive | Règles métier d’EnerVision |
|
||||
|
||||
Les anomalies historiques décrites dans les JSON sont conservées
|
||||
dans `datasets.metadata`. Elles servent à l’analyse des données
|
||||
dans `dataset.metadata`. Elles servent à l’analyse des données
|
||||
et ne sont pas considérées comme des alertes actuelles.
|
||||
|
||||
### Relations entre les tables
|
||||
|
||||
@@ -10,7 +10,7 @@ contredisent, c'est l'ADR qui fait foi et la vue qui est en retard.
|
||||
|---|---|
|
||||
| [00-vue-ensemble.md](00-vue-ensemble.md) | Jalons du projet, contexte, conteneurs, sécurité, flux bout en bout |
|
||||
| [10-infra.md](10-infra.md) | Poste de développement, cible k3s, décisions figées, ports et noms |
|
||||
| [20-backend.md](20-backend.md) | Couches FastAPI, séquence de démarrage, routes, configuration |
|
||||
| [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 |
|
||||
| [31-contrat-authentification.md](31-contrat-authentification.md) | Ce que le frontend doit savoir pour coder la connexion |
|
||||
| [40-data.md](40-data.md) | Frontières `db/` et `alembic/`, cycle de vie d'une mesure, modèle |
|
||||
|
||||
@@ -8,8 +8,9 @@ de réponse honnête.
|
||||
Ce qui est défendable, c'est une ligne par contrôle réellement implémenté, l'item qu'il adresse,
|
||||
et une section qui dit ce qui n'est pas couvert et pourquoi.
|
||||
|
||||
Statut : `Fait` pour le périmètre authentification et autorisation. Les endpoints métier
|
||||
n'existent pas encore, donc plusieurs lignes resteront à compléter.
|
||||
Statut : `Fait` pour le périmètre authentification et autorisation. `GET /sites` et
|
||||
`GET /recommendations`, chacune avec sa route de détail, sont les premiers endpoints métier, en
|
||||
lecture seule ; plusieurs lignes resteront à compléter une fois les endpoints d'écriture posés.
|
||||
|
||||
## Contrôles en place
|
||||
|
||||
@@ -48,7 +49,7 @@ règles Bandit. Ajouter Bandit à la CI serait redondant, contrairement à ce qu
|
||||
|
||||
| Item | État | Raison |
|
||||
|---|---|---|
|
||||
| **API1 Broken Object Level Authorization** | **ouvert** | Les rôles sont globaux, il n'y a pas de portée par site. Un opérateur du site A pourra agir sur le site B dès que les endpoints métier existeront. Correctif prévu : table d'affectation compte-site, contrôle d'appartenance dans la même dépendance que le contrôle de rôle. |
|
||||
| **API1 Broken Object Level Authorization** | **ouvert** | Les rôles sont globaux, il n'y a pas de portée par site : `GET /sites/{site_id}` et `GET /recommendations/{recommendation_id}` répondent à tout compte `lecteur` pour n'importe quel site ou recommandation, sans vérifier une affectation compte-site qui n'existe pas encore. Un opérateur du site A pourra agir sur le site B dès que les endpoints d'écriture métier existeront. Correctif prévu : table d'affectation compte-site, contrôle d'appartenance dans la même dépendance que le contrôle de rôle. |
|
||||
| **API4, lectures de séries temporelles** | **ouvert** | Pas encore d'endpoint métier, donc ni pagination plafonnée, ni fenêtre temporelle maximale, ni `statement_timeout`. C'est la façon la plus probable dont la démonstration tombera : une requête sur dix ans d'historique suffit. |
|
||||
| **API8 Security Misconfiguration, transport** | **ouvert** | Pas de TLS, donc ni HSTS, ni cookie `Secure` réellement posé en production. Ils appartiennent au terminateur TLS, qui n'existe pas. |
|
||||
| **API10 Unsafe Consumption of APIs** | **ouvert, et spécifique à ce projet** | L'API Mock de l'école n'a aucune authentification, tourne en HTTP clair sur le réseau de l'école, et expose un endpoint mutatif à quiconque. Sa réponse doit être traitée comme une entrée hostile : bornes physiques, taille de tableau plafonnée, timeout, et frontière d'anti-corruption. La conséquence la plus sérieuse n'est pas la fausse alerte, c'est l'empoisonnement du jeu d'entraînement du modèle de prédiction. |
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
locals {
|
||||
frontend_environments = {
|
||||
dev = {
|
||||
source_dir = "${path.root}/../../../apps/frontend/dist/frontend-dev/browser"
|
||||
domain = "dev.enervision"
|
||||
}
|
||||
|
||||
rec = {
|
||||
source_dir = "${path.root}/../../../apps/frontend/dist/frontend-rec/browser"
|
||||
domain = "rec.enervision"
|
||||
}
|
||||
|
||||
prod = {
|
||||
source_dir = "${path.root}/../../../apps/frontend/dist/frontend-prod/browser"
|
||||
domain = "enervision"
|
||||
}
|
||||
}
|
||||
|
||||
selected_frontend = local.frontend_environments[var.deployment_environment]
|
||||
}
|
||||
|
||||
resource "null_resource" "frontend" {
|
||||
depends_on = [module.k3s]
|
||||
|
||||
triggers = {
|
||||
environment = var.deployment_environment
|
||||
|
||||
build_hash = sha256(join("", [
|
||||
for file in fileset("${path.root}/../../../apps/frontend/dist/frontend/browser", "**") :
|
||||
filesha256("${path.root}/../../../apps/frontend/dist/frontend/browser/${file}")
|
||||
]))
|
||||
}
|
||||
|
||||
// Variables pour la connexion SSH
|
||||
connection {
|
||||
type = "ssh"
|
||||
host = var.ssh_host
|
||||
port = var.ssh_port
|
||||
user = var.ssh_user
|
||||
private_key = file(pathexpand(var.ssh_private_key_path))
|
||||
}
|
||||
|
||||
// Lancement de script en SSH avec remote-exec
|
||||
// Installation de Nginx et initialisation du répertoire du frontend
|
||||
provisioner "remote-exec" {
|
||||
inline = [
|
||||
"sudo apt-get update",
|
||||
"sudo apt-get install -y nginx",
|
||||
"sudo mkdir -p /var/www/enervision",
|
||||
"sudo rm -rf /var/www/enervision/*"
|
||||
]
|
||||
}
|
||||
|
||||
// Copie des fichiers vers le serveur
|
||||
provisioner "file" {
|
||||
source = "${path.root}/../../../apps/frontend/dist/frontend/browser/"
|
||||
destination = "/tmp/enervision-frontend"
|
||||
}
|
||||
|
||||
// Déplacement des fichiers
|
||||
provisioner "remote-exec" {
|
||||
inline = [
|
||||
"sudo cp -r /tmp/enervision-frontend/* /var/www/enervision/",
|
||||
"sudo chown -R www-data:www-data /var/www/enervision"
|
||||
]
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user