Fuel Advisor: stations reelles avec Waze/Google Maps, liste depliable, enseignes sans monogramme, contexte marche et Brent quotidien FRED

57 stations renvoyees au lieu de 12; cout reel par option (carburant + detour marginal) et ecart en euros; bouton Afficher les N autres stations alimente par un compte serveur teste (0/1-2/3/>3); pictogramme neutre + nom complet, aucun logo de marque tierce; Brent DCOILBRENTEU (EIA via FRED) quotidien avec date d observation reelle; sections techniques repliees.
This commit is contained in:
root
2026-09-13 12:50:49 +02:00
parent 755d28dc4c
commit 8f5b47e9dc
11 changed files with 682 additions and 50 deletions

109
app.py
View File

@@ -21,6 +21,7 @@ from pathlib import Path
from xml.etree import ElementTree as ET
import brands
import brent
import collector
import enseignes
import forecast
@@ -100,6 +101,90 @@ def detour_context(stations, vehicle, price_now):
)
# Nombre de stations montrées d'emblée ; le reste est derrière « Afficher les N autres ».
VISIBLE_STATIONS = 3
def station_display(total, visible=VISIBLE_STATIONS):
"""Découpe de la liste : ce qui est visible d'emblée et ce qui reste replié.
Le nombre annoncé par le bouton est calculé ici, donc réel : jamais un bouton relié à une
liste vide. Cas couverts : aucune station, une ou deux, exactement trois, plus de trois.
"""
total = max(0, int(total or 0))
visible = max(0, min(int(visible), total))
return dict(total=total, visible=visible, hidden=total - visible)
def station_options(stations, vehicle, litres):
"""Coût réel de chaque station : carburant acheté + carburant brûlé pour le détour.
Le détour est **marginal** : kilomètres en plus par rapport à la station la plus proche du
domicile, valorisés au prix de la station concernée. On ne compare donc pas des prix affichés
mais des coûts totaux, ce qui rend visible qu'un prix plus bas à 10 km peut coûter plus cher.
"""
distances = [s.route_distance_km for s in stations if s.route_distance_km]
if not distances:
return {}
nearest_km = min(distances)
consumption = (vehicle or {}).get("consumption")
litres = float(litres or 0)
options = {}
for station in stations:
km = station.route_distance_km
extra = max(0.0, round(km - nearest_km, 1)) if km else 0.0
fuel_cost = round(litres * station.price, 2) if litres else None
detour_cost = (
round(extra * consumption / 100 * station.price, 2)
if consumption and extra
else 0.0
)
options[station.id] = dict(
extra_km=extra,
nearest_km=round(nearest_km, 1),
litres=round(litres, 1) if litres else None,
fuel_cost_eur=fuel_cost,
detour_cost_eur=detour_cost,
total_cost_eur=(
round(fuel_cost + detour_cost, 2) if fuel_cost is not None else None
),
)
comparable = [
(option["total_cost_eur"], identifier)
for identifier, option in options.items()
if option["total_cost_eur"] is not None
]
if comparable:
best_total = min(comparable)[0]
for option in options.values():
option["delta_eur"] = (
round(option["total_cost_eur"] - best_total, 2)
if option["total_cost_eur"] is not None
else None
)
option["best"] = option.get("delta_eur") == 0
return options
def brand_component(station):
"""Enseigne affichable : nom complet, slug, et logo **seulement** s'il est autorisé.
Un logo commercial n'est utilisé que si la marque publie des conditions autorisant
explicitement cet usage. En l'absence d'autorisation claire, on renvoie un composant neutre :
l'interface affiche le pictogramme Fuel Advisor et le nom complet de l'enseigne.
"""
name = station.get("brand") or None
slug = station.get("brand_slug") or enseignes.brand_slug(name)
asset = enseignes.LOGO_ASSETS.get(slug)
return dict(
name=name,
slug=slug,
logo_asset=asset["asset"] if asset else None,
logo_source=asset["source"] if asset else None,
logo_usage_status=asset["usage"] if asset else "neutre",
)
def navigation_links(lat, lon):
"""Liens officiels d'itinéraire vers une coordonnée exacte de station."""
coords = f"{lat:.6f},{lon:.6f}"
@@ -470,13 +555,35 @@ def advice(lat, lon, fuel, radius_km, vehicle=None, remaining_km=None, trip=None
best_tie_count=prices.count(prices[0]),
price_buckets=[dict(price=p, count=prices.count(p)) for p in sorted(set(prices))],
)
# Coût réel de chaque station : la quantité conseillée sert de base commune aux options.
litres = stock.get("litres_high") or stock.get("litres") or None
if not litres and vehicle:
try:
litres = quantity.max_addable_liters(vehicle, remaining_km)
except Exception:
LOG.warning("Quantité de comparaison indisponible")
litres = None
options = station_options(stations, vehicle, litres)
for station in enriched:
station["economics"] = options.get(station["id"])
station["brand_info"] = brand_component(station)
result.update(
generated_at=now_iso(),
fuel=fuel,
trend=observed_trend((hist or {}).get("average_series")),
history=hist,
local_stats=stats,
stations=enriched[:12],
# Toutes les stations du rayon sont renvoyées : l'affichage décide de ce qu'il montre.
stations=enriched,
stations_total=len(enriched),
stations_display=station_display(len(enriched)),
station_options_note=(
"Coût total = carburant acheté au prix affiché + carburant brûlé pour le détour "
"marginal par rapport à la station la plus proche. Détour non chiffré sans routage."
if options
else "Coût réel par option indisponible sans distance routière."
),
brent=brent.context(),
market=market_signal(),
ai_used=False,
brands_source=(

View File

@@ -1,23 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" style="display:none" aria-hidden="true">
<symbol id="brand-totalenergies" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#1d4ed8"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">T</text></symbol>
<symbol id="brand-total-access" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#1d4ed8"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">T</text></symbol>
<symbol id="brand-total" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#1d4ed8"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">T</text></symbol>
<symbol id="brand-intermarche" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#c2410c"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">I</text></symbol>
<symbol id="brand-e-leclerc" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#0f766e"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">L</text></symbol>
<symbol id="brand-carrefour" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#1e40af"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">C</text></symbol>
<symbol id="brand-carrefour-market" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#1e40af"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">C</text></symbol>
<symbol id="brand-auchan" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#b91c1c"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">A</text></symbol>
<symbol id="brand-super-u" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#15803d"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">U</text></symbol>
<symbol id="brand-systeme-u" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#15803d"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">U</text></symbol>
<symbol id="brand-station-u" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#15803d"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">U</text></symbol>
<symbol id="brand-u" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#15803d"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">U</text></symbol>
<symbol id="brand-esso-express" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#7c2d12"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">E</text></symbol>
<symbol id="brand-esso" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#7c2d12"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">E</text></symbol>
<symbol id="brand-avia" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#0369a1"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">A</text></symbol>
<symbol id="brand-shell" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#a16207"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">S</text></symbol>
<symbol id="brand-elan" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#4d7c0f"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">E</text></symbol>
<symbol id="brand-monoprix" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#7e22ce"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">M</text></symbol>
<symbol id="brand-spar" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#166534"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">S</text></symbol>
<symbol id="brand-inconnue" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#475569"/><path d="M12 9h11a3 3 0 0 1 3 3v20H9V12a3 3 0 0 1 3-3z" fill="#ffffff"/><rect x="14" y="13" width="7" height="6" rx="1.5" fill="#475569"/><path d="M26 14h2.6a2 2 0 0 1 2 2v6.5a1.8 1.8 0 0 0 3.6 0V17" fill="none" stroke="#ffffff" stroke-width="2.4" stroke-linecap="round"/><rect x="16" y="30" width="14" height="2.6" rx="1.3" fill="#cbd5e1"/></symbol>
<!-- Pictogramme neutre unique : aucune marque tierce n'est reproduite. -->
<symbol id="enseigne-neutre" viewBox="0 0 40 40">
<rect width="40" height="40" rx="9" fill="#475569"/>
<path d="M12 9h11a3 3 0 0 1 3 3v20H9V12a3 3 0 0 1 3-3z" fill="#ffffff"/>
<rect x="14" y="13" width="7" height="6" rx="1.5" fill="#475569"/>
<path d="M26 14h2.6a2 2 0 0 1 2 2v6.5a1.8 1.8 0 0 0 3.6 0V17" fill="none" stroke="#ffffff" stroke-width="2.4" stroke-linecap="round"/>
<rect x="16" y="30" width="14" height="2.6" rx="1.3" fill="#cbd5e1"/>
</symbol>
</svg>

Before

Width:  |  Height:  |  Size: 5.1 KiB

After

Width:  |  Height:  |  Size: 687 B

174
brent.py Normal file
View File

@@ -0,0 +1,174 @@
"""Brent quotidien — série FRED DCOILBRENTEU (source d'origine EIA).
« Crude Oil Prices: Brent - Europe », U.S. Energy Information Administration, diffusée
quotidiennement par FRED en USD par baril. Contrairement au future BZ=F, il s'agit d'un prix
au comptant : aucun roll de contrat à gérer.
Ce module est **informatif**. Il n'alimente ni le score, ni le conseil, ni la quantité.
Règles tenues ici :
- aucune interpolation, aucun report : une journée sans observation n'existe pas ;
- `observed_at` (jour de l'observation) reste distinct de `available_at` (jour à partir duquel
la donnée est publiable, délai de publication retenu) et de `fetched_at` (notre téléchargement) ;
- une série périmée est annoncée comme périmée, jamais présentée comme le cours du jour.
"""
from __future__ import annotations
import csv
import io
import logging
import urllib.request
from contextlib import contextmanager
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
LOG = logging.getLogger("fuel-advisor.brent")
SOURCE = "EIA via FRED"
SERIES = "DCOILBRENTEU"
URL = f"https://fred.stlouisfed.org/graph/fredgraph.csv?id={SERIES}"
# Délai de publication retenu : une observation n'est utilisable que le lendemain.
PUBLICATION_LAG_DAYS = 1
# Au-delà, on ne parle plus de « Brent du jour » mais de la dernière observation connue.
STALE_AFTER_DAYS = 5
SCHEMA = """
CREATE TABLE IF NOT EXISTS brent_daily (
observed_at TEXT PRIMARY KEY,
usd_per_barrel REAL NOT NULL,
available_at TEXT NOT NULL,
fetched_at TEXT NOT NULL,
source TEXT NOT NULL
)
"""
def _storage():
import storage
return storage
@contextmanager
def _connection(db=None):
"""Connexion fournie par l'appelant, ou ouverte via la couche stockage de l'application."""
if db is not None:
yield db
return
with _storage().connect() as connection:
yield connection
def ensure_schema(db):
db.execute(SCHEMA)
db.commit()
def parse(text):
"""Extrait (jour, valeur) en ignorant les valeurs manquantes de FRED (« . »)."""
rows = []
reader = csv.DictReader(io.StringIO(text))
for line in reader:
day = (line.get("observation_date") or "").strip()
raw = (line.get(SERIES) or line.get("value") or "").strip()
if not day or raw in ("", "."):
continue
try:
value = float(raw)
except ValueError:
continue
if value <= 0: # un baril à zéro ou négatif n'est pas une observation exploitable
continue
rows.append((day, value))
return rows
def refresh(url=URL, db=None, fetched_at=None, text=None):
"""Télécharge la série complète et enregistre les observations absentes.
Les observations déjà connues ne sont jamais réécrites : une donnée révisée par la source
doit être traitée comme une nouvelle publication, pas comme un écrasement silencieux.
"""
with _connection(db) as db:
ensure_schema(db)
if text is None:
request = urllib.request.Request(url, headers={"User-Agent": "fuel-advisor/1.0"})
with urllib.request.urlopen(request, timeout=60) as response:
payload = response.read().decode("utf-8", "replace")
else:
payload = text
rows = parse(payload)
if not rows:
raise ValueError("série Brent vide")
stamp = fetched_at or datetime.now(timezone.utc).isoformat(timespec="seconds")
before = db.execute("SELECT COUNT(*) FROM brent_daily").fetchone()[0]
for day, value in rows:
measured = date.fromisoformat(day)
db.execute(
"INSERT OR IGNORE INTO brent_daily"
" (observed_at, usd_per_barrel, available_at, fetched_at, source)"
" VALUES (?, ?, ?, ?, ?)",
(
day,
value,
(measured + timedelta(days=PUBLICATION_LAG_DAYS)).isoformat(),
stamp,
SOURCE,
),
)
db.commit()
after = db.execute("SELECT COUNT(*) FROM brent_daily").fetchone()[0]
return dict(stored=after - before, total=after, fetched_at=stamp, source=SOURCE)
def latest(db=None, today=None):
"""Dernière observation connue, avec son âge réel et son caractère périmé ou non."""
with _connection(db) as db:
ensure_schema(db)
row = db.execute(
"SELECT observed_at, usd_per_barrel, available_at, fetched_at, source"
" FROM brent_daily ORDER BY observed_at DESC LIMIT 1"
).fetchone()
if not row:
return dict(
available=False,
summary="Brent spot temporairement indisponible",
source=SOURCE,
series=SERIES,
)
observed = date.fromisoformat(row["observed_at"])
reference = today or date.today()
age = (reference - observed).days
return dict(
available=True,
observed_at=row["observed_at"],
available_at=row["available_at"],
fetched_at=row["fetched_at"],
usd_per_barrel=round(float(row["usd_per_barrel"]), 2),
age_days=age,
stale=age > STALE_AFTER_DAYS,
source=row["source"],
series=SERIES,
summary=(
f"Dernière observation disponible il y a {age} jour{'s' if age != 1 else ''}"
if age > STALE_AFTER_DAYS
else f"Observation du {datetime.fromisoformat(row['observed_at']).strftime('%d/%m/%Y')}"
),
)
def context(db=None, today=None):
"""Bloc prêt pour l'affichage : jamais un cours du jour inventé."""
return latest(db=db, today=today)
def count(db=None):
with _connection(db) as db:
ensure_schema(db)
return db.execute("SELECT COUNT(*) FROM brent_daily").fetchone()[0]
def cached_path():
"""Emplacement du fichier de série, pour information et sauvegarde."""
storage = _storage()
return Path(storage.DB_PATH).parent / "brent_daily.csv"

View File

@@ -502,6 +502,29 @@ def job_brent_history(force=False):
)
def job_brent_daily(force=False):
"""Brent au comptant quotidien (EIA via FRED) — contexte informatif, jamais une décision.
Série DCOILBRENTEU, sans clé d'API et sans roll de contrat. Aucune valeur n'est reportée :
une journée sans observation reste sans observation, et la date affichée est celle de la
source, pas celle de notre passage.
"""
import brent
report = brent.refresh()
latest = brent.latest()
return dict(
status="ok",
stored=report["stored"],
total=report["total"],
last_observation_at=latest.get("observed_at"),
detail=(
f"{report['stored']} nouvelle(s) observation(s) · "
f"dernière : {latest.get('observed_at')} à {latest.get('usd_per_barrel')} USD/baril"
),
)
def job_fx_history(force=False):
"""Historique quotidien USD/EUR (BCE, service EXR) : indispensable aux variantes de marché."""
import market

View File

@@ -102,6 +102,14 @@ def clean_name(name):
return text
# Ressources officielles des enseignes présentes dans nos stations : aucune ne publie de
# conditions autorisant explicitement l'affichage de son logo dans une application tierce. Le
# dictionnaire reste donc vide, et l'interface retombe sur le pictogramme neutre + nom complet.
# « Trouvé sur un moteur d'images » n'est pas une autorisation ; « c'est une marque » n'est pas
# non plus une interdiction — c'est l'absence de conditions explicites qui tranche ici.
LOGO_ASSETS = {}
def brand_slug(name):
"""Slug stable pour choisir un pictogramme local. Enseigne inconnue -> 'inconnue'."""
if not name:

View File

@@ -4,7 +4,7 @@
<body><main>
<header><div class="brand"><img src="/logo.svg" alt="" class="brand-logo" width="40" height="40"><div><div class="eyebrow">Fuel Advisor</div><h1>Le bon arrêt.<br><span>Au bon moment.</span></h1></div></div><div class="header-actions"><button class="secondary" id="manage-vehicles">Mes véhicules</button><button class="secondary" id="manage-favorites">Mes favoris</button><button class="secondary" id="diagnostic">Supervision</button></div></header>
<section class="card top-bar">
<div class="top-bar-row"><div class="top-field"><label for="vehicle">Véhicule</label><select id="vehicle"><option value="">Comparer seulement les stations</option></select></div>
<div class="top-bar-row"><div class="top-field" id="vehicle-field"><label for="vehicle">Véhicule</label><select id="vehicle"><option value="">Comparer seulement les stations</option></select></div>
<div class="top-field" id="autonomy-field" hidden><label for="remaining-km-top">Autonomie affichée (km)</label><input id="remaining-km-top" type="number" min="0" max="5000" step="1" inputmode="numeric" autocomplete="off" placeholder="ex. 320"></div>
<button id="advise" class="primary">Obtenir mon conseil</button></div>
<p id="vehicle-info" class="hint">Ajoutez un véhicule pour adapter le conseil à votre autonomie.</p>

View File

@@ -123,6 +123,16 @@ JOBS = {
func="job_brent_history",
note="sans historique quotidien, aucune variante de marché n’est entraînable",
),
"brent_daily": dict(
source="Brent au comptant quotidien – EIA via FRED (série DCOILBRENTEU, sans clé)",
frequency="quotidienne",
cadence_seconds=86400,
retry_seconds=6 * 3600,
window=_daily_at(8, 45),
func="job_brent_daily",
note="prix au comptant, donc aucun roll de contrat ; la date affichée reste celle de "
"l’observation source, jamais celle de notre passage",
),
"fx_history": dict(
source="BCE – USD/EUR historique quotidien (service EXR officiel)",
frequency="mensuel",

View File

@@ -67,3 +67,45 @@ img.brand-logo{width:40px;height:40px;flex:0 0 auto}
.brand-tile{width:26px;height:26px;flex:0 0 auto;border-radius:7px;display:inline-block;vertical-align:middle}
.station-head .brand-tile{width:30px;height:30px;margin-right:.4rem}
.badge.brand{gap:.45rem}
/* --- Cartes station : lisibles au doigt, navigation explicite --- */
.station-title{display:flex;flex-direction:column;min-width:0;flex:1 1 auto}
.station-title strong{overflow-wrap:anywhere}
.station-age{font-size:.78rem;opacity:.72}
.station-price{font-weight:700;white-space:nowrap}
.station-line,.station-cost{margin:.2rem 0}
.station-nav{display:flex;gap:.5rem;margin-top:.45rem}
.station-nav .nav-btn{flex:1 1 0;display:inline-flex;align-items:center;justify-content:center;min-height:44px;padding:.5rem .7rem;border-radius:10px;border:1px solid #34455b;background:#203048;color:var(--text);text-decoration:none;font-size:.92rem;font-weight:700;white-space:nowrap}
.station-nav .nav-btn:hover{background:#27395a}
.station-nav .nav-btn:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
button.ghost{background:#203048;color:var(--text);border-color:#34455b}
button.ghost:hover{background:#27395a}
.badge.best-badge{background:#1d4ed8;color:#fff;border-color:#1d4ed8}
.badge.delta{background:#f1f5f9}
.hero-reason{margin:.15rem 0 .5rem}
.top-stations .compact-station{padding:.6rem .7rem}
@media (max-width:759px){.station-card .station-head{gap:.5rem}}
/* Débordement horizontal : une piste `1fr` ne doit jamais s'étirer au-delà de son conteneur
à cause du contenu (min-content). On borne donc les pistes et les enfants de flex. */
.station-cards{grid-template-columns:repeat(auto-fill,minmax(min(190px,100%),1fr))}
.top-stations{grid-template-columns:minmax(0,1fr)}
.metrics{grid-template-columns:repeat(3,minmax(0,1fr))}
.two{grid-template-columns:repeat(2,minmax(0,1fr))}
.station-head,.station-nav,.station-title{min-width:0}
.station-line,.station-cost,.station-title strong,.station-age{overflow-wrap:anywhere}
@media (min-width:760px){
.top-stations{grid-template-columns:repeat(3,minmax(0,1fr))}
}
/* Véhicule et autonomie sur la même ligne, avec des libellés alignés : le libellé du champ
autonomie est plus long et se replie sur deux lignes, ce qui décalait les deux colonnes. */
.top-bar-row{align-items:flex-start}
.top-bar .top-field label{min-height:2.3em}
@media (min-width:760px){.top-bar #advise{align-self:flex-end}}
/* La règle .station-head span (prix) ciblait aussi la ligne d'âge du prix et l'empêchait de se
replier : la carte débordait alors de 100 px sur mobile. Le prix garde nowrap, pas l'âge. */
.station-title strong,.station-title .station-age{white-space:normal}
.station-title .station-age{font-size:.78rem;font-weight:500;color:var(--muted)}
.station-title strong{font-size:.98rem}

83
tests/test_brent.py Normal file
View File

@@ -0,0 +1,83 @@
"""Brent quotidien : parsing, âge réel et absence de report de valeur."""
import sqlite3
from datetime import date
import pytest
import brent
HEADER = "observation_date,DCOILBRENTEU\n"
FIXTURE = HEADER + "2026-09-07,104.47\n2026-09-08,.\n2026-09-09,109.51\n2026-09-10,\n"
def memory():
db = sqlite3.connect(":memory:")
db.row_factory = sqlite3.Row
return db
def test_parse_ignore_les_valeurs_manquantes():
rows = brent.parse(FIXTURE)
assert rows == [("2026-09-07", 104.47), ("2026-09-09", 109.51)]
def test_parse_rejette_une_valeur_non_exploitable():
assert brent.parse(HEADER + "2026-09-09,-3.2\n") == []
assert brent.parse(HEADER + "2026-09-09,abc\n") == []
def test_refresh_conserve_la_date_d_observation_et_fetched_at_distincts():
db = memory()
report = brent.refresh(db=db, text=FIXTURE, fetched_at="2026-09-11T06:00:00+00:00")
assert report["stored"] == 2
row = db.execute("SELECT * FROM brent_daily ORDER BY observed_at").fetchone()
assert row["observed_at"] == "2026-09-07"
assert row["available_at"] == "2026-09-08"
assert row["fetched_at"] == "2026-09-11T06:00:00+00:00"
assert row["source"] == "EIA via FRED"
def test_aucun_report_de_valeur_sur_une_journee_absente():
db = memory()
brent.refresh(db=db, text=FIXTURE)
days = [row[0] for row in db.execute("SELECT observed_at FROM brent_daily ORDER BY 1")]
assert days == ["2026-09-07", "2026-09-09"] # le 08 et le 10 n'existent pas, pas de report
def test_refresh_ne_reecrit_pas_une_observation_connue():
db = memory()
brent.refresh(db=db, text=FIXTURE)
brent.refresh(db=db, text=FIXTURE)
assert brent.count(db) == 2
def test_latest_annonce_la_derniere_observation_disponible_quand_elle_vieillit():
db = memory()
brent.refresh(db=db, text=FIXTURE)
block = brent.latest(db=db, today=date(2026, 9, 20))
assert block["usd_per_barrel"] == 109.51
assert block["age_days"] == 11
assert block["stale"] is True
assert block["summary"] == "Dernière observation disponible il y a 11 jours"
assert block["summary"] != "cours du jour"
def test_latest_affiche_la_date_quand_l_observation_est_recente():
db = memory()
brent.refresh(db=db, text=FIXTURE)
block = brent.latest(db=db, today=date(2026, 9, 10))
assert block["stale"] is False
assert block["summary"] == "Observation du 09/09/2026"
def test_latest_sans_donnee_ne_pretend_pas_a_un_prix():
block = brent.latest(db=memory())
assert block["available"] is False
assert block["summary"] == "Brent spot temporairement indisponible"
assert "usd_per_barrel" not in block
def test_refresh_refuse_une_serie_vide():
with pytest.raises(ValueError):
brent.refresh(db=memory(), text="")

109
tests/test_station_list.py Normal file
View File

@@ -0,0 +1,109 @@
"""Liste des stations : découpe de l'affichage, coûts réels et liens de navigation."""
import pytest
import app as application
NAV = (44.777, -0.61)
def station(identifier, price, distance=None):
class Station:
pass
item = Station()
item.id = identifier
item.price = price
item.route_distance_km = distance
return item
def vehicle(consumption=5.0):
return dict(consumption=consumption)
@pytest.mark.parametrize(
("total", "visible", "hidden"),
[
(0, 0, 0), # aucune station
(1, 1, 0), # une seule
(2, 2, 0), # deux
(3, 3, 0), # exactement trois
(4, 3, 1), # le bouton doit annoncer 1
(57, 3, 54),
],
)
def test_decoupe_de_la_liste(total, visible, hidden):
block = application.station_display(total)
assert (block["visible"], block["hidden"]) == (visible, hidden)
assert block["total"] == total
def test_le_bouton_n_est_jamais_relie_a_une_liste_vide():
for total in range(0, 6):
block = application.station_display(total)
assert block["hidden"] == 0 if total <= 3 else block["hidden"] > 0
def test_liens_de_navigation_exacts():
links = application.navigation_links(*NAV)
assert links["google_maps"] == (
"https://www.google.com/maps/dir/?api=1&destination=44.777000,-0.610000&travelmode=driving"
)
assert links["waze"] == "https://waze.com/ul?ll=44.777000,-0.610000&navigate=yes"
assert links["coordinates"] == "44.777000,-0.610000"
def test_liens_de_navigation_transportes_par_chaque_station():
class Station:
pass
item = Station()
item.id = "1"
item.price = 1.7
item.route_distance_km = 5.0
item.navigation = application.navigation_links(*NAV)
assert "destination=44.777000" in item.navigation["google_maps"]
assert "ll=44.777000" in item.navigation["waze"]
def test_cout_reel_du_detour_penalise_la_station_lointaine():
stations = [station("proche", 1.80, 2.0), station("loin", 1.70, 12.0)]
options = application.station_options(stations, vehicle(5.0), 30)
proche, loin = options["proche"], options["loin"]
assert proche["extra_km"] == 0.0 and loin["extra_km"] == 10.0
assert proche["fuel_cost_eur"] == 54.0
# 10 km de détour consomment 0,5 L au prix de la station lointaine
assert loin["detour_cost_eur"] == 0.85
assert loin["total_cost_eur"] == pytest.approx(51.0 + 0.85, abs=0.01)
assert loin["total_cost_eur"] < proche["total_cost_eur"]
assert proche["delta_eur"] > 0 and loin["delta_eur"] == 0
assert loin["best"] is True and proche["best"] is False
def test_une_station_plus_chere_et_plus_loin_perd():
stations = [station("proche", 1.70, 1.0), station("loin", 1.79, 11.0)]
options = application.station_options(stations, vehicle(6.0), 30)
assert options["proche"]["best"] is True
assert options["loin"]["delta_eur"] > 0
def test_sans_distance_routiere_aucun_cout_invente():
stations = [station("a", 1.70, None)]
assert application.station_options(stations, vehicle(5.0), 30) == {}
def test_composant_de_marque_ne_pretend_pas_a_un_logo():
component = application.brand_component(dict(brand="TotalEnergies", brand_slug="totalenergies"))
assert component["name"] == "TotalEnergies"
assert component["slug"] == "totalenergies"
assert component["logo_asset"] is None
assert component["logo_source"] is None
assert component["logo_usage_status"] == "neutre"
def test_composant_de_marque_sans_enseigne_reste_neutre():
component = application.brand_component({})
assert component["name"] is None
assert component["slug"] == "inconnue"
assert component["logo_usage_status"] == "neutre"

144
ui.js
View File

@@ -108,14 +108,67 @@ function stationCards(rows){
// Décision opérationnelle : elle vient de l'autonomie, de la réserve et du prix local,
// jamais d'une prédiction. Tant que le modèle n'est pas validé, aucune ligne ne doit laisser
// croire à une prévision.
const DECISION_LABELS={refuel:'ACHETER MAINTENANT',topup:'FAIRE UN APPOINT',wait:'ATTENDRE'};
// Pictogramme local : monogramme d'enseigne ou pompe Fuel Advisor. Jamais un logo de marque
// tierce (licence de marque non détenue) et jamais une image distante.
function brandTile(slug, label){
const known=/^[a-z0-9-]+$/.test(slug||'')?slug:'inconnue';
return `<svg class="brand-tile" role="img" aria-label="${esc(label||'Enseigne')}"><use href="/brands.svg#brand-${known}"></use></svg>`;
}
const DECISION_LABELS={refuel:'FAIS LE PLEIN MAINTENANT',refill:'FAIS LE PLEIN MAINTENANT',topup:'FAIS UN APPOINT',wait:'TU PEUX ATTENDRE'};
function decisionLabel(action){return DECISION_LABELS[action]||'PAS DE SIGNAL PRÉDICTIF FIABLE';}
function heroReason(d){
if(d.action==='wait')return 'Autonomie suffisante au-delà de la réserve : vous n’êtes pas obligé de passer maintenant.';
if(d.action==='topup')return 'Un appoint suffit pour couvrir le besoin, sans remplir le réservoir.';
if(d.action==='refuel'||d.action==='refill')return 'Marge de sécurité atteinte : le plein évite de rouler sous la réserve.';
return 'Sélectionnez un véhicule et indiquez son autonomie pour un conseil chiffré.';
}
// Pictogramme neutre Fuel Advisor tant qu'aucun logo officiel n'est autorisé à cet usage.
// Jamais un monogramme de remplacement, jamais une image distante : le nom complet suffit.
function brandMark(brand){
const b=brand||{};
if(b.logo_asset)return `<img class="brand-logo" src="${esc(b.logo_asset)}" alt="" width="30" height="30">`;
return `<svg class="brand-tile" role="img" aria-label="Enseigne ${esc(b.name||'inconnue')} — logo officiel non utilisé"><use href="/brands.svg#enseigne-neutre"></use></svg>`;
}
function navButtons(label, nav){
const n=nav||{};
if(!n.waze&&!n.google_maps)return '';
const maps=n.google_maps?`<a class="nav-btn" href="${esc(n.google_maps)}" target="_blank" rel="noopener noreferrer" aria-label="Itinéraire Google Maps vers ${esc(label)}">Google Maps</a>`:'';
const waze=n.waze?`<a class="nav-btn" href="${esc(n.waze)}" target="_blank" rel="noopener noreferrer" aria-label="Itinéraire Waze vers ${esc(label)}">Waze</a>`:'';
return `<div class="station-nav">${maps}${waze}</div>`;
}
function stationCard(s, index){
const e=s.economics||{},b=s.brand_info||{},nav=s.navigation||{};
const label=b.name||s.brand||s.name||'Station-service';
const km=s.route_distance_km===null||s.route_distance_km===undefined?null:s.route_distance_km;
const where=[];
if(km!==null)where.push(`${num(km,1)} km`);
if(e.extra_km)where.push(`détour +${num(e.extra_km,1)} km`);
else if(km!==null)where.push('station la plus proche');
if(e.litres)where.push(`pour ${num(e.litres,0)} L`);
const cost=e.total_cost_eur===null||e.total_cost_eur===undefined?null:e.total_cost_eur;
const badge=e.best?'<span class="badge best-badge">Meilleur choix</span>':(e.delta_eur?`<span class="badge delta">+${num(e.delta_eur,2)} €</span>`:'');
const costLine=cost===null?'':'<p class="hint station-cost">Coût réel estimé : '
+`${num(e.fuel_cost_eur,2)} € de carburant`
+(e.detour_cost_eur?` + ${num(e.detour_cost_eur,2)} € de détour`:'')
+` = <strong>${num(cost,2)} €</strong> ${badge}</p>`;
return `<div class="station-card compact-station${e.best?' best':''}" data-station="${esc(s.id)}">
<div class="station-head">${brandMark(Object.assign({},b,{name:label}))}<div class="station-title"><strong>${esc(label)}</strong><span class="station-age">Prix déclaré : ${esc(s.updated||'date inconnue')}</span></div><span class="station-price">${num(s.price,3)}<small> €/L</small></span></div>
<p class="hint station-line">${where.length?esc(where.join(' · ')):'distance inconnue'}</p>
${costLine}
${badge&&cost===null?`<p class="hint">${badge}</p>`:''}
${navButtons(label,nav)}</div>`;
}
function stationsSection(d){
const all=Array.isArray(d.stations)?d.stations:[];
if(!all.length)return '<section class="card"><div class="eyebrow">Où acheter</div><p class="hint">Aucune station trouvée dans ce rayon. Élargissez la recherche pour comparer.</p></section>';
// Le nombre annoncé vient du serveur (stations_display) : jamais un bouton sur liste vide.
const disp=d.stations_display||{visible:Math.min(3,all.length),hidden:Math.max(0,all.length-3)};
const shown=Math.max(0,Math.min(disp.visible,all.length));
const head=all.slice(0,shown).map((s,i)=>stationCard(s,i)).join('');
const rest=all.slice(shown);
const more=rest.length?`<button type="button" class="wide ghost" id="stations-more">Afficher les ${disp.hidden} autres stations</button><button type="button" class="wide ghost" id="stations-less" hidden>Réduire la liste</button>`:'';
return `<section class="card"><div class="eyebrow">Où acheter · ${shown} meilleure${shown>1?'s':''} option${shown>1?'s':''} sur ${all.length}</div><div class="station-cards top-stations">${head}</div><div class="station-cards" id="stations-rest" hidden>${rest.map((s,i)=>stationCard(s,i+shown)).join('')}</div>${more}<p class="hint">${esc(d.station_options_note||'')}</p></section>`;
}
function bindStationToggle(){
const more=$('stations-more'),less=$('stations-less'),rest=$('stations-rest');
if(!more||!rest)return;
more.onclick=()=>{rest.hidden=false;more.hidden=true;if(less)less.hidden=false;};
if(less)less.onclick=()=>{rest.hidden=true;more.hidden=false;less.hidden=true;};
}
function heroQuantity(d){
const q=d.quantity||{};
if(d.action==='wait')return 'Aucune quantité nécessaire aujourd’hui.';
@@ -129,22 +182,54 @@ function heroTrend(d){
if(!t.direction||t.direction==='unknown')return `<p class="hero-trend muted">→ Tendance récente indisponible</p>`;
const cls=t.direction==='up'?'tone-refuel':t.direction==='down'?'tone-wait':'muted';
const word=t.direction==='up'?'hausse':t.direction==='down'?'baisse':'stable';
return `<p class="hero-trend ${cls}"><strong>${esc(t.arrow||'→')} ${word}</strong> · ${num(Math.abs(t.change_cents),1)} c€/L sur ${num(t.days,0)} jours <span class="hint-inline">tendance observée, pas une prévision</span></p>`;
const sign=t.direction==='up'?'+':t.direction==='down'?'−':'';
return `<p class="hero-trend ${cls}">Tendance observée : <strong>${esc(t.arrow||'→')} ${sign}${num(Math.abs(t.change_cents),1)} c€/L sur ${num(t.days,0)} jours</strong> <span class="hint-inline">(prix locaux réellement mesurés — aucun texte ici n’est une prévision)</span></p>`;
}
function topStations(d){
const rows=(d.stations||[]).slice(0,3);
if(!rows.length)return '';
const nearest=d.detour?d.detour.nearest_km:null;
const cards=rows.map((s,index)=>{
const km=s.route_distance_km;
const extra=(km!==null&&km!==undefined&&nearest!==null&&nearest!==undefined)?Math.max(0,Math.round((km-nearest)*10)/10):null;
return `<div class="station-card compact-station${index===0?' best':''}">
<div class="station-head">${brandTile(s.brand_slug,s.brand||s.name)}<strong>${esc(s.brand||s.name)}</strong><span>${num(s.price,3)} €<small>/L</small></span></div>
<p class="hint">${esc(s.city||'')}${km!==null&&km!==undefined?` · ${num(km,1)} km${extra?` (détour ≈ ${num(extra,1)} km)`:''}`:' · distance inconnue'}</p>
<p class="hint">Prix déclaré : ${esc(s.updated)}${index===0?' · <strong>meilleur choix</strong>':''}</p>
</div>`;
// --- Contexte marché : compact, explicite, jamais décisionnel -------------------------
function factorOf(d, key){
return ((d.upstream_synthesis||{}).factors||[]).find(f=>f.key===key)||{};
}
function marketInline(d){
const b=d.brent||{};
const iso=String(b.observed_at||'');
const shortDate=/^\d{4}-\d{2}-\d{2}$/.test(iso)?` (${iso.slice(8,10)}/${iso.slice(5,7)}/${iso.slice(0,4)})`:'';
const parts=[b.available?`Brent spot ${num(b.usd_per_barrel,2)} $/bbl${shortDate}`:'Brent spot indisponible'];
const fx=factorOf(d,'change'),log=factorOf(d,'logistique'),ev=factorOf(d,'evenements');
if(fx.observation)parts.push(fx.observation.trim());
if(log.observation)parts.push(log.observation.split(':')[0]);
const news=/^(\d+)/.exec(ev.observation||'');
if(news)parts.push(`${news[1]} événements suivis`);
return parts.join(' · ');
}
function marketRows(d){
return ['change','raffinage','logistique','evenements'].map(key=>{
const f=factorOf(d,key);
if(!f.observation)return '';
const date=f.observed_at?` <span class="hint-inline">(${esc(String(f.observed_at))})</span>`:'';
return `<p class="hint"><strong>${esc(f.label||key)}</strong> : ${esc(f.observation)}${date}</p>`;
}).join('');
return `<section class="card"><div class="eyebrow">Où acheter · 3 meilleures options</div><div class="station-cards top-stations">${cards}</div><details><summary>Afficher toutes les stations</summary></details></section>`;
}
function dgecReference(d){
const c=factorOf(d,'brut').historical_context;
if(!c)return '';
return `<p class="hint">Référence mensuelle DGEC : ${num(c.value,2)} ${esc(c.unit||'')} (${esc(String(c.day||'date inconnue'))}) — donnée mensuelle, jamais un cours du jour.</p>`;
}
function marketCard(d){
const b=d.brent||{};
const brentLine=b.available
? `<p class="hint"><strong>Brent spot : ${num(b.usd_per_barrel,2)} $/baril</strong> · ${esc(b.summary||'')} · Source : ${esc(b.source||'')}</p>`
: '<p class="hint">Brent spot temporairement indisponible.</p>';
return `<details class="card section-collapse"><summary><span class="eyebrow">Contexte marché</span><strong>${esc(marketInline(d))}</strong></summary>${brentLine}${marketRows(d)}${dgecReference(d)}<p class="hint">Informations descriptives — non utilisées pour prédire ni décider le conseil actuel.</p><details><summary>Voir le détail</summary>${synthesisBlock(d.upstream_synthesis)}</details></details>`;
}
function priceStatsSection(d){
const s=d.local_stats||{},r=d.routing||{};
const notices=(d.price_warning?`<p class="notice">${esc(d.price_warning)}</p>`:'')
+(r.provider==='none'?`<p class="notice">${esc(r.note||'Routage indisponible')}</p>`:'')
+(r.eta_note?`<p class="hint">${esc(r.eta_note)}</p>`:'')
+(d.brands_warning?`<p class="hint">${esc(d.brands_warning)}</p>`:'')
+(d.brands_source?`<p class="hint">Enseignes : ${esc(d.brands_source)}</p>`:'');
const stats=s.count?`<div class="metrics"><div class="metric"><strong>${num(s.min,3)}</strong><span>minimum €/L</span></div><div class="metric"><strong>${num(s.median,3)}</strong><span>médiane €/L</span></div><div class="metric"><strong>${num(s.max,3)}</strong><span>maximum €/L</span></div></div><p class="hint">${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.</p><details><summary>Répartition des prix</summary><div class="buckets">${s.price_buckets.map(x=>`<span class="bucket">${num(x.price,3)} € · ${x.count}</span>`).join('')}</div></details>`:'';
return `<h3>Prix observés</h3>${notices}${stats}<p class="hint">${esc(d.distance_note||'')} Un bon prix local ne signifie pas que c'est le bon moment pour remplir le réservoir.</p>`;
}
function render(d){
const s=d.local_stats||{},h=d.history||{};
@@ -155,14 +240,17 @@ function render(d){
const eta=s.route_eta_min!==null&&s.route_eta_min!==undefined?` · ≈ ${num(s.route_eta_min,0)} min avec trafic (mesuré il y a ${num((s.route_eta_age_seconds||0)/60,0)} min)`:'';
const distance=routed?`${num(s.route_distance_km,1)} km en voiture${duree}${eta}`:`${num(s.distance_km,1)} km à vol d’oiseau (routage indisponible)`;
const nav=s.navigation?`<div class="nav-actions"><a class="nav-btn" href="${esc(s.navigation.google_maps)}" target="_blank" rel="noopener">Google Maps</a><a class="nav-btn" href="${esc(s.navigation.waze)}" target="_blank" rel="noopener">Waze</a></div>`:'';
return `<div class="station"><div>${s.brand?`<span class="badge brand">${brandTile(s.brand_slug,s.brand)}${esc(s.brand)}</span>`:'<span class="badge brand">Enseigne inconnue</span>'}${s.road?`<span class="badge">${esc(s.road)}</span>`:''}<strong>${esc(s.name)}</strong><p class="hint">${esc(s.city)} · ${distance}</p><p class="hint">Déclaré : ${esc(s.updated)}</p>${nav}</div><div class="price">${num(s.price,3)} <small>€/L</small></div></div>`;}).join('');
return `<div class="station"><div>${s.brand?`<span class="badge brand">${brandMark(s.brand_info||{name:s.brand,slug:s.brand_slug})}${esc(s.brand)}</span>`:'<span class="badge brand">Enseigne inconnue</span>'}${s.road?`<span class="badge">${esc(s.road)}</span>`:''}<strong>${esc(s.name)}</strong><p class="hint">${esc(s.city)} · ${distance}</p><p class="hint">Déclaré : ${esc(s.updated)}</p>${nav}</div><div class="price">${num(s.price,3)} <small>€/L</small></div></div>`;}).join('');
const reasons=d.reasons.map(r=>`<li>${esc(r)}</li>`).join('');
const metrics=d.usable_km!==null?`<div class="metrics"><div class="metric"><strong>${num(d.usable_km)} km</strong><span>avant votre marge</span></div><div class="metric"><strong>${d.days_left===null?'Occasionnel':num(d.days_left,1)+' j'}</strong><span>${d.days_left===null?'pas de moyenne imposée':'usage moyen estimé'}</span></div><div class="metric"><strong>${d.topup_liters===null?'—':num(d.topup_liters,1)+' L'}</strong><span>appoint indicatif</span></div></div>`:'';
$('result').innerHTML=`<section class="card hero tone-${esc(d.action)}"><div class="eyebrow">Conseil Fuel Advisor · ${esc(d.fuel)}</div><h2 class="verdict">${esc(decisionLabel(d.action))}</h2><p class="hero-quantity">${esc(heroQuantity(d))}</p>${heroTrend(d)}<p class="hint">${esc(d.quantity_headline||d.label)}</p><details><summary>Pourquoi ce conseil ?</summary>${quantityBlock(d)}<ul class="reasons">${reasons}</ul></details><div class="tags"><span>Sans décision par IA</span><span>Aucun signal prédictif utilisé dans le conseil</span>${fresh}</div></section>
${topStations(d)}
<section class="card"><div class="eyebrow">Où acheter</div><h2>Les prix autour de vous</h2>${d.price_warning?`<p class="notice">${esc(d.price_warning)}</p>`:''}${d.routing?.provider==='none'?`<p class="notice">${esc(d.routing?.note||'Routage indisponible')}</p>`:''}${d.routing?.eta_note?`<p class="hint">${esc(d.routing.eta_note)}</p>`:''}${d.brands_warning?`<p class="hint">${esc(d.brands_warning)}</p>`:''}${s.count?`<div class="metrics"><div class="metric"><strong>${num(s.min,3)}</strong><span>minimum €/L</span></div><div class="metric"><strong>${num(s.median,3)}</strong><span>médiane €/L</span></div><div class="metric"><strong>${num(s.max,3)}</strong><span>maximum €/L</span></div></div><p class="hint">${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.</p><details><summary>Répartition des prix</summary><div class="buckets">${s.price_buckets.map(b=>`<span class="bucket">${num(b.price,3)} € · ${b.count}</span>`).join('')}</div></details>`:''}<details><summary>Toutes les stations (${d.stations.length})</summary><div>${stations}</div></details><p class="hint">${esc(d.distance_note)} Un bon prix local ne signifie pas que c’est le bon moment pour remplir le réservoir.</p></section>
<details class="card section-collapse"><summary><span class="eyebrow">Historique des prix</span><strong>Ce que les prix ont réellement fait</strong></summary><p>${esc(h.summary)}</p>${h.confidence==='limited'?'<p class="notice">Panel réduit : tendance peu représentative du secteur.</p>':''}<h3>Moyenne des prix enregistrés</h3>${averageChart(h.average_series)}<h3>Évolution par station</h3>${stationCards(h.stations_series)}<p class="hint">${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.</p></details>
<details class="card section-collapse"><summary><span class="eyebrow">Contexte marché · descriptif, non utilisé par le modèle</span><strong>Ce que disent les sources amont</strong></summary><p class="hint">EUR/USD, raffinage et prix HTT, trafic des détroits (PortWatch), Brent DGEC, actualités et promotions : affichés pour situer le marché, jamais utilisés pour décider.</p>${synthesisBlock(d.upstream_synthesis)}<p class="hint">${esc(d.market?.summary||'Cotation indisponible')} ${d.market?.reference?esc(d.market.reference):''}</p>${technicalBlock()}${promotionsBlock(d.promotions,d.promotions_note)}</details>${modelVariablesBlock()}`;
$('result').innerHTML=`<section class="card hero tone-${esc(d.action)}"><div class="eyebrow">Conseil Fuel Advisor · ${esc(d.fuel)}</div><h2 class="verdict">${esc(decisionLabel(d.action))}</h2><p class="hero-quantity">${esc(heroQuantity(d))}</p>${heroTrend(d)}<p class="hero-reason">${esc(heroReason(d))}</p><p class="hint">${esc(d.quantity_headline||d.label)}</p><details><summary>Pourquoi ce conseil ?</summary>${quantityBlock(d)}<ul class="reasons">${reasons}</ul></details><div class="tags"><span>Sans décision par IA</span><span>Aucun signal prédictif utilisé dans le conseil</span>${fresh}</div></section>
${stationsSection(d)}
<details class="card section-collapse"><summary><span class="eyebrow">Historique des prix</span><strong>Ce que les prix ont réellement fait</strong></summary><p>${esc(h.summary)}</p>${h.confidence==='limited'?'<p class="notice">Panel réduit : tendance peu représentative du secteur.</p>':''}<h3>Moyenne des prix enregistrés</h3>${averageChart(h.average_series)}<h3>Évolution par station</h3>${stationCards(h.stations_series)}<p class="hint">${h.days||0} jours observés. Moyenne calculée sur les relevés réellement enregistrés ce jour-là ; dates manquantes non interpolées, aucune prévision.</p></details>
${marketCard(d)}
<details class="card section-collapse"><summary><span class="eyebrow">Actualités et promotions</span><strong>Actualités et promotions</strong></summary>${promotionsBlock(d.promotions,d.promotions_note)}</details>
<details class="card section-collapse"><summary><span class="eyebrow">Détails scientifiques</span><strong>Modèle prédictif expérimental — non utilisé dans le conseil</strong></summary>${modelVariablesBlock()}${priceStatsSection(d)}</details>
<details class="card section-collapse"><summary><span class="eyebrow">Sources et fraîcheur</span><strong>Sources et fraîcheur des données</strong></summary><p class="hint">Valeurs brutes, unités, dates et provenance. Ces indicateurs décrivent le marché ; ils ne décident pas du conseil.</p>${technicalBlock()}</details>`;
bindStationToggle();
status('Conseil calculé à '+stamp(d.generated_at));
}
const JOB_STATE={ok:['ok','tone-none'],unchanged:['sans changement','muted'],error:['échec','tone-refuel'],never:['jamais exécuté','muted'],'not_due':['non dû','muted']};
@@ -198,7 +286,7 @@ function synthesisBlock(s){
${(f.notes||[]).map(n=>`<p class="hint">${sourceText(n)}</p>`).join('')}
${f.historical_context?`<p class="hint">Contexte historique : moyenne mensuelle DGEC à ${num(f.historical_context.value,2)} ${esc(f.historical_context.unit)} (${esc(f.historical_context.day)}) — donnée mensuelle, pas un cours du jour.</p>`:''}
${f.evidence_text?`<p class="hint">${sourceText(f.evidence_text)}</p>`:''}
<p class="hint">Donnée du ${esc(String(f.observed_at||'—'))}${f.age_days!==null&&f.age_days!==undefined?` (${f.age_days} j)`:''} · source : ${sourceText(f.source||'—')}</p></div></div>`).join('');
${f.observed_at?`<p class="hint">Donnée du ${esc(String(f.observed_at))}${f.age_days!==null&&f.age_days!==undefined?` (${f.age_days} j)`:''}${f.source?` · source : ${sourceText(f.source)}`:''}</p>`:(f.source?`<p class="hint">Source : ${sourceText(f.source)} (date d’observation non fournie par la source)</p>`:'')}</div></div>`).join('');
return `<div class="pressure pressure-${esc(s.pressure_key)}"><strong>Pression sur les prix : ${esc(s.pressure)}</strong>${conf}</div>${factors?`<div class="factors">${factors}</div>`:''}<h3>En clair</h3><p>${esc(s.plain||'')}</p><p class="hint">${esc(s.disclaimer||'')}</p>`;
}
function modelVariablesBlock(){