diff --git a/.env.example b/.env.example index 423f50e..5c8e95f 100644 --- a/.env.example +++ b/.env.example @@ -3,7 +3,21 @@ 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. + +# Prix : flux officiel public. +FUEL_PRICES_URL='https://donnees.roulez-eco.fr/opendata/instantane' + +# Pétrole : fournisseurs essayés dans l'ordre (stooq = CSV public, page = page publique de cotation). +FUEL_MARKET_PROVIDERS=stooq,page +# Mettre les 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' +FUEL_MARKET_PAGE_URL='https://tradingeconomics.com/commodity/brent-crude-oil' +FUEL_MARKET_TTL=3600 + +# Enseignes (OpenStreetMap/Nominatim) : durée de cache par zone. +FUEL_BRAND_TTL=2592000 + +# Certaines sources publiques refusent les agents non navigateur. +FUEL_HTTP_USER_AGENT='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36' + # Ollama n'est plus appelé : les anciennes variables OLLAMA_* sont ignorées. diff --git a/README.md b/README.md index 3d7a612..fa597d9 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ VM actuelle Alpine/OpenRC (pas Docker). Le venv sert uniquement à pytest/Ruff. 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. +3. La liste des stations affiche l'**enseigne** (OpenStreetMap) et signale les stations d'autoroute quand la source l'indique. 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. @@ -29,13 +29,41 @@ Modifier/supprimer véhicules et favoris via les fenêtres correspondantes. Un c 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. +## Enseignes des stations (enseigne commerciale) + +Le flux officiel des prix **ne contient aucune enseigne**. L'app interroge donc OpenStreetMap via Nominatim (recherche `amenity=fuel` bornée à la zone, `extratags=1`) et associe chaque station à l'établissement OSM le plus proche, dans la limite de **120 m**. Enseigne retenue par ordre de priorité : `brand`, puis `operator`, puis le nom OSM. + +- Une seule requête de ce type par lieu, mise en cache **30 jours** (`FUEL_BRAND_TTL`). Un échec n'est pas mis en cache et n'empêche jamais le conseil. +- Aucune enseigne n'est inventée : sans correspondance, l'interface affiche « Enseigne inconnue ». +- La liste Nominatim est limitée à 50 établissements par zone : sur un très grand rayon, une partie des stations peut rester sans enseigne. Réduire le rayon améliore la couverture. +- Les enseignes trouvées sont mémorisées par station (`station_brand`) pour les graphiques par station. +- La correspondance repose sur la proximité géographique : une erreur reste possible si deux stations sont très proches. L'enseigne est une aide au repérage, pas une donnée officielle. + ## 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. +### Courbes affichées + +Deux graphiques sans dépendance externe (SVG généré côté navigateur) : + +- **Moyenne des prix enregistrés** : moyenne, jour par jour, de tous les relevés réellement enregistrés dans la zone (les jours sans relevé n'apparaissent pas). +- **Évolution par station** : une mini-courbe par station suivie (24 au maximum), avec enseigne, dernier prix, variation sur la période, minimum et maximum. Les stations au-delà de la limite restent comptées dans la moyenne. + +Les valeurs ne sont pas interpolées : un jour manquant n'est pas inventé. + +### Cours du pétrole + +Chaîne de fournisseurs, sans clé d'API, configurable avec `FUEL_MARKET_PROVIDERS` (défaut `stooq,page`) : + +1. `stooq` — CSV public quotidien (source d'origine, actuellement en maintenance : HTTP 503). +2. `page` — page publique de cotation Trading Economics, ligne Brent uniquement, lue de façon légère (cache 1 h). Source **non officielle** : à retirer si son usage ne convient pas. + +Le taux de change vient de la **BCE** (API officielle sans clé), ce qui permet d'afficher le baril en euros. Une erreur, un cours N/D, NaN ou vieux de plus de 5 jours donne **« tendance inconnue »**, jamais « stable ». Les cours valides et leur date sont conservés lors des collectes, sans jamais influencer la marge de sécurité. + +**Pas de prévision pétrole → pompe** avant constitution et validation d'un historique suffisant. ## Déploiement et maintenance diff --git a/app.py b/app.py index 3d82b84..75f50a6 100755 --- a/app.py +++ b/app.py @@ -3,7 +3,6 @@ from __future__ import annotations -import csv import io import json import logging @@ -16,12 +15,14 @@ import urllib.parse import urllib.request import zipfile from dataclasses import dataclass -from datetime import date, datetime, timezone +from datetime import datetime, timezone from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from xml.etree import ElementTree as ET +import brands import collector +import market import storage from decision import recommend @@ -37,7 +38,6 @@ USER_AGENT = "CortexFuelAdvisor/0.2 (+internal homelab)" FUEL_TYPES = storage.FUELS DEFAULT_FUEL = os.environ.get("FUEL_DEFAULT_TYPE", "Gazole") FETCH_LOCK = threading.Lock() -MARKET_LOCK = threading.Lock() LOG = logging.getLogger("fuel-advisor") @@ -52,6 +52,8 @@ class Station: price: float updated: str distance_km: float + road: str = "" + brand: str | None = None def now_iso(): @@ -128,6 +130,7 @@ def load_fuel_data(force=False): if prices: rows.append( dict( + road="autoroute" if str(pdv.attrib.get("pop", "")).upper() == "A" else "", id=pdv.attrib.get("id", ""), name=pdv.findtext("adresse", "Station-service"), address=pdv.findtext("adresse", ""), @@ -165,47 +168,15 @@ def nearest_stations(lat, lon, fuel, radius_km): price=row["prices"][fuel], updated=row["updates"].get(fuel, ""), distance_km=round(distance, 1), + road=row.get("road", ""), ) ) return sorted(stations, key=lambda s: (s.price, s.distance_km)) -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] - 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" - 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 market_signal(force=False): + """Délègue au module marché (fournisseurs en chaîne, jamais de fausse stabilité).""" + return market.fetch(force=force) def geocode_address(query): @@ -220,14 +191,19 @@ def geocode_address(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: LOG.warning("Source des prix inaccessible : %s", type(exc).__name__) error = "Source des prix inaccessible ; aucun ancien prix présenté comme actuel." + # Enseignes : enrichissement OpenStreetMap best-effort, sans jamais en inventer. + enriched = brands.enrich(lat, lon, radius_km, [s.__dict__ for s in stations]) + brands_known = [(item["id"], item["brand"]) for item in enriched if item.get("brand")] + if brands_known: + storage.set_brands(brands_known) + hist = storage.history(lat, lon, radius_km, fuel) + result = recommend(vehicle, remaining_km, hist, trip) prices = [s.price for s in stations] stats = {} if prices: @@ -246,12 +222,16 @@ def advice(lat, lon, fuel, radius_km, vehicle=None, remaining_km=None, trip=None fuel=fuel, history=hist, local_stats=stats, - stations=[s.__dict__ for s in stations[:12]], + stations=enriched[:12], market=market_signal(), ai_used=False, + brands_source="OpenStreetMap via Nominatim" if brands_known else None, + brands_warning=None + if brands_known + else "Enseignes indisponibles pour cette zone (source OpenStreetMap muette).", 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.", + summary="Le choix de la station et le moment de ravitaillement 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, ) diff --git a/brands.py b/brands.py new file mode 100644 index 0000000..220ab76 --- /dev/null +++ b/brands.py @@ -0,0 +1,161 @@ +"""Enseignes des stations : enrichissement OpenStreetMap/Nominatim, best-effort. + +Le flux officiel des prix ne contient aucune enseigne. On interroge donc Nominatim +(recherche de catégorie `amenity=fuel` dans la zone, avec `extratags=1`) et on associe +une station à l'établissement OSM le plus proche. Une seule requête par lieu, mise en +cache : aucune enseigne inventée, et l'absence de réponse n'empêche rien. +""" + +from __future__ import annotations + +import json +import math +import os +import sqlite3 +import time +import urllib.parse +import urllib.request +from pathlib import Path + +DB_PATH = Path(os.environ.get("FUEL_ADVISOR_DATA_DIR", "/var/lib/fuel-advisor")) / "fuel.sqlite3" +NOMINATIM = os.environ.get("FUEL_NOMINATIM_URL", "https://nominatim.openstreetmap.org/search") +USER_AGENT = os.environ.get("FUEL_HTTP_USER_AGENT", "CortexFuelAdvisor/0.3 (+internal homelab)") +CACHE_TTL = int(os.environ.get("FUEL_BRAND_TTL", str(30 * 86400))) +MATCH_KM = 0.12 +MAX_BRAND_LENGTH = 40 + + +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( + "CREATE TABLE IF NOT EXISTS brand_cache (key TEXT PRIMARY KEY, payload TEXT NOT NULL, ts INTEGER NOT NULL)" + ) + return db + + +def key_for(lat, lon, radius_km): + return f"{round(float(lat), 2)}:{round(float(lon), 2)}:{round(float(radius_km), 1)}" + + +def cache_get(key, ttl=CACHE_TTL): + try: + with connect() as db: + row = db.execute("SELECT payload,ts FROM brand_cache WHERE key=?", (key,)).fetchone() + except sqlite3.Error: + return None + if not row or time.time() - row["ts"] > ttl: + return None + try: + return json.loads(row["payload"]) + except ValueError: + return None + + +def cache_set(key, payload): + try: + with connect() as db: + db.execute( + "REPLACE INTO brand_cache VALUES(?,?,?)", + (key, json.dumps(payload, ensure_ascii=False), int(time.time())), + ) + except sqlite3.Error: + pass + + +def label_from_tags(tags): + for field in ("brand", "operator", "name"): + value = str(tags.get(field) or "").strip() + if value: + return value[:MAX_BRAND_LENGTH] + return None + + +def parse_results(rows): + out = [] + for row in rows: + try: + lat, lon = float(row["lat"]), float(row["lon"]) + except (KeyError, TypeError, ValueError): + continue + tags = row.get("extratags") or {} + if not isinstance(tags, dict): + tags = {} + label = label_from_tags(tags) or label_from_tags({"name": row.get("name")}) + if label: + out.append({"lat": lat, "lon": lon, "name": row.get("name") or label, "brand": label}) + return out + + +def fetch_candidates(lat, lon, radius_km): + """Une requête Nominatim bornée ; lève en cas d'échec réseau.""" + span = min(0.35, max(0.02, float(radius_km) / 111.0)) + params = urllib.parse.urlencode( + { + "amenity": "fuel", + "format": "jsonv2", + "extratags": 1, + "limit": 50, + "viewbox": f"{lon - span},{lat + span},{lon + span},{lat - span}", + "bounded": 1, + "addressdetails": 0, + } + ) + request = urllib.request.Request( + f"{NOMINATIM}?{params}", headers={"User-Agent": USER_AGENT, "Accept-Language": "fr"} + ) + with urllib.request.urlopen(request, timeout=20) as response: + rows = json.loads(response.read(2_000_000).decode("utf-8", "replace")) + if not isinstance(rows, list): + raise ValueError("réponse Nominatim inattendue") + return parse_results(rows) + + +def candidates(lat, lon, radius_km, source=None): + """Résultats OSM pour la zone, mis en cache. Un échec n'est pas mis en cache.""" + key = key_for(lat, lon, radius_km) + cached = cache_get(key) + if isinstance(cached, list): + return cached + try: + rows = (source or fetch_candidates)(lat, lon, radius_km) + except Exception: + return [] + if rows: + cache_set(key, rows) + return rows + + +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 match(station, candidates_rows, max_km=MATCH_KM): + best, best_distance = None, max_km + for row in candidates_rows or []: + try: + away = distance_km(row["lat"], row["lon"], station["lat"], station["lon"]) + except (KeyError, TypeError): + continue + if away <= best_distance: + best, best_distance = row.get("brand"), away + return best + + +def attach(stations, candidates_rows, max_km=MATCH_KM): + """Ajoute ``brand`` (ou None) à chaque station, sans jamais en inventer.""" + out = [] + for station in stations: + item = dict(station) + item["brand"] = match(station, candidates_rows, max_km) + out.append(item) + return out + + +def enrich(lat, lon, radius_km, stations): + """Raccourci : récupère les enseignes de la zone puis les associe aux stations.""" + return attach(stations, candidates(lat, lon, radius_km)) diff --git a/index.html b/index.html index c600e56..1780eb4 100644 --- a/index.html +++ b/index.html @@ -17,7 +17,7 @@
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
- +

Mes véhicules

Ajouter un véhicule

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

diff --git a/market.py b/market.py new file mode 100644 index 0000000..4b54f77 --- /dev/null +++ b/market.py @@ -0,0 +1,232 @@ +"""Cours du pétrole : fournisseurs en chaîne, conversion BCE, jamais de fausse stabilité. + +Deux fournisseurs sans clé d'API sont disponibles : +- ``stooq`` : CSV public (source historique, actuellement en maintenance côté Stooq) ; +- ``page`` : page publique Trading Economics, lue de façon légère (une requête par heure). + +Aucun n'est officiel ni garanti : en cas d'échec, la tendance doit rester ``unknown``. +Le taux de change vient de la BCE (données officielles, sans clé). +""" + +from __future__ import annotations + +import csv +import io +import json +import math +import os +import re +import sqlite3 +import time +import urllib.parse +import urllib.request +from datetime import date, datetime, timedelta, timezone +from pathlib import Path + +DB_PATH = Path(os.environ.get("FUEL_ADVISOR_DATA_DIR", "/var/lib/fuel-advisor")) / "fuel.sqlite3" +STOOQ_URL = os.environ.get("FUEL_MARKET_URL", "https://stooq.com/q/l/?s=cl.f&f=sd2t2ohlcv&h&e=csv") +PAGE_URL = os.environ.get("FUEL_MARKET_PAGE_URL", "https://tradingeconomics.com/commodity/brent-crude-oil") +ECB_URL = ( + "https://data-api.ecb.europa.eu/service/data/EXR/D.USD.EUR.SP00.A?format=csvdata&lastNObservations=6" +) +CACHE_TTL = int(os.environ.get("FUEL_MARKET_TTL", "3600")) +MAX_QUOTE_AGE_DAYS = 5 +USER_AGENT = os.environ.get( + "FUEL_HTTP_USER_AGENT", + "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36", +) +LABELS = {"stooq": "Stooq (CSV public)", "page": "Trading Economics (page publique)"} + + +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( + "CREATE TABLE IF NOT EXISTS market_cache (key TEXT PRIMARY KEY, payload TEXT NOT NULL, ts INTEGER NOT NULL)" + ) + return db + + +def cache_get(key, ttl): + with connect() as db: + row = db.execute("SELECT payload,ts FROM market_cache WHERE key=?", (key,)).fetchone() + if not row or time.time() - row["ts"] > ttl: + return None + try: + return json.loads(row["payload"]) + except ValueError: + return None + + +def cache_set(key, payload): + with connect() as db: + db.execute( + "REPLACE INTO market_cache VALUES(?,?,?)", + (key, json.dumps(payload, ensure_ascii=False), int(time.time())), + ) + + +def fetch_bytes(url, timeout=20, limit=4_000_000): + request = urllib.request.Request( + url, headers={"User-Agent": USER_AGENT, "Accept-Language": "fr-FR,fr;q=0.9"} + ) + with urllib.request.urlopen(request, timeout=timeout) as response: + return response.read(limit) + + +def _signed(value, name): + try: + out = float(str(value).replace(",", ".").strip()) + except (TypeError, ValueError): + raise ValueError(f"{name} illisible") from None + if not math.isfinite(out): + raise ValueError(f"{name} invalide") + return out + + +def _number(value, name): + try: + out = float(str(value).replace(",", ".").strip()) + except (TypeError, ValueError): + raise ValueError(f"{name} illisible") from None + if not math.isfinite(out) or out <= 0: + raise ValueError(f"{name} invalide") + return out + + +def parse_stooq(text, today=None): + """CSV Stooq : Symbol,Date,Open,Close (ignore les lignes N/D).""" + today = today or datetime.now(timezone.utc).date() + rows = list(csv.DictReader(io.StringIO(text))) + if not rows: + raise ValueError("flux vide") + row = rows[-1] + quote_day = date.fromisoformat(str(row.get("Date", "")).strip()) + if not 0 <= (today - quote_day).days <= MAX_QUOTE_AGE_DAYS: + raise ValueError("cours périmé ou daté dans le futur") + close = _number(row.get("Close"), "cours") + opening = _number(row.get("Open"), "ouverture") + return {"price_usd": close, "date": quote_day, "change_pct": (close - opening) / opening * 100} + + +def parse_page(html, today=None): + """Page publique de cotation : ligne Brent identifiée par son symbole CO1:COM.""" + today = today or datetime.now(timezone.utc).date() + for chunk in re.findall(r"]*>.*?", html, re.S): + if "CO1:COM" not in chunk or not re.search(r"brent", chunk, re.I): + continue + price = re.search(r'id="p"[^>]*>\s*([0-9][0-9.,]*)', chunk) + if not price: + continue + change = re.search(r'id="pch"[^>]*>\s*([+\-]?[0-9][0-9.,]*)%', chunk) + quote_day = today + stamp = re.search(r'id="date"[^>]*>\s*([A-Za-z]{3})/([0-9]{1,2})', chunk) + if stamp: + months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"] + try: + month = months.index(stamp.group(1).lower()) + 1 + quote_day = date(today.year, month, int(stamp.group(2))) + if quote_day > today + timedelta(days=1): + quote_day = date(today.year - 1, month, int(stamp.group(2))) + except ValueError: + quote_day = today + if not 0 <= (today - quote_day).days <= MAX_QUOTE_AGE_DAYS: + raise ValueError("cours périmé") + return { + "price_usd": _number(price.group(1), "cours"), + "date": quote_day, + "change_pct": _signed(change.group(1).replace("%", ""), "variation") if change else 0.0, + } + raise ValueError("ligne Brent absente") + + +def provider_stooq(): + return parse_stooq(fetch_bytes(STOOQ_URL, 8).decode("utf-8", "replace")) + + +def provider_page(): + return parse_page(fetch_bytes(PAGE_URL, 12).decode("utf-8", "replace")) + + +PROVIDERS = {"stooq": provider_stooq, "page": provider_page} + + +def ecb_usd_per_eur(): + """Taux USD par euro publié par la BCE (cache 24 h). Retourne None si indisponible.""" + cached = cache_get("fx", 86400) + if cached is not None: + return cached or None + try: + text = fetch_bytes(ECB_URL, 15).decode("utf-8", "replace") + rows = [line for line in text.splitlines() if line and not line.startswith(("KEY,", '"KEY'))] + rate = _number(rows[-1].split(",")[7], "taux de change") + cache_set("fx", rate) + return rate + except Exception: + cache_set("fx", 0) + return None + + +def trend_from_pct(pct): + if pct is None or not isinstance(pct, (int, float)) or not math.isfinite(pct): + return "unknown" + return "up" if pct > 0.7 else "down" if pct < -0.7 else "flat" + + +def fetch(providers=None, force=False): + """Interroge les fournisseurs dans l'ordre et renvoie toujours un dictionnaire exploitable.""" + if not force: + cached = cache_get("market", CACHE_TTL) + if cached is not None: + return cached + names = providers or [ + n.strip() for n in os.environ.get("FUEL_MARKET_PROVIDERS", "stooq,page").split(",") if n.strip() + ] + out = { + "summary": "Pétrole indisponible — tendance inconnue", + "trend": "unknown", + "delta_pct": None, + "price_usd": None, + "price_eur": None, + "date": None, + "source": None, + "stale": False, + "reference": "Brent en USD, converti en euros avec le taux BCE quand il est disponible.", + } + errors = [] + for name in names: + provider = PROVIDERS.get(name) + if provider is None: + continue + try: + quote = provider() + except Exception as exc: + errors.append(f"{name} : {type(exc).__name__}") + continue + age = (datetime.now(timezone.utc).date() - quote["date"]).days + stale = not 0 <= age <= MAX_QUOTE_AGE_DAYS + out.update( + price_usd=round(quote["price_usd"], 2), + date=quote["date"].isoformat(), + delta_pct=round(quote["change_pct"], 2), + source=LABELS.get(name, name), + stale=stale, + trend="unknown" if stale else trend_from_pct(quote["change_pct"]), + ) + rate = ecb_usd_per_eur() + if rate: + out["price_eur"] = round(quote["price_usd"] / rate, 2) + parts = [f"Brent {out['price_usd']:.2f} USD/baril"] + if out["price_eur"]: + parts.append(f"{out['price_eur']:.2f} €/baril") + if out["delta_pct"] is not None: + parts.append(f"{out['delta_pct']:+.2f} % sur la dernière séance cotée") + parts.append(f"({out['date']}, {out['source']})") + out["summary"] = " ; ".join(parts) + ". Indicateur de contexte, pas une prévision du prix à la pompe." + break + else: + if errors: + out["summary"] = "Pétrole indisponible — tendance inconnue (" + ", ".join(errors) + ")." + cache_set("market", out) + return out diff --git a/storage.py b/storage.py index 32d214c..068e995 100644 --- a/storage.py +++ b/storage.py @@ -52,9 +52,71 @@ def record_observations(rows, now=None): lat=excluded.lat,lon=excluded.lon""", list(values.values()), ) + # Noms/communes/type de voie conservés une fois par station (affichage des graphiques). + seen = { + str(row["id"]): ( + str(row["id"]), + str(row.get("name") or "")[:120], + str(row.get("city") or "")[:80], + str(row.get("road") or "")[:20], + row["lat"], + row["lon"], + now.isoformat(), + ) + for row in rows + if row.get("id") + } + if seen: + db.executemany( + """INSERT INTO stations VALUES(?,?,?,?,?,?,?) + ON CONFLICT(id) DO UPDATE SET name=excluded.name,city=excluded.city, + road=excluded.road,lat=excluded.lat,lon=excluded.lon,seen_at=excluded.seen_at""", + list(seen.values()), + ) return len(values) +def set_brands(pairs, now=None): + """Mémorise les enseignes trouvées (station_id -> enseigne) sans écraser par du vide.""" + now = now or datetime.now(timezone.utc) + rows = [ + (str(station_id), str(brand)[:40], now.isoformat()) + for station_id, brand in pairs + if station_id and brand + ] + if not rows: + return 0 + with connect() as db: + db.executemany( + """INSERT INTO station_brand VALUES(?,?,?) + ON CONFLICT(station_id) DO UPDATE SET brand=excluded.brand,fetched_at=excluded.fetched_at""", + rows, + ) + return len(rows) + + +def station_meta(station_ids): + """Nom, commune, type de voie et enseigne connus pour ces stations.""" + ids = [str(s) for s in station_ids if s] + if not ids: + return {} + marks = ",".join("?" * len(ids)) + with connect() as db: + rows = db.execute(f"SELECT id, name, city, road FROM stations WHERE id IN ({marks})", ids).fetchall() + brands = db.execute( + f"SELECT station_id, brand FROM station_brand WHERE station_id IN ({marks})", ids + ).fetchall() + out = { + station_id: dict(name="", city="", road="", brand=None) + for station_id in {row["id"] for row in rows} | {row["station_id"] for row in brands} + } + for row in rows: + out[row["id"]].update(name=row["name"], city=row["city"], road=row["road"]) + for row in brands: + out[row["station_id"]]["brand"] = row["brand"] + return out + + def history(lat, lon, radius, fuel, now=None): now = now or datetime.now(timezone.utc) today = now.astimezone(PARIS).date() @@ -79,10 +141,37 @@ def history(lat, lon, radius, fuel, now=None): matched_stations=0, days=len(days), series=[], + average_series=[], + stations_series=[], summary="Historique insuffisant : au moins 7 jours observés couvrant une semaine sont nécessaires.", ) if not days: return out + # Moyenne brute des prix réellement enregistrés chaque jour (toutes stations confondues). + out["average_series"] = [ + dict(day=day, average=round(statistics.mean(values.values()), 3), count=len(values)) + for day, values in sorted(days.items()) + ] + # Série par station : uniquement les jours où cette station a réellement été observée. + per_station = {} + for day, values in sorted(days.items()): + for station_id, price in values.items(): + per_station.setdefault(station_id, []).append(dict(day=day, price=round(price, 3))) + meta = station_meta(per_station.keys()) + out["stations_series"] = [ + dict( + station_id=station_id, + name=(meta.get(station_id, {}).get("name") or f"Station {station_id}"), + city=meta.get(station_id, {}).get("city") or "", + road=meta.get(station_id, {}).get("road") or "", + brand=meta.get(station_id, {}).get("brand"), + series=points, + lowest=min(p["price"] for p in points), + highest=max(p["price"] for p in points), + delta=round(points[-1]["price"] - points[0]["price"], 3), + ) + for station_id, points in sorted(per_station.items(), key=lambda item: item[1][-1]["price"]) + ] # Graphe sur panel constant : aucun effet dû à l'apparition d'une station. common = set.intersection(*(set(values) for values in days.values())) if common: @@ -144,7 +233,13 @@ def connect(): detail TEXT NOT NULL DEFAULT ''); CREATE TABLE IF NOT EXISTS market_daily ( day TEXT PRIMARY KEY, payload TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS stations ( + id TEXT PRIMARY KEY, name TEXT NOT NULL DEFAULT '', city TEXT NOT NULL DEFAULT '', + road TEXT NOT NULL DEFAULT '', lat REAL, lon REAL, seen_at TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS station_brand ( + station_id TEXT PRIMARY KEY, brand TEXT, fetched_at TEXT NOT NULL); CREATE INDEX IF NOT EXISTS observations_day ON observations(day); + CREATE INDEX IF NOT EXISTS observations_station ON observations(station_id); """) yield db finally: diff --git a/style.css b/style.css index 6ef372c..f044d58 100644 --- a/style.css +++ b/style.css @@ -1 +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}} +: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}.badge{display:inline-block;margin:0 6px 6px 0}.badge.brand{background:#1d4a44;color:#a7f3e3;font-weight:700}.station-cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:12px;margin:14px 0}.station-card{background:#0d192a;border:1px solid #25364b;border-radius:12px;padding:12px}.station-head{display:flex;justify-content:space-between;align-items:baseline;gap:8px}.station-head strong{font-size:14px;overflow-wrap:anywhere}.station-head span{font-size:17px;font-weight:750;color:var(--accent);white-space:nowrap}.station-head small{font-size:10px;color:var(--muted)}.station-card p{margin:4px 0}.mini{width:100%;height:52px;display:block;margin:8px 0}.mini polyline{stroke:var(--accent);stroke-width:2;fill:none;vector-effect:non-scaling-stroke}.mini circle{fill:var(--accent)}.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 index 325c03b..015437e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,9 +1,23 @@ +"""Fixtures partagées : aucune base de production, aucun accès réseau.""" + import pytest +import brands +import market import storage +@pytest.fixture(autouse=True) +def isolated_database(tmp_path, monkeypatch): + """Toutes les bases pointent vers un fichier temporaire, jamais /var/lib.""" + for module in (storage, brands, market): + monkeypatch.setattr(module, "DB_PATH", tmp_path / f"{module.__name__}.sqlite3") + # Aucun test ne doit interroger Nominatim ou un fournisseur de cours. + monkeypatch.setattr(brands, "fetch_candidates", lambda *args, **kwargs: []) + monkeypatch.setattr(market, "PROVIDERS", {}) + return tmp_path + + @pytest.fixture -def store(tmp_path, monkeypatch): - monkeypatch.setattr(storage, "DB_PATH", tmp_path / "test.sqlite3") +def store(): return storage diff --git a/tests/test_brands.py b/tests/test_brands.py new file mode 100644 index 0000000..e2ea9e1 --- /dev/null +++ b/tests/test_brands.py @@ -0,0 +1,61 @@ +import importlib + +import pytest + + +@pytest.fixture +def brands(monkeypatch, tmp_path): + assert importlib.util.find_spec("brands"), "Module enseignes absent" + module = importlib.import_module("brands") + monkeypatch.setattr(module, "DB_PATH", tmp_path / "brands.sqlite3") + return module + + +CANDIDATES = [ + {"lat": 47.2186, "lon": -1.5541, "name": "Total", "brand": "TotalEnergies"}, + {"lat": 47.2400, "lon": -1.6100, "name": "Carrefour", "brand": None, "operator": "Carrefour"}, +] + + +def test_normalise_prefers_brand_then_operator_then_name(brands): + assert brands.label_from_tags({"brand": "Esso", "operator": "X", "name": "Y"}) == "Esso" + assert brands.label_from_tags({"operator": "E.Leclerc", "name": "Y"}) == "E.Leclerc" + assert brands.label_from_tags({"name": "Station du port"}) == "Station du port" + assert brands.label_from_tags({}) is None + assert brands.label_from_tags({"brand": " ", "operator": "BP"}) == "BP" + + +def test_match_requires_proximity(brands): + near = {"lat": 47.21865, "lon": -1.55415} + far = {"lat": 47.2300, "lon": -1.5700} + assert brands.match(near, CANDIDATES) == "TotalEnergies" + assert brands.match(far, CANDIDATES) is None + assert brands.match(near, []) is None + + +def test_attach_adds_label_and_keeps_stations_without_match(brands): + stations = [{"lat": 47.21865, "lon": -1.55415, "name": "A"}, {"lat": 49.0, "lon": 2.0, "name": "B"}] + out = brands.attach(stations, CANDIDATES) + assert out[0]["brand"] == "TotalEnergies" + assert out[1]["brand"] is None + + +def test_cache_roundtrip_and_source_failure_is_not_fatal(brands, monkeypatch): + calls = [] + + def source(lat, lon, radius): + calls.append((lat, lon, radius)) + return CANDIDATES + + first = brands.candidates(47.2186, -1.5541, 15, source=source) + second = brands.candidates(47.2186, -1.5541, 15, source=source) + assert first == second == CANDIDATES + assert len(calls) == 1, "le cache doit éviter un second appel" + + def broken(lat, lon, radius): + raise OSError("nominatim indisponible") + + assert brands.candidates(48.0, 2.0, 10, source=broken) == [] + assert brands.attach([{"lat": 48.0, "lon": 2.0, "name": "C"}], []) == [ + {"lat": 48.0, "lon": 2.0, "name": "C", "brand": None} + ] diff --git a/tests/test_history.py b/tests/test_history.py index f150c4d..b4b54d6 100644 --- a/tests/test_history.py +++ b/tests/test_history.py @@ -45,3 +45,23 @@ def test_old_reports_do_not_become_new_evidence(store): 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" + + +def test_history_exposes_daily_average_and_per_station_series(store): + today = datetime.now(timezone.utc) + for age in range(4): + day = today - timedelta(days=age) + store.record_observations( + [sample(day, 1.80 + age * 0.10, "A"), sample(day, 2.00 + age * 0.10, "B")], day + ) + out = store.history(48.8, 2.3, 10, "Gazole", today) + assert len(out["average_series"]) == 4 + assert out["average_series"][-1]["average"] == pytest.approx(1.90) + assert len(out["stations_series"]) == 2 + first = out["stations_series"][0] + assert first["station_id"] == "A" + assert len(first["series"]) == 4 + assert first["delta"] == pytest.approx(-0.30) + assert first["lowest"] == pytest.approx(1.80) + # Les mêmes chiffres doivent rester disponibles quand la tendance est incalculable. + assert out["trend"] == "unknown" diff --git a/tests/test_http.py b/tests/test_http.py index 96eead3..5950658 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1,7 +1,8 @@ import http.client +import importlib import json import threading -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone import pytest from test_app import fuel_app as app @@ -65,28 +66,60 @@ def test_http_advice_requires_fresh_range(server, store, monkeypatch): 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_failure_is_unknown(monkeypatch): + market = importlib.import_module("market") + monkeypatch.setattr(market, "PROVIDERS", {"stooq": lambda: (_ for _ in ()).throw(OSError("maintenance"))}) + monkeypatch.setattr(market, "ecb_usd_per_eur", lambda: None) + out = app.market_signal(force=True) + assert out["trend"] == "unknown" + assert "indisponible" in out["summary"].lower() -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) +def test_market_rejects_nd_nan_and_old_quotes(monkeypatch, tmp_path): + market = importlib.import_module("market") + monkeypatch.setattr(market, "DB_PATH", tmp_path / "market.sqlite3") 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", + f"Symbol,Date,Open,Close\nCL.F,{datetime.now(timezone.utc).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" + monkeypatch.setattr(market, "fetch_bytes", lambda *args, text=text: text.encode()) + with pytest.raises(ValueError): + market.parse_stooq(text, today=datetime.now(timezone.utc).date()) + monkeypatch.setattr(market, "PROVIDERS", {"stooq": lambda text=text: market.parse_stooq(text)}) + monkeypatch.setattr(market, "ecb_usd_per_eur", lambda: None) + assert app.market_signal(force=True)["trend"] == "unknown" + + +def test_http_advice_includes_brand_when_osm_matches(server, store, monkeypatch): + brands = importlib.import_module("brands") + 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( + brands, + "fetch_candidates", + lambda *args, **kwargs: [{"lat": 48.8, "lon": 2.3, "name": "Total", "brand": "TotalEnergies"}], + ) + code, out = request( + server, "POST", "/api/advice", {"lat": 48.8, "lon": 2.3, "radius_km": 15, "fuel": "Gazole"} + ) + assert code == 200 + assert out["stations"][0]["brand"] == "TotalEnergies" + assert out["brands_source"] + # L'enseigne est mémorisée pour les graphiques par station. + assert store.station_meta([row["id"]])[row["id"]]["brand"] == "TotalEnergies" + + +def test_http_history_exposes_average_and_stations(server, store): + now = datetime.now(timezone.utc) + for age in range(3): + day = now - timedelta(days=age) + store.record_observations([sample(day, 1.80 + age * 0.05, "A")], day) + code, out = request(server, "GET", "/api/history?lat=48.8&lon=2.3&radius_km=15&fuel=Gazole") + assert code == 200 + assert len(out["average_series"]) == 3 + assert out["stations_series"][0]["station_id"] == "A" def test_http_ui_and_validation(server): @@ -94,6 +127,9 @@ def test_http_ui_and_validation(server): assert status == 200 assert "Autonomie restante" in html assert "Mes favoris" in html + code, js = request(server, "GET", "/ui.js") + assert code == 200 + assert "stationCards" in js and "averageChart" in js assert ( request( server, "POST", "/api/favorites", {"name": "X", "lat": float("nan"), "lon": 2, "radius_km": 10} diff --git a/tests/test_market.py b/tests/test_market.py new file mode 100644 index 0000000..6ca36ff --- /dev/null +++ b/tests/test_market.py @@ -0,0 +1,107 @@ +import importlib +from datetime import date, timedelta + +import pytest + + +@pytest.fixture +def market(monkeypatch, tmp_path): + assert importlib.util.find_spec("market"), "Module marché absent" + module = importlib.import_module("market") + monkeypatch.setattr(module, "DB_PATH", tmp_path / "market.sqlite3") + return module + + +TODAY = date.today() +STOOQ_OK = f"Symbol,Date,Open,Close\nCL.F,{TODAY},80.0,82.4\n" +TE_ROW = ( + ' Brent' + ' 104.61 -3.020' + '-2.81%Sep/11' +) + + +def test_stooq_parsing_accepts_fresh_quote(market): + out = market.parse_stooq(STOOQ_OK) + assert out["price_usd"] == pytest.approx(82.4) + assert out["date"] == date.today() + assert out["change_pct"] == pytest.approx(3.0) + + +def test_stooq_rejects_nd_stale_and_nan(market): + for text in ( + "Symbol,Date,Open,Close\nCL.F,N/D,N/D,N/D\n", + "Symbol,Date,Open,Close\nCL.F,2020-01-01,80,85\n", + "Symbol,Date,Open,Close\nCL.F,%s,nan,85\n" % date.today(), + ): + with pytest.raises(ValueError): + market.parse_stooq(text) + + +def test_trading_economics_row_parsing(market): + out = market.parse_page(TE_ROW, today=date(2026, 9, 12)) + assert out["price_usd"] == pytest.approx(104.61) + assert out["change_pct"] == pytest.approx(-2.81) + assert out["date"] == date(2026, 9, 11) + + +def test_trading_economics_page_without_brent_fails(market): + with pytest.raises(ValueError): + market.parse_page('WTI70.0', today=TODAY) + + +def test_trend_thresholds_and_never_flat_on_failure(market): + assert market.trend_from_pct(1.2) == "up" + assert market.trend_from_pct(-1.2) == "down" + assert market.trend_from_pct(0.1) == "flat" + assert market.trend_from_pct(None) == "unknown" + assert market.trend_from_pct(float("nan")) == "unknown" + + +def test_fetch_falls_back_and_reports_unknown_when_all_fail(market, monkeypatch): + monkeypatch.setattr(market, "ecb_usd_per_eur", lambda: None) + calls = [] + + def failing(name): + def run(*args, **kwargs): + calls.append(name) + raise OSError("source indisponible") + + return run + + monkeypatch.setattr(market, "PROVIDERS", {"stooq": failing("stooq"), "page": failing("page")}) + out = market.fetch(providers=["stooq", "page"]) + assert calls == ["stooq", "page"] + assert out["trend"] == "unknown" + assert out["price_usd"] is None + assert "indisponible" in out["summary"].lower() + + +def test_fetch_uses_first_working_provider_and_converts_to_euro(market, monkeypatch): + monkeypatch.setattr(market, "ecb_usd_per_eur", lambda: 1.1) + + def boom(): + raise OSError("down") + + def good(): + return {"price_usd": 88.0, "date": TODAY, "change_pct": -1.5} + + monkeypatch.setattr(market, "PROVIDERS", {"stooq": boom, "page": good}) + out = market.fetch(providers=["stooq", "page"]) + assert out["trend"] == "down" + assert out["price_usd"] == pytest.approx(88.0) + assert out["price_eur"] == pytest.approx(80.0) + assert out["date"] == TODAY.isoformat() + assert out["stale"] is False + + +def test_fetch_marks_stale_quote_as_unknown(market, monkeypatch): + monkeypatch.setattr(market, "ecb_usd_per_eur", lambda: None) + monkeypatch.setattr( + market, + "PROVIDERS", + {"stooq": lambda: {"price_usd": 70.0, "date": TODAY - timedelta(days=20), "change_pct": -5.0}}, + ) + out = market.fetch(providers=["stooq"]) + assert out["trend"] == "unknown" + assert out["stale"] is True diff --git a/ui.js b/ui.js index 7fbea91..c5f0d29 100644 --- a/ui.js +++ b/ui.js @@ -45,22 +45,41 @@ async function geocode(){ 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); +function sparkline(points,width=150,height=42){ + const values=points.map(p=>p.price),lo=Math.min(...values),hi=Math.max(...values),span=Math.max(.02,hi-lo); + const first=new Date(points[0].day+'T12:00:00').getTime(),last=new Date(points.at(-1).day+'T12:00:00').getTime(); + const step=Math.max(86400000,last-first); + const pts=points.map(p=>({x:2+(new Date(p.day+'T12:00:00').getTime()-first)/step*(width-4),y:height-4-(p.price-lo)/span*(height-12),p})); + return `${pts.length===1?``:''}${esc(points[0].day)} → ${esc(points.at(-1).day)} · min ${num(lo,3)} €, max ${num(hi,3)} €`; +} +function averageChart(series,label='Moyenne des prix enregistrés'){ + if(!series?.length)return '

Aucune observation quotidienne enregistrée pour ce lieu et ce carburant. L’historique se construit à partir du suivi quotidien.

'; + const values=series.map(p=>p.average),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)}`; + const step=Math.max(86400000,last-first); + const pts=series.map(p=>({x:55+(new Date(p.day+'T12:00:00').getTime()-first)/step*510,y:115-(p.average-lo)/span*85,p})); + return `${num(hi,3)} €${num(lo,3)} €${pts.map(p=>`${esc(p.p.day)} : ${num(p.p.average,3)} €/L · ${p.p.count} stations observées`).join('')}${esc(series[0].day)}${esc(series.at(-1).day)}`; +} +function stationCards(rows){ + if(!rows?.length)return ''; + const shown=rows.slice(0,24); + const cards=shown.map(s=>{ + const tone=s.delta>0.005?'tone-refuel':s.delta<-0.005?'tone-wait':'muted'; + const trend=s.delta>0.005?`+${num(s.delta,3)} €`:`${num(s.delta,3)} €`; + return `
${esc(s.brand||s.name)}${num(s.series.at(-1).price,3)} €/L

${esc(s.city||'')}${s.road?` · ${esc(s.road)}`:''} · ${s.series.length} relevé${s.series.length>1?'s':''}

${sparkline(s.series)}

${esc(s.series[0].day)} → ${esc(s.series.at(-1).day)} · ${trend} · min ${num(s.lowest,3)} € · max ${num(s.highest,3)} €

`; + }).join(''); + const rest=rows.length-shown.length; + return `
${cards}
${rest>0?`

${rest} autres stations suivies ne sont pas tracées ici (maximum 24 courbes) ; elles restent comptées dans la moyenne.

`:''}`; } 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 stations=(d.stations||[]).map(s=>`
${s.brand?`${esc(s.brand)}`:'Enseigne inconnue'}${s.road?`${esc(s.road)}`:''}${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}
    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.

    `; +
    Où acheter

    Les prix autour de vous

    ${d.price_warning?`

    ${esc(d.price_warning)}

    `:''}${d.brands_warning?`

    ${esc(d.brands_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.

    ':''}

    Moyenne des prix enregistrés

    ${averageChart(h.average_series)}

    Évolution par station

    ${stationCards(h.stations_series)}

    ${h.days||0} jours observés. Moyenne calculée sur les relevés réellement enregistrés ce jour-là ; les stations apparaissent à partir de leur premier relevé. Dates manquantes non interpolées, aucune prévision. Enregistrez ce lieu en favori pour prolonger son suivi.

    +

    Cours du pétrole

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

    ${d.market?.reference?esc(d.market.reference):''} 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 local.

    `; 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};}