diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..423f50e --- /dev/null +++ b/.env.example @@ -0,0 +1,9 @@ +FUEL_ADVISOR_HOST=0.0.0.0 +FUEL_ADVISOR_PORT=8003 +FUEL_ADVISOR_DATA_DIR=/var/lib/fuel-advisor +FUEL_DEFAULT_TYPE=Gazole +FUEL_CACHE_TTL=21600 +FUEL_PRICES_URL=https://donnees.roulez-eco.fr/opendata/instantane +# Mettre l'URL entre quotes pour le chargement par le shell. +FUEL_MARKET_URL='https://stooq.com/q/l/?s=cl.f&f=sd2t2ohlcv&h&e=csv' +# Ollama n'est plus appelé : les anciennes variables OLLAMA_* sont ignorées. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5ca94b5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +.venv/ +__pycache__/ +*.py[cod] +.pytest_cache/ +.ruff_cache/ +.env +*.sqlite3 +*.sqlite3-* diff --git a/README.md b/README.md index d7e2b07..3d7a612 100644 --- a/README.md +++ b/README.md @@ -1,43 +1,81 @@ -# Conseiller carburant +# Conseiller carburant — v2 -Application web interne légère exposée sur le port `8003`. +Application interne indépendante de Cortex, Python standard + SQLite, sur `http://10.53.10.103:8003`. +Code : `/opt/fuel-advisor`. Aucune dépendance Python d'exécution, Python >=3.11 avec tzdata Europe/Paris. +VM actuelle Alpine/OpenRC (pas Docker). Le venv sert uniquement à pytest/Ruff. -## Fonctionnement +## Utiliser -- Le navigateur demande la géolocalisation du téléphone si le site est servi en contexte sécurisé. -- En HTTP simple sur `:8003`, les navigateurs mobiles peuvent bloquer la géolocalisation ; l'appli propose alors un fallback par ville/adresse via Nominatim/OpenStreetMap. -- L'API `/api/advice` cherche les stations les moins chères dans le rayon demandé. -- Sources best-effort : - - prix locaux : `https://donnees.roulez-eco.fr/opendata/instantane` - - tendance marché : CSV pétrole Stooq configurable - - actualités : RSS configurable - - synthèse IA optionnelle via Ollama `http://10.53.2.22:11434` -- La position n'est pas persistée ; seules les données publiques collectées sont mises en cache SQLite. +1. Rechercher une ville/adresse ou se géolocaliser, puis **Enregistrer ce lieu** : nom et rayon. +2. **Mes véhicules** : carburant, consommation, marge minimale d'autonomie, usage. Km mensuels pour usage régulier ; capacité réservoir facultative. +3. Sélectionner le lieu et le véhicule puis **Obtenir mon conseil**. Saisir l'autonomie affichée, sans déduire soi-même la marge. La saisie est effacée après chaque demande/fermeture. +4. Usage occasionnel : aucun trajet par défaut ; si déplacement prévu, indiquer date et distance totale (retour inclus si prévu). +5. **Suivi quotidien / Actualiser** lance une collecte réelle des stations suivies. L'enregistrement d'un favori déclenche aussi la première collecte dans l'interface. -## Configuration +Modifier/supprimer véhicules et favoris via les fenêtres correspondantes. Un changement de contexte invalide le résultat précédent : relancer volontairement un conseil demande une autonomie fraîche. Pas de profil ou lieu fictif préchargé. -Fichier : `/etc/fuel-advisor.env` +## Comment le conseil est calculé -```env -FUEL_ADVISOR_HOST=0.0.0.0 -FUEL_ADVISOR_PORT=8003 -FUEL_ADVISOR_DIR=/opt/fuel-advisor -FUEL_ADVISOR_DATA_DIR=/var/lib/fuel-advisor -OLLAMA_URL=http://10.53.2.22:11434 -OLLAMA_MODEL=gemma4:12b -FUEL_DEFAULT_TYPE=Gazole -FUEL_CACHE_TTL=21600 -``` +- Autonomie utilisable = max(0, autonomie affichée − marge minimale). +- Marge atteinte : ravitailler **avant de rouler**, quel que soit le prix. +- Usage régulier : km mensuels / 30 ; jours avant marge = autonomie utilisable / km quotidiens. +- Seuil pratique explicite : besoin proche si <=2 jours. Appoint calculé pour couvrir 7 jours d'usage plus la marge, en déduisant l'autonomie restante. Ces constantes ne prédisent pas les cours. +- Usage occasionnel : aucune moyenne mensuelle supposée. Sans trajet et au-dessus de la marge, aucun achat nécessaire. Départ sous 2 jours avec autonomie insuffisante : appoint pour le trajet et la marge ; plus loin, réévaluer avant le départ. +- Appoint estimé = kilomètres manquants × consommation / 100. Si capacité déclarée incompatible avec le besoin, conseil de plein et étapes de ravitaillement, pas de quantité impossible. +- Au-dessus des besoins immédiats : attendre **est possible**, sans promesse de baisse. +- Sans véhicule : comparaison des stations uniquement. +- Où acheter : prix minimal, médiane réelle, moyenne et distribution locale, indépendamment du conseil d'autonomie. Les distances sont à vol d'oiseau ; aucun gain net de détour ni prévision de prix n'est inventé. +- Prix absents/périmés n'empêchent pas de signaler une marge atteinte. Seuls les tarifs déclarés depuis moins de 7 jours sont comparés ; vérifier le tarif avant déplacement. -## Commandes +L'ancien score arbitraire et les appels Ollama/RSS ont été retirés. Le conseil est déterministe. Les anciennes variables `OLLAMA_*` de l'environnement ne sont plus utilisées. + +## Collecte et historique + +`collector.py` télécharge une seule fois le flux national officiel frais pour tous les favoris, puis ne conserve que les stations de leurs rayons, tous carburants. SQLite : un enregistrement par station/carburant/jour (Europe/Paris), dédupliqué même quand les favoris se chevauchent. Une actualisation dans la même journée remplace l'observation, pas de pseudo-historique intrajournalier. Prix, date de déclaration source et horodatage de collecte distincts. + +Historique conservé 730 jours ; journal des collectes 90 jours. Graphique des 30 derniers jours à panel constant. Tendance descriptive : au moins 7 dates observées, intervalle d'au moins 7 jours, dernière observation au plus la veille ; comparaison des mêmes stations sur les 10 derniers jours. Écart médian par station >=0,02 €/L : hausse, <=-0,02 : baisse, sinon stabilité observée. Moins de 3 stations : panel limité affiché. Les déclarations âgées de plus de 7 jours lors de l'observation sont exclues des tendances. + +**Pas de prévision pétrole/pompe** avant constitution et validation d'un historique suffisant. Stooq reste best-effort ; erreur/maintenance/N/D/NaN/cours de plus de 4 jours => tendance inconnue, jamais stable. Les cours valides et leur date sont conservés lors des collectes, sans influencer la marge. Flux par défaut WTI USD/baril, variation ouverture/dernier cours seulement. Changer de référentiel ou devise demande un adaptateur explicite. + +## Déploiement et maintenance + +Configuration : `/etc/fuel-advisor.env` (voir `.env.example`). État/cache : `/var/lib/fuel-advisor/fuel.sqlite3`. Logs service : `/var/log/fuel-advisor.log`. Logs job : `/var/log/fuel-advisor-collect.log`. ```sh -rc-service fuel-advisor start -rc-service fuel-advisor status +cd /opt/fuel-advisor +python3 -m venv .venv +.venv/bin/python -m pip install -r requirements-dev.txt +.venv/bin/python -m pytest -q +.venv/bin/ruff check . +.venv/bin/ruff format --check . +python3 -m py_compile app.py storage.py decision.py collector.py rc-service fuel-advisor restart -curl -fsS http://127.0.0.1:8003/healthz +rc-service fuel-advisor status +python3 -c "import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:8003/healthz').read().decode())" ``` -## Limites assumées +Planification native OpenRC/BusyBox : -La prédiction est un conseil probabiliste simple, pas une garantie : les changements fiscaux, ruptures locales, jours fériés et opérations commerciales peuvent dominer les signaux marché. +```sh +chmod 755 /opt/fuel-advisor/collect.sh +install -m 755 deploy/fuel-advisor-hourly /etc/periodic/hourly/fuel-advisor +rc-update add crond default +rc-service crond start # si pas déjà démarré +/opt/fuel-advisor/collect.sh --force +``` + +Le passage horaire effectue une collecte par jour civil, puis saute les passages suivants après succès. Échec : nouvel essai au prochain passage. Verrou `flock` interprocessus ; aucune collecte concurrente. Sans favoris, pas de téléchargement national ni données fictives. Le script reprend exactement le même environnement que le service. + +Sur Debian, utiliser un service systemd pour `run.sh` et un timer horaire pour `collect.sh` (ne pas installer les fichiers OpenRC tels quels). + +API : `GET /api/config`, `/api/vehicles`, `/api/favorites`, `/api/status`, `/api/history?lat=...&lon=...&radius_km=...&fuel=...`; `POST /api/advice` avec lat/lon/radius_km, vehicle_id, remaining_km, trip optionnel {date,km}. CRUD : POST collection, PUT/DELETE `/api/vehicles/` ou `/api/favorites/`. `POST /api/collect` actualise les favoris. Écritures : JSON et en-tête `X-Fuel-Request: 1`, origine identique si présente. Tests HTTP sur base temporaire, jamais la production. + +## Confidentialité et limites + +Instance interne partagée **sans authentification individuelle** : véhicules/favoris visibles et modifiables par les personnes ayant accès à l'instance. Ne pas exposer directement sur Internet ; réseau privé ou reverse proxy avec authentification. Protection anti-requêtes intersites, échappement HTML et CSP ne remplacent pas l'authentification. + +Autonomie et trajets saisis non persistés. Géolocalisation non enregistrée sauf favori explicite. Adresses recherchées transmises à Nominatim mais non mises en cache localement ; logs applicatifs sans query string/corps. Le cache historique de l'ancienne version peut contenir d'anciennes recherches de géocodage. + +Géolocalisation mobile exige généralement HTTPS ; recherche par adresse disponible en HTTP. Source officielle best-effort, prix déclaratifs, ruptures connues exclues. L'autonomie annoncée varie avec la conduite ; aucun conseil ne garantit l'absence de panne ni une économie future. Le service Python est adapté à cet usage interne léger, pas à un service public chargé. + +Git : commits locaux sur la VM ; aucun serveur Git distant configuré actuellement. diff --git a/app.py b/app.py index 693632d..3d82b84 100755 --- a/app.py +++ b/app.py @@ -1,108 +1,45 @@ #!/usr/bin/env python3 -"""Conseiller carburant local, sans dépendance externe. +"""Conseiller carburant : prix publics, profils explicites et décisions prudentes.""" -Sources best-effort : prix-carburants.gouv.fr, Stooq/Yahoo compatibles CSV, -flux RSS Google News. Les erreurs de collecte n'empêchent pas l'avis local. -""" from __future__ import annotations import csv import io import json -import math +import logging import os -import re import sqlite3 +import statistics +import threading import time import urllib.parse import urllib.request import zipfile from dataclasses import dataclass -from datetime import datetime, timezone -from http import HTTPStatus +from datetime import date, datetime, timezone from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path -from typing import Any from xml.etree import ElementTree as ET -APP_DIR = Path(os.environ.get("FUEL_ADVISOR_DIR", "/opt/fuel-advisor")) +import collector +import storage +from decision import recommend + +APP_DIR = Path(__file__).resolve().parent DATA_DIR = Path(os.environ.get("FUEL_ADVISOR_DATA_DIR", "/var/lib/fuel-advisor")) CACHE_DB = DATA_DIR / "fuel.sqlite3" HOST = os.environ.get("FUEL_ADVISOR_HOST", "0.0.0.0") PORT = int(os.environ.get("FUEL_ADVISOR_PORT", "8003")) -OLLAMA_URL = os.environ.get("OLLAMA_URL", "http://10.53.2.22:11434") -OLLAMA_MODEL = os.environ.get("OLLAMA_MODEL", "gemma4:12b") -FUEL_URL = os.environ.get( - "FUEL_PRICES_URL", "https://donnees.roulez-eco.fr/opendata/instantane" -) -MARKET_URL = os.environ.get( - "FUEL_MARKET_URL", "https://stooq.com/q/l/?s=cl.f&f=sd2t2ohlcv&h&e=csv" -) -NEWS_URL = os.environ.get( - "FUEL_NEWS_URL", - "https://news.google.com/rss/search?q=carburant%20p%C3%A9trole%20France&hl=fr&gl=FR&ceid=FR:fr", -) +FUEL_URL = os.environ.get("FUEL_PRICES_URL", "https://donnees.roulez-eco.fr/opendata/instantane") +MARKET_URL = os.environ.get("FUEL_MARKET_URL", "https://stooq.com/q/l/?s=cl.f&f=sd2t2ohlcv&h&e=csv") CACHE_TTL = int(os.environ.get("FUEL_CACHE_TTL", "21600")) +USER_AGENT = "CortexFuelAdvisor/0.2 (+internal homelab)" +FUEL_TYPES = storage.FUELS DEFAULT_FUEL = os.environ.get("FUEL_DEFAULT_TYPE", "Gazole") -USER_AGENT = "CortexFuelAdvisor/0.1 (+internal homelab)" -FUEL_TYPES = ["Gazole", "SP95", "SP98", "E10", "E85", "GPLc"] +FETCH_LOCK = threading.Lock() +MARKET_LOCK = threading.Lock() +LOG = logging.getLogger("fuel-advisor") -INDEX_HTML = """ - - - - - Conseiller carburant - - -
-
Cortex Lab · Carburant

Acheter maintenant ou attendre ?

L’application croise les prix locaux autour du téléphone, une tendance marché pétrole et des signaux d’actualité. La recommandation reste indicative : elle favorise le meilleur prix local mesurable.
-
-
Clique sur géolocaliser ou saisis une ville/adresse.
-
Aucun calcul pour l’instant.
-
-
""" @dataclass class Station: @@ -117,105 +54,106 @@ class Station: distance_km: float -def now_iso() -> str: - return datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M") +def now_iso(): + return datetime.now(timezone.utc).isoformat() -def ensure_db() -> None: +def ensure_db(): DATA_DIR.mkdir(parents=True, exist_ok=True) - with sqlite3.connect(CACHE_DB) as db: - db.execute("CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY, value TEXT NOT NULL, ts INTEGER NOT NULL)") + with sqlite3.connect(CACHE_DB, timeout=20) as db: + db.execute( + "CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY, value TEXT NOT NULL, ts INTEGER NOT NULL)" + ) -def cache_get(key: str, ttl: int = CACHE_TTL) -> Any | None: +def cache_get(key, ttl=CACHE_TTL): ensure_db() - with sqlite3.connect(CACHE_DB) as db: - row = db.execute("SELECT value, ts FROM cache WHERE key=?", (key,)).fetchone() - if not row or int(time.time()) - row[1] > ttl: + with sqlite3.connect(CACHE_DB, timeout=20) as db: + row = db.execute("SELECT value,ts FROM cache WHERE key=?", (key,)).fetchone() + if not row or time.time() - row[1] > ttl: return None return json.loads(row[0]) -def cache_set(key: str, value: Any) -> None: +def cache_set(key, value): ensure_db() - with sqlite3.connect(CACHE_DB) as db: + with sqlite3.connect(CACHE_DB, timeout=20) as db: db.execute( - "REPLACE INTO cache(key,value,ts) VALUES(?,?,?)", - (key, json.dumps(value, ensure_ascii=False), int(time.time())), + "REPLACE INTO cache VALUES(?,?,?)", (key, json.dumps(value, ensure_ascii=False), int(time.time())) ) -def fetch_bytes(url: str, timeout: int = 20) -> bytes: +def fetch_bytes(url, timeout=20): req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) - with urllib.request.urlopen(req, timeout=timeout) as r: - return r.read() + with urllib.request.urlopen(req, timeout=timeout) as response: + raw = response.read(50_000_001) + if len(raw) > 50_000_000: + raise ValueError("Source trop volumineuse") + return raw -def load_fuel_data() -> list[dict[str, Any]]: - cached = cache_get("fuel_data") - if cached is not None: - return cached - raw = fetch_bytes(FUEL_URL, 45) - if raw[:2] == b"PK": - with zipfile.ZipFile(io.BytesIO(raw)) as zf: - name = next(n for n in zf.namelist() if n.lower().endswith(".xml")) - xml_data = zf.read(name) - else: - xml_data = raw - root = ET.fromstring(xml_data) - rows: list[dict[str, Any]] = [] - for pdv in root.findall(".//pdv"): - try: - lat = float(pdv.attrib.get("latitude", "0")) / 100000 - lon = float(pdv.attrib.get("longitude", "0")) / 100000 - except ValueError: - continue - prices = {} - updates = {} - for prix in pdv.findall("prix"): - nom = prix.attrib.get("nom") - val = prix.attrib.get("valeur") - if not nom or not val: - continue +def load_fuel_data(force=False): + with FETCH_LOCK: + cached = None if force else cache_get("fuel_data") + if cached is not None: + return cached + raw = fetch_bytes(FUEL_URL, 45) + if raw[:2] == b"PK": + with zipfile.ZipFile(io.BytesIO(raw)) as archive: + name = next(n for n in archive.namelist() if n.lower().endswith(".xml")) + if archive.getinfo(name).file_size > 100_000_000: + raise ValueError("Archive trop volumineuse") + raw = archive.read(name) + root = ET.fromstring(raw) + rows = [] + for pdv in root.findall(".//pdv"): try: - parsed = float(val) - prices[nom] = parsed / 1000 if parsed > 10 else parsed - updates[nom] = prix.attrib.get("maj", "") - except ValueError: - pass - if prices: - rows.append( - { - "id": pdv.attrib.get("id", ""), - "name": pdv.findtext("adresse", "Station-service"), - "address": pdv.findtext("adresse", ""), - "city": pdv.findtext("ville", ""), - "lat": lat, - "lon": lon, - "prices": prices, - "updates": updates, - } - ) - cache_set("fuel_data", rows) - return rows + lat = storage.number(float(pdv.attrib["latitude"]) / 100000, "Latitude", -90, 90) + lon = storage.number(float(pdv.attrib["longitude"]) / 100000, "Longitude", -180, 180) + except (ValueError, KeyError): + continue + prices, updates = {}, {} + ruptures = {r.attrib.get("nom") for r in pdv.findall("rupture") if not r.attrib.get("fin")} + for prix in pdv.findall("prix"): + fuel = prix.attrib.get("nom") + if fuel not in FUEL_TYPES or fuel in ruptures: + continue + try: + value = float(prix.attrib["valeur"]) + value = value / 1000 if value > 10 else value + prices[fuel] = storage.number(value, "Prix", 0.01, 10) + updates[fuel] = prix.attrib.get("maj", "") + except (ValueError, KeyError): + continue + if prices: + rows.append( + dict( + id=pdv.attrib.get("id", ""), + name=pdv.findtext("adresse", "Station-service"), + address=pdv.findtext("adresse", ""), + city=pdv.findtext("ville", ""), + lat=lat, + lon=lon, + prices=prices, + updates=updates, + ) + ) + if not rows: + raise ValueError("Aucune station exploitable dans la source") + cache_set("fuel_data", rows) + return rows -def haversine(a_lat: float, a_lon: float, b_lat: float, b_lon: float) -> float: - r = 6371.0 - p1, p2 = math.radians(a_lat), math.radians(b_lat) - dphi = math.radians(b_lat - a_lat) - dl = math.radians(b_lon - a_lon) - q = math.sin(dphi / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2 - return 2 * r * math.atan2(math.sqrt(q), math.sqrt(1 - q)) +haversine = storage.distance_km -def nearest_stations(lat: float, lon: float, fuel: str, radius_km: float) -> list[Station]: +def nearest_stations(lat, lon, fuel, radius_km): stations = [] for row in load_fuel_data(): - if fuel not in row["prices"]: + if fuel not in row["prices"] or not storage.fresh_price(row["updates"].get(fuel, "")): continue - d = haversine(lat, lon, row["lat"], row["lon"]) - if d <= radius_km: + distance = haversine(lat, lon, row["lat"], row["lon"]) + if distance <= radius_km: stations.append( Station( id=row["id"], @@ -226,208 +164,245 @@ def nearest_stations(lat: float, lon: float, fuel: str, radius_km: float) -> lis lon=row["lon"], price=row["prices"][fuel], updated=row["updates"].get(fuel, ""), - distance_km=round(d, 1), + distance_km=round(distance, 1), ) ) return sorted(stations, key=lambda s: (s.price, s.distance_km)) -def market_signal() -> dict[str, Any]: - cached = cache_get("market", 3600) - if cached is not None: - return cached - result = {"summary": "indisponible", "trend": "flat", "delta_pct": 0.0} - try: - text = fetch_bytes(MARKET_URL, 12).decode("utf-8", "ignore") - rows = list(csv.DictReader(io.StringIO(text))) - if rows: +def market_signal(): + with MARKET_LOCK: + cached = cache_get("market_v2", 3600) + if cached is not None: + return cached + result = dict( + summary="Pétrole indisponible — tendance inconnue", + trend="unknown", + delta_pct=None, + source="Stooq (flux configuré)", + date=None, + ) + try: + rows = list(csv.DictReader(io.StringIO(fetch_bytes(MARKET_URL, 5).decode("utf-8", "replace")))) + if not rows: + raise ValueError("Flux vide") row = rows[-1] - close = float(row.get("Close") or 0) - open_ = float(row.get("Open") or close) - delta = ((close - open_) / open_ * 100) if open_ else 0 + quote_day = date.fromisoformat(row.get("Date", "")) + if not 0 <= (datetime.now(timezone.utc).date() - quote_day).days <= 4: + raise ValueError("Cours périmé") + close = storage.number(row.get("Close"), "Dernier cours", 0.01, 10000) + opening = storage.number(row.get("Open"), "Ouverture", 0.01, 10000) + delta = (close - opening) / opening * 100 trend = "up" if delta > 0.7 else "down" if delta < -0.7 else "flat" - result = {"summary": f"pétrole {trend} ({delta:+.1f}%)", "trend": trend, "delta_pct": round(delta, 2)} + symbol = str(row.get("Symbol", "pétrole"))[:30] + result.update( + summary=f"{symbol} : {close:.2f} USD/baril, {delta:+.1f}% depuis l’ouverture ({quote_day}). Signal intrajournalier, pas une prévision à la pompe.", + trend=trend, + delta_pct=round(delta, 2), + price_usd=close, + date=quote_day.isoformat(), + ) + except Exception as exc: + result["error"] = type(exc).__name__ + cache_set("market_v2", result) + return result + + +def geocode_address(query): + # Une recherche non enregistrée n'est pas conservée dans le cache SQL. + params = urllib.parse.urlencode(dict(q=query, format="jsonv2", limit=1, countrycodes="fr")) + rows = json.loads(fetch_bytes("https://nominatim.openstreetmap.org/search?" + params, 12)) + if not rows: + raise ValueError("Adresse introuvable") + return dict( + lat=float(rows[0]["lat"]), lon=float(rows[0]["lon"]), label=rows[0].get("display_name", query) + ) + + +def advice(lat, lon, fuel, radius_km, vehicle=None, remaining_km=None, trip=None): + hist = storage.history(lat, lon, radius_km, fuel) + result = recommend(vehicle, remaining_km, hist, trip) + stations, error = [], None + try: + stations = nearest_stations(lat, lon, fuel, radius_km) except Exception as exc: - result["summary"] = f"indisponible ({exc.__class__.__name__})" - cache_set("market", result) + LOG.warning("Source des prix inaccessible : %s", type(exc).__name__) + error = "Source des prix inaccessible ; aucun ancien prix présenté comme actuel." + prices = [s.price for s in stations] + stats = {} + if prices: + stats = dict( + count=len(prices), + best=prices[0], + min=min(prices), + max=max(prices), + average=round(statistics.mean(prices), 3), + median=round(statistics.median(prices), 3), + best_tie_count=prices.count(prices[0]), + price_buckets=[dict(price=p, count=prices.count(p)) for p in sorted(set(prices))], + ) + result.update( + generated_at=now_iso(), + fuel=fuel, + history=hist, + local_stats=stats, + stations=[s.__dict__ for s in stations[:12]], + market=market_signal(), + ai_used=False, + price_warning=error + or (None if prices else "Aucun prix déclaré depuis moins de 7 jours dans ce rayon."), + summary="Le choix de la station et le moment de ravitailler sont évalués séparément.", + distance_note="Distances à vol d’oiseau, pas des trajets routiers. Le détour peut annuler l’économie.", + price_max_age_days=storage.MAX_PRICE_AGE_DAYS, + ) return result -def news_signal() -> list[str]: - cached = cache_get("news", 7200) - if cached is not None: - return cached - items: list[str] = [] - try: - xml = fetch_bytes(NEWS_URL, 10) - root = ET.fromstring(xml) - for item in root.findall(".//item")[:5]: - title = re.sub(r"\s+-\s+[^-]+$", "", item.findtext("title", "")).strip() - if title: - items.append(title[:160]) - except Exception: - pass - cache_set("news", items) - return items - - -def geocode_address(query: str) -> dict[str, Any]: - key = "geocode:" + query.lower().strip() - cached = cache_get(key, 604800) - if cached is not None: - return cached - params = urllib.parse.urlencode({"q": query, "format": "jsonv2", "limit": "1", "countrycodes": "fr"}) - req = urllib.request.Request( - "https://nominatim.openstreetmap.org/search?" + params, - headers={"User-Agent": USER_AGENT}, - ) - with urllib.request.urlopen(req, timeout=12) as r: - rows = json.loads(r.read().decode()) - if not rows: - raise ValueError("Adresse introuvable") - out = {"lat": float(rows[0]["lat"]), "lon": float(rows[0]["lon"]), "label": rows[0].get("display_name", query)} - cache_set(key, out) - return out - - -def ollama_summary(context: dict[str, Any]) -> tuple[str | None, bool]: - prompt = ( - "Réponds en français en 2 phrases max. Donne un conseil prudent pour acheter du carburant, " - "basé uniquement sur ces données JSON. Ne prétends pas connaître l'avenir.\n" - + json.dumps(context, ensure_ascii=False) - ) - payload = json.dumps({"model": OLLAMA_MODEL, "prompt": prompt, "stream": False, "options": {"num_predict": 120}}).encode() - try: - req = urllib.request.Request( - urllib.parse.urljoin(OLLAMA_URL.rstrip("/") + "/", "api/generate"), - data=payload, - headers={"Content-Type": "application/json", "User-Agent": USER_AGENT}, - ) - with urllib.request.urlopen(req, timeout=25) as r: - data = json.loads(r.read().decode()) - summary = str(data.get("response", "")).strip() - return summary or None, bool(summary) - except Exception: - return None, False - - -def advice(lat: float, lon: float, fuel: str, radius_km: float) -> dict[str, Any]: - stations = nearest_stations(lat, lon, fuel, radius_km) - if not stations: - return {"error": "Aucune station trouvée", "detail": f"Pas de prix {fuel} dans un rayon de {radius_km:g} km."} - prices = [s.price for s in stations] - best = stations[0] - local_avg = sum(prices) / len(prices) - median = sorted(prices)[len(prices) // 2] - spread = median - best.price - market = market_signal() - news = news_signal() - score = 50 - reasons = [] - if spread >= 0.07: - score += 25; reasons.append(f"meilleure station {spread:.3f} €/L sous la médiane locale") - elif spread >= 0.03: - score += 12; reasons.append(f"prix local intéressant ({spread:.3f} €/L sous médiane)") - else: - score -= 8; reasons.append("écart local faible") - if best.price <= local_avg - 0.04: - score += 10; reasons.append("sous la moyenne locale") - if market["trend"] == "up": - score += 12; reasons.append("signal marché en hausse") - elif market["trend"] == "down": - score -= 12; reasons.append("signal marché en baisse") - if len(stations) < 3: - score -= 8; reasons.append("peu de stations comparables") - action = "buy" if score >= 66 else "wait" if score >= 45 else "avoid" - label = "Acheter maintenant" if action == "buy" else "Attendre un peu" if action == "wait" else "Éviter sauf urgence" - base_summary = ( - f"Meilleur prix {fuel}: {best.price:.3f} €/L à {best.distance_km} km. " - f"Moyenne locale: {local_avg:.3f} €/L sur {len(stations)} stations." - ) - ai_text, ai_used = ollama_summary({"label": label, "best": best.price, "avg": local_avg, "spread": spread, "market": market, "reasons": reasons}) - price_counts: dict[str, int] = {} - for p in prices: - key = f"{p:.3f}" - price_counts[key] = price_counts.get(key, 0) + 1 - best_tie_count = sum(1 for s in stations if round(s.price, 3) == round(best.price, 3)) - return { - "generated_at": now_iso(), - "fuel": fuel, - "action": action, - "label": label, - "score": score, - "summary": ai_text or base_summary, - "reasons": reasons, - "market": market, - "news": news[:4], - "ai_used": ai_used, - "local_stats": { - "count": len(stations), - "best": round(best.price, 3), - "best_tie_count": best_tie_count, - "average": round(local_avg, 3), - "median": round(median, 3), - "min": round(min(prices), 3), - "max": round(max(prices), 3), - "price_buckets": [ - {"price": float(price), "count": count} - for price, count in sorted(price_counts.items(), key=lambda item: float(item[0]))[:12] - ], - }, - "stations": [s.__dict__ for s in stations[:8]], - } +def from_payload(data): + lat = storage.number(data.get("lat"), "Latitude", -90, 90) + lon = storage.number(data.get("lon"), "Longitude", -180, 180) + radius = storage.number(data.get("radius_km", 15), "Rayon", 1, 80) + vehicle = storage.get_entity("vehicles", int(data["vehicle_id"])) if data.get("vehicle_id") else None + fuel = vehicle["fuel"] if vehicle else data.get("fuel", DEFAULT_FUEL) + if fuel not in FUEL_TYPES: + raise ValueError("Carburant non supporté") + trip = data.get("trip") + if trip is not None and not isinstance(trip, dict): + raise ValueError("Trajet invalide") + return advice(lat, lon, fuel, radius, vehicle, data.get("remaining_km"), trip) class Handler(BaseHTTPRequestHandler): - def log_message(self, fmt: str, *args: Any) -> None: - print(f"{self.address_string()} - {fmt % args}", flush=True) + def setup(self): + super().setup() + self.connection.settimeout(70) - def send_json(self, payload: Any, status: HTTPStatus = HTTPStatus.OK) -> None: - data = json.dumps(payload, ensure_ascii=False).encode() + def log_message(self, fmt, *args): + # Pas de query string (géolocalisation/adresse), ni de corps de requête dans les logs. + LOG.info("%s %s", self.command, urllib.parse.urlparse(self.path).path) + + def send_body(self, body, content_type, status=200): self.send_response(status) - self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", "no-store") - self.send_header("Content-Length", str(len(data))) - self.end_headers(); self.wfile.write(data) + self.send_header("X-Content-Type-Options", "nosniff") + self.send_header("Referrer-Policy", "same-origin") + self.send_header( + "Content-Security-Policy", + "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'", + ) + self.end_headers() + self.wfile.write(body) - def do_GET(self) -> None: - parsed = urllib.parse.urlparse(self.path) - if parsed.path == "/healthz": - return self.send_json({"ok": True, "time": now_iso()}) - if parsed.path == "/api/geocode": - try: - q = urllib.parse.parse_qs(parsed.query).get("q", [""])[0].strip() - if len(q) < 2: - raise ValueError("Adresse trop courte") - return self.send_json(geocode_address(q)) - except Exception as exc: - return self.send_json({"error": f"Géocodage impossible: {exc}"}, HTTPStatus.BAD_REQUEST) - if parsed.path == "/api/advice": - try: - q = urllib.parse.parse_qs(parsed.query) - lat = float(q.get("lat", [""])[0]); lon = float(q.get("lon", [""])[0]) - radius = max(1, min(80, float(q.get("radius_km", ["15"])[0]))) - fuel = q.get("fuel", [DEFAULT_FUEL])[0] + def send_json(self, payload, status=200): + self.send_body( + json.dumps(payload, ensure_ascii=False, allow_nan=False).encode(), + "application/json; charset=utf-8", + status, + ) + + def do_GET(self): + try: + parsed = urllib.parse.urlparse(self.path) + path = parsed.path + q = {k: v[0] for k, v in urllib.parse.parse_qs(parsed.query).items()} + if path == "/healthz": + return self.send_json(dict(ok=True, version=2, time=now_iso())) + if path in ("/", "/index.html", "/ui.js", "/style.css"): + name = "index.html" if path in ("/", "/index.html") else path[1:] + content_type = { + "index.html": "text/html; charset=utf-8", + "ui.js": "text/javascript; charset=utf-8", + "style.css": "text/css; charset=utf-8", + }[name] + return self.send_body((APP_DIR / name).read_bytes(), content_type) + if path == "/api/config": + return self.send_json(dict(fuels=FUEL_TYPES, default_fuel=DEFAULT_FUEL)) + if path == "/api/status": + return self.send_json(collector.status()) + if path in ("/api/vehicles", "/api/favorites"): + return self.send_json(dict(items=storage.list_entities(path.split("/")[-1]))) + if path == "/api/geocode": + query = q.get("q", "").strip() + if not 2 <= len(query) <= 200: + raise ValueError("Adresse requise, 200 caractères maximum") + return self.send_json(geocode_address(query)) + if path == "/api/advice": + # Compatibilité comparaison publique, autonomie seulement via POST. + q.pop("vehicle_id", None) + return self.send_json(from_payload(q)) + if path == "/api/history": + lat = storage.number(q.get("lat"), "Latitude", -90, 90) + lon = storage.number(q.get("lon"), "Longitude", -180, 180) + radius = storage.number(q.get("radius_km", 15), "Rayon", 1, 80) + fuel = q.get("fuel", DEFAULT_FUEL) if fuel not in FUEL_TYPES: - raise ValueError("carburant non supporté") - return self.send_json(advice(lat, lon, fuel, radius)) - except Exception as exc: - return self.send_json({"error": "Paramètres invalides", "detail": str(exc)}, HTTPStatus.BAD_REQUEST) - if parsed.path in ("/", "/index.html"): - html = INDEX_HTML.replace("%FUEL_TYPES%", json.dumps(FUEL_TYPES)).replace("%DEFAULT_FUEL%", DEFAULT_FUEL) - data = html.encode() - self.send_response(HTTPStatus.OK) - self.send_header("Content-Type", "text/html; charset=utf-8") - self.send_header("Content-Length", str(len(data))) - self.end_headers(); self.wfile.write(data); return - self.send_error(HTTPStatus.NOT_FOUND) + raise ValueError("Carburant invalide") + return self.send_json(storage.history(lat, lon, radius, fuel)) + return self.send_json(dict(error="Route introuvable"), 404) + except Exception as exc: + self.handle_error(exc) + + def handle_error(self, exc): + if isinstance(exc, (ValueError, TypeError)): + self.send_json(dict(error=str(exc)), 400) + elif isinstance(exc, LookupError): + self.send_json(dict(error=str(exc)), 404) + else: + LOG.exception("Erreur de traitement") + self.send_json(dict(error="Service temporairement indisponible"), 503) + + def mutation(self): + try: + origin = self.headers.get("Origin") + if self.headers.get("X-Fuel-Request") != "1" or ( + origin and urllib.parse.urlparse(origin).netloc != self.headers.get("Host") + ): + return self.send_json(dict(error="Requête externe refusée"), 403) + content_type = self.headers.get("Content-Type", "").split(";")[0].strip() + if content_type and content_type != "application/json": + return self.send_json({"error": "Content-Type application/json requis"}, 415) + length = int(self.headers.get("Content-Length", 0)) + if not 0 <= length <= 16384: + return self.send_json({"error": "Requête trop volumineuse"}, 413) + if length and content_type != "application/json": + return self.send_json({"error": "Content-Type application/json requis"}, 415) + data = json.loads(self.rfile.read(length)) if length else {} + if not isinstance(data, dict): + raise ValueError("Objet JSON attendu") + path = urllib.parse.urlparse(self.path).path + if path == "/api/advice" and self.command == "POST": + return self.send_json(from_payload(data)) + if path == "/api/collect" and self.command == "POST": + result = collector.collect(force=True) + return self.send_json(result, 503 if result["status"] == "error" else 200) + parts = path.strip("/").split("/") + if len(parts) not in (2, 3) or parts[0] != "api" or parts[1] not in ("vehicles", "favorites"): + return self.send_json(dict(error="Route introuvable"), 404) + entity_id = int(parts[2]) if len(parts) == 3 else None + if self.command == "POST" and entity_id is None: + result = storage.save_entity(parts[1], data) + return self.send_json(result, 201) + if self.command == "PUT" and entity_id is not None: + return self.send_json(storage.save_entity(parts[1], data, entity_id)) + if self.command == "DELETE" and entity_id is not None: + storage.delete_entity(parts[1], entity_id) + return self.send_json(dict(ok=True)) + return self.send_json(dict(error="Méthode non autorisée"), 405) + except Exception as exc: + self.handle_error(exc) + + do_POST = mutation + do_PUT = mutation + do_DELETE = mutation -def main() -> None: +def main(): + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") ensure_db() - server = ThreadingHTTPServer((HOST, PORT), Handler) - print(f"Fuel advisor listening on http://{HOST}:{PORT}", flush=True) - server.serve_forever() + LOG.info("Fuel advisor v2 écoute sur %s:%s", HOST, PORT) + ThreadingHTTPServer((HOST, PORT), Handler).serve_forever() if __name__ == "__main__": diff --git a/collect.sh b/collect.sh new file mode 100755 index 0000000..7799fcf --- /dev/null +++ b/collect.sh @@ -0,0 +1,8 @@ +#!/bin/sh +set -eu +if [ -f /etc/fuel-advisor.env ]; then + set -a + . /etc/fuel-advisor.env + set +a +fi +exec /usr/bin/python3 /opt/fuel-advisor/collector.py "$@" diff --git a/collector.py b/collector.py new file mode 100644 index 0000000..07ee53a --- /dev/null +++ b/collector.py @@ -0,0 +1,107 @@ +"""Collecte quotidienne et relance horaire après échec, verrou interprocessus.""" + +import fcntl +import json +from datetime import datetime, timedelta, timezone + +import storage + + +def status(): + with storage.connect() as db: + latest = db.execute("SELECT * FROM collections ORDER BY id DESC LIMIT 1").fetchone() + good = db.execute("SELECT * FROM collections WHERE status='ok' ORDER BY id DESC LIMIT 1").fetchone() + count = db.execute("SELECT count(*) FROM observations").fetchone()[0] + return dict( + latest=dict(latest) if latest else None, last_success=dict(good) if good else None, observations=count + ) + + +def collect(load=None, market=None, force=False): + if load is None: + import app + + def load(): + return app.load_fuel_data(force=True) + + market = app.market_signal + now = datetime.now(timezone.utc) + day = now.astimezone(storage.PARIS).date().isoformat() + storage.DB_PATH.parent.mkdir(parents=True, exist_ok=True) + with (storage.DB_PATH.parent / "collection.lock").open("a") as lock: + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + return {"status": "busy", "count": 0} + favorites = storage.list_entities("favorites") + if not favorites: + return {"status": "no_favorites", "count": 0} + with storage.connect() as db: + last = db.execute( + "SELECT finished_at FROM collections WHERE status='ok' ORDER BY id DESC LIMIT 1" + ).fetchone() + if ( + not force + and last + and datetime.fromisoformat(last[0]).astimezone(storage.PARIS).date().isoformat() == day + ): + return {"status": "skipped", "count": 0} + db.execute( + "UPDATE collections SET status='error', detail='Collecte précédente interrompue' WHERE status='running'" + ) + job = db.execute( + "INSERT INTO collections(started_at,status) VALUES(?,'running')", (now.isoformat(),) + ).lastrowid + count, detail, outcome = 0, "", "ok" + try: + rows = load() + if not rows: + raise ValueError("Le flux national ne contient aucune station exploitable") + selected = [ + row + for row in rows + if any( + storage.distance_km(f["lat"], f["lon"], row["lat"], row["lon"]) <= f["radius_km"] + for f in favorites + ) + ] + count = storage.record_observations(selected, now) + # L'indisponibilité du pétrole ne doit pas annuler l'historique local. + try: + market_data = market() if market else {"trend": "unknown"} + if market_data.get("trend") != "unknown" and market_data.get("date"): + with storage.connect() as db: + db.execute( + "REPLACE INTO market_daily VALUES(?,?)", + (market_data["date"], json.dumps(market_data)), + ) + except Exception as exc: + detail = f"Prix locaux collectés ; pétrole indisponible ({type(exc).__name__})" + if not selected: + detail = "Aucune station dans les favoris actuels" + except Exception as exc: + outcome, detail = "error", f"{type(exc).__name__}: {str(exc)[:250]}" + with storage.connect() as db: + db.execute( + "UPDATE collections SET finished_at=?, status=?, count=?, detail=? WHERE id=?", + (datetime.now(timezone.utc).isoformat(), outcome, count, detail, job), + ) + # Fenêtre glissante suffisante pour une future validation ; limiter le volume. + db.execute( + "DELETE FROM observations WHERE day 0: + out.update(action="topup", label="Prévoir un appoint") + reasons.append( + "Le besoin de déplacement est proche ; un appoint suffit au besoin calculé, sans imposer un plein." + ) + else: + out.update(action="wait", label="Vous pouvez attendre et réévaluer") + reasons.append( + "L’autonomie couvre le besoin immédiat. Cela ne signifie pas que les prix vont baisser." + ) + + if out["action"] in ("refuel", "topup") and needed > 0: + liters = needed * consumption / 100 + tank = vehicle.get("tank_liters") + estimated_liters = remaining * consumption / 100 + if tank and (liters + estimated_liters > tank): + out.update(action="refuel", label="Faire le plein et prévoir les étapes") + reasons.append( + "Le besoin dépasse la capacité déclarée : prévoir des étapes de ravitaillement ; quantité d’appoint non fiable." + ) + else: + out["topup_liters"] = round(liters, 1) + reasons.append( + f"Appoint indicatif : {needed:g} km × {consumption:g} L/100 km = {liters:.1f} L, à ajuster au réservoir réel." + ) + if history.get("trend") in ("down", "up", "flat"): + reasons.append( + "La tendance locale décrit le passé seulement : elle ne modifie pas la marge de sécurité ni ne garantit le prochain prix." + ) + else: + reasons.append("Historique insuffisant : aucun signal de baisse ou de hausse future retenu.") + return out diff --git a/deploy/fuel-advisor-hourly b/deploy/fuel-advisor-hourly new file mode 100644 index 0000000..5fb52fe --- /dev/null +++ b/deploy/fuel-advisor-hourly @@ -0,0 +1,3 @@ +#!/bin/sh +# Passage horaire : collecte une fois par jour, nouvelle tentative si échec. +exec /opt/fuel-advisor/collect.sh >> /var/log/fuel-advisor-collect.log 2>&1 diff --git a/index.html b/index.html new file mode 100644 index 0000000..c600e56 --- /dev/null +++ b/index.html @@ -0,0 +1,26 @@ + + +Conseiller carburant +
+
Cortex Lab · Mobilité

Le bon arrêt.
Au bon moment.

+
+
Un conseil, pas une promesse

Où acheter et quand ravitailler
sont deux questions différentes.

Choisissez un lieu, puis un véhicule si vous souhaitez un conseil personnalisé. L’application vous demandera l’autonomie restante à chaque calcul.

Votre marge de sécurité d’abordPrix locaux observésSans décision par IA
+
+
Prix publics : prix-carburants.gouv.fr · Pétrole : Stooq, disponibilité variable.
Les favoris et véhicules sont enregistrés sur cette instance interne partagée. L’autonomie saisie n’est pas conservée. Les recherches d’adresse sont transmises à OpenStreetMap/Nominatim.
+
+

Mes véhicules

+

Ajouter un véhicule

Le conseil n’encouragera pas à entamer cette marge pour attendre une baisse.

+

Mes favoris

Pour un nouveau lieu, recherchez une adresse sur la page puis choisissez « Enregistrer ce lieu ».

Enregistrer le lieu

+

Autonomie restante

Saisissez l’autonomie totale affichée. Votre marge sera déduite automatiquement. Cette valeur ne sera pas enregistrée.

+ diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..3ee8fe0 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,9 @@ +[tool.ruff] +line-length = 110 +target-version = "py311" + +[tool.ruff.lint] +select = ["E4", "E7", "E9", "F", "I", "B"] + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..cc4631b --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,2 @@ +pytest==9.1.1 +ruff==0.16.7 diff --git a/storage.py b/storage.py new file mode 100644 index 0000000..32d214c --- /dev/null +++ b/storage.py @@ -0,0 +1,238 @@ +"""Persistance locale : profils explicites et observations publiques quotidiennes.""" + +from __future__ import annotations + +import json +import math +import os +import sqlite3 +import statistics +from contextlib import contextmanager +from datetime import datetime, timedelta, timezone +from pathlib import Path +from zoneinfo import ZoneInfo + +PARIS = ZoneInfo("Europe/Paris") +MAX_PRICE_AGE_DAYS = 7 + + +def fresh_price(updated, now=None): + now = now or datetime.now(timezone.utc) + try: + stamp = datetime.fromisoformat(updated) + if stamp.tzinfo is None: + stamp = stamp.replace(tzinfo=PARIS) + return timedelta(hours=-1) <= now - stamp <= timedelta(days=MAX_PRICE_AGE_DAYS) + except (ValueError, TypeError): + return False + + +def distance_km(lat, lon, other_lat, other_lon): + p1, p2 = math.radians(lat), math.radians(other_lat) + dlat, dlon = p2 - p1, math.radians(other_lon - lon) + a = math.sin(dlat / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dlon / 2) ** 2 + return 6371 * 2 * math.asin(math.sqrt(min(1, max(0, a)))) + + +def record_observations(rows, now=None): + now = now or datetime.now(timezone.utc) + day = now.astimezone(PARIS).date().isoformat() + values = {} + for row in rows: + for fuel, price in row["prices"].items(): + if fuel not in FUELS or not math.isfinite(price) or not 0 < price < 20: + continue + key = (row["id"], fuel, day) + values[key] = (*key, price, row["updates"].get(fuel, ""), now.isoformat(), row["lat"], row["lon"]) + with connect() as db: + db.executemany( + """INSERT INTO observations VALUES(?,?,?,?,?,?,?,?) + ON CONFLICT(station_id,fuel,day) DO UPDATE SET price=excluded.price, + source_updated=excluded.source_updated,collected_at=excluded.collected_at, + lat=excluded.lat,lon=excluded.lon""", + list(values.values()), + ) + return len(values) + + +def history(lat, lon, radius, fuel, now=None): + now = now or datetime.now(timezone.utc) + today = now.astimezone(PARIS).date() + with connect() as db: + rows = db.execute( + """SELECT * FROM observations WHERE fuel=? AND day>=? AND day<=? + ORDER BY day,station_id""", + (fuel, (today - timedelta(days=29)).isoformat(), today.isoformat()), + ).fetchall() + days = {} + for row in rows: + if distance_km(lat, lon, row["lat"], row["lon"]) > radius: + continue + observed = datetime.fromisoformat(row["collected_at"]) + if not fresh_price(row["source_updated"], observed): + continue + days.setdefault(row["day"], {})[row["station_id"]] = row["price"] + out = dict( + trend="unknown", + confidence="insufficient", + delta_per_liter=None, + matched_stations=0, + days=len(days), + series=[], + summary="Historique insuffisant : au moins 7 jours observés couvrant une semaine sont nécessaires.", + ) + if not days: + return out + # Graphe sur panel constant : aucun effet dû à l'apparition d'une station. + common = set.intersection(*(set(values) for values in days.values())) + if common: + out["series"] = [ + dict(day=day, median=round(statistics.median(values[s] for s in common), 3), count=len(common)) + for day, values in days.items() + ] + recent = {d: v for d, v in days.items() if d >= (today - timedelta(days=10)).isoformat()} + if len(recent) < 7: + return out + first, last = min(recent), max(recent) + if (today - datetime.fromisoformat(last).date()).days > 1 or ( + datetime.fromisoformat(last) - datetime.fromisoformat(first) + ).days < 7: + return out + common = set.intersection(*(set(values) for values in recent.values())) + if not common: + out["summary"] = "Panel de stations constant insuffisant pour comparer les prix." + return out + delta = statistics.median(recent[last][s] - recent[first][s] for s in common) + trend = "up" if delta >= 0.02 else "down" if delta <= -0.02 else "flat" + label = {"up": "hausse", "down": "baisse", "flat": "stabilité"}[trend] + out.update( + trend=trend, + confidence="limited" if len(common) < 3 else "observed", + delta_per_liter=round(delta, 3), + matched_stations=len(common), + start=first, + end=last, + summary=f"{label.capitalize()} observée : {delta:+.3f} €/L du {first} au {last}, " + f"sur les mêmes {len(common)} stations. Ce n’est pas une prévision.", + ) + return out + + +DB_PATH = Path(os.environ.get("FUEL_ADVISOR_DATA_DIR", "/var/lib/fuel-advisor")) / "fuel.sqlite3" +FUELS = ["Gazole", "SP95", "SP98", "E10", "E85", "GPLc"] + + +@contextmanager +def connect(): + DB_PATH.parent.mkdir(parents=True, exist_ok=True) + db = sqlite3.connect(DB_PATH, timeout=20) + db.row_factory = sqlite3.Row + db.execute("PRAGMA foreign_keys=ON") + try: + with db: + db.executescript(""" + CREATE TABLE IF NOT EXISTS vehicles (id INTEGER PRIMARY KEY, data TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS favorites (id INTEGER PRIMARY KEY, data TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS observations ( + station_id TEXT NOT NULL, fuel TEXT NOT NULL, day TEXT NOT NULL, + price REAL NOT NULL, source_updated TEXT NOT NULL, + collected_at TEXT NOT NULL, lat REAL NOT NULL, lon REAL NOT NULL, + PRIMARY KEY(station_id, fuel, day)); + CREATE TABLE IF NOT EXISTS collections ( + id INTEGER PRIMARY KEY, started_at TEXT NOT NULL, + finished_at TEXT, status TEXT NOT NULL, count INTEGER DEFAULT 0, + detail TEXT NOT NULL DEFAULT ''); + CREATE TABLE IF NOT EXISTS market_daily ( + day TEXT PRIMARY KEY, payload TEXT NOT NULL); + CREATE INDEX IF NOT EXISTS observations_day ON observations(day); + """) + yield db + finally: + db.close() + + +def number(value, name, minimum, maximum): + try: + if isinstance(value, bool): + raise ValueError + out = float(value) + if not math.isfinite(out) or not minimum <= out <= maximum: + raise ValueError + return out + except (TypeError, ValueError): + raise ValueError(f"{name} : valeur attendue entre {minimum} et {maximum}.") from None + + +def table_name(kind): + if kind not in ("vehicles", "favorites"): + raise ValueError("Type inconnu") + return kind + + +def list_entities(kind): + with connect() as db: + return [ + dict(id=row["id"], **json.loads(row["data"])) + for row in db.execute(f"SELECT id,data FROM {table_name(kind)} ORDER BY id") + ] + + +def get_entity(kind, entity_id): + with connect() as db: + row = db.execute(f"SELECT data FROM {table_name(kind)} WHERE id=?", (entity_id,)).fetchone() + if row is None: + raise LookupError("Élément introuvable") + return dict(id=int(entity_id), **json.loads(row["data"])) + + +def save_entity(kind, data, entity_id=None): + table_name(kind) + if not isinstance(data, dict): + raise ValueError("Objet JSON attendu") + name = str(data.get("name", "")).strip() + if not 1 <= len(name) <= 80: + raise ValueError("Nom requis, 80 caractères maximum") + clean = {"name": name} + if kind == "favorites": + clean.update( + lat=number(data.get("lat"), "Latitude", -90, 90), + lon=number(data.get("lon"), "Longitude", -180, 180), + radius_km=number(data.get("radius_km"), "Rayon", 1, 80), + ) + else: + fuel, usage = data.get("fuel"), data.get("usage") + if fuel not in FUELS or usage not in ("regular", "occasional"): + raise ValueError("Carburant ou usage invalide") + clean.update( + fuel=fuel, + usage=usage, + consumption=number(data.get("consumption"), "Consommation", 0.1, 60), + min_range_km=number(data.get("min_range_km"), "Marge km", 0, 1500), + monthly_km=number( + data.get("monthly_km", 0), "Km mensuels", 1 if usage == "regular" else 0, 30000 + ), + tank_liters=None + if data.get("tank_liters") in (None, "") + else number(data["tank_liters"], "Réservoir", 1, 300), + ) + with connect() as db: + if entity_id is None: + if db.execute(f"SELECT count(*) FROM {kind}").fetchone()[0] >= 100: + raise ValueError("Limite de 100 éléments atteinte") + entity_id = db.execute( + f"INSERT INTO {kind}(data) VALUES(?)", (json.dumps(clean, ensure_ascii=False),) + ).lastrowid + elif ( + db.execute( + f"UPDATE {kind} SET data=? WHERE id=?", (json.dumps(clean, ensure_ascii=False), entity_id) + ).rowcount + == 0 + ): + raise LookupError("Élément introuvable") + return dict(id=entity_id, **clean) + + +def delete_entity(kind, entity_id): + with connect() as db: + if not db.execute(f"DELETE FROM {table_name(kind)} WHERE id=?", (entity_id,)).rowcount: + raise LookupError("Élément introuvable") diff --git a/style.css b/style.css new file mode 100644 index 0000000..6ef372c --- /dev/null +++ b/style.css @@ -0,0 +1 @@ +:root{color-scheme:dark;--bg:#0b1220;--panel:#142035;--line:#29374b;--text:#edf3fa;--muted:#a2b0c4;--accent:#68dfc3;--warn:#f9cb72;--bad:#ff9393}*{box-sizing:border-box}body{margin:0;background:radial-gradient(ellipse at top left,#193749,transparent 65%),var(--bg);font:15px/1.55 system-ui,-apple-system,Segoe UI,sans-serif;color:var(--text);min-height:100vh}main{max-width:1240px;margin:auto;padding:36px 24px}header{display:flex;justify-content:space-between;align-items:center;gap:24px;margin-bottom:30px}.eyebrow{font-size:11px;letter-spacing:.14em;text-transform:uppercase;color:var(--accent);font-weight:750}h1{font-size:clamp(32px,4vw,52px);line-height:1.08;letter-spacing:-.045em;margin:12px 0}h1 span{color:var(--accent)}h2{font-size:20px;letter-spacing:-.025em;margin:0 0 16px}h3{font-size:16px;margin:22px 0 10px}p{margin:10px 0}.header-actions,.inline,.section-title,.dialog-head,.item-actions{display:flex;align-items:center;gap:10px}.layout{display:grid;grid-template-columns:355px minmax(0,1fr);gap:20px}aside,#result{display:grid;gap:18px;align-content:start}.card{background:linear-gradient(135deg,#17263b,#101c2d);border:1px solid var(--line);border-radius:20px;padding:24px;box-shadow:0 12px 30px #0002}.compact{padding:20px}.section-title,.dialog-head{justify-content:space-between}.section-title h2{margin:0;font-size:17px}label{display:block;font-size:13px;font-weight:650;color:#c6d4e7;margin:16px 0 7px}input,select{display:block;width:100%;background:#0b1627;color:var(--text);border:1px solid #36465c;border-radius:10px;padding:11px 12px;font:inherit;min-height:44px}label input,label select{margin-top:7px}input:focus,select:focus,button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}button{font:inherit;font-size:13px;font-weight:700;border:1px solid transparent;border-radius:10px;padding:11px 14px;cursor:pointer;min-height:42px;white-space:normal}.primary{background:var(--accent);color:#09211e}.secondary{background:#203048;color:var(--text);border-color:#34455b}button:hover{filter:brightness(1.12)}button:disabled{opacity:.55;cursor:wait}select:disabled{opacity:.75}.wide{width:100%;margin-top:20px}.small{padding:6px 10px;min-height:34px;font-size:12px}.hint,.muted{color:var(--muted);font-size:13px}.hint:empty,.form-error:empty{display:none}.inline>input,.inline>div{min-width:0;flex:1}.location-actions{margin-top:12px}.location-label{font-size:12px;color:var(--accent);padding-top:30px;overflow-wrap:anywhere}.empty{min-height:320px;padding-top:36px}.empty h2{font-size:26px;margin:16px 0}.empty p{max-width:520px;color:var(--muted)}.tags{display:flex;flex-wrap:wrap;gap:8px;margin-top:20px}.tags span,.badge{font-size:11px;background:#23374a;color:#cee5e5;padding:5px 9px;border-radius:7px}.verdict{font-size:clamp(24px,3vw,34px);line-height:1.2;margin:12px 0 20px}.tone-refuel,.tone-topup{color:var(--warn)}.tone-wait,.tone-none{color:var(--accent)}.metrics{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin:18px 0}.metric{background:#0d192a;border:1px solid #25364b;border-radius:12px;padding:14px}.metric strong{display:block;font-size:22px;line-height:1.4}.metric span{font-size:11px;color:var(--muted)}.reasons{padding-left:19px;color:#c1cee0;font-size:13px}.reasons li{margin:8px 0}.notice{padding:12px;border:1px solid #78603c;background:#382d1e;color:#f3d9ac;border-radius:10px;font-size:13px}.station{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;align-items:center;border-top:1px solid var(--line);padding:15px 0}.station:first-child{border-top:0}.station strong{font-size:14px;overflow-wrap:anywhere}.station .price{font-size:23px;font-weight:750;color:var(--accent);white-space:nowrap}.station .price small{font-size:11px}.station p{margin:2px 0}.buckets{display:flex;gap:6px;flex-wrap:wrap;max-height:110px;overflow:auto;margin:12px 0}.bucket{font-size:11px;padding:4px 7px;background:#203048;border-radius:6px}.chart{width:100%;height:170px;display:block;margin-top:16px}.chart polyline{stroke:var(--accent);stroke-width:2.5;fill:none;vector-effect:non-scaling-stroke}.chart circle{fill:var(--accent)}.chart text{fill:var(--muted);font-size:10px}.chart line{stroke:var(--line)}.error,.form-error{color:var(--bad);font-size:13px}.loading{color:var(--muted);padding:32px}.two{display:grid;grid-template-columns:1fr 1fr;gap:14px}dialog{border:1px solid #35465b;border-radius:20px;background:var(--panel);color:var(--text);width:min(560px,calc(100% - 24px));max-height:90vh;padding:24px;box-shadow:0 30px 100px #0009}dialog::backdrop{background:#030a16b8}dialog h2{margin:0}.close{font-size:24px;padding:0 12px}form h3{border-top:1px solid var(--line);padding-top:18px}form button[type=submit]{margin-top:20px}.item{padding:14px 0;border-bottom:1px solid var(--line)}.item-actions{margin-top:8px}.items{margin-bottom:16px}footer{font-size:11px;color:#8a9bb1;margin-top:30px;max-width:950px}details{margin-top:16px}summary{cursor:pointer;color:#cbd8e8;font-size:13px}[hidden]{display:none!important}@media(max-width:850px){main{padding:22px 16px}.layout{grid-template-columns:1fr}header{align-items:flex-start;flex-direction:column;gap:14px}.header-actions{width:100%}.header-actions button{flex:1}.card{padding:20px}.empty{min-height:240px}.metrics{gap:6px}.metric{padding:11px}.metric strong{font-size:19px}.two{gap:10px}.station .price{font-size:20px}} diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..325c03b --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,9 @@ +import pytest + +import storage + + +@pytest.fixture +def store(tmp_path, monkeypatch): + monkeypatch.setattr(storage, "DB_PATH", tmp_path / "test.sqlite3") + return storage diff --git a/tests/test_app.py b/tests/test_app.py index eb8d3d4..7e7b17d 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -14,16 +14,50 @@ def test_haversine_paris_close(): assert d == 0 -def test_advice_uses_best_price(monkeypatch): +def test_advice_uses_best_price(monkeypatch, tmp_path): + from datetime import datetime, timezone + + import storage + + monkeypatch.setattr(storage, "DB_PATH", tmp_path / "test.sqlite3") rows = [ - {"id": "1", "name": "A", "address": "rue A", "city": "Paris", "lat": 48.8566, "lon": 2.3522, "prices": {"Gazole": 1.70}, "updates": {"Gazole": "2026-01-01"}}, - {"id": "2", "name": "B", "address": "rue B", "city": "Paris", "lat": 48.8570, "lon": 2.3530, "prices": {"Gazole": 1.82}, "updates": {"Gazole": "2026-01-01"}}, - {"id": "3", "name": "C", "address": "rue C", "city": "Paris", "lat": 48.8580, "lon": 2.3540, "prices": {"Gazole": 1.80}, "updates": {"Gazole": "2026-01-01"}}, + { + "id": "1", + "name": "A", + "address": "rue A", + "city": "Paris", + "lat": 48.8566, + "lon": 2.3522, + "prices": {"Gazole": 1.70}, + "updates": {"Gazole": "2026-01-01"}, + }, + { + "id": "2", + "name": "B", + "address": "rue B", + "city": "Paris", + "lat": 48.8570, + "lon": 2.3530, + "prices": {"Gazole": 1.82}, + "updates": {"Gazole": "2026-01-01"}, + }, + { + "id": "3", + "name": "C", + "address": "rue C", + "city": "Paris", + "lat": 48.8580, + "lon": 2.3540, + "prices": {"Gazole": 1.80}, + "updates": {"Gazole": "2026-01-01"}, + }, ] + for row in rows: + row["updates"]["Gazole"] = datetime.now(timezone.utc).isoformat() monkeypatch.setattr(fuel_app, "load_fuel_data", lambda: rows) - monkeypatch.setattr(fuel_app, "market_signal", lambda: {"summary": "pétrole flat", "trend": "flat", "delta_pct": 0}) - monkeypatch.setattr(fuel_app, "news_signal", lambda: []) - monkeypatch.setattr(fuel_app, "ollama_summary", lambda context: (None, False)) + monkeypatch.setattr( + fuel_app, "market_signal", lambda: {"summary": "pétrole flat", "trend": "flat", "delta_pct": 0} + ) out = fuel_app.advice(48.8566, 2.3522, "Gazole", 5) assert out["stations"][0]["name"] == "A" - assert out["action"] == "buy" + assert out["action"] == "compare" diff --git a/tests/test_collector.py b/tests/test_collector.py new file mode 100644 index 0000000..30cd678 --- /dev/null +++ b/tests/test_collector.py @@ -0,0 +1,48 @@ +import importlib +from datetime import datetime, timezone + +import pytest +from test_history import sample + + +@pytest.fixture +def collector(store): + assert importlib.util.find_spec("collector"), "Collecteur absent" + return importlib.import_module("collector") + + +def test_collect_overlapping_favorites_once_daily(store, collector): + for name in ("Maison", "Travail"): + store.save_entity("favorites", dict(name=name, lat=48.8, lon=2.3, radius_km=15)) + calls = [] + + def load(): + calls.append(1) + return [sample(datetime.now(timezone.utc))] + + out = collector.collect(load, lambda: {"trend": "unknown"}, force=True) + assert out["status"] == "ok" + assert out["count"] == 1 + assert len(calls) == 1 + assert collector.collect(load, lambda: {}, force=False)["status"] == "skipped" + assert len(calls) == 1 + with store.connect() as db: + assert db.execute("select count(*) from observations").fetchone()[0] == 1 + + +def test_failed_collection_logged_and_retryable(store, collector): + store.save_entity("favorites", dict(name="Maison", lat=48.8, lon=2.3, radius_km=15)) + + def fail(): + raise OSError("source inaccessible") + + assert collector.collect(fail, lambda: {}, force=True)["status"] == "error" + out = collector.collect(lambda: [sample(datetime.now(timezone.utc))], lambda: {}, force=False) + assert out["status"] == "ok" + + +def test_empty_favorites_does_not_download(store, collector): + def forbidden(): + raise AssertionError("Aucun téléchargement sans favori") + + assert collector.collect(forbidden, forbidden)["status"] == "no_favorites" diff --git a/tests/test_decision.py b/tests/test_decision.py new file mode 100644 index 0000000..5feedd6 --- /dev/null +++ b/tests/test_decision.py @@ -0,0 +1,76 @@ +import importlib +from datetime import date, timedelta + +import pytest + + +@pytest.fixture +def decide(): + assert importlib.util.find_spec("decision"), "Moteur de conseil absent" + return importlib.import_module("decision").recommend + + +VEHICLE = dict( + name="Auto", + consumption=6, + min_range_km=80, + monthly_km=1200, + usage="regular", + tank_liters=50, + fuel="Gazole", +) + + +def test_reserve_overrides_downward_trend(decide): + out = decide(VEHICLE, 80, {"trend": "down"}) + assert out["action"] == "refuel" + assert out["usable_km"] == 0 + assert out["days_left"] == 0 + + +def test_missing_range_is_rejected_and_not_defaulted(decide): + with pytest.raises(ValueError): + decide(VEHICLE, None, {}) + with pytest.raises(ValueError): + decide(VEHICLE, float("nan"), {}) + + +def test_sufficient_range_is_not_buy_on_unknown_market(decide): + out = decide(VEHICLE, 480, {"trend": "unknown"}) + assert out["action"] == "wait" + assert out["days_left"] == 10 + assert out["usable_km"] == 400 + assert out["topup_liters"] is None + + +def test_near_need_proposes_measured_topup(decide): + out = decide(VEHICLE, 120, {"trend": "down"}) + assert out["action"] == "topup" + assert out["topup_liters"] == pytest.approx(14.4) + + +def test_van_no_trip_no_monthly_assumption(decide): + out = decide({**VEHICLE, "usage": "occasional"}, 300, {}) + assert out["action"] == "none" + assert out["days_left"] is None + assert out["usable_km"] == 220 + + +def test_van_imminent_trip_needs_fuel(decide): + trip = dict(date=(date.today() + timedelta(days=1)).isoformat(), km=400) + out = decide({**VEHICLE, "usage": "occasional"}, 300, {}, trip) + assert out["action"] == "topup" + assert out["topup_liters"] == pytest.approx(10.8) + assert out["days_left"] is None + + +def test_trip_over_tank_requires_stops(decide): + out = decide({**VEHICLE, "usage": "occasional"}, 100, {}, dict(date=date.today().isoformat(), km=2000)) + assert out["action"] == "refuel" + assert out["topup_liters"] is None + assert any("ravitaillement" in x for x in out["reasons"]) + + +def test_no_vehicle_no_timing_claim(decide): + out = decide(None, None, {"trend": "up"}) + assert out["action"] == "compare" diff --git a/tests/test_history.py b/tests/test_history.py new file mode 100644 index 0000000..f150c4d --- /dev/null +++ b/tests/test_history.py @@ -0,0 +1,47 @@ +from datetime import datetime, timedelta, timezone + +import pytest + + +def sample(day, price=1.8, station="A", age=0): + stamp = (day - timedelta(days=age)).isoformat() + return {"id": station, "lat": 48.8, "lon": 2.3, "prices": {"Gazole": price}, "updates": {"Gazole": stamp}} + + +def test_observations_daily_dedup_and_freshness(store): + assert hasattr(store, "record_observations"), "Historique absent" + day = datetime.now(timezone.utc) + row = sample(day) + store.record_observations([row, row], day) + store.record_observations([row], day) + with store.connect() as db: + assert db.execute("select count(*) from observations").fetchone()[0] == 1 + assert store.fresh_price(row["updates"]["Gazole"], day) + assert not store.fresh_price(sample(day, age=20)["updates"]["Gazole"], day) + + +def test_trend_requires_days_and_same_stations(store): + assert hasattr(store, "history"), "Tendance absente" + today = datetime.now(timezone.utc) + store.save_entity("favorites", dict(name="Maison", lat=48.8, lon=2.3, radius_km=10)) + for age in range(8): + day = today - timedelta(days=age) + store.record_observations([sample(day, 1.8 + age * 0.01)], day) + # Une nouvelle station moins chère ne doit pas simuler une baisse générale. + store.record_observations([sample(today, 1.0, "B")], today) + h = store.history(48.8, 2.3, 10, "Gazole", today) + assert h["trend"] == "down" + assert h["delta_per_liter"] == pytest.approx(-0.07) + assert h["matched_stations"] == 1 + assert len(h["series"]) == 8 + assert h["confidence"] == "limited" + assert store.history(0, 0, 10, "Gazole", today)["trend"] == "unknown" + + +def test_old_reports_do_not_become_new_evidence(store): + assert hasattr(store, "history"), "Tendance absente" + today = datetime.now(timezone.utc) + for age in range(8): + day = today - timedelta(days=age) + store.record_observations([sample(day, age=30)], day) + assert store.history(48.8, 2.3, 10, "Gazole", today)["trend"] == "unknown" diff --git a/tests/test_http.py b/tests/test_http.py new file mode 100644 index 0000000..96eead3 --- /dev/null +++ b/tests/test_http.py @@ -0,0 +1,104 @@ +import http.client +import json +import threading +from datetime import datetime, timezone + +import pytest +from test_app import fuel_app as app +from test_history import sample + + +@pytest.fixture +def server(store, monkeypatch, tmp_path): + monkeypatch.setattr(app, "CACHE_DB", tmp_path / "cache.sqlite3") + monkeypatch.setattr(app, "DATA_DIR", tmp_path) + httpd = app.ThreadingHTTPServer(("127.0.0.1", 0), app.Handler) + thread = threading.Thread(target=httpd.serve_forever, daemon=True) + thread.start() + yield httpd.server_port + httpd.shutdown() + httpd.server_close() + thread.join() + + +def request(port, method, path, body=None, headers=None): + conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5) + data = json.dumps(body) if body is not None else None + hdrs = {"Content-Type": "application/json", "X-Fuel-Request": "1"} + if headers: + hdrs.update(headers) + conn.request(method, path, body=data, headers=hdrs) + res = conn.getresponse() + status, raw = res.status, res.read() + conn.close() + return status, json.loads(raw) if raw.startswith(b"{") else raw.decode() + + +def test_http_vehicle_crud_and_csrf(server): + data = dict(name="Van", fuel="Gazole", consumption=9, min_range_km=80, usage="occasional", monthly_km=0) + status, v = request(server, "POST", "/api/vehicles", data) + assert status == 201 + assert request(server, "GET", "/api/vehicles")[1]["items"][0]["id"] == v["id"] + assert request(server, "PUT", f"/api/vehicles/{v['id']}", {**data, "name": "Mon van"})[0] == 200 + assert request(server, "POST", "/api/vehicles", data, {"Origin": "https://evil.example"})[0] == 403 + assert request(server, "DELETE", f"/api/vehicles/{v['id']}", headers={"Content-Type": ""})[0] == 200 + assert request(server, "GET", "/api/vehicles")[1]["items"] == [] + + +def test_http_advice_requires_fresh_range(server, store, monkeypatch): + vehicle = store.save_entity( + "vehicles", + dict(name="Auto", fuel="Gazole", consumption=6, min_range_km=80, monthly_km=1200, usage="regular"), + ) + row = sample(datetime.now(timezone.utc)) + row.update(name="A", city="Paris", address="Rue") + monkeypatch.setattr(app, "load_fuel_data", lambda **kwargs: [row]) + monkeypatch.setattr(app, "market_signal", lambda: {"trend": "unknown", "summary": "indisponible"}) + data = dict(lat=48.8, lon=2.3, radius_km=15, vehicle_id=vehicle["id"]) + assert request(server, "POST", "/api/advice", data)[0] == 400 + code, out = request(server, "POST", "/api/advice", {**data, "remaining_km": 80}) + assert code == 200 + assert out["action"] == "refuel" + assert out["ai_used"] is False + assert out["stations"][0]["name"] == "A" + # L'autonomie n'est jamais stockée dans le profil. + assert "remaining_km" not in store.get_entity("vehicles", vehicle["id"]) + + +def test_market_failure_is_unknown(store, monkeypatch, tmp_path): + monkeypatch.setattr(app, "CACHE_DB", tmp_path / "cache.sqlite3") + monkeypatch.setattr(app, "DATA_DIR", tmp_path) + + def fail(*args): + raise OSError("maintenance") + + monkeypatch.setattr(app, "fetch_bytes", fail) + assert app.market_signal()["trend"] == "unknown" + + +def test_market_rejects_nd_nan_and_old_quotes(store, monkeypatch, tmp_path): + monkeypatch.setattr(app, "CACHE_DB", tmp_path / "cache.sqlite3") + monkeypatch.setattr(app, "DATA_DIR", tmp_path) + for text in ( + "Symbol,Date,Open,Close\nCL.F,N/D,N/D,N/D", + "Symbol,Date,Open,Close\nCL.F,2020-01-01,80,85", + f"Symbol,Date,Open,Close\nCL.F,{datetime.now().date()},nan,85", + ): + app.cache_set("market_v2", None) + monkeypatch.setattr(app, "fetch_bytes", lambda *args, text=text: text.encode()) + assert app.market_signal()["trend"] == "unknown" + + +def test_http_ui_and_validation(server): + status, html = request(server, "GET", "/") + assert status == 200 + assert "Autonomie restante" in html + assert "Mes favoris" in html + assert ( + request( + server, "POST", "/api/favorites", {"name": "X", "lat": float("nan"), "lon": 2, "radius_km": 10} + )[0] + == 400 + ) + assert request(server, "GET", "/api/advice?lat=nan&lon=2")[0] == 400 + assert request(server, "GET", "/api/status")[0] == 200 diff --git a/tests/test_store.py b/tests/test_store.py new file mode 100644 index 0000000..3eb6ccd --- /dev/null +++ b/tests/test_store.py @@ -0,0 +1,34 @@ +import sqlite3 + +import pytest + + +def test_vehicle_crud_persists_and_validates(store): + data = dict( + name="Van", + fuel="Gazole", + consumption=9, + min_range_km=80, + monthly_km=0, + usage="occasional", + tank_liters=None, + ) + v = store.save_entity("vehicles", data) + assert store.list_entities("vehicles") == [v] + assert v["min_range_km"] == 80 + assert store.save_entity("vehicles", {**data, "name": "Van aménagé"}, v["id"])["name"] == "Van aménagé" + with pytest.raises(ValueError): + store.save_entity("vehicles", {**data, "consumption": float("nan")}) + with pytest.raises(ValueError): + store.save_entity("vehicles", {**data, "min_range_km": -1}) + store.delete_entity("vehicles", v["id"]) + assert store.list_entities("vehicles") == [] + + +def test_favorite_crud_limits_and_overlap(store): + f = store.save_entity("favorites", dict(name="Maison", lat=48.8, lon=2.3, radius_km=15)) + assert store.list_entities("favorites")[0] == f + with pytest.raises(ValueError): + store.save_entity("favorites", dict(name="X", lat=91, lon=2, radius_km=10)) + with sqlite3.connect(store.DB_PATH) as db: + assert db.execute("PRAGMA integrity_check").fetchone()[0] == "ok" diff --git a/ui.js b/ui.js new file mode 100644 index 0000000..7fbea91 --- /dev/null +++ b/ui.js @@ -0,0 +1,101 @@ +'use strict'; +const $=id=>document.getElementById(id); +const esc=x=>String(x??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); +const num=(n,d=0)=>Number.isFinite(n)?n.toLocaleString('fr-FR',{minimumFractionDigits:d,maximumFractionDigits:d}):'—'; +const stamp=s=>s?new Date(s).toLocaleString('fr-FR'):'—'; +let vehicles=[],favorites=[],coords=null,sequence=0; +async function api(path,method='GET',body){ + const controller=new AbortController(), timer=setTimeout(()=>controller.abort(),75000); + try{ + const r=await fetch(path,{method,headers:{'Content-Type':'application/json','X-Fuel-Request':'1'},body:body===undefined?undefined:JSON.stringify(body),signal:controller.signal}); + const data=await r.json(); + if(!r.ok)throw new Error(data.error||data.detail||'Service indisponible'); + return data; + }catch(e){if(e.name==='AbortError')throw new Error('Délai dépassé. Réessayez dans quelques instants.');throw e;} + finally{clearTimeout(timer);} +} +function status(message,error=false){$('status').textContent=message;$('status').className=error?'error':'hint';} +function vehicle(){return vehicles.find(v=>String(v.id)===$('vehicle').value);} +function invalidate(){sequence++;$('result').innerHTML='

Prêt pour un nouveau conseil

Vérifiez le lieu et le véhicule, puis cliquez sur « Obtenir mon conseil ».

';} +function locationSet(lat,lon,label){coords={lat,lon};$('location-label').textContent=label||`${lat.toFixed(4)}, ${lon.toFixed(4)}`;invalidate();} +function renderChoices(){ + const v=$('vehicle').value,f=$('favorite').value; + $('vehicle').innerHTML=''+vehicles.map(v=>``).join(''); + $('favorite').innerHTML=''+favorites.map(f=>``).join(''); + $('vehicle').value=vehicles.some(x=>String(x.id)===v)?v:''; + $('favorite').value=favorites.some(x=>String(x.id)===f)?f:''; + vehicleChanged(false); +} +function vehicleChanged(clear=true){ + const v=vehicle();$('fuel').disabled=Boolean(v); + if(v)$('fuel').value=v.fuel; + $('vehicle-info').textContent=v?`${v.fuel} · ${num(v.consumption,1)} L/100 km · marge ${num(v.min_range_km)} km · ${v.usage==='regular'?'usage régulier':'usage occasionnel'}`:'Comparaison locale uniquement, sans conseil d’autonomie.'; + if(clear)invalidate(); +} +async function reload(){const [v,f]=await Promise.all([api('/api/vehicles'),api('/api/favorites')]);vehicles=v.items;favorites=f.items;renderChoices();renderLists();} +function renderLists(){ + $('vehicles-list').innerHTML=vehicles.length?vehicles.map(v=>`
${esc(v.name)}

${esc(v.fuel)} · marge ${num(v.min_range_km)} km · ${v.usage==='regular'?'régulier':'occasionnel'}

`).join(''):'

Aucun véhicule enregistré.

'; + $('favorites-list').innerHTML=favorites.length?favorites.map(f=>`
${esc(f.name)}

${num(f.lat,4)}, ${num(f.lon,4)} · rayon ${num(f.radius_km)} km

`).join(''):'

Aucun favori. Enregistrez un lieu pour démarrer son suivi quotidien.

'; +} +function fillForm(form,data){form.reset();for(const [k,v]of Object.entries(data)){if(form.elements.namedItem(k))form.elements.namedItem(k).value=v??'';}form.querySelector('.form-error').textContent='';} +function usageChanged(){const form=$('vehicle-form'),occasional=form.elements.usage.value==='occasional';$('monthly-field').hidden=occasional;form.elements.monthly_km.required=!occasional;form.elements.monthly_km.disabled=occasional;} +async function geocode(){ + const query=$('place').value.trim();if(!query){status('Saisissez une ville ou une adresse.',true);return;} + const ticket=++sequence;status('Recherche du lieu…');$('search').disabled=true; + try{const d=await api('/api/geocode?q='+encodeURIComponent(query));if(ticket!==sequence)return;$('favorite').value='';locationSet(d.lat,d.lon,d.label);status('Lieu trouvé. Vous pouvez l’enregistrer en favori.');} + catch(e){if(ticket===sequence)status(e.message,true);}finally{$('search').disabled=false;} +} +function chart(series){ + if(!series?.length)return '

Aucune observation quotidienne exploitable pour ce lieu et ce carburant.

'; + const values=series.map(p=>p.median),lo=Math.min(...values),hi=Math.max(...values),span=Math.max(.02,hi-lo); + const first=new Date(series[0].day+'T12:00:00').getTime(),last=new Date(series.at(-1).day+'T12:00:00').getTime(); + const pts=series.map(p=>({x:55+(new Date(p.day+'T12:00:00').getTime()-first)/Math.max(86400000,last-first)*510,y:115-(p.median-lo)/span*85,p})); + return `${num(hi,3)} €${num(lo,3)} €${pts.map(p=>`${esc(p.p.day)} : ${num(p.p.median,3)} €/L · ${p.p.count} stations`).join('')}${esc(series[0].day)}${esc(series.at(-1).day)}`; +} +function render(d){ + const s=d.local_stats||{},h=d.history||{}; + const stations=(d.stations||[]).map(s=>`
${esc(s.name)}

${esc(s.city)} · ${num(s.distance_km,1)} km à vol d’oiseau

Déclaré : ${esc(s.updated)}

${num(s.price,3)} €/L
`).join(''); + const reasons=d.reasons.map(r=>`
  • ${esc(r)}
  • `).join(''); + const metrics=d.usable_km!==null?`
    ${num(d.usable_km)} kmavant votre marge
    ${d.days_left===null?'Occasionnel':num(d.days_left,1)+' j'}${d.days_left===null?'pas de moyenne imposée':'usage moyen estimé'}
    ${d.topup_liters===null?'—':num(d.topup_liters,1)+' L'}appoint indicatif
    `:''; + $('result').innerHTML=`
    Quand ravitailler · ${esc(d.fuel)}

    ${esc(d.label)}

    ${metrics}
      ${reasons}
    Calcul explicable · sans IAÉvolution future inconnue
    +
    Où acheter

    Les prix autour de vous

    ${d.price_warning?`

    ${esc(d.price_warning)}

    `:''}${s.count?`
    ${num(s.min,3)}minimum €/L
    ${num(s.median,3)}médiane €/L
    ${num(s.max,3)}maximum €/L

    ${s.count} stations comparées · ${s.best_tie_count} au meilleur prix · ${d.stations.length} affichées. Prix déclarés depuis moins de ${d.price_max_age_days} jours.

    Répartition des prix
    ${s.price_buckets.map(b=>`${num(b.price,3)} € · ${b.count}`).join('')}
    `:''}
    ${stations}

    ${esc(d.distance_note)} Un bon prix local ne signifie pas que c’est le bon moment pour remplir le réservoir.

    +
    Historique local · 30 jours

    Ce que les prix ont réellement fait

    ${esc(h.summary)}

    ${h.confidence==='limited'?'

    Panel réduit : tendance peu représentative du secteur.

    ':''}${chart(h.series)}

    ${h.days||0} jours observés. Graphe à panel constant ; dates manquantes non interpolées dans les calculs. Enregistrez ce lieu en favori pour prolonger son suivi.

    +

    Cours du pétrole

    ${esc(d.market?.summary||'Indisponible')}

    Le pétrole n’est pas utilisé pour prédire un délai de répercussion à la pompe. Il faut d’abord constituer et valider un historique.

    `; + status('Conseil calculé à '+stamp(d.generated_at)); +} +function basePayload(){if(!coords)throw new Error('Choisissez d’abord un lieu.');return {...coords,radius_km:Number($('radius').value),fuel:$('fuel').value};} +async function calculate(extra={}){ + const ticket=++sequence;$('advise').disabled=true;status('Comparaison des prix et calcul…');$('result').innerHTML='
    Vérification des données et de votre marge de sécurité…
    '; + try{const data=await api('/api/advice','POST',{...basePayload(),...extra});if(ticket===sequence)render(data);} + catch(e){if(ticket===sequence){status(e.message,true);$('result').innerHTML='

    '+esc(e.message)+'

    ';}} + finally{$('advise').disabled=false;} +} +async function collectionStatus(){try{const s=await api('/api/status');$('collection-state').textContent=s.latest?`${s.latest.status==='ok'?'Dernière collecte réussie':s.latest.status==='error'?'Échec de collecte — nouvelle tentative automatique':'Collecte en cours'} : ${stamp(s.latest.finished_at||s.latest.started_at)}. ${s.observations} observations conservées.${s.latest.detail?' '+s.latest.detail:''}`:'Pas encore de collecte. Ajoutez un favori puis actualisez.';}catch(e){$('collection-state').textContent=e.message;}} +async function collectNow(){ + $('collect').disabled=true;$('collection-state').textContent='Collecte des stations suivies…'; + try{const out=await api('/api/collect','POST',{});await collectionStatus();if(out.status==='no_favorites')$('collection-state').textContent='Ajoutez un favori pour commencer le suivi.';if(out.status==='busy')$('collection-state').textContent='Une collecte est déjà en cours. Réactualisez dans un instant.';} + catch(e){$('collection-state').textContent='Collecte impossible : '+e.message;} + finally{$('collect').disabled=false;} +} +function bind(){ + document.querySelectorAll('[data-close]').forEach(b=>b.onclick=()=>$(b.dataset.close).close()); + $('vehicle').onchange=()=>vehicleChanged();$('fuel').onchange=invalidate; + $('favorite').onchange=()=>{const f=favorites.find(f=>String(f.id)===$('favorite').value);if(f){$('radius').value=f.radius_km;$('place').value=f.name;locationSet(f.lat,f.lon,f.name);}else{coords=null;$('location-label').textContent='Choisissez un lieu';invalidate();}}; + $('radius').oninput=invalidate;$('place').oninput=()=>{coords=null;$('favorite').value='';$('location-label').textContent='Adresse à rechercher';invalidate();}; + $('place').onkeydown=e=>{if(e.key==='Enter')geocode();};$('search').onclick=geocode; + $('locate').onclick=()=>{if(!navigator.geolocation){status('Géolocalisation indisponible. Recherchez une adresse.',true);return;}const ticket=++sequence;status('Localisation en cours…');navigator.geolocation.getCurrentPosition(p=>{if(ticket!==sequence)return;$('favorite').value='';$('place').value='Ma position';locationSet(p.coords.latitude,p.coords.longitude);status('Position trouvée.');},()=>{if(ticket===sequence)status('Géolocalisation refusée ou HTTP non sécurisé : utilisez une adresse.',true);},{timeout:12000,enableHighAccuracy:true});}; + $('advise').onclick=()=>{try{basePayload();const v=vehicle();if(!v){calculate();return;}const f=$('range-form');f.reset();f.querySelector('.form-error').textContent='';$('trip-fields').hidden=v.usage!=='occasional';$('trip-details').hidden=true;f.elements.trip_date.required=false;f.elements.trip_km.required=false;$('range-vehicle').textContent=`${v.name} · marge minimale ${num(v.min_range_km)} km`;$('range-dialog').showModal();$('remaining-km').focus();}catch(e){status(e.message,true);}}; + $('trip-mode').onchange=()=>{const planned=$('trip-mode').value==='planned';$('trip-details').hidden=!planned;$('range-form').elements.trip_date.required=planned;$('range-form').elements.trip_km.required=planned;}; + $('range-form').onsubmit=e=>{e.preventDefault();const f=e.target,v=vehicle();if(!v)return;const extra={vehicle_id:v.id,remaining_km:Number(f.elements.remaining_km.value)};if(v.usage==='occasional'&&$('trip-mode').value==='planned')extra.trip={date:f.elements.trip_date.value,km:Number(f.elements.trip_km.value)};$('range-dialog').close();f.reset();calculate(extra);}; + $('range-dialog').addEventListener('close',()=>{$('range-form').reset();}); + $('manage-vehicles').onclick=()=>{$('vehicles-dialog').showModal();};$('manage-favorites').onclick=()=>{$('favorites-dialog').showModal();}; + $('new-vehicle').onclick=()=>{fillForm($('vehicle-form'),{id:'',min_range_km:80,monthly_km:1000});$('vehicle-form-title').textContent='Ajouter un véhicule';usageChanged();}; + $('vehicle-form').elements.usage.onchange=usageChanged; + $('save-place').onclick=()=>{if(!coords){status('Recherchez d’abord le lieu à enregistrer.',true);return;}fillForm($('favorite-form'),{id:'',name:'',...coords,radius_km:$('radius').value});$('favorites-dialog').showModal();$('favorite-form').elements.name.focus();}; + $('vehicle-form').onsubmit=async e=>{e.preventDefault();const f=e.target,b=f.querySelector('[type=submit]'),data=Object.fromEntries(new FormData(f));data.monthly_km=data.usage==='occasional'?0:Number(data.monthly_km);const id=data.id;delete data.id;b.disabled=true;try{const v=await api('/api/vehicles'+(id?'/'+id:''),id?'PUT':'POST',data);await reload();$('vehicle').value=v.id;vehicleChanged();$('vehicles-dialog').close();fillForm(f,{id:'',min_range_km:80,monthly_km:1000});usageChanged();status('Véhicule enregistré.');}catch(e){f.querySelector('.form-error').textContent=e.message;}finally{b.disabled=false;}}; + $('favorite-form').onsubmit=async e=>{e.preventDefault();const f=e.target,b=f.querySelector('[type=submit]'),data=Object.fromEntries(new FormData(f)),id=data.id;delete data.id;b.disabled=true;try{const place=await api('/api/favorites'+(id?'/'+id:''),id?'PUT':'POST',data);await reload();$('favorite').value=place.id;$('radius').value=place.radius_km;$('place').value=place.name;locationSet(place.lat,place.lon,place.name);$('favorites-dialog').close();fillForm(f,{id:'',radius_km:15});status('Favori enregistré. Première collecte en cours…');collectNow();}catch(e){f.querySelector('.form-error').textContent=e.message;}finally{b.disabled=false;}}; + document.addEventListener('click',async e=>{const b=e.target.closest('button');if(!b)return;const ev=b.dataset.editVehicle,ef=b.dataset.editFavorite,dv=b.dataset.deleteVehicle,df=b.dataset.deleteFavorite;if(ev){fillForm($('vehicle-form'),vehicles.find(v=>v.id===Number(ev)));$('vehicle-form-title').textContent='Modifier le véhicule';usageChanged();}if(ef)fillForm($('favorite-form'),favorites.find(f=>f.id===Number(ef)));if(dv||df){if(!confirm('Supprimer cet élément ? L’historique public déjà collecté sera conservé.'))return;try{await api('/api/'+(dv?'vehicles/':'favorites/')+(dv||df),'DELETE');await reload();invalidate();}catch(err){status(err.message,true);}}}); + $('collect').onclick=collectNow; +} +async function init(){bind();try{const config=await api('/api/config');const options=config.fuels.map(f=>``).join('');$('fuel').innerHTML=options;$('vehicle-fuel').innerHTML=options;$('fuel').value=config.default_fuel;await reload();await collectionStatus();usageChanged();}catch(e){status('Chargement impossible : '+e.message,true);}} +init();