Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a158d6f84c | ||
|
|
8d28113f03 | ||
|
|
3692d486c6 | ||
|
|
24bf8bf4b9 | ||
|
|
9f465538bf | ||
|
|
515a92b395 | ||
|
|
0174272bdd | ||
|
|
c740b61b24 | ||
|
|
5669cd63ec | ||
|
|
06cb60463c | ||
|
|
1c6b6105bd | ||
|
|
77440281f8 | ||
|
|
63ee79cf32 | ||
|
|
76fa90dfcb | ||
|
|
6ecec1afef | ||
|
|
e13096c62a | ||
|
|
970a4a50b8 | ||
|
|
3fb907d6f6 | ||
|
|
1654e4dd81 | ||
|
|
e50921c907 | ||
|
|
730adb69b1 | ||
|
|
f43c9f76a0 | ||
|
|
04e4913952 | ||
|
|
d1e4d8cfa0 | ||
|
|
1f0eb410eb | ||
|
|
078983a41d | ||
|
|
596cf43eda | ||
|
|
11baea7117 | ||
|
|
61b3494d12 | ||
|
|
b5cffbf56f | ||
|
|
3ef7de5baa | ||
|
|
ff6e3c288c | ||
|
|
2390e58f78 | ||
|
|
b300be5186 | ||
|
|
b8f806518f | ||
|
|
83392c7ff4 |
@@ -0,0 +1,27 @@
|
||||
# Dépendances (réinstallées dans l'image)
|
||||
node_modules/
|
||||
vendor/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Git et IDE
|
||||
.git/
|
||||
.gitignore
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
|
||||
# Fichiers de build locaux
|
||||
dist/
|
||||
build/
|
||||
*.log
|
||||
|
||||
# Secrets et config locale (CRITIQUE : risque d'exfiltration)
|
||||
.env
|
||||
.env.local
|
||||
*.pem
|
||||
*.key
|
||||
secrets/
|
||||
.npmrc
|
||||
.pypirc
|
||||
kubeconfig
|
||||
@@ -0,0 +1,77 @@
|
||||
name: Frontend
|
||||
# Pipeline à choix multiple
|
||||
|
||||
on:
|
||||
# workflow_dispatch -> lancement manuel des jobs
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
job_choice:
|
||||
required: true
|
||||
description: "Choix du job"
|
||||
type: choice
|
||||
default: all
|
||||
options:
|
||||
- build
|
||||
- sonarqube
|
||||
- test
|
||||
- all # lancer tous les jobs
|
||||
push:
|
||||
paths:
|
||||
- "apps/frontend/**"
|
||||
- ".github/workflows/frontend.yml"
|
||||
pull_request:
|
||||
paths:
|
||||
- "apps/frontend/**"
|
||||
- ".github/workflows/frontend.yml"
|
||||
# Ordre de lancement des jobs
|
||||
# build -> test -> sonarqube -> deploy
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
cache-dependency-path: apps/frontend/package-lock.json
|
||||
|
||||
- run: npm ci
|
||||
working-directory: apps/frontend
|
||||
- run: npm run build
|
||||
working-directory: apps/frontend
|
||||
|
||||
test:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
cache-dependency-path: apps/frontend/package-lock.json
|
||||
- run: npm ci
|
||||
working-directory: apps/frontend
|
||||
- run: npm test -- --watch=false
|
||||
working-directory: apps/frontend
|
||||
|
||||
sonarqube:
|
||||
needs: [build, test]
|
||||
name: SonarQube
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
|
||||
with:
|
||||
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
|
||||
- name: SonarQube Scan
|
||||
uses: SonarSource/sonarqube-scan-action@7006c4492b2e0ee0f816d36501671557c97f5995 # v8.1.0
|
||||
env:
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
|
||||
|
||||
# deploy:
|
||||
# runs-on: ubuntu-latest
|
||||
# steps:
|
||||
# - run: echo "DEPLOY job is running"
|
||||
@@ -21,6 +21,7 @@ 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
|
||||
@@ -28,8 +29,11 @@ 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.reading import ReadingService
|
||||
from app.services.recommendation import RecommendationService
|
||||
from app.services.sensor import SensorService
|
||||
from app.services.site import SiteService
|
||||
from app.services.stats import StatsService
|
||||
from app.services.user import UserService
|
||||
@@ -144,6 +148,13 @@ def get_site_service(session: SessionDep) -> SiteService:
|
||||
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))
|
||||
|
||||
@@ -158,6 +169,20 @@ def get_stats_service(session: SessionDep) -> StatsService:
|
||||
StatsServiceDep = Annotated[StatsService, Depends(get_stats_service)]
|
||||
|
||||
|
||||
def get_reading_service(session: SessionDep) -> ReadingService:
|
||||
return ReadingService(readings=ReadingRepository(session))
|
||||
|
||||
|
||||
ReadingServiceDep = Annotated[ReadingService, Depends(get_reading_service)]
|
||||
|
||||
|
||||
def get_sensor_service(session: SessionDep) -> SensorService:
|
||||
return SensorService(sites=SiteRepository(session), readings=ReadingRepository(session))
|
||||
|
||||
|
||||
SensorServiceDep = Annotated[SensorService, Depends(get_sensor_service)]
|
||||
|
||||
|
||||
async def get_current_principal(
|
||||
credentials: CredentialsDep,
|
||||
session: SessionDep,
|
||||
|
||||
@@ -54,6 +54,11 @@ TAGS: Final[list[dict[str, Any]]] = [
|
||||
"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": (
|
||||
@@ -66,6 +71,18 @@ TAGS: Final[list[dict[str, Any]]] = [
|
||||
"description": "Statistiques agrégées de consommation. Accessible à partir du rôle "
|
||||
"`lecteur`.",
|
||||
},
|
||||
{
|
||||
"name": "readings",
|
||||
"description": (
|
||||
"Historique des lectures de consommation. Fenêtre temporelle plafonnée à 90 jours, "
|
||||
"24 dernières heures par défaut si `start`/`end` sont omis. Accessible à partir du "
|
||||
"rôle `lecteur`."
|
||||
),
|
||||
},
|
||||
{
|
||||
"name": "sensors",
|
||||
"description": "État de santé des capteurs par site. Réservé au rôle `admin`.",
|
||||
},
|
||||
]
|
||||
|
||||
cookie_de_rafraichissement = APIKeyCookie(
|
||||
|
||||
@@ -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]
|
||||
@@ -0,0 +1,54 @@
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query, status
|
||||
|
||||
from app.api.deps import LecteurDep, ReadingServiceDep
|
||||
from app.api.openapi import REPONSE_VALIDATION, Reponses
|
||||
from app.schemas.errors import ErrorResponse
|
||||
from app.schemas.reading import ReadingResponse
|
||||
from app.services.reading import FenetreInverseeError, FenetreTropLargeError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
REPONSES_FENETRE: Reponses = {
|
||||
**REPONSE_VALIDATION,
|
||||
400: {
|
||||
"model": ErrorResponse,
|
||||
"description": (
|
||||
"Fenêtre temporelle invalide : `start` postérieur ou égal à `end`, ou écart entre "
|
||||
"les deux supérieur à 90 jours."
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=list[ReadingResponse],
|
||||
summary="Liste l'historique des lectures",
|
||||
responses=REPONSES_FENETRE,
|
||||
)
|
||||
async def list_readings(
|
||||
_: LecteurDep,
|
||||
service: ReadingServiceDep,
|
||||
site_id: str | None = None,
|
||||
start: datetime | None = None,
|
||||
end: datetime | None = None,
|
||||
limit: int = Query(500, ge=1, le=2000),
|
||||
offset: int = Query(0, ge=0),
|
||||
) -> list[ReadingResponse]:
|
||||
try:
|
||||
lectures = await service.list_history(
|
||||
site_id=site_id, start=start, end=end, limit=limit, offset=offset
|
||||
)
|
||||
except FenetreInverseeError as erreur:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="`start` doit être strictement antérieur à `end`",
|
||||
) from erreur
|
||||
except FenetreTropLargeError as erreur:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="L'écart entre `start` et `end` ne peut pas dépasser 90 jours",
|
||||
) from erreur
|
||||
return [ReadingResponse.model_validate(lecture) for lecture in lectures]
|
||||
@@ -0,0 +1,16 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api.deps import AdminDep, SensorServiceDep
|
||||
from app.schemas.sensor import SensorStatusResponse
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get(
|
||||
"/status",
|
||||
response_model=SensorStatusResponse,
|
||||
summary="État de santé des capteurs par site",
|
||||
)
|
||||
async def get_status(_: AdminDep, service: SensorServiceDep) -> SensorStatusResponse:
|
||||
etat = await service.status()
|
||||
return SensorStatusResponse.model_validate(etat)
|
||||
@@ -1,13 +1,26 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api.openapi import REPONSE_SERVEUR, REPONSES_ADMIN, REPONSES_LECTEUR
|
||||
from app.api.v1.endpoints import auth, health, recommendations, sites, stats, users
|
||||
from app.api.v1.endpoints import (
|
||||
alerts,
|
||||
auth,
|
||||
health,
|
||||
readings,
|
||||
recommendations,
|
||||
sensors,
|
||||
sites,
|
||||
stats,
|
||||
users,
|
||||
)
|
||||
|
||||
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"], 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",
|
||||
@@ -15,3 +28,9 @@ api_router.include_router(
|
||||
responses=REPONSES_LECTEUR,
|
||||
)
|
||||
api_router.include_router(stats.router, prefix="/stats", tags=["stats"], responses=REPONSES_LECTEUR)
|
||||
api_router.include_router(
|
||||
readings.router, prefix="/readings", tags=["readings"], responses=REPONSES_LECTEUR
|
||||
)
|
||||
api_router.include_router(
|
||||
sensors.router, prefix="/sensors", tags=["sensors"], responses=REPONSES_ADMIN
|
||||
)
|
||||
|
||||
@@ -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()
|
||||
@@ -1,4 +1,5 @@
|
||||
from collections.abc import Sequence
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
@@ -19,3 +20,23 @@ class ReadingRepository:
|
||||
.order_by(Reading.site_id, Reading.timestamp.desc())
|
||||
)
|
||||
return (await self._session.execute(requete)).scalars().all()
|
||||
|
||||
async def list_history(
|
||||
self,
|
||||
*,
|
||||
start: datetime,
|
||||
end: datetime,
|
||||
site_id: str | None = None,
|
||||
limit: int,
|
||||
offset: int,
|
||||
) -> Sequence[Reading]:
|
||||
requete = (
|
||||
select(Reading)
|
||||
.where(Reading.timestamp >= start, Reading.timestamp < end)
|
||||
.order_by(Reading.timestamp.desc(), Reading.reading_id.desc())
|
||||
.limit(limit)
|
||||
.offset(offset)
|
||||
)
|
||||
if site_id is not None:
|
||||
requete = requete.where(Reading.site_id == site_id)
|
||||
return (await self._session.scalars(requete)).all()
|
||||
|
||||
@@ -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,45 @@
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
|
||||
class ReadingSource(StrEnum):
|
||||
CSV = "csv"
|
||||
API_CURRENT = "api_current"
|
||||
API_HISTORY = "api_history"
|
||||
|
||||
|
||||
class ReadingDataQuality(StrEnum):
|
||||
GOOD = "good"
|
||||
PARTIAL = "partial"
|
||||
DEGRADED = "degraded"
|
||||
CRITICAL = "critical"
|
||||
|
||||
|
||||
class ReadingResponse(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
reading_id: int
|
||||
site_id: str
|
||||
timestamp: datetime
|
||||
source: ReadingSource
|
||||
consumption_kw: float | None
|
||||
consumption_kwh: float | None
|
||||
# Piège : `Decimal` (miroir de `Numeric(14, 2)` en base, pour ne pas arrondir un montant)
|
||||
# sérialise en chaîne dans le JSON, pas en nombre — un consommateur qui ferait un `parseFloat`
|
||||
# naïf perdrait la précision que ce choix visait à garder.
|
||||
consumption_euros: Decimal | None
|
||||
voltage_v: float | None
|
||||
current_a: float | None
|
||||
power_factor: float | None
|
||||
temperature_celsius: float | None
|
||||
humidity_percent: float | None
|
||||
solar_irradiance_wm2: float | None
|
||||
is_working_hours: bool | None
|
||||
data_quality: ReadingDataQuality | None
|
||||
null_reasons: list[str] | None
|
||||
imputed_values: dict[str, Any] | None
|
||||
imputation_method: str | None
|
||||
@@ -0,0 +1,42 @@
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class SensorDiagnosticResponse(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
status: Literal["ok", "failing"]
|
||||
since: datetime | None = Field(
|
||||
description=(
|
||||
"Horodatage de la dernière lecture reçue pour ce site. Ce n'est pas le début de la "
|
||||
"panne : l'historique ne permet pas de le dater sans requête supplémentaire."
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class SiteSensorsResponse(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
consumption: SensorDiagnosticResponse
|
||||
electrical: SensorDiagnosticResponse
|
||||
temperature: SensorDiagnosticResponse
|
||||
humidity: SensorDiagnosticResponse
|
||||
network: SensorDiagnosticResponse
|
||||
|
||||
|
||||
class SiteSensorStatusResponse(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
site_id: str
|
||||
site_name: str
|
||||
sensors: SiteSensorsResponse
|
||||
overall: Literal["ok", "degraded", "critical"]
|
||||
|
||||
|
||||
class SensorStatusResponse(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
timestamp: datetime
|
||||
sites: list[SiteSensorStatusResponse]
|
||||
@@ -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,59 @@
|
||||
from collections.abc import Sequence
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from app.models.energy import Reading
|
||||
from app.repositories.reading import ReadingRepository
|
||||
|
||||
FENETRE_PAR_DEFAUT = timedelta(hours=24)
|
||||
FENETRE_MAXIMALE = timedelta(days=90)
|
||||
|
||||
|
||||
class FenetreInverseeError(Exception):
|
||||
"""`start` est postérieur ou égal à `end`."""
|
||||
|
||||
|
||||
class FenetreTropLargeError(Exception):
|
||||
"""L'écart entre `start` et `end` dépasse `FENETRE_MAXIMALE`."""
|
||||
|
||||
|
||||
class ReadingService:
|
||||
def __init__(self, *, readings: ReadingRepository) -> None:
|
||||
self._readings = readings
|
||||
|
||||
async def list_history(
|
||||
self,
|
||||
*,
|
||||
site_id: str | None = None,
|
||||
start: datetime | None = None,
|
||||
end: datetime | None = None,
|
||||
limit: int,
|
||||
offset: int,
|
||||
) -> Sequence[Reading]:
|
||||
debut, fin = self._resoudre_fenetre(start, end)
|
||||
return await self._readings.list_history(
|
||||
site_id=site_id, start=debut, end=fin, limit=limit, offset=offset
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _resoudre_fenetre(
|
||||
start: datetime | None, end: datetime | None
|
||||
) -> tuple[datetime, datetime]:
|
||||
# Piège : un datetime naïf (sans fuseau dans la chaîne ISO reçue) fait échouer la
|
||||
# comparaison à `reading.timestamp` (`timestamptz`) au niveau du pilote, en 500 plutôt
|
||||
# qu'un refus propre. On le traite comme de l'UTC plutôt que de le rejeter.
|
||||
debut = _vers_utc(start)
|
||||
fin = _vers_utc(end) or datetime.now(UTC)
|
||||
if debut is None:
|
||||
debut = fin - FENETRE_PAR_DEFAUT
|
||||
|
||||
if debut >= fin:
|
||||
raise FenetreInverseeError
|
||||
if fin - debut > FENETRE_MAXIMALE:
|
||||
raise FenetreTropLargeError
|
||||
return debut, fin
|
||||
|
||||
|
||||
def _vers_utc(instant: datetime | None) -> datetime | None:
|
||||
if instant is None:
|
||||
return None
|
||||
return instant if instant.tzinfo is not None else instant.replace(tzinfo=UTC)
|
||||
@@ -0,0 +1,137 @@
|
||||
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
|
||||
|
||||
CapteurStatus = Literal["ok", "failing"]
|
||||
OverallStatus = Literal["ok", "degraded", "critical"]
|
||||
|
||||
QUALITES_CONNUES: frozenset[str] = frozenset({"good", "partial", "degraded", "critical"})
|
||||
|
||||
RAISON_VERS_CAPTEUR: dict[str, str] = {
|
||||
"consumption_sensor_failure": "consumption",
|
||||
"electrical_sensor_failure": "electrical",
|
||||
"temperature_sensor_failure": "temperature",
|
||||
"humidity_sensor_failure": "humidity",
|
||||
"network_loss": "network",
|
||||
}
|
||||
|
||||
CHAMPS_PAR_CAPTEUR: dict[str, tuple[str, ...]] = {
|
||||
"consumption": ("consumption_kw",),
|
||||
"electrical": ("voltage_v", "current_a", "power_factor"),
|
||||
"temperature": ("temperature_celsius",),
|
||||
"humidity": ("humidity_percent",),
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DiagnosticCapteur:
|
||||
status: CapteurStatus
|
||||
since: datetime | None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SanteCapteurs:
|
||||
consumption: DiagnosticCapteur
|
||||
electrical: DiagnosticCapteur
|
||||
temperature: DiagnosticCapteur
|
||||
humidity: DiagnosticCapteur
|
||||
network: DiagnosticCapteur
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SanteSite:
|
||||
site_id: str
|
||||
site_name: str
|
||||
sensors: SanteCapteurs
|
||||
overall: OverallStatus
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class EtatCapteurs:
|
||||
timestamp: datetime
|
||||
sites: list[SanteSite]
|
||||
|
||||
|
||||
class SensorService:
|
||||
def __init__(self, sites: SiteRepository, readings: ReadingRepository) -> None:
|
||||
self._sites = sites
|
||||
self._readings = readings
|
||||
|
||||
async def status(self) -> EtatCapteurs:
|
||||
sites = await self._sites.list_all()
|
||||
dernieres = {lecture.site_id: lecture for lecture in await self._readings.latest_by_site()}
|
||||
|
||||
return EtatCapteurs(
|
||||
timestamp=datetime.now(UTC),
|
||||
sites=[_sante_site(site, dernieres.get(site.site_id)) for site in sites],
|
||||
)
|
||||
|
||||
|
||||
def _sante_site(site: Site, derniere: Reading | None) -> SanteSite:
|
||||
if derniere is None:
|
||||
return SanteSite(
|
||||
site_id=site.site_id,
|
||||
site_name=site.site_name,
|
||||
sensors=_tout_en_echec(since=None),
|
||||
overall="critical",
|
||||
)
|
||||
|
||||
qualite = derniere.data_quality if derniere.data_quality in QUALITES_CONNUES else "critical"
|
||||
overall = _overall_depuis_qualite(qualite)
|
||||
|
||||
if overall == "critical":
|
||||
return SanteSite(
|
||||
site_id=site.site_id,
|
||||
site_name=site.site_name,
|
||||
sensors=_tout_en_echec(since=derniere.timestamp),
|
||||
overall="critical",
|
||||
)
|
||||
|
||||
raisons_signalees = {
|
||||
RAISON_VERS_CAPTEUR[raison]
|
||||
for raison in (derniere.null_reasons or [])
|
||||
if raison in RAISON_VERS_CAPTEUR
|
||||
}
|
||||
|
||||
return SanteSite(
|
||||
site_id=site.site_id,
|
||||
site_name=site.site_name,
|
||||
sensors=SanteCapteurs(
|
||||
consumption=_diagnostic("consumption", derniere, raisons_signalees),
|
||||
electrical=_diagnostic("electrical", derniere, raisons_signalees),
|
||||
temperature=_diagnostic("temperature", derniere, raisons_signalees),
|
||||
humidity=_diagnostic("humidity", derniere, raisons_signalees),
|
||||
network=_diagnostic("network", derniere, raisons_signalees),
|
||||
),
|
||||
overall=overall,
|
||||
)
|
||||
|
||||
|
||||
def _overall_depuis_qualite(qualite: str) -> OverallStatus:
|
||||
if qualite == "good":
|
||||
return "ok"
|
||||
if qualite in ("partial", "degraded"):
|
||||
return "degraded"
|
||||
return "critical"
|
||||
|
||||
|
||||
def _diagnostic(capteur: str, derniere: Reading, raisons_signalees: set[str]) -> DiagnosticCapteur:
|
||||
champs = CHAMPS_PAR_CAPTEUR.get(capteur, ())
|
||||
en_echec = capteur in raisons_signalees or any(
|
||||
getattr(derniere, champ) is None for champ in champs
|
||||
)
|
||||
return DiagnosticCapteur(
|
||||
status="failing" if en_echec else "ok",
|
||||
since=derniere.timestamp if en_echec else None,
|
||||
)
|
||||
|
||||
|
||||
def _tout_en_echec(since: datetime | None) -> SanteCapteurs:
|
||||
echec = DiagnosticCapteur(status="failing", since=since)
|
||||
return SanteCapteurs(
|
||||
consumption=echec, electrical=echec, temperature=echec, humidity=echec, network=echec
|
||||
)
|
||||
@@ -921,6 +921,110 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/alerts": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"alerts"
|
||||
],
|
||||
"summary": "Liste les alertes",
|
||||
"operationId": "list_alerts_api_v1_alerts_get",
|
||||
"security": [
|
||||
{
|
||||
"Jeton d'accès": []
|
||||
}
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "site_id",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Site Id"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "severity",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/AlertSeverity"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Severity"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/AlertResponse"
|
||||
},
|
||||
"title": "Response List Alerts Api V1 Alerts Get"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas renvoyée au client.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/InternalErrorResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Jeton absent, illisible, périmé, ou rendu caduc par un changement de rôle ou une désactivation. L'en-tête `WWW-Authenticate` porte la cause dans `error=`.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "Mot de passe provisoire à changer (`detail` vaut `password_change_required`).",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"422": {
|
||||
"description": "Corps invalide. Le détail nomme le champ fautif et le type d'erreur, jamais la valeur envoyée.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ValidationErrorResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/recommendations": {
|
||||
"get": {
|
||||
"tags": [
|
||||
@@ -1123,6 +1227,217 @@
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/readings": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"readings"
|
||||
],
|
||||
"summary": "Liste l'historique des lectures",
|
||||
"operationId": "list_readings_api_v1_readings_get",
|
||||
"security": [
|
||||
{
|
||||
"Jeton d'accès": []
|
||||
}
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "site_id",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Site Id"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "start",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Start"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "end",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "End"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "limit",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"maximum": 2000,
|
||||
"minimum": 1,
|
||||
"default": 500,
|
||||
"title": "Limit"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "offset",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"default": 0,
|
||||
"title": "Offset"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/ReadingResponse"
|
||||
},
|
||||
"title": "Response List Readings Api V1 Readings Get"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas renvoyée au client.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/InternalErrorResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Jeton absent, illisible, périmé, ou rendu caduc par un changement de rôle ou une désactivation. L'en-tête `WWW-Authenticate` porte la cause dans `error=`.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "Mot de passe provisoire à changer (`detail` vaut `password_change_required`).",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"422": {
|
||||
"description": "Corps invalide. Le détail nomme le champ fautif et le type d'erreur, jamais la valeur envoyée.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ValidationErrorResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Fenêtre temporelle invalide : `start` postérieur ou égal à `end`, ou écart entre les deux supérieur à 90 jours.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/sensors/status": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"sensors"
|
||||
],
|
||||
"summary": "État de santé des capteurs par site",
|
||||
"operationId": "get_status_api_v1_sensors_status_get",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/SensorStatusResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Erreur interne. `correlation` identifie la trace côté serveur, qui n'est pas renvoyée au client.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/InternalErrorResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Jeton absent, illisible, périmé, ou rendu caduc par un changement de rôle ou une désactivation. L'en-tête `WWW-Authenticate` porte la cause dans `error=`.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "Droits insuffisants, ou mot de passe provisoire à changer quand `detail` vaut `password_change_required`.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"security": [
|
||||
{
|
||||
"Jeton d'accès": []
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
@@ -1135,6 +1450,112 @@
|
||||
],
|
||||
"title": "AccountKind"
|
||||
},
|
||||
"AlertResponse": {
|
||||
"properties": {
|
||||
"alert_id": {
|
||||
"type": "integer",
|
||||
"title": "Alert Id"
|
||||
},
|
||||
"site_id": {
|
||||
"type": "string",
|
||||
"title": "Site Id"
|
||||
},
|
||||
"timestamp": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"title": "Timestamp"
|
||||
},
|
||||
"type": {
|
||||
"$ref": "#/components/schemas/AlertType"
|
||||
},
|
||||
"severity": {
|
||||
"$ref": "#/components/schemas/AlertSeverity"
|
||||
},
|
||||
"message": {
|
||||
"type": "string",
|
||||
"title": "Message"
|
||||
},
|
||||
"value": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "number"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Value"
|
||||
},
|
||||
"threshold": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "number"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Threshold"
|
||||
},
|
||||
"metric": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Metric"
|
||||
},
|
||||
"prediction_id": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Prediction Id"
|
||||
}
|
||||
},
|
||||
"type": "object",
|
||||
"required": [
|
||||
"alert_id",
|
||||
"site_id",
|
||||
"timestamp",
|
||||
"type",
|
||||
"severity",
|
||||
"message",
|
||||
"value",
|
||||
"threshold",
|
||||
"metric",
|
||||
"prediction_id"
|
||||
],
|
||||
"title": "AlertResponse"
|
||||
},
|
||||
"AlertSeverity": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
"critical"
|
||||
],
|
||||
"title": "AlertSeverity"
|
||||
},
|
||||
"AlertType": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"spike",
|
||||
"threshold",
|
||||
"anomaly",
|
||||
"outage",
|
||||
"sensor"
|
||||
],
|
||||
"title": "AlertType"
|
||||
},
|
||||
"ErrorResponse": {
|
||||
"properties": {
|
||||
"detail": {
|
||||
@@ -1314,6 +1735,225 @@
|
||||
],
|
||||
"title": "ReadinessStatus"
|
||||
},
|
||||
"ReadingDataQuality": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"good",
|
||||
"partial",
|
||||
"degraded",
|
||||
"critical"
|
||||
],
|
||||
"title": "ReadingDataQuality"
|
||||
},
|
||||
"ReadingResponse": {
|
||||
"properties": {
|
||||
"reading_id": {
|
||||
"type": "integer",
|
||||
"title": "Reading Id"
|
||||
},
|
||||
"site_id": {
|
||||
"type": "string",
|
||||
"title": "Site Id"
|
||||
},
|
||||
"timestamp": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"title": "Timestamp"
|
||||
},
|
||||
"source": {
|
||||
"$ref": "#/components/schemas/ReadingSource"
|
||||
},
|
||||
"consumption_kw": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "number"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Consumption Kw"
|
||||
},
|
||||
"consumption_kwh": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "number"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Consumption Kwh"
|
||||
},
|
||||
"consumption_euros": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Consumption Euros"
|
||||
},
|
||||
"voltage_v": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "number"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Voltage V"
|
||||
},
|
||||
"current_a": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "number"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Current A"
|
||||
},
|
||||
"power_factor": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "number"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Power Factor"
|
||||
},
|
||||
"temperature_celsius": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "number"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Temperature Celsius"
|
||||
},
|
||||
"humidity_percent": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "number"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Humidity Percent"
|
||||
},
|
||||
"solar_irradiance_wm2": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "number"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Solar Irradiance Wm2"
|
||||
},
|
||||
"is_working_hours": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Is Working Hours"
|
||||
},
|
||||
"data_quality": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/ReadingDataQuality"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"null_reasons": {
|
||||
"anyOf": [
|
||||
{
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Null Reasons"
|
||||
},
|
||||
"imputed_values": {
|
||||
"anyOf": [
|
||||
{
|
||||
"additionalProperties": true,
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Imputed Values"
|
||||
},
|
||||
"imputation_method": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Imputation Method"
|
||||
}
|
||||
},
|
||||
"type": "object",
|
||||
"required": [
|
||||
"reading_id",
|
||||
"site_id",
|
||||
"timestamp",
|
||||
"source",
|
||||
"consumption_kw",
|
||||
"consumption_kwh",
|
||||
"consumption_euros",
|
||||
"voltage_v",
|
||||
"current_a",
|
||||
"power_factor",
|
||||
"temperature_celsius",
|
||||
"humidity_percent",
|
||||
"solar_irradiance_wm2",
|
||||
"is_working_hours",
|
||||
"data_quality",
|
||||
"null_reasons",
|
||||
"imputed_values",
|
||||
"imputation_method"
|
||||
],
|
||||
"title": "ReadingResponse"
|
||||
},
|
||||
"ReadingSource": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"csv",
|
||||
"api_current",
|
||||
"api_history"
|
||||
],
|
||||
"title": "ReadingSource"
|
||||
},
|
||||
"RecommendationResponse": {
|
||||
"properties": {
|
||||
"recommendation_id": {
|
||||
@@ -1362,6 +2002,59 @@
|
||||
],
|
||||
"title": "Role"
|
||||
},
|
||||
"SensorDiagnosticResponse": {
|
||||
"properties": {
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"ok",
|
||||
"failing"
|
||||
],
|
||||
"title": "Status"
|
||||
},
|
||||
"since": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Since",
|
||||
"description": "Horodatage de la dernière lecture reçue pour ce site. Ce n'est pas le début de la panne : l'historique ne permet pas de le dater sans requête supplémentaire."
|
||||
}
|
||||
},
|
||||
"type": "object",
|
||||
"required": [
|
||||
"status",
|
||||
"since"
|
||||
],
|
||||
"title": "SensorDiagnosticResponse"
|
||||
},
|
||||
"SensorStatusResponse": {
|
||||
"properties": {
|
||||
"timestamp": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"title": "Timestamp"
|
||||
},
|
||||
"sites": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/SiteSensorStatusResponse"
|
||||
},
|
||||
"type": "array",
|
||||
"title": "Sites"
|
||||
}
|
||||
},
|
||||
"type": "object",
|
||||
"required": [
|
||||
"timestamp",
|
||||
"sites"
|
||||
],
|
||||
"title": "SensorStatusResponse"
|
||||
},
|
||||
"SiteResponse": {
|
||||
"properties": {
|
||||
"site_id": {
|
||||
@@ -1421,6 +2114,66 @@
|
||||
],
|
||||
"title": "SiteResponse"
|
||||
},
|
||||
"SiteSensorStatusResponse": {
|
||||
"properties": {
|
||||
"site_id": {
|
||||
"type": "string",
|
||||
"title": "Site Id"
|
||||
},
|
||||
"site_name": {
|
||||
"type": "string",
|
||||
"title": "Site Name"
|
||||
},
|
||||
"sensors": {
|
||||
"$ref": "#/components/schemas/SiteSensorsResponse"
|
||||
},
|
||||
"overall": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"ok",
|
||||
"degraded",
|
||||
"critical"
|
||||
],
|
||||
"title": "Overall"
|
||||
}
|
||||
},
|
||||
"type": "object",
|
||||
"required": [
|
||||
"site_id",
|
||||
"site_name",
|
||||
"sensors",
|
||||
"overall"
|
||||
],
|
||||
"title": "SiteSensorStatusResponse"
|
||||
},
|
||||
"SiteSensorsResponse": {
|
||||
"properties": {
|
||||
"consumption": {
|
||||
"$ref": "#/components/schemas/SensorDiagnosticResponse"
|
||||
},
|
||||
"electrical": {
|
||||
"$ref": "#/components/schemas/SensorDiagnosticResponse"
|
||||
},
|
||||
"temperature": {
|
||||
"$ref": "#/components/schemas/SensorDiagnosticResponse"
|
||||
},
|
||||
"humidity": {
|
||||
"$ref": "#/components/schemas/SensorDiagnosticResponse"
|
||||
},
|
||||
"network": {
|
||||
"$ref": "#/components/schemas/SensorDiagnosticResponse"
|
||||
}
|
||||
},
|
||||
"type": "object",
|
||||
"required": [
|
||||
"consumption",
|
||||
"electrical",
|
||||
"temperature",
|
||||
"humidity",
|
||||
"network"
|
||||
],
|
||||
"title": "SiteSensorsResponse"
|
||||
},
|
||||
"SiteSummaryResponse": {
|
||||
"properties": {
|
||||
"site_id": {
|
||||
@@ -1738,6 +2491,10 @@
|
||||
"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`."
|
||||
@@ -1745,6 +2502,14 @@
|
||||
{
|
||||
"name": "stats",
|
||||
"description": "Statistiques agrégées de consommation. Accessible à partir du rôle `lecteur`."
|
||||
},
|
||||
{
|
||||
"name": "readings",
|
||||
"description": "Historique des lectures de consommation. Fenêtre temporelle plafonnée à 90 jours, 24 dernières heures par défaut si `start`/`end` sont omis. Accessible à partir du rôle `lecteur`."
|
||||
},
|
||||
{
|
||||
"name": "sensors",
|
||||
"description": "État de santé des capteurs par site. Réservé au rôle `admin`."
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -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() == []
|
||||
@@ -31,9 +31,12 @@ ROUTES_A_ROLE = {
|
||||
("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"),
|
||||
("GET", "/api/v1/readings"),
|
||||
("GET", "/api/v1/sensors/status"),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
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_reading_service
|
||||
from app.core.principal import Principal
|
||||
from app.core.roles import AccountKind, Role
|
||||
from app.models.energy import Reading
|
||||
from app.services.reading import FenetreInverseeError, FenetreTropLargeError
|
||||
|
||||
|
||||
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 reading(reading_id: int = 1, site_id: str = "site-1") -> Reading:
|
||||
return Reading(
|
||||
reading_id=reading_id,
|
||||
site_id=site_id,
|
||||
timestamp=datetime(2026, 9, 16, tzinfo=UTC),
|
||||
source="api_current",
|
||||
consumption_kw=42.5,
|
||||
consumption_kwh=None,
|
||||
consumption_euros=None,
|
||||
voltage_v=230.0,
|
||||
current_a=None,
|
||||
power_factor=None,
|
||||
temperature_celsius=None,
|
||||
humidity_percent=None,
|
||||
solar_irradiance_wm2=None,
|
||||
is_working_hours=True,
|
||||
data_quality="good",
|
||||
null_reasons=None,
|
||||
imputed_values=None,
|
||||
imputation_method=None,
|
||||
raw_data={},
|
||||
)
|
||||
|
||||
|
||||
class FauxService:
|
||||
def __init__(self, leve: Exception | None = None) -> None:
|
||||
self.reading = reading()
|
||||
self.leve = leve
|
||||
self.appels: list[tuple[str | None, str | None, str | None, int, int]] = []
|
||||
|
||||
async def list_history(
|
||||
self,
|
||||
*,
|
||||
site_id: str | None = None,
|
||||
start: datetime | None = None,
|
||||
end: datetime | None = None,
|
||||
limit: int,
|
||||
offset: int,
|
||||
) -> list[Reading]:
|
||||
self.appels.append((site_id, start, end, limit, offset))
|
||||
if self.leve is not None:
|
||||
raise self.leve
|
||||
return [self.reading]
|
||||
|
||||
|
||||
@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(*, leve: Exception | None = None) -> FauxService:
|
||||
service = FauxService(leve=leve)
|
||||
app.dependency_overrides[get_reading_service] = lambda: service
|
||||
return service
|
||||
|
||||
yield installe
|
||||
app.dependency_overrides.pop(get_reading_service, None)
|
||||
|
||||
|
||||
async def test_list_readings_returns_the_readings(
|
||||
servi: Callable[..., FauxService], client: AsyncClient
|
||||
) -> None:
|
||||
servi()
|
||||
|
||||
response = await client.get("/api/v1/readings")
|
||||
|
||||
assert response.status_code == 200
|
||||
corps = response.json()
|
||||
assert corps == [
|
||||
{
|
||||
"reading_id": 1,
|
||||
"site_id": "site-1",
|
||||
"timestamp": "2026-09-16T00:00:00Z",
|
||||
"source": "api_current",
|
||||
"consumption_kw": 42.5,
|
||||
"consumption_kwh": None,
|
||||
"consumption_euros": None,
|
||||
"voltage_v": 230.0,
|
||||
"current_a": None,
|
||||
"power_factor": None,
|
||||
"temperature_celsius": None,
|
||||
"humidity_percent": None,
|
||||
"solar_irradiance_wm2": None,
|
||||
"is_working_hours": True,
|
||||
"data_quality": "good",
|
||||
"null_reasons": None,
|
||||
"imputed_values": None,
|
||||
"imputation_method": None,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
async def test_list_readings_transmits_the_filters_and_pagination(
|
||||
servi: Callable[..., FauxService], client: AsyncClient
|
||||
) -> None:
|
||||
service = servi()
|
||||
|
||||
response = await client.get(
|
||||
"/api/v1/readings",
|
||||
params={
|
||||
"site_id": "site-1",
|
||||
"start": "2026-09-01T00:00:00Z",
|
||||
"end": "2026-09-02T00:00:00Z",
|
||||
"limit": 50,
|
||||
"offset": 10,
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert service.appels == [
|
||||
(
|
||||
"site-1",
|
||||
datetime(2026, 9, 1, tzinfo=UTC),
|
||||
datetime(2026, 9, 2, tzinfo=UTC),
|
||||
50,
|
||||
10,
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
async def test_list_readings_returns_400_when_the_window_is_inverted(
|
||||
servi: Callable[..., FauxService], client: AsyncClient
|
||||
) -> None:
|
||||
servi(leve=FenetreInverseeError())
|
||||
|
||||
response = await client.get("/api/v1/readings")
|
||||
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
async def test_list_readings_returns_400_when_the_window_is_too_large(
|
||||
servi: Callable[..., FauxService], client: AsyncClient
|
||||
) -> None:
|
||||
servi(leve=FenetreTropLargeError())
|
||||
|
||||
response = await client.get("/api/v1/readings")
|
||||
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
async def test_list_readings_returns_422_for_a_limit_above_the_maximum(
|
||||
servi: Callable[..., FauxService], client: AsyncClient
|
||||
) -> None:
|
||||
servi()
|
||||
|
||||
response = await client.get("/api/v1/readings", params={"limit": 5000})
|
||||
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
async def test_list_readings_returns_422_for_a_negative_offset(
|
||||
servi: Callable[..., FauxService], client: AsyncClient
|
||||
) -> None:
|
||||
servi()
|
||||
|
||||
response = await client.get("/api/v1/readings", params={"offset": -1})
|
||||
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
async def test_list_readings_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/readings")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == []
|
||||
@@ -0,0 +1,91 @@
|
||||
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_sensor_service
|
||||
from app.core.principal import Principal
|
||||
from app.core.roles import AccountKind, Role
|
||||
from app.services.sensor import DiagnosticCapteur, EtatCapteurs, SanteCapteurs, SanteSite
|
||||
|
||||
TIMESTAMP = datetime(2026, 9, 16, 12, 0, tzinfo=UTC)
|
||||
|
||||
|
||||
def principal(role: Role = Role.ADMIN) -> 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:
|
||||
ok = DiagnosticCapteur(status="ok", since=None)
|
||||
en_echec = DiagnosticCapteur(status="failing", since=TIMESTAMP)
|
||||
self.etat = EtatCapteurs(
|
||||
timestamp=TIMESTAMP,
|
||||
sites=[
|
||||
SanteSite(
|
||||
site_id="SITE001",
|
||||
site_name="Bureau Paris La Défense",
|
||||
sensors=SanteCapteurs(
|
||||
consumption=ok,
|
||||
electrical=ok,
|
||||
temperature=en_echec,
|
||||
humidity=ok,
|
||||
network=ok,
|
||||
),
|
||||
overall="degraded",
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
async def status(self) -> EtatCapteurs:
|
||||
return self.etat
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_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, admin_connecte: None) -> Iterator[Callable[[], FauxService]]:
|
||||
def installe() -> FauxService:
|
||||
service = FauxService()
|
||||
app.dependency_overrides[get_sensor_service] = lambda: service
|
||||
return service
|
||||
|
||||
yield installe
|
||||
app.dependency_overrides.pop(get_sensor_service, None)
|
||||
|
||||
|
||||
async def test_get_status_returns_the_service_result(
|
||||
servi: Callable[[], FauxService], client: AsyncClient
|
||||
) -> None:
|
||||
servi()
|
||||
|
||||
response = await client.get("/api/v1/sensors/status")
|
||||
|
||||
assert response.status_code == 200
|
||||
corps = response.json()
|
||||
assert corps["sites"][0]["site_id"] == "SITE001"
|
||||
assert corps["sites"][0]["overall"] == "degraded"
|
||||
assert corps["sites"][0]["sensors"]["temperature"]["status"] == "failing"
|
||||
assert corps["sites"][0]["sensors"]["consumption"]["status"] == "ok"
|
||||
|
||||
|
||||
async def test_get_status_refuses_a_reader(app: FastAPI, client: AsyncClient) -> None:
|
||||
app.dependency_overrides[get_current_principal] = lambda: principal(Role.LECTEUR)
|
||||
|
||||
response = await client.get("/api/v1/sensors/status")
|
||||
|
||||
assert response.status_code == 403
|
||||
@@ -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) == []
|
||||
@@ -6,6 +6,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.energy import Reading, Site
|
||||
from app.repositories.reading import ReadingRepository
|
||||
from tests.repositories.test_site import creer as creer_site
|
||||
from tests.repositories.test_site import identifiant as identifiant_site
|
||||
|
||||
pytestmark = pytest.mark.integration
|
||||
|
||||
@@ -25,6 +27,20 @@ def lecture(site_id: str, *, timestamp: datetime, consumption_kw: float) -> Read
|
||||
)
|
||||
|
||||
|
||||
async def creer_lecture(session: AsyncSession, *, site_id: str, **overrides: object) -> Reading:
|
||||
reading = Reading(
|
||||
site_id=site_id,
|
||||
timestamp=overrides.get("timestamp", datetime(2026, 9, 16, tzinfo=UTC)),
|
||||
source=overrides.get("source", "api_current"),
|
||||
consumption_kw=overrides.get("consumption_kw", 10.0),
|
||||
data_quality=overrides.get("data_quality", "good"),
|
||||
raw_data=overrides.get("raw_data", {}),
|
||||
)
|
||||
session.add(reading)
|
||||
await session.flush()
|
||||
return reading
|
||||
|
||||
|
||||
async def test_latest_by_site_keeps_only_the_most_recent_reading(session: AsyncSession) -> None:
|
||||
site_id = identifiant()
|
||||
maintenant = datetime.now(UTC)
|
||||
@@ -70,3 +86,110 @@ async def test_latest_by_site_returns_one_row_per_site(session: AsyncSession) ->
|
||||
await session.rollback()
|
||||
|
||||
assert identifiants == {premier, second}
|
||||
|
||||
|
||||
async def test_list_history_orders_the_readings_by_timestamp_descending(
|
||||
session: AsyncSession,
|
||||
) -> None:
|
||||
site = await creer_site(session)
|
||||
depot = ReadingRepository(session)
|
||||
ancienne = await creer_lecture(
|
||||
session, site_id=site.site_id, timestamp=datetime(2026, 9, 1, tzinfo=UTC)
|
||||
)
|
||||
recente = await creer_lecture(
|
||||
session, site_id=site.site_id, timestamp=datetime(2026, 9, 15, tzinfo=UTC)
|
||||
)
|
||||
|
||||
resultats = await depot.list_history(
|
||||
start=datetime(2026, 8, 1, tzinfo=UTC),
|
||||
end=datetime(2026, 10, 1, tzinfo=UTC),
|
||||
limit=100,
|
||||
offset=0,
|
||||
)
|
||||
identifiants = [
|
||||
r.reading_id for r in resultats if r.reading_id in (ancienne.reading_id, recente.reading_id)
|
||||
]
|
||||
await session.rollback()
|
||||
|
||||
assert identifiants == [recente.reading_id, ancienne.reading_id]
|
||||
|
||||
|
||||
async def test_list_history_filters_by_site_id(session: AsyncSession) -> None:
|
||||
premier = await creer_site(session)
|
||||
second = await creer_site(session)
|
||||
depot = ReadingRepository(session)
|
||||
voulue = await creer_lecture(session, site_id=premier.site_id)
|
||||
await creer_lecture(session, site_id=second.site_id)
|
||||
|
||||
resultats = await depot.list_history(
|
||||
site_id=premier.site_id,
|
||||
start=datetime(2026, 8, 1, tzinfo=UTC),
|
||||
end=datetime(2026, 10, 1, tzinfo=UTC),
|
||||
limit=100,
|
||||
offset=0,
|
||||
)
|
||||
identifiants = [r.reading_id for r in resultats]
|
||||
await session.rollback()
|
||||
|
||||
assert identifiants == [voulue.reading_id]
|
||||
|
||||
|
||||
async def test_list_history_excludes_readings_outside_the_window(session: AsyncSession) -> None:
|
||||
site = await creer_site(session)
|
||||
depot = ReadingRepository(session)
|
||||
dedans = await creer_lecture(
|
||||
session, site_id=site.site_id, timestamp=datetime(2026, 9, 10, tzinfo=UTC)
|
||||
)
|
||||
await creer_lecture(session, site_id=site.site_id, timestamp=datetime(2026, 8, 1, tzinfo=UTC))
|
||||
await creer_lecture(session, site_id=site.site_id, timestamp=datetime(2026, 10, 1, tzinfo=UTC))
|
||||
|
||||
resultats = await depot.list_history(
|
||||
site_id=site.site_id,
|
||||
start=datetime(2026, 9, 1, tzinfo=UTC),
|
||||
end=datetime(2026, 9, 30, tzinfo=UTC),
|
||||
limit=100,
|
||||
offset=0,
|
||||
)
|
||||
identifiants = [r.reading_id for r in resultats]
|
||||
await session.rollback()
|
||||
|
||||
assert identifiants == [dedans.reading_id]
|
||||
|
||||
|
||||
async def test_list_history_respects_limit_and_offset(session: AsyncSession) -> None:
|
||||
site = await creer_site(session)
|
||||
depot = ReadingRepository(session)
|
||||
lectures = [
|
||||
await creer_lecture(
|
||||
session, site_id=site.site_id, timestamp=datetime(2026, 9, jour, tzinfo=UTC)
|
||||
)
|
||||
for jour in (1, 2, 3)
|
||||
]
|
||||
|
||||
resultats = await depot.list_history(
|
||||
site_id=site.site_id,
|
||||
start=datetime(2026, 8, 1, tzinfo=UTC),
|
||||
end=datetime(2026, 10, 1, tzinfo=UTC),
|
||||
limit=1,
|
||||
offset=1,
|
||||
)
|
||||
identifiants = [r.reading_id for r in resultats]
|
||||
await session.rollback()
|
||||
|
||||
assert identifiants == [lectures[1].reading_id]
|
||||
|
||||
|
||||
async def test_list_history_returns_an_empty_list_when_there_is_nothing(
|
||||
session: AsyncSession,
|
||||
) -> None:
|
||||
depot = ReadingRepository(session)
|
||||
|
||||
resultats = await depot.list_history(
|
||||
site_id=identifiant_site(),
|
||||
start=datetime(2026, 8, 1, tzinfo=UTC),
|
||||
end=datetime(2026, 10, 1, tzinfo=UTC),
|
||||
limit=100,
|
||||
offset=0,
|
||||
)
|
||||
|
||||
assert list(resultats) == []
|
||||
|
||||
@@ -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,153 @@
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models.energy import Reading
|
||||
from app.services.reading import (
|
||||
FENETRE_MAXIMALE,
|
||||
FENETRE_PAR_DEFAUT,
|
||||
FenetreInverseeError,
|
||||
FenetreTropLargeError,
|
||||
ReadingService,
|
||||
)
|
||||
|
||||
|
||||
def reading(reading_id: int = 1, site_id: str = "site-1") -> Reading:
|
||||
return Reading(
|
||||
reading_id=reading_id,
|
||||
site_id=site_id,
|
||||
timestamp=datetime(2026, 9, 16, tzinfo=UTC),
|
||||
source="api_current",
|
||||
consumption_kw=10.0,
|
||||
data_quality="good",
|
||||
raw_data={},
|
||||
)
|
||||
|
||||
|
||||
class FakeRepository:
|
||||
def __init__(self, readings: list[Reading]) -> None:
|
||||
self._readings = readings
|
||||
self.appels: list[tuple[str | None, datetime, datetime, int, int]] = []
|
||||
|
||||
async def list_history(
|
||||
self,
|
||||
*,
|
||||
start: datetime,
|
||||
end: datetime,
|
||||
site_id: str | None = None,
|
||||
limit: int,
|
||||
offset: int,
|
||||
) -> list[Reading]:
|
||||
self.appels.append((site_id, start, end, limit, offset))
|
||||
return self._readings
|
||||
|
||||
|
||||
async def test_list_history_returns_the_repository_readings() -> None:
|
||||
service = ReadingService(readings=FakeRepository([reading(1), reading(2)]))
|
||||
|
||||
lectures = await service.list_history(limit=500, offset=0)
|
||||
|
||||
assert [r.reading_id for r in lectures] == [1, 2]
|
||||
|
||||
|
||||
async def test_list_history_relays_the_site_id_limit_and_offset() -> None:
|
||||
depot = FakeRepository([])
|
||||
service = ReadingService(readings=depot)
|
||||
debut = datetime(2026, 9, 1, tzinfo=UTC)
|
||||
fin = datetime(2026, 9, 2, tzinfo=UTC)
|
||||
|
||||
await service.list_history(site_id="site-1", start=debut, end=fin, limit=50, offset=10)
|
||||
|
||||
assert depot.appels == [("site-1", debut, fin, 50, 10)]
|
||||
|
||||
|
||||
async def test_list_history_defaults_to_the_last_24_hours_when_no_window_is_given() -> None:
|
||||
depot = FakeRepository([])
|
||||
service = ReadingService(readings=depot)
|
||||
avant = datetime.now(UTC)
|
||||
|
||||
await service.list_history(limit=500, offset=0)
|
||||
|
||||
apres = datetime.now(UTC)
|
||||
_, debut, fin, _, _ = depot.appels[0]
|
||||
assert avant <= fin <= apres
|
||||
assert fin - debut == FENETRE_PAR_DEFAUT
|
||||
|
||||
|
||||
async def test_list_history_defaults_end_to_now_when_only_start_is_given() -> None:
|
||||
depot = FakeRepository([])
|
||||
service = ReadingService(readings=depot)
|
||||
debut = datetime.now(UTC) - timedelta(hours=1)
|
||||
avant = datetime.now(UTC)
|
||||
|
||||
await service.list_history(start=debut, limit=500, offset=0)
|
||||
|
||||
apres = datetime.now(UTC)
|
||||
_, debut_transmis, fin, _, _ = depot.appels[0]
|
||||
assert debut_transmis == debut
|
||||
assert avant <= fin <= apres
|
||||
|
||||
|
||||
async def test_list_history_defaults_start_to_24_hours_before_end_when_only_end_is_given() -> None:
|
||||
depot = FakeRepository([])
|
||||
service = ReadingService(readings=depot)
|
||||
fin = datetime(2026, 9, 16, tzinfo=UTC)
|
||||
|
||||
await service.list_history(end=fin, limit=500, offset=0)
|
||||
|
||||
_, debut, fin_transmise, _, _ = depot.appels[0]
|
||||
assert fin_transmise == fin
|
||||
assert debut == fin - FENETRE_PAR_DEFAUT
|
||||
|
||||
|
||||
async def test_list_history_normalizes_naive_datetimes_to_utc() -> None:
|
||||
depot = FakeRepository([])
|
||||
service = ReadingService(readings=depot)
|
||||
|
||||
await service.list_history(
|
||||
start=datetime(2026, 9, 1), end=datetime(2026, 9, 2), limit=500, offset=0
|
||||
)
|
||||
|
||||
_, debut, fin, _, _ = depot.appels[0]
|
||||
assert debut == datetime(2026, 9, 1, tzinfo=UTC)
|
||||
assert fin == datetime(2026, 9, 2, tzinfo=UTC)
|
||||
|
||||
|
||||
async def test_list_history_raises_when_start_is_after_end() -> None:
|
||||
service = ReadingService(readings=FakeRepository([]))
|
||||
|
||||
with pytest.raises(FenetreInverseeError):
|
||||
await service.list_history(
|
||||
start=datetime(2026, 9, 2, tzinfo=UTC),
|
||||
end=datetime(2026, 9, 1, tzinfo=UTC),
|
||||
limit=500,
|
||||
offset=0,
|
||||
)
|
||||
|
||||
|
||||
async def test_list_history_raises_when_start_equals_end() -> None:
|
||||
service = ReadingService(readings=FakeRepository([]))
|
||||
instant = datetime(2026, 9, 1, tzinfo=UTC)
|
||||
|
||||
with pytest.raises(FenetreInverseeError):
|
||||
await service.list_history(start=instant, end=instant, limit=500, offset=0)
|
||||
|
||||
|
||||
async def test_list_history_raises_when_the_window_exceeds_the_maximum_span() -> None:
|
||||
service = ReadingService(readings=FakeRepository([]))
|
||||
debut = datetime(2026, 1, 1, tzinfo=UTC)
|
||||
fin = debut + FENETRE_MAXIMALE + timedelta(seconds=1)
|
||||
|
||||
with pytest.raises(FenetreTropLargeError):
|
||||
await service.list_history(start=debut, end=fin, limit=500, offset=0)
|
||||
|
||||
|
||||
async def test_list_history_accepts_a_window_exactly_at_the_maximum_span() -> None:
|
||||
depot = FakeRepository([])
|
||||
service = ReadingService(readings=depot)
|
||||
debut = datetime(2026, 1, 1, tzinfo=UTC)
|
||||
fin = debut + FENETRE_MAXIMALE
|
||||
|
||||
await service.list_history(start=debut, end=fin, limit=500, offset=0)
|
||||
|
||||
assert depot.appels == [(None, debut, fin, 500, 0)]
|
||||
@@ -0,0 +1,224 @@
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from app.services.sensor import SensorService
|
||||
|
||||
TIMESTAMP = datetime(2026, 9, 16, 12, 0, tzinfo=UTC)
|
||||
|
||||
|
||||
@dataclass
|
||||
class FauxSite:
|
||||
site_id: str
|
||||
site_name: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class FauxLecture:
|
||||
site_id: str
|
||||
timestamp: datetime
|
||||
data_quality: str | None
|
||||
null_reasons: list[str] | None = field(default_factory=list)
|
||||
consumption_kw: float | None = 10.0
|
||||
voltage_v: float | None = 230.0
|
||||
current_a: float | None = 5.0
|
||||
power_factor: float | None = 0.95
|
||||
temperature_celsius: float | None = 21.0
|
||||
humidity_percent: float | None = 40.0
|
||||
|
||||
|
||||
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_status_marks_a_site_without_any_reading_as_critical_with_every_sensor_failing() -> (
|
||||
None
|
||||
):
|
||||
service = SensorService(
|
||||
sites=FauxDepotSites([FauxSite("A", "Site A")]), # type: ignore[arg-type]
|
||||
readings=FauxDepotLectures([]), # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
etat = await service.status()
|
||||
|
||||
site = etat.sites[0]
|
||||
assert site.overall == "critical"
|
||||
for capteur in (
|
||||
site.sensors.consumption,
|
||||
site.sensors.electrical,
|
||||
site.sensors.temperature,
|
||||
site.sensors.humidity,
|
||||
site.sensors.network,
|
||||
):
|
||||
assert capteur.status == "failing"
|
||||
assert capteur.since is None
|
||||
|
||||
|
||||
async def test_status_marks_every_sensor_ok_on_a_good_quality_reading_with_no_null_field() -> None:
|
||||
service = SensorService(
|
||||
sites=FauxDepotSites([FauxSite("A", "Site A")]), # type: ignore[arg-type]
|
||||
readings=FauxDepotLectures([FauxLecture("A", TIMESTAMP, "good")]), # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
etat = await service.status()
|
||||
|
||||
site = etat.sites[0]
|
||||
assert site.overall == "ok"
|
||||
for capteur in (
|
||||
site.sensors.consumption,
|
||||
site.sensors.electrical,
|
||||
site.sensors.temperature,
|
||||
site.sensors.humidity,
|
||||
site.sensors.network,
|
||||
):
|
||||
assert capteur.status == "ok"
|
||||
assert capteur.since is None
|
||||
|
||||
|
||||
async def test_status_flags_the_sensor_named_in_null_reasons() -> None:
|
||||
service = SensorService(
|
||||
sites=FauxDepotSites([FauxSite("A", "Site A")]), # type: ignore[arg-type]
|
||||
readings=FauxDepotLectures( # type: ignore[arg-type]
|
||||
[
|
||||
FauxLecture(
|
||||
"A",
|
||||
TIMESTAMP,
|
||||
"partial",
|
||||
null_reasons=["temperature_sensor_failure"],
|
||||
temperature_celsius=None,
|
||||
)
|
||||
]
|
||||
),
|
||||
)
|
||||
|
||||
etat = await service.status()
|
||||
|
||||
site = etat.sites[0]
|
||||
assert site.overall == "degraded"
|
||||
assert site.sensors.temperature.status == "failing"
|
||||
assert site.sensors.temperature.since == TIMESTAMP
|
||||
assert site.sensors.consumption.status == "ok"
|
||||
assert site.sensors.electrical.status == "ok"
|
||||
assert site.sensors.humidity.status == "ok"
|
||||
assert site.sensors.network.status == "ok"
|
||||
|
||||
|
||||
async def test_status_flags_a_sensor_from_a_null_field_even_without_a_null_reason() -> None:
|
||||
service = SensorService(
|
||||
sites=FauxDepotSites([FauxSite("A", "Site A")]), # type: ignore[arg-type]
|
||||
readings=FauxDepotLectures( # type: ignore[arg-type]
|
||||
[FauxLecture("A", TIMESTAMP, "partial", null_reasons=[], humidity_percent=None)]
|
||||
),
|
||||
)
|
||||
|
||||
etat = await service.status()
|
||||
|
||||
site = etat.sites[0]
|
||||
assert site.sensors.humidity.status == "failing"
|
||||
assert site.sensors.humidity.since == TIMESTAMP
|
||||
|
||||
|
||||
async def test_status_flags_electrical_as_failing_when_any_of_its_three_fields_is_null() -> None:
|
||||
service = SensorService(
|
||||
sites=FauxDepotSites([FauxSite("A", "Site A")]), # type: ignore[arg-type]
|
||||
readings=FauxDepotLectures( # type: ignore[arg-type]
|
||||
[FauxLecture("A", TIMESTAMP, "partial", null_reasons=[], power_factor=None)]
|
||||
),
|
||||
)
|
||||
|
||||
etat = await service.status()
|
||||
|
||||
site = etat.sites[0]
|
||||
assert site.sensors.electrical.status == "failing"
|
||||
|
||||
|
||||
async def test_status_forces_every_sensor_to_failing_when_overall_is_critical() -> None:
|
||||
service = SensorService(
|
||||
sites=FauxDepotSites([FauxSite("A", "Site A")]), # type: ignore[arg-type]
|
||||
readings=FauxDepotLectures([FauxLecture("A", TIMESTAMP, "critical", null_reasons=[])]), # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
etat = await service.status()
|
||||
|
||||
site = etat.sites[0]
|
||||
assert site.overall == "critical"
|
||||
for capteur in (
|
||||
site.sensors.consumption,
|
||||
site.sensors.electrical,
|
||||
site.sensors.temperature,
|
||||
site.sensors.humidity,
|
||||
site.sensors.network,
|
||||
):
|
||||
assert capteur.status == "failing"
|
||||
assert capteur.since == TIMESTAMP
|
||||
|
||||
|
||||
async def test_status_treats_an_unknown_data_quality_as_critical() -> None:
|
||||
service = SensorService(
|
||||
sites=FauxDepotSites([FauxSite("A", "Site A")]), # type: ignore[arg-type]
|
||||
readings=FauxDepotLectures([FauxLecture("A", TIMESTAMP, None, null_reasons=[])]), # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
etat = await service.status()
|
||||
|
||||
assert etat.sites[0].overall == "critical"
|
||||
|
||||
|
||||
async def test_status_ignores_an_unknown_null_reason() -> None:
|
||||
service = SensorService(
|
||||
sites=FauxDepotSites([FauxSite("A", "Site A")]), # type: ignore[arg-type]
|
||||
readings=FauxDepotLectures( # type: ignore[arg-type]
|
||||
[FauxLecture("A", TIMESTAMP, "good", null_reasons=["something_else"])]
|
||||
),
|
||||
)
|
||||
|
||||
etat = await service.status()
|
||||
|
||||
site = etat.sites[0]
|
||||
assert site.overall == "ok"
|
||||
for capteur in (
|
||||
site.sensors.consumption,
|
||||
site.sensors.electrical,
|
||||
site.sensors.temperature,
|
||||
site.sensors.humidity,
|
||||
site.sensors.network,
|
||||
):
|
||||
assert capteur.status == "ok"
|
||||
|
||||
|
||||
async def test_status_flags_network_from_null_reasons_only() -> None:
|
||||
service = SensorService(
|
||||
sites=FauxDepotSites([FauxSite("A", "Site A")]), # type: ignore[arg-type]
|
||||
readings=FauxDepotLectures( # type: ignore[arg-type]
|
||||
[
|
||||
FauxLecture(
|
||||
"A",
|
||||
TIMESTAMP,
|
||||
"partial",
|
||||
null_reasons=["network_loss"],
|
||||
)
|
||||
]
|
||||
),
|
||||
)
|
||||
|
||||
etat = await service.status()
|
||||
|
||||
site = etat.sites[0]
|
||||
assert site.overall == "degraded"
|
||||
assert site.sensors.network.status == "failing"
|
||||
assert site.sensors.network.since == TIMESTAMP
|
||||
assert site.sensors.consumption.status == "ok"
|
||||
assert site.sensors.electrical.status == "ok"
|
||||
assert site.sensors.temperature.status == "ok"
|
||||
assert site.sensors.humidity.status == "ok"
|
||||
@@ -0,0 +1,47 @@
|
||||
# ==================
|
||||
# Étape 1 : Build
|
||||
# ==================
|
||||
|
||||
# Image pour frontend
|
||||
FROM node:24-alpine3.22 AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json package-lock.json* ./
|
||||
|
||||
# Installation des dépendances du projet avec npm
|
||||
RUN npm ci
|
||||
|
||||
# Copie du code source vers le conteneur
|
||||
COPY . .
|
||||
|
||||
# Build
|
||||
RUN npm run build
|
||||
|
||||
# ==================
|
||||
# Étape 2 : Runner
|
||||
# ==================
|
||||
|
||||
|
||||
FROM dhi.io/nginx:1.28.0-alpine3.21-dev AS runner
|
||||
|
||||
# Copie de la configuration de nginx
|
||||
COPY --chown=root:root --chmod=755 nginx.conf /etc/nginx/nginx.conf
|
||||
|
||||
# Copy the static build output from the build stage to Nginx's default HTML serving directory
|
||||
COPY --chown=root:root --chmod=755 --from=builder /app/dist/*/browser /usr/share/nginx/html
|
||||
|
||||
# Create necessary directories with proper permissions for nginx
|
||||
RUN mkdir -p /var/log/nginx /var/cache/nginx && \
|
||||
chown -R nginx:nginx /var/log/nginx /var/cache/nginx /usr/share/nginx/html
|
||||
|
||||
# Use a non-root user for security best practices
|
||||
USER nginx
|
||||
|
||||
# Frontend : port 3000
|
||||
# Backend : port 8000
|
||||
EXPOSE 3000
|
||||
|
||||
# Start Nginx directly with custom config
|
||||
ENTRYPOINT ["nginx", "-c", "/etc/nginx/nginx.conf"]
|
||||
CMD ["-g", "daemon off;"]
|
||||
@@ -81,6 +81,7 @@
|
||||
"builder": "@angular/build:unit-test",
|
||||
"options": {
|
||||
"coverage": true,
|
||||
"isolate": true,
|
||||
"coverageReporters": [
|
||||
"text-summary",
|
||||
"lcov",
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
worker_processes auto;
|
||||
error_log /var/log/nginx/error.log warn;
|
||||
pid /tmp/nginx.pid;
|
||||
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
include /etc/nginx/mime.types;
|
||||
default_type application/octet-stream;
|
||||
|
||||
sendfile on;
|
||||
keepalive_timeout 65;
|
||||
|
||||
|
||||
server {
|
||||
listen 3000;
|
||||
server_name _;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
location ~ /\. {
|
||||
deny all;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,21 @@
|
||||
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
|
||||
import {ApplicationConfig, inject, provideAppInitializer, 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([mockApiInterceptor])),
|
||||
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))));
|
||||
}),
|
||||
],
|
||||
};
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
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',
|
||||
loadComponent: () => import('./features/dashboard/dashboard').then((m) => m.Dashboard),
|
||||
canActivate: [authGuard],
|
||||
loadComponent: () => import('./features/dashboard/dashboard').then(m => m.Dashboard),
|
||||
},
|
||||
];
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
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;
|
||||
};
|
||||
@@ -0,0 +1,161 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
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);
|
||||
})
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,86 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
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`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<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>
|
||||
@@ -0,0 +1,88 @@
|
||||
: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;
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
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',
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
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).');
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<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>
|
||||
@@ -0,0 +1,81 @@
|
||||
: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;
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
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' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
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,7 +1,10 @@
|
||||
<div class="dashboard">
|
||||
<header class="dashboard__header">
|
||||
<h1>Vue d'ensemble</h1>
|
||||
<p class="dashboard__subtitle">Consommation instantanée du parc</p>
|
||||
<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>
|
||||
</header>
|
||||
|
||||
@if (error(); as message) {
|
||||
|
||||
@@ -144,3 +144,30 @@ 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,6 +4,8 @@ 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 {
|
||||
@@ -92,4 +94,58 @@ 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,10 +2,12 @@ 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';
|
||||
|
||||
@@ -23,6 +25,8 @@ 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);
|
||||
@@ -50,6 +54,17 @@ 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;
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
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: 'http://localhost:8000/api/v1',
|
||||
apiUrl: '/api/v1',
|
||||
useMockFixtures: false,
|
||||
};
|
||||
|
||||
@@ -43,5 +43,12 @@ services:
|
||||
- "${BACKEND_PORT:-8000}:8000"
|
||||
restart: unless-stopped
|
||||
|
||||
frontend:
|
||||
build: ./apps/frontend
|
||||
ports:
|
||||
- "${FRONTEND_PORT:-3000}:80"
|
||||
restart: unless-stopped
|
||||
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
|
||||
@@ -74,7 +74,7 @@ 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`, contrat OpenAPI versionné, routes `sites` et `recommendations` en lecture (endpoints → services → repositories → models) |
|
||||
| Backend | FastAPI, Python 3.14 | `apps/backend` | `En cours` | Factory, configuration, journalisation, 2 sondes de santé, `/metrics`, contrat OpenAPI versionné, routes `sites`, `alerts`, `recommendations`, `stats/summary` et `readings` en lecture (endpoints → services → repositories → models) |
|
||||
| Frontend | Angular 22, Node 24 | `apps/frontend` | `En cours` | Tableau de bord sur route `/dashboard`, deux services HTTP, graphiques Chart.js, données servies par des fixtures |
|
||||
| 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 |
|
||||
|
||||
@@ -12,10 +12,10 @@ Les quatre couches existent désormais, portées par l'authentification.
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
ep["endpoints<br/>health, auth, users, sites,<br/>recommendations, stats"]
|
||||
ep["endpoints<br/>health, auth, users, sites, alerts,<br/>recommendations, stats, sensors"]
|
||||
sc["schemas<br/>Pydantic"]
|
||||
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"]
|
||||
sv["services<br/>AuthService, UserService,<br/>SiteService, AlertService, RecommendationService,<br/>StatsService, SensorService"]
|
||||
rp["repositories<br/>user, refresh_token,<br/>login_attempt, audit_log,<br/>site, alert, recommendation, reading"]
|
||||
md["models<br/>10 tables"]
|
||||
db[("PostgreSQL")]
|
||||
|
||||
@@ -142,9 +142,12 @@ Deux fichiers d'environnement, deux usages : `.env` à la racine alimente `docke
|
||||
| POST | `/api/v1/users/{id}/password-reset` | Réinitialise et ferme les sessions. `admin` | 401, 403, 404, 422, 500 |
|
||||
| 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 | `/api/v1/readings` | Historique des lectures, filtrable par `site_id`, fenêtre `start`/`end` (24h par défaut, 90 jours maximum) et paginé par `limit`/`offset`. `lecteur` | 400, 401, 403, 422, 500 |
|
||||
| GET | `/api/v1/sensors/status` | État de santé des capteurs par site, dérivé de la dernière lecture. `admin` | 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` | |
|
||||
|
||||
@@ -156,21 +159,34 @@ Les codes de la dernière colonne sont ceux que le schéma **déclare**, et le f
|
||||
é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.
|
||||
|
||||
`GET /sites` et `GET /sites/{site_id}` sont la première route métier, et le gabarit à réutiliser
|
||||
pour les suivantes (`reading`, `dataset`, `prediction`, `alert`, `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
|
||||
`GET /sites` et `GET /sites/{site_id}` sont la première route métier, et le gabarit repris pour
|
||||
`GET /alerts` puis pour les suivantes (`dataset`, `prediction`) : les quatre couches
|
||||
`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` et `GET /sensors/status` agrègent chacune deux repositories (`SiteRepository`,
|
||||
`ReadingRepository`) dans un service dédié plutôt que d'exposer une table : elles n'entrent donc
|
||||
pas dans ce gabarit route-par-table. Le contrat détaillé pour le frontend est dans
|
||||
[31-contrat-authentification.md](31-contrat-authentification.md).
|
||||
|
||||
`GET /readings` reprend le même gabarit mais s'en écarte sur un point : `reading` est l'hypertable,
|
||||
donc la seule table métier pouvant porter des années d'historique, ce que `docs/architecture/
|
||||
owasp-traceabilite.md` documentait comme un risque ouvert (API4, aucune pagination plafonnée ni
|
||||
fenêtre temporelle maximale). `ReadingService` porte donc une couche de validation absente des
|
||||
autres routes de lecture : `start`/`end` sont optionnels (24 dernières heures par défaut si les
|
||||
deux sont omis, l'un défaut par rapport à l'autre sinon), l'écart entre les deux est plafonné à 90
|
||||
jours (`FENETRE_MAXIMALE`), et `limit`/`offset` (défaut 500, plafond 2000) empêchent qu'une fenêtre
|
||||
large mais peu dense reste malgré tout coûteuse. Un dépassement de plafond répond `400` (règle
|
||||
métier, portée par le service) plutôt que `422` (réservé à la validation structurelle de FastAPI,
|
||||
par exemple `limit` hors bornes). Un datetime sans fuseau dans `start`/`end` est traité comme de
|
||||
l'UTC plutôt que rejeté : le comparer tel quel à `reading.timestamp` (`timestamptz`) échouerait
|
||||
côté pilote, en `500` plutôt qu'un refus propre.
|
||||
|
||||
### `/health/ready`
|
||||
|
||||
Cette sonde porte une garde décrite dans l'[ADR 0001](../adr/0001-postgresql-timescaledb.md) : un
|
||||
@@ -245,8 +261,8 @@ Les modèles de `app/schemas/errors.py` décrivent ce que les gestionnaires renv
|
||||
|
||||
### Ajouter une route métier
|
||||
|
||||
Checklist pour toute nouvelle route sur le gabarit `sites`/`recommendations`/`stats`
|
||||
(`reading`, `dataset`, `prediction`, `alert`) :
|
||||
Checklist pour toute nouvelle route sur le gabarit `sites`/`alerts`/`recommendations`/`stats`/
|
||||
`readings`/`sensors` (`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
|
||||
@@ -323,7 +339,9 @@ Trois fichiers méritent d'être connus avant de toucher à l'authentification :
|
||||
agir sur le site B. C'est la limite connue du modèle, et le risque BOLA du top 10 API.
|
||||
- **Rôles PostgreSQL cantonnés** pour l'ETL et le travail d'apprentissage, plus le `REVOKE` sur
|
||||
`audit_log`. Dette assumée, décrite dans les ADR 0003 et 0004.
|
||||
- **Pagination et fenêtrage** des lectures de séries temporelles, qui conditionnent la forme des
|
||||
endpoints métier. Sans plafond dur, une requête sur dix ans d'historique suffit à faire tomber
|
||||
l'API.
|
||||
- **Pagination et fenêtrage** : posés sur `GET /readings` (fenêtre plafonnée à 90 jours,
|
||||
`limit`/`offset` plafonné à 2000), mais toujours en `limit`/`offset` simple — pas de curseur ni
|
||||
de plan de secours si un `offset` élevé sur une fenêtre dense devient lent en pratique.
|
||||
`statement_timeout` reste absent au niveau de la connexion, donc rien n'empêche une requête
|
||||
individuelle de tourner longtemps si les plafonds au-dessus d'elle s'avéraient insuffisants.
|
||||
- **Politique de versionnement de l'API** au-delà du préfixe `/api/v1`.
|
||||
|
||||
@@ -22,6 +22,7 @@ lecture seule ; plusieurs lignes resteront à compléter une fois les endpoints
|
||||
| Argon2id m=19456 t=2 p=1, re-hachage passif quand les paramètres changent | `app/core/hashing.py` | A02 Cryptographic Failures, A07 Identification and Authentication Failures |
|
||||
| Message et temps de réponse identiques quelle que soit la cause de l'échec, haché leurre sur adresse inconnue | `app/services/auth.py` | A07, API2 |
|
||||
| Limitation de débit à fenêtre glissante sur trois clés, évaluée avant le hachage | `app/services/auth.py`, `app/repositories/login_attempt.py` | A07, API4 Unrestricted Resource Consumption |
|
||||
| `GET /readings` : fenêtre temporelle plafonnée à 90 jours (24h par défaut), `limit`/`offset` plafonné à 2000, refus `400` si la fenêtre est inversée ou trop large | `app/services/reading.py` | API4 |
|
||||
| Absence de verrouillage de compte, qui serait un déni de service | ADR 0002 | API4 |
|
||||
| Jeton de rafraîchissement opaque, haché en base, rotation avec détection de réutilisation | `app/services/auth.py`, `app/repositories/refresh_token.py` | A07, API2 |
|
||||
| Séparation structurelle accès / rafraîchissement, impossible à confondre | ADR 0002 | API2 |
|
||||
@@ -50,7 +51,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 : `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. |
|
||||
| **API4, lectures de séries temporelles** | **partiel** | `GET /readings` plafonne la fenêtre temporelle (90 jours) et la pagination (`limit` ≤ 2000), voir plus haut. Reste ouvert : pagination en `limit`/`offset` simple plutôt qu'en curseur (un `offset` élevé sur une fenêtre dense reste coûteux), et aucun `statement_timeout` au niveau de la connexion pour borner une requête individuelle si les plafonds au-dessus s'avéraient insuffisants. |
|
||||
| **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. |
|
||||
| **A08 Software and Data Integrity Failures** | **partiel** | La CI vérifie le code mais n'analyse ni les dépendances ni les images. `.terraform.lock.hcl` reste ignoré par git, ce qui contredit une chaîne d'approvisionnement maîtrisée. |
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
sonar.projectKey=ProjetPiscine_EnerVision
|
||||
sonar.organization=groupe3-ener-vision
|
||||
|
||||
|
||||
# This is the name and version displayed in the SonarCloud UI.
|
||||
#sonar.projectName=ProjetPiscine_EnerVision
|
||||
#sonar.projectVersion=1.0
|
||||
|
||||
|
||||
# Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows.
|
||||
#sonar.sources=.
|
||||
|
||||
# Encoding of the source code. Default is default system encoding
|
||||
#sonar.sourceEncoding=UTF-8
|
||||
Reference in New Issue
Block a user