"""Persistance locale : profils explicites et observations publiques quotidiennes.""" from __future__ import annotations import json import math import os import sqlite3 import statistics from contextlib import contextmanager from datetime import datetime, timedelta, timezone from pathlib import Path from zoneinfo import ZoneInfo PARIS = ZoneInfo("Europe/Paris") MAX_PRICE_AGE_DAYS = 7 def fresh_price(updated, now=None): now = now or datetime.now(timezone.utc) try: stamp = datetime.fromisoformat(updated) if stamp.tzinfo is None: stamp = stamp.replace(tzinfo=PARIS) return timedelta(hours=-1) <= now - stamp <= timedelta(days=MAX_PRICE_AGE_DAYS) except (ValueError, TypeError): return False def distance_km(lat, lon, other_lat, other_lon): p1, p2 = math.radians(lat), math.radians(other_lat) dlat, dlon = p2 - p1, math.radians(other_lon - lon) a = math.sin(dlat / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dlon / 2) ** 2 return 6371 * 2 * math.asin(math.sqrt(min(1, max(0, a)))) def record_observations(rows, now=None): now = now or datetime.now(timezone.utc) day = now.astimezone(PARIS).date().isoformat() values = {} for row in rows: for fuel, price in row["prices"].items(): if fuel not in FUELS or not math.isfinite(price) or not 0 < price < 20: continue key = (row["id"], fuel, day) values[key] = (*key, price, row["updates"].get(fuel, ""), now.isoformat(), row["lat"], row["lon"]) with connect() as db: db.executemany( """INSERT INTO observations VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(station_id,fuel,day) DO UPDATE SET price=excluded.price, source_updated=excluded.source_updated,collected_at=excluded.collected_at, lat=excluded.lat,lon=excluded.lon""", list(values.values()), ) return len(values) def history(lat, lon, radius, fuel, now=None): now = now or datetime.now(timezone.utc) today = now.astimezone(PARIS).date() with connect() as db: rows = db.execute( """SELECT * FROM observations WHERE fuel=? AND day>=? AND day<=? ORDER BY day,station_id""", (fuel, (today - timedelta(days=29)).isoformat(), today.isoformat()), ).fetchall() days = {} for row in rows: if distance_km(lat, lon, row["lat"], row["lon"]) > radius: continue observed = datetime.fromisoformat(row["collected_at"]) if not fresh_price(row["source_updated"], observed): continue days.setdefault(row["day"], {})[row["station_id"]] = row["price"] out = dict( trend="unknown", confidence="insufficient", delta_per_liter=None, matched_stations=0, days=len(days), series=[], summary="Historique insuffisant : au moins 7 jours observés couvrant une semaine sont nécessaires.", ) if not days: return out # Graphe sur panel constant : aucun effet dû à l'apparition d'une station. common = set.intersection(*(set(values) for values in days.values())) if common: out["series"] = [ dict(day=day, median=round(statistics.median(values[s] for s in common), 3), count=len(common)) for day, values in days.items() ] recent = {d: v for d, v in days.items() if d >= (today - timedelta(days=10)).isoformat()} if len(recent) < 7: return out first, last = min(recent), max(recent) if (today - datetime.fromisoformat(last).date()).days > 1 or ( datetime.fromisoformat(last) - datetime.fromisoformat(first) ).days < 7: return out common = set.intersection(*(set(values) for values in recent.values())) if not common: out["summary"] = "Panel de stations constant insuffisant pour comparer les prix." return out delta = statistics.median(recent[last][s] - recent[first][s] for s in common) trend = "up" if delta >= 0.02 else "down" if delta <= -0.02 else "flat" label = {"up": "hausse", "down": "baisse", "flat": "stabilité"}[trend] out.update( trend=trend, confidence="limited" if len(common) < 3 else "observed", delta_per_liter=round(delta, 3), matched_stations=len(common), start=first, end=last, summary=f"{label.capitalize()} observée : {delta:+.3f} €/L du {first} au {last}, " f"sur les mêmes {len(common)} stations. Ce n’est pas une prévision.", ) return out DB_PATH = Path(os.environ.get("FUEL_ADVISOR_DATA_DIR", "/var/lib/fuel-advisor")) / "fuel.sqlite3" FUELS = ["Gazole", "SP95", "SP98", "E10", "E85", "GPLc"] @contextmanager def connect(): DB_PATH.parent.mkdir(parents=True, exist_ok=True) db = sqlite3.connect(DB_PATH, timeout=20) db.row_factory = sqlite3.Row db.execute("PRAGMA foreign_keys=ON") try: with db: db.executescript(""" CREATE TABLE IF NOT EXISTS vehicles (id INTEGER PRIMARY KEY, data TEXT NOT NULL); CREATE TABLE IF NOT EXISTS favorites (id INTEGER PRIMARY KEY, data TEXT NOT NULL); CREATE TABLE IF NOT EXISTS observations ( station_id TEXT NOT NULL, fuel TEXT NOT NULL, day TEXT NOT NULL, price REAL NOT NULL, source_updated TEXT NOT NULL, collected_at TEXT NOT NULL, lat REAL NOT NULL, lon REAL NOT NULL, PRIMARY KEY(station_id, fuel, day)); CREATE TABLE IF NOT EXISTS collections ( id INTEGER PRIMARY KEY, started_at TEXT NOT NULL, finished_at TEXT, status TEXT NOT NULL, count INTEGER DEFAULT 0, detail TEXT NOT NULL DEFAULT ''); CREATE TABLE IF NOT EXISTS market_daily ( day TEXT PRIMARY KEY, payload TEXT NOT NULL); CREATE INDEX IF NOT EXISTS observations_day ON observations(day); """) yield db finally: db.close() def number(value, name, minimum, maximum): try: if isinstance(value, bool): raise ValueError out = float(value) if not math.isfinite(out) or not minimum <= out <= maximum: raise ValueError return out except (TypeError, ValueError): raise ValueError(f"{name} : valeur attendue entre {minimum} et {maximum}.") from None def table_name(kind): if kind not in ("vehicles", "favorites"): raise ValueError("Type inconnu") return kind def list_entities(kind): with connect() as db: return [ dict(id=row["id"], **json.loads(row["data"])) for row in db.execute(f"SELECT id,data FROM {table_name(kind)} ORDER BY id") ] def get_entity(kind, entity_id): with connect() as db: row = db.execute(f"SELECT data FROM {table_name(kind)} WHERE id=?", (entity_id,)).fetchone() if row is None: raise LookupError("Élément introuvable") return dict(id=int(entity_id), **json.loads(row["data"])) def save_entity(kind, data, entity_id=None): table_name(kind) if not isinstance(data, dict): raise ValueError("Objet JSON attendu") name = str(data.get("name", "")).strip() if not 1 <= len(name) <= 80: raise ValueError("Nom requis, 80 caractères maximum") clean = {"name": name} if kind == "favorites": clean.update( lat=number(data.get("lat"), "Latitude", -90, 90), lon=number(data.get("lon"), "Longitude", -180, 180), radius_km=number(data.get("radius_km"), "Rayon", 1, 80), ) else: fuel, usage = data.get("fuel"), data.get("usage") if fuel not in FUELS or usage not in ("regular", "occasional"): raise ValueError("Carburant ou usage invalide") clean.update( fuel=fuel, usage=usage, consumption=number(data.get("consumption"), "Consommation", 0.1, 60), min_range_km=number(data.get("min_range_km"), "Marge km", 0, 1500), monthly_km=number( data.get("monthly_km", 0), "Km mensuels", 1 if usage == "regular" else 0, 30000 ), tank_liters=None if data.get("tank_liters") in (None, "") else number(data["tank_liters"], "Réservoir", 1, 300), ) with connect() as db: if entity_id is None: if db.execute(f"SELECT count(*) FROM {kind}").fetchone()[0] >= 100: raise ValueError("Limite de 100 éléments atteinte") entity_id = db.execute( f"INSERT INTO {kind}(data) VALUES(?)", (json.dumps(clean, ensure_ascii=False),) ).lastrowid elif ( db.execute( f"UPDATE {kind} SET data=? WHERE id=?", (json.dumps(clean, ensure_ascii=False), entity_id) ).rowcount == 0 ): raise LookupError("Élément introuvable") return dict(id=entity_id, **clean) def delete_entity(kind, entity_id): with connect() as db: if not db.execute(f"DELETE FROM {table_name(kind)} WHERE id=?", (entity_id,)).rowcount: raise LookupError("Élément introuvable")