From 176e6acd6f57b3ba168437992e52d412fa6f0121 Mon Sep 17 00:00:00 2001 From: Claptrap Date: Fri, 27 Nov 2026 22:14:06 +0100 Subject: [PATCH] Benzina Abruzzo: PWA completa (mappa PMTiles, lista a pannello, dettaglio impianto) --- .gitignore | 7 + README.md | 40 + app.py | 529 ++++++++++++ index.html | 259 ++++++ static/app.css | 369 +++++++++ static/app.js | 1225 ++++++++++++++++++++++++++++ static/icons/apple-touch-icon.png | Bin 0 -> 6150 bytes static/icons/favicon-32.png | Bin 0 -> 1183 bytes static/icons/icon-192.png | Bin 0 -> 6500 bytes static/icons/icon-512.png | Bin 0 -> 16603 bytes static/icons/maskable-512.png | Bin 0 -> 8509 bytes static/manifest.webmanifest | 22 + static/sw.js | 39 + static/vendor/leaflet.css | 661 +++++++++++++++ static/vendor/leaflet.js | 6 + static/vendor/protomaps-leaflet.js | 23 + 16 files changed, 3180 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100755 app.py create mode 100644 index.html create mode 100644 static/app.css create mode 100644 static/app.js create mode 100644 static/icons/apple-touch-icon.png create mode 100644 static/icons/favicon-32.png create mode 100644 static/icons/icon-192.png create mode 100644 static/icons/icon-512.png create mode 100644 static/icons/maskable-512.png create mode 100644 static/manifest.webmanifest create mode 100644 static/sw.js create mode 100644 static/vendor/leaflet.css create mode 100644 static/vendor/leaflet.js create mode 100644 static/vendor/protomaps-leaflet.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6ff867d --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +data/*.db +data/*.db-* +static/tiles/*.pmtiles +__pycache__/ +*.pyc +.DS_Store +*.log diff --git a/README.md b/README.md new file mode 100644 index 0000000..91a11d9 --- /dev/null +++ b/README.md @@ -0,0 +1,40 @@ +# Benzina Abruzzo + +PWA per i prezzi dei carburanti in Abruzzo, su open data MIMIT. + +**Live:** https://benzina.feedme.work + +## Cosa fa +Mappa a tutto schermo (PMTiles vettoriali self-hosted), pannello lista che si apre +a richiesta, dettaglio impianto come bottom sheet con tutti i carburanti, storico +prezzi e costo del pieno calcolato sul veicolo scelto. + +## Stack +- `app.py` — server HTTP + API (Python stdlib, nessuna dipendenza), gzip, ETag, + cache in memoria; DB SQLite `data/benzina.db`. +- `index.html`, `static/app.css`, `static/app.js` — frontend vanilla, nessun build. +- `static/vendor/` — Leaflet 1.9.4 + protomaps-leaflet 5.1.0, serviti in locale. +- Service worker `benzina-v17`. + +## API +| Endpoint | Descrizione | +|---|---| +| `/api/meta` | province, carburanti, data ultima estrazione | +| `/api/data` | impianti filtrati (`carburante`, `provincia`, `self`, `sort`, `tank`, `cons`) | +| `/api/station?id=` | dettaglio impianto, tutti i carburanti | +| `/api/history?id=` | storico prezzi | +| `/api/comuni` | elenco comuni | +| `/healthz` | stato | + +## Dati +Open data MIMIT (`anagrafica_impianti_attivi.csv`, `prezzo_alle_8.csv`), +estrazione giornaliera alle 08:45 UTC via timer systemd. Province AQ, CH, PE, TE. + +## Setup +```bash +python3 app.py collect # scarica e importa i dati +python3 app.py # server su 172.18.0.1:2590 +``` + +Le tile vettoriali (`static/tiles/abruzzo.pmtiles`, ~104 MB) non sono nel repo: +si estraggono da build.protomaps.com con `pmtiles extract` (bbox 12.9–14.6 / 41.6–43.0, z0–14). diff --git a/app.py b/app.py new file mode 100755 index 0000000..5079e11 --- /dev/null +++ b/app.py @@ -0,0 +1,529 @@ +#!/usr/bin/env python3 +# benzina-abruzzo: prezzi carburanti Abruzzo dagli open data MIMIT. +# Uso: app.py collect | serve [porta] [bind] | stats +import csv +import hashlib +import datetime +import io +import json +import math +import mimetypes +import os +import sqlite3 +import sys +import threading +import time +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlparse + +BASE = os.path.dirname(os.path.abspath(__file__)) +DB = os.path.join(BASE, 'data', 'benzina.db') +PAGE = os.path.join(BASE, 'index.html') +STATIC = os.path.join(BASE, 'static') +URL_ANA = 'https://www.mimit.gov.it/images/exportCSV/anagrafica_impianti_attivi.csv' +URL_PRE = 'https://www.mimit.gov.it/images/exportCSV/prezzo_alle_8.csv' +PROVINCE = ('AQ', 'CH', 'PE', 'TE') +UA = {'User-Agent': 'Mozilla/5.0 (compatible; benzina-abruzzo/1.1)'} + +SCHEMA = [ + '''CREATE TABLE IF NOT EXISTS stations( + id INTEGER PRIMARY KEY, gestore TEXT, bandiera TEXT, tipo TEXT, nome TEXT, + indirizzo TEXT, comune TEXT, provincia TEXT, lat REAL, lon REAL)''', + '''CREATE TABLE IF NOT EXISTS prices( + id INTEGER, carburante TEXT, prezzo REAL, self INTEGER, dt_comu TEXT, + collected TEXT, PRIMARY KEY(id, carburante, self, collected))''', + 'CREATE INDEX IF NOT EXISTS ix_prices ON prices(carburante, self, collected)', + '''CREATE TABLE IF NOT EXISTS runs( + collected TEXT PRIMARY KEY, source_date TEXT, stations INTEGER, prices INTEGER)''', +] + + +def conn(): + os.makedirs(os.path.dirname(DB), exist_ok=True) + c = sqlite3.connect(DB, timeout=15) + for stmt in SCHEMA: + c.execute(stmt) + return c + + +def fetch(url): + req = urllib.request.Request(url, headers=UA) + with urllib.request.urlopen(req, timeout=180) as r: + return r.read().decode('utf-8', 'replace') + + +def rows_of(text): + lines = text.splitlines() + src = '' + if lines and 'Estrazione' in lines[0]: + src = lines[0].replace('Estrazione del ', '').strip() + body = '\n'.join(lines[1:]) + return src, list(csv.DictReader(io.StringIO(body), delimiter='|')) + + +def collect(): + c = conn() + src, ana = rows_of(fetch(URL_ANA)) + _, pre = rows_of(fetch(URL_PRE)) + now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + abruzzo = {} + for r in ana: + if (r.get('Provincia') or '').strip().upper() not in PROVINCE: + continue + try: + i = int(r['idImpianto']) + lat = float(r.get('Latitudine') or 0) + lon = float(r.get('Longitudine') or 0) + except (KeyError, ValueError, TypeError): + continue + abruzzo[i] = (r.get('Gestore', ''), r.get('Bandiera', ''), r.get('Tipo Impianto', ''), + r.get('Nome Impianto', ''), r.get('Indirizzo', ''), r.get('Comune', ''), + (r.get('Provincia') or '').strip().upper(), lat, lon) + c.executemany('INSERT OR REPLACE INTO stations VALUES (?,?,?,?,?,?,?,?,?,?)', + [(i,) + v for i, v in abruzzo.items()]) + np = 0 + for r in pre: + try: + i = int(r['idImpianto']) + except (KeyError, ValueError, TypeError): + continue + if i not in abruzzo: + continue + try: + pr = float((r.get('prezzo') or '').replace(',', '.')) + except ValueError: + continue + if not (0.5 < pr < 4.0): + continue + c.execute('INSERT OR REPLACE INTO prices VALUES (?,?,?,?,?,?)', + (i, (r.get('descCarburante') or '').strip(), pr, + 1 if str(r.get('isSelf')).strip() in ('1', 'True', 'true') else 0, + r.get('dtComu', ''), now)) + np += 1 + c.execute('INSERT OR REPLACE INTO runs VALUES (?,?,?,?)', (now, src, len(abruzzo), np)) + c.commit() + print('collected %s | fonte %s | impianti Abruzzo %d | prezzi %d' % (now, src, len(abruzzo), np)) + return len(abruzzo), np + + +def latest(c): + return c.execute('SELECT MAX(collected) FROM prices').fetchone()[0] + + +def meta(c): + r = c.execute('SELECT collected, source_date FROM runs ORDER BY collected DESC LIMIT 1').fetchone() + n = c.execute('SELECT COUNT(*) FROM stations').fetchone()[0] + return {'aggiornato': r[0] if r else None, 'fonte': r[1] if r else None, 'impianti': n} + + +def fuels(c): + return [r[0] for r in c.execute( + 'SELECT DISTINCT carburante FROM prices WHERE collected=? ORDER BY 1', (latest(c),))] + + +def summary(c, fuel, self_only): + sql = ('SELECT s.provincia, COUNT(*), MIN(p.prezzo), AVG(p.prezzo), MAX(p.prezzo) ' + 'FROM prices p JOIN stations s ON s.id=p.id ' + 'WHERE p.collected=? AND p.carburante=? ' + + ('AND p.self=1 ' if self_only else '') + + 'GROUP BY s.provincia ORDER BY s.provincia') + return [{'provincia': r[0], 'impianti': r[1], 'min': round(r[2], 3), + 'media': round(r[3], 3), 'max': round(r[4], 3)} + for r in c.execute(sql, (latest(c), fuel))] + + +def haversine(lat1, lon1, lat2, lon2): + if not lat2 or not lon2: + return None + r = 6371.0 + p1, p2 = math.radians(lat1), math.radians(lat2) + dp = p2 - p1 + dl = math.radians(lon2 - lon1) + a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2 + return round(2 * r * math.asin(math.sqrt(a)), 2) + + +def bandiere(c): + return [{'bandiera': r[0], 'n': r[1]} for r in c.execute( + 'SELECT bandiera, COUNT(*) FROM stations GROUP BY bandiera ORDER BY COUNT(*) DESC')] + + +def comuni(c): + return [{'comune': r[0], 'provincia': r[1], 'lat': round(r[2], 5), 'lon': round(r[3], 5), 'n': r[4]} + for r in c.execute('''SELECT comune, provincia, AVG(lat), AVG(lon), COUNT(*) + FROM stations WHERE lat<>0 GROUP BY comune, provincia + ORDER BY comune''')] + + +# ---------- cache ---------- +# I prezzi MIMIT cambiano una volta al giorno: ricalcolare le stesse righe a +# ogni caricamento e' lavoro sprecato. Teniamo le righe base in memoria per +# PRICE_TTL secondi, chiave = (estrazione, carburante, self, provincia, bandiera). +PRICE_TTL = 7200 +_CACHE = {} +_CACHE_LOCK = threading.Lock() + + +def cache_get(key, ttl=None): + t = ttl if ttl is not None else PRICE_TTL + with _CACHE_LOCK: + hit = _CACHE.get(key) + if hit and (time.time() - hit[0]) < t: + return hit[1] + return None + + +def cache_put(key, val): + with _CACHE_LOCK: + _CACHE[key] = (time.time(), val) + if len(_CACHE) > 200: # anti-crescita: via le voci piu vecchie + for k in sorted(_CACHE, key=lambda k: _CACHE[k][0])[:80]: + _CACHE.pop(k, None) + return val + + +def cache_clear(): + with _CACHE_LOCK: + _CACHE.clear() + + +def stations(c, fuel, self_only, provincia=None, bandiera=None): + sql = ('SELECT s.id, s.bandiera, s.gestore, s.nome, s.indirizzo, s.comune, s.provincia, ' + 's.tipo, p.prezzo, p.self, p.dt_comu, s.lat, s.lon ' + 'FROM prices p JOIN stations s ON s.id=p.id ' + 'WHERE p.collected=? AND p.carburante=? ' + + ('AND p.self=1 ' if self_only else '') + + ('AND s.provincia=? ' if provincia else '') + + ('AND s.bandiera=? ' if bandiera else '') + + 'ORDER BY p.prezzo ASC') + lt = latest(c) + args = [lt, fuel] + if provincia: + args.append(provincia) + if bandiera: + args.append(bandiera) + by = {} + for r in c.execute(sql, args): + sid = r[0] + rec = {'bandiera': r[1], 'gestore': r[2], 'nome': r[3], 'indirizzo': r[4], + 'comune': r[5], 'provincia': r[6], 'tipo': r[7], 'dt': r[10], + 'lat': r[11], 'lon': r[12], 'prezzi': {}} + rec['prezzi']['self' if r[9] else 'servito'] = round(r[8], 3) + if sid in by: + by[sid]['prezzi'].update(rec['prezzi']) + else: + by[sid] = rec + out = [] + for sid, rec in by.items(): + pz = rec.pop('prezzi') + cheapest = min(pz.items(), key=lambda kv: kv[1]) + rec['id'] = sid + rec['prezzo'] = cheapest[1] + rec['self'] = cheapest[0] == 'self' + rec['p_self'] = pz.get('self') + rec['p_serv'] = pz.get('servito') + out.append(rec) + out.sort(key=lambda r: r['prezzo']) + return out + + +def stations_cached(c, fuel, self_only, provincia=None, bandiera=None, lt=None): + key = ('st', lt, fuel, self_only, provincia, bandiera) + hit = cache_get(key) + if hit is not None: + return hit + return cache_put(key, stations(c, fuel, self_only, provincia, bandiera)) + + +def history(c, sid, fuel): + return [{'t': r[0], 'p': round(r[1], 3)} for r in c.execute( + 'SELECT collected, AVG(prezzo) FROM prices WHERE id=? AND carburante=? ' + 'GROUP BY collected ORDER BY collected', (sid, fuel))] + + +def station_detail(c, sid): + '''Tutti i carburanti di un impianto, all'ultima estrazione disponibile. + Serve al pannello di dettaglio: "cosa costa qui" in una schermata.''' + st = c.execute('SELECT id, gestore, bandiera, tipo, nome, indirizzo, comune, ' + 'provincia, lat, lon FROM stations WHERE id=?', (sid,)).fetchone() + if not st: + return None + last = c.execute('SELECT MAX(collected) FROM prices WHERE id=?', (sid,)).fetchone()[0] + rows = c.execute('SELECT carburante, self, prezzo, dt_comu FROM prices ' + 'WHERE id=? AND collected=? ORDER BY carburante, self', + (sid, last)).fetchall() + fuels = {} + for carb, selbst, prezzo, dt in rows: + f = fuels.setdefault(carb, {'carburante': carb, 'servito': None, + 'self': None, 'dt': dt}) + if selbst: + f['self'] = round(prezzo, 3) + else: + f['servito'] = round(prezzo, 3) + return { + 'id': st[0], 'gestore': st[1], 'bandiera': st[2], 'tipo': st[3], + 'nome': st[4], 'indirizzo': st[5], 'comune': st[6], 'provincia': st[7], + 'lat': st[8], 'lon': st[9], 'collected': last, + 'fuels': sorted(fuels.values(), key=lambda f: f['carburante']), + } + + +def province_stats(c, fuel): + return {s['provincia']: s for s in summary(c, fuel, False)} + + +def stats(): + c = conn() + m = meta(c) + print('fonte MIMIT: %s | raccolto: %s | impianti Abruzzo: %d' + % (m['fonte'], m['aggiornato'], m['impianti'])) + for f in fuels(c): + print('\n' + f) + for s in summary(c, f, False): + print(' %s: min %.3f media %.3f max %.3f (%d impianti)' + % (s['provincia'], s['min'], s['media'], s['max'], s['impianti'])) + + +class Handler(BaseHTTPRequestHandler): + server_version = 'benzina-abruzzo/1.1' + + def log_message(self, *a): + pass + + def send(self, code, body, ctype='application/json; charset=utf-8', extra=None): + import gzip as _gzip + b = body.encode('utf-8') if isinstance(body, str) else body + extra = dict(extra or {}) + if 'Cache-Control' not in extra: + extra['Cache-Control'] = 'no-store' + ae = self.headers.get('Accept-Encoding', '') or '' + compressible = ('json' in ctype or 'javascript' in ctype or 'css' in ctype + or 'text/' in ctype or 'svg' in ctype) + if compressible and 'gzip' in ae and len(b) > 1400: + b = _gzip.compress(b, 6) + extra['Content-Encoding'] = 'gzip' + extra['Vary'] = 'Accept-Encoding' + self.send_response(code) + self.send_header('Content-Type', ctype) + self.send_header('Content-Length', str(len(b))) + self.send_header('Permissions-Policy', 'geolocation=(self)') + for k, v in extra.items(): + self.send_header(k, v) + self.end_headers() + try: + self.wfile.write(b) + except (BrokenPipeError, ConnectionResetError): + pass + + def serve_file(self, path): + if not os.path.isfile(path): + return self.send(404, json.dumps({'error': 'not found'})) + ctype = mimetypes.guess_type(path)[0] or 'application/octet-stream' + if path.endswith('.webmanifest'): + ctype = 'application/manifest+json' + if path.endswith('.pmtiles'): + ctype = 'application/vnd.pmtiles' + fname = os.path.basename(path) + cache = 'public, max-age=86400' + if path == PAGE or path.endswith('sw.js'): + cache = 'no-cache' + elif fname in ('index.html',): + cache = 'no-cache' + if path.endswith('.pmtiles'): + cache = 'public, max-age=604800, immutable' + + size = os.path.getsize(path) + # --- Range requests: indispensabili per PMTiles (lettura a blocchi) --- + rng = self.headers.get('Range') + start, end = 0, size - 1 + partial = False + if rng and rng.startswith('bytes='): + try: + spec = rng.split('=', 1)[1].split(',')[0].strip() + a_, _, b_ = spec.partition('-') + if a_: + start = int(a_) + if b_: + end = int(b_) + elif b_: + start = max(0, size - int(b_)) + end = min(end, size - 1) + if start > end or start >= size: + self.send_response(416) + self.send_header('Content-Range', 'bytes */%d' % size) + self.send_header('Content-Length', '0') + self.end_headers() + return + partial = True + except Exception: + start, end, partial = 0, size - 1, False + + length = end - start + 1 + self.send_response(206 if partial else 200) + self.send_header('Content-Type', ctype) + self.send_header('Content-Length', str(length)) + self.send_header('Cache-Control', cache) + self.send_header('Accept-Ranges', 'bytes') + self.send_header('Permissions-Policy', 'geolocation=(self)') + if partial: + self.send_header('Content-Range', 'bytes %d-%d/%d' % (start, end, size)) + self.end_headers() + remaining = length + with open(path, 'rb') as f: + f.seek(start) + while remaining > 0: + chunk = f.read(min(65536, remaining)) + if not chunk: + break + try: + self.wfile.write(chunk) + except (BrokenPipeError, ConnectionResetError): + return + remaining -= len(chunk) + + def api_data(self, c, g): + lt = latest(c) + fuel = g('carburante', 'Benzina') + prov = (g('provincia') or '').upper() or None + self_only = g('self', '0') == '1' + band = g('bandiera') or None + try: + ulat = float(g('lat')) if g('lat') else None + ulon = float(g('lon')) if g('lon') else None + except ValueError: + ulat = ulon = None + sort = g('sort', 'price') + try: + tank = float(g('tank', '50') or 50) + except ValueError: + tank = 50.0 + try: + cons = float((g('cons', '5.8') or '5.8').replace(',', '.')) + except ValueError: + cons = 5.8 + lim = int(g('limit', '800') or 800) + + # 1) righe base in cache per 2 ore (dipendono dall'estrazione) + rows = stations_cached(c, fuel, self_only, prov, band, lt) + + # 2) risposta gia' calcolata per questa combinazione esatta + lat_r = round(ulat, 3) if ulat is not None else None + lon_r = round(ulon, 3) if ulon is not None else None + rkey = ('resp', lt, fuel, self_only, prov, band, sort, + lat_r, lon_r, round(tank, 1), round(cons, 2), lim) + cached = cache_get(rkey) + if cached is not None: + body, etag = cached + inm = self.headers.get('If-None-Match') + if inm and inm == etag: + self.send_response(304) + self.send_header('ETag', etag) + self.send_header('Cache-Control', 'public, max-age=600') + self.end_headers() + return + return self.send(200, body, extra={ + 'Cache-Control': 'public, max-age=600, stale-while-revalidate=3600', + 'ETag': etag}) + + # 3) calcolo (copia, per non sporcare la cache con km/costi) + rows = [dict(r) for r in rows] + if ulat is not None and ulon is not None: + for r in rows: + r['km'] = haversine(ulat, ulon, r['lat'], r['lon']) + if sort == 'dist' and ulat is not None: + rows.sort(key=lambda r: (r['km'] if r['km'] is not None else 9999, r['prezzo'])) + elif sort == 'value' and ulat is not None: + for r in rows: + k = r['km'] or 0 + litres = min(k, 60) * 2 * cons / 100.0 + r['costo_pieno'] = round(r['prezzo'] * tank, 2) + r['costo_viaggio'] = round(litres * r['prezzo'], 2) + r['costo_totale'] = round(r['costo_pieno'] + r['costo_viaggio'], 2) + rows.sort(key=lambda r: r['costo_totale']) + + body = json.dumps({ + 'meta': meta(c), 'carburante': fuel, 'self': self_only, + 'summary': summary(c, fuel, self_only), + 'user': {'lat': ulat, 'lon': ulon}, + 'cheapest': rows[:lim]}) + etag = '"%s"' % hashlib.md5(body.encode('utf-8')).hexdigest()[:16] + cache_put(rkey, (body, etag)) + return self.send(200, body, extra={ + 'Cache-Control': 'public, max-age=600, stale-while-revalidate=3600', + 'ETag': etag}) + + def do_GET(self): + u = urlparse(self.path) + qs = parse_qs(u.query) + + def g(k, d=None): + return (qs.get(k) or [d])[0] + + try: + if u.path in ('/', '/index.html'): + return self.serve_file(PAGE) + if u.path.startswith('/static/'): + safe = os.path.normpath(u.path.lstrip('/')) + if not safe.startswith('static'): + return self.send(403, json.dumps({'error': 'forbidden'})) + return self.serve_file(os.path.join(BASE, safe)) + if u.path == '/healthz': + return self.send(200, json.dumps({'status': 'ok'})) + c = conn() + if u.path == '/api/meta': + mk = ('meta', latest(c), g('carburante', 'Benzina')) + hitc = cache_get(mk) + if hitc is None: + hitc = cache_put(mk, json.dumps({ + 'meta': meta(c), 'carburanti': fuels(c), + 'province': list(PROVINCE), + 'province_stats': province_stats(c, g('carburante', 'Benzina')), + 'bandiere': bandiere(c)})) + return self.send(200, hitc, extra={ + 'Cache-Control': 'public, max-age=1800, stale-while-revalidate=7200'}) + if u.path == '/api/data': + return self.api_data(c, g) + + if u.path == '/api/comuni': + ck = ('comuni',) + hitc = cache_get(ck, 86400) + if hitc is None: + hitc = cache_put(ck, json.dumps(comuni(c))) + return self.send(200, hitc, extra={ + 'Cache-Control': 'public, max-age=86400'}) + if u.path == '/api/station': + sid = int(g('id', '0')) + ck = ('station', sid) + hitc = cache_get(ck, 7200) + if hitc is None: + d = station_detail(c, sid) + if d is None: + return self.send(404, json.dumps({'error': 'impianto sconosciuto'})) + hitc = cache_put(ck, json.dumps(d)) + return self.send(200, hitc, extra={ + 'Cache-Control': 'public, max-age=1800, stale-while-revalidate=7200'}) + if u.path == '/api/history': + return self.send(200, json.dumps(history(c, int(g('id', '0')), + g('carburante', 'Benzina')))) + return self.send(404, json.dumps({'error': 'not found'})) + except Exception as e: + return self.send(500, json.dumps({'error': str(e)})) + + +def serve(port=2590, bind='172.18.0.1'): + ThreadingHTTPServer.allow_reuse_address = True + with ThreadingHTTPServer((bind, port), Handler) as httpd: + print('benzina-abruzzo su %s:%d' % (bind, port), flush=True) + httpd.serve_forever() + + +if __name__ == '__main__': + cmd = sys.argv[1] if len(sys.argv) > 1 else 'stats' + if cmd == 'collect': + collect() + elif cmd == 'serve': + serve(int(sys.argv[2]) if len(sys.argv) > 2 else 2590, + sys.argv[3] if len(sys.argv) > 3 else '172.18.0.1') + else: + stats() diff --git a/index.html b/index.html new file mode 100644 index 0000000..642d50d --- /dev/null +++ b/index.html @@ -0,0 +1,259 @@ + + + + + +Benzina Abruzzo — prezzi carburanti + + + + + + + + + + + + +
+
+
+ +
+
+ + Benzina +
+ + +
+ +
+ + + +
+ +
+ + +
+
+ + +
+ + + + + +
+ +

Il tuo veicolo

+

Serve a stimare il costo reale del rifornimento: quanto ti costa arrivare all'impianto più economico e quanto costa il pieno.

+ +
+ +
+ + + +
+
+ +
+ + +
Seleziona il modello per riempire il consumo tipico dichiarato.
+
+ +
+ + +
+ + +
+
+ +
+ + +
Litri. Serve per il costo del pieno.
+
+ +
+ +
+ + +
+
+ + +
I dati restano sul tuo telefono, non vengono inviati da nessuna parte.
+
+
+ + + + + + + + + + + +
+ + + + + + + + + diff --git a/static/app.css b/static/app.css new file mode 100644 index 0000000..0a01d88 --- /dev/null +++ b/static/app.css @@ -0,0 +1,369 @@ +:root{ + --bg:#FBF9F6; --surface:#FFFFFF; --surface-2:#F4F1EC; + --ink:#14181C; --ink-2:#5A6570; --ink-3:#98A2AC; + --brand:#0B7A5A; --brand-2:#0E9C73; --brand-soft:#E4F3ED; + --cheap:#0B7A5A; --mid:#C08A1E; --pricey:#C24A38; + --accent:#E19A2B; + --line:#E7E3DC; + --safe-b:env(safe-area-inset-bottom,0px); + --safe-t:env(safe-area-inset-top,0px); +} +@media (prefers-color-scheme:dark){ + :root{ + --bg:#0E1114; --surface:#171C21; --surface-2:#1F262C; + --ink:#EEF2F5; --ink-2:#A3AEB8; --ink-3:#6B7883; + --brand:#25B98C; --brand-2:#2FD39F; --brand-soft:#123028; + --cheap:#2FD39F; --mid:#E2B352; --pricey:#E87461; + --line:#262E35; + } +} +*{box-sizing:border-box;-webkit-tap-highlight-color:transparent} +html,body{height:100%} +body{ + margin:0;background:var(--bg);color:var(--ink); + font:15px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Inter,Roboto,sans-serif; + overscroll-behavior-y:none; +} +button,select,input{font:inherit;color:inherit} +button{border:0;background:none;cursor:pointer} +a{color:var(--brand);text-decoration:none} + +/* ============================================================ + LAYOUT — la mappa occupa tutto. La lista e' un pannello che si + apre solo se lo chiedi. Riferimenti: Apple Maps e Waze (controlli + in capsule, nessun pannello permanente) e i pattern di Mobbin per + le liste di luoghi (una riga per item, prezzo a destra). + ============================================================ */ +.app{height:100dvh;display:flex;flex-direction:column;overflow:hidden;position:relative} +#map{position:absolute;inset:0;z-index:0;background:var(--surface-2)} +.map-wrap{position:relative;flex:1;min-height:0} +.leaflet-container{background:var(--surface-2);font:inherit} +.leaflet-control-attribution{ + font-size:9px;opacity:.5;background:transparent!important; + padding:0 4px!important;bottom:0!important;right:0!important; +} + +/* ---------- barra superiore ---------- */ +.topbar{ + position:absolute;top:calc(10px + var(--safe-t));left:10px;right:10px;z-index:600; + display:flex;gap:8px;align-items:center;pointer-events:none; +} +.topbar>*{pointer-events:auto} +.pill{ + display:flex;align-items:center;gap:7px;height:42px;padding:0 14px; + background:var(--surface); + font-size:14px;font-weight:650;white-space:nowrap;color:var(--ink); +} +.pill.round{width:42px;padding:0;justify-content:center;position:relative} +.pill.brand{font-size:15px;letter-spacing:-.01em} +.pill.brand svg{color:var(--brand)} +#filterchip,#vbtn{margin-left:auto} +#filterchip+#vbtn{margin-left:0} +.badge-dot{ + position:absolute;top:-2px;right:-2px;min-width:17px;height:17px;padding:0 5px; + background:var(--brand);color:#fff; + font-size:10.5px;font-weight:800;display:none;align-items:center;justify-content:center; +} +.badge-dot.on{display:flex} +.pill:active{background:var(--surface-2)} + +/* ---------- chips ordinamento ---------- */ +.chips{ + position:absolute;top:calc(60px + var(--safe-t));left:10px;right:10px;z-index:600; + display:flex;gap:7px;padding:0 0 4px;overflow-x:auto;scrollbar-width:none; +} +.chips::-webkit-scrollbar{display:none} +.chip{ + flex:0 0 auto;height:32px;padding:0 13px;background:var(--surface);color:var(--ink-2); + font-size:13px;font-weight:600;display:flex;align-items:center; + transition:background .15s,color .15s; +} +.chip[aria-pressed="true"]{background:var(--ink);color:var(--bg)} + +/* ---------- comandi in basso a destra ---------- */ +.fab-stack{ + position:absolute;right:10px;bottom:calc(14px + var(--safe-b));z-index:600; + display:flex;flex-direction:column;gap:9px;align-items:flex-end; + transition:opacity .22s ease,transform .22s ease; +} +/* con la lista aperta i comandi spariscono: la lista e' il contesto */ +.app.sheet-open .fab-stack{opacity:0;pointer-events:none;transform:translateY(8px)} +.fab{width:44px;height:44px} +.fab.on{background:var(--brand);color:#fff} +.btn-list{ + display:flex;align-items:center;gap:8px;height:46px;padding:0 18px 0 15px; + background:var(--ink);color:var(--bg); + font-size:14.5px;font-weight:650;letter-spacing:-.01em; +} +.btn-list:active{transform:scale(.97)} + +/* ============================================================ + PANNELLO LISTA — chiuso per default, si apre dal pulsante + ============================================================ */ +.sheet{ + position:absolute;left:0;right:0;bottom:0;z-index:700; + background:var(--bg); + display:flex;flex-direction:column; + height:min(74dvh,620px); + padding-bottom:var(--safe-b); + transform:translateY(102%);visibility:hidden; + transition:transform .3s cubic-bezier(.32,.72,0,1),visibility .3s; +} +.sheet.open{transform:none;visibility:visible} +.grab{width:100%;padding:10px 0 2px;display:flex;justify-content:center;flex:0 0 auto} +.grab span{width:34px;height:4px;border-radius:99px;background:var(--ink-3);opacity:.3} +.sheet-head{ + padding:6px 16px 10px;display:flex;align-items:flex-start; + justify-content:space-between;gap:12px;flex:0 0 auto; +} +.sheet-head h2{font-size:19px;margin:0;letter-spacing:-.022em;font-weight:700} +.sheet-head .sub{font-size:12.5px;color:var(--ink-3);font-weight:500;margin-top:1px} +.icon-btn{ + width:32px;height:32px;border-radius:50%;background:var(--surface-2); + display:flex;align-items:center;justify-content:center;color:var(--ink-2);flex:0 0 auto; +} +.list{flex:1;overflow-y:auto;padding:0 8px 8px;-webkit-overflow-scrolling:touch;overscroll-behavior:contain} +.list.empty{display:flex;align-items:center;justify-content:center;color:var(--ink-3);font-size:14px;padding:30px} +.footline{padding:8px 16px calc(6px + var(--safe-b));font-size:11px;color:var(--ink-3);font-weight:500; + border-top:1px solid var(--line);flex:0 0 auto} + +/* ---------- riga impianto: una linea, prezzo a destra ---------- */ +.card{ + display:flex;align-items:center;gap:12px; + padding:11px 10px;transition:background .15s;cursor:pointer; +} +.card+.card{border-top:1px solid var(--line);} +.card:active,.card.sel{background:var(--surface-2)} +.card .dot{ + width:9px;height:9px;border-radius:50%;flex:0 0 auto;background:var(--ink-3); + box-shadow:0 0 0 3px color-mix(in srgb,var(--ink-3) 14%,transparent); +} +.card .dot.c-cheap{background:var(--cheap);box-shadow:0 0 0 3px color-mix(in srgb,var(--cheap) 16%,transparent)} +.card .dot.c-mid{background:var(--mid);box-shadow:0 0 0 3px color-mix(in srgb,var(--mid) 16%,transparent)} +.card .dot.c-pricey{background:var(--pricey);box-shadow:0 0 0 3px color-mix(in srgb,var(--pricey) 16%,transparent)} +.card .body{flex:1;min-width:0} +.card .brand{ + font-size:14.5px;font-weight:600;letter-spacing:-.012em; + white-space:nowrap;overflow:hidden;text-overflow:ellipsis; +} +.card .sub{ + font-size:12.5px;color:var(--ink-3);margin-top:1px; + white-space:nowrap;overflow:hidden;text-overflow:ellipsis; +} +.card .sub .d{color:var(--ink-2);font-weight:600} +.card .right{display:flex;flex-direction:column;align-items:flex-end;flex:0 0 auto} +.card .price{ + font-size:16.5px;font-weight:700;letter-spacing:-.022em; + font-variant-numeric:tabular-nums;line-height:1.15; +} +.card .per{font-size:10.5px;color:var(--ink-3);font-weight:600;letter-spacing:.03em;text-transform:uppercase} +.c-cheap{color:var(--cheap)} .c-mid{color:var(--mid)} .c-pricey{color:var(--pricey)} +.dist{color:var(--ink-3);font-size:12px;font-weight:600} + +/* ============================================================ + DETTAGLIO — il pannello che risponde a "cosa costa qui". + Non un cruscotto: una tabella di prezzi leggibile, un pulsante. + ============================================================ */ +.modal.sheet-modal#detail{align-items:flex-end;padding:0;overflow:hidden} +#detail .det{ + width:100%;max-height:min(90dvh,700px);overflow-y:auto;overscroll-behavior:contain; + background:var(--bg);padding:6px 18px calc(18px + var(--safe-b)); + animation:sheetUp .3s cubic-bezier(.32,.72,0,1); +} +.det-head{display:flex;align-items:flex-start;gap:12px;margin-bottom:16px} +.det-title{flex:1;min-width:0} +.det-x{ + width:32px;height:32px;border-radius:50%;background:var(--surface-2);flex:0 0 auto; + display:flex;align-items:center;justify-content:center;color:var(--ink-2);margin-top:2px; +} +#detail h2{ + font-size:19px;line-height:1.28;letter-spacing:-.022em;margin:0;font-weight:700; + overflow-wrap:anywhere; +} +.det-addr{font-size:13px;line-height:1.4;color:var(--ink-3);margin:3px 0 0;overflow-wrap:anywhere} + +/* tabella carburanti: nome a sinistra, self e servito incolonnati */ +.fuel-head{ + display:flex;justify-content:space-between;align-items:baseline; + font-size:10.5px;font-weight:700;letter-spacing:.07em;text-transform:uppercase; + color:var(--ink-3);padding:0 2px 7px;border-bottom:1px solid var(--line); +} +.fuel-list{display:flex;flex-direction:column} +.fuel-row{ + display:flex;align-items:baseline;gap:10px; + padding:11px 2px;border-bottom:1px solid var(--line); +} +.fuel-row:last-child{border-bottom:0} +.fuel-row .fname{flex:1;min-width:0;font-size:14.5px;font-weight:600;letter-spacing:-.012em} +.fuel-row .fv{ + font-size:14.5px;font-weight:650;font-variant-numeric:tabular-nums; + min-width:56px;text-align:right;letter-spacing:-.015em; +} +.fuel-row .fv.empty{color:var(--ink-3);font-weight:500} +.fuel-row.main{background:var(--brand-soft);margin:0 -8px;padding:11px 10px;border-bottom:0} +.fuel-row.main .fname{font-weight:700;color:var(--brand)} +.det-meta{font-size:11.5px;color:var(--ink-3);margin:12px 0 16px;line-height:1.45} + +.det-actions{display:flex;gap:9px;margin-bottom:16px} +.det-nav{ + flex:1;height:50px;background:var(--brand);color:#fff; + display:flex;align-items:center;justify-content:center;gap:8px; + font-size:15.5px;font-weight:650;letter-spacing:-.01em; +} +.det-nav:active{opacity:.9} +.det-icon-btn{ + width:50px;height:50px;background:var(--surface-2); + display:flex;align-items:center;justify-content:center;color:var(--ink);flex:0 0 auto; +} +.histwrap{background:var(--surface-2);padding:10px 12px;margin-bottom:12px} +.histhead{ + font-size:10.5px;text-transform:uppercase;letter-spacing:.06em;color:var(--ink-3); + font-weight:700;margin-bottom:6px;display:flex;justify-content:space-between; +} +#d-hist{width:100%;height:44px;display:block;overflow:visible} +#d-hist polyline{fill:none;stroke:var(--brand);stroke-width:2;stroke-linejoin:round;stroke-linecap:round;vector-effect:non-scaling-stroke} +#d-hist polygon{fill:var(--brand);opacity:.10} +#d-hist circle{fill:var(--brand);r:2.2} +#d-hist text{font-size:8px;fill:var(--ink-3);font-weight:600} + +/* ---------- setup sheet ---------- */ +.setup{display:none;position:fixed;inset:0;z-index:950;background:var(--bg);overflow-y:auto; + padding:calc(20px + var(--safe-t)) 20px calc(28px + var(--safe-b)); + overscroll-behavior:contain} +.setup.open{display:block} +.setup h2{font-size:22px;margin:8px 0 6px;letter-spacing:-.02em} +.setup p.lede{color:var(--ink-2);font-size:14px;margin:0 0 20px} +.field{margin-bottom:16px} +.field label{display:block;font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--ink-3);margin-bottom:7px} +.field input,.field select{ + width:100%;height:52px;padding:0 14px;background:var(--surface-2); + font-size:16px; +} +.hintline{font-size:12px;color:var(--ink-3);margin-top:6px} +.seg{display:flex;background:var(--surface-2);padding:4px;gap:4px} +.seg button{flex:1;height:44px;font-weight:600;font-size:14px;color:var(--ink-2)} +.seg button[aria-pressed="true"]{background:var(--bg);color:var(--ink)} + +/* ---------- misc ---------- */ +.toast{ + position:fixed;left:50%;bottom:calc(26px + var(--safe-b));transform:translate(-50%,20px); + background:var(--ink);color:var(--bg);padding:11px 18px;font-size:13.5px;font-weight:600; + opacity:0;pointer-events:none;transition:.25s;z-index:1000;max-width:88vw;text-align:center; +} +.toast.show{opacity:1;transform:translate(-50%,0)} +.skel{height:74px;background:linear-gradient(90deg,var(--surface-2) 25%,var(--surface) 50%,var(--surface-2) 75%); + background-size:200% 100%;animation:sh 1.3s infinite;margin-bottom:6px} +@keyframes sh{0%{background-position:200% 0}100%{background-position:-200% 0}} +.mk{width:30px;height:30px;border-radius:50%;background:var(--brand);color:#fff;border:2.5px solid #fff; + box-shadow:0 2px 8px rgba(0,0,0,.35);display:flex;align-items:center;justify-content:center; + font-size:11px;font-weight:800;font-variant-numeric:tabular-nums} +.mk.cheap{background:var(--cheap)} .mk.mid{background:var(--brand)} .mk.pricey{background:var(--pricey)} +.mk.user{background:#2E7DF6;width:16px;height:16px;border-width:3px} +@media (min-width:820px){ + .sheet{ + left:auto;right:16px;bottom:16px;width:400px; + height:min(72dvh,640px);transform:translateX(112%); + } + .sheet.open{transform:none} + .fab-stack{bottom:16px;transition:right .3s cubic-bezier(.32,.72,0,1),opacity .2s} + .app.sheet-open .fab-stack{opacity:1;pointer-events:auto;transform:none} + .app.sheet-open .fab-stack{right:432px} + .modal.sheet-modal#detail{align-items:flex-end} +} + + +/* ---------- modali ---------- */ +.modal{ + position:fixed;inset:0;z-index:980;display:none; + background:rgba(20,24,28,.42);backdrop-filter:blur(3px); + padding:16px;overflow-y:auto; +} +.modal.open{display:flex;align-items:flex-start;justify-content:center} +/* margin-top:auto spinge il box in basso ma, se e' piu' alto dello schermo, + il margine collassa a 0 e il contenuto resta raggiungibile in cima (niente + taglio del titolo su iPhone SE). Niente align-items:flex-end, che creerebbe + overflow non scrollabile. */ +.modal-box{margin-top:auto} +@media(min-width:640px){.modal-box{margin-top:auto;margin-bottom:auto}} +.modal-box{ + width:100%;max-width:440px;background:var(--bg);padding:20px 20px calc(20px + var(--safe-b)); + animation:up .25s cubic-bezier(.32,.72,0,1); +} +@keyframes up{from{transform:translateY(24px);opacity:.6}to{transform:none;opacity:1}} +.modal-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px} +.modal-head h2{font-size:20px;margin:0;letter-spacing:-.02em} +.xbtn{width:36px;height:36px;border-radius:50%;background:var(--surface-2);display:flex;align-items:center;justify-content:center;font-size:15px} +.geolook{width:72px;height:72px;border-radius:50%;background:var(--brand-soft);color:var(--brand); + display:flex;align-items:center;justify-content:center;margin:4px auto 14px} +.modal-box h2{text-align:center} +.modal-box .lede{text-align:center} +.modal-box .field label{text-align:left} +.modal-box .btn{height:50px} + +/* ============================================================ + SHEET D'AVVISO — una sola grammatica per GPS e installazione + Riferimenti: sheet di Apple Maps (grabber, stato, azione singola) + e HIG iOS (pre-prompt con beneficio, non con il nome del permesso). + Niente icone giganti, niente gradienti: tipografia e spazi. + ============================================================ */ +.modal.sheet-modal{align-items:flex-end;padding:0;overflow:hidden} +.sheet-modal .shd{ + width:100%;max-width:520px;margin:auto auto 0;background:var(--surface); + padding:10px 22px calc(22px + var(--safe-b)); + animation:sheetUp .32s cubic-bezier(.32,.72,0,1); +} +@keyframes sheetUp{from{transform:translateY(100%)}to{transform:none}} +.shd-grab{width:36px;height:4px;border-radius:99px;background:var(--ink-3);opacity:.28;margin:0 auto 18px} +.shd-status{ + display:flex;align-items:center;gap:7px;margin:0 0 10px; + font-size:11.5px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--ink-3); +} +.shd-dot{width:6px;height:6px;border-radius:50%;background:var(--ink-3);flex:none} +.shd-status.ok .shd-dot{background:var(--brand)} +.shd-status.bad .shd-dot{background:var(--pricey)} +.shd-status.wait .shd-dot{background:var(--mid);animation:blink 1.1s steps(2,start) infinite} +@keyframes blink{50%{opacity:.25}} +.shd h2{ + font-size:24px;line-height:1.22;letter-spacing:-.026em;font-weight:700; + margin:0 0 8px;text-align:left; +} +.shd .lede{font-size:14.5px;line-height:1.5;color:var(--ink-2);margin:0 0 20px;text-align:left} +.shd-steps{list-style:none;margin:0 0 20px;padding:0;display:flex;flex-direction:column;gap:0} +.shd-steps:empty{display:none} +.shd-steps li{display:flex;gap:13px;align-items:flex-start;padding:11px 0;border-top:1px solid var(--line)} +.shd-steps li:first-child{border-top:0;padding-top:0} +.shd-steps .k{ + flex:none;width:24px;height:24px;background:var(--surface-2); + display:flex;align-items:center;justify-content:center; + font-size:11.5px;font-weight:700;color:var(--ink-2); +} +.shd-steps .v{font-size:14px;line-height:1.42;color:var(--ink-2);padding-top:2px} +.shd-steps .v b{color:var(--ink);font-weight:600} +.shd-btn{ + width:100%;height:50px;background:var(--ink);color:var(--bg); + font-size:15.5px;font-weight:600;display:flex;align-items:center;justify-content:center;gap:8px; + transition:transform .12s ease,opacity .12s ease; +} +.shd-btn:active{transform:scale(.985);opacity:.9} +.shd-btn[disabled]{opacity:.4} +.shd-btn.ghost{background:var(--surface-2);color:var(--ink);margin-top:8px} +.shd-skip{ + display:block;width:100%;margin-top:6px;padding:13px 8px 4px; + font-size:14px;font-weight:500;color:var(--ink-3); +} +.shd-note{font-size:12.5px;line-height:1.45;color:var(--ink-3);margin:8px 0 0;text-align:left} +.shd-note:empty{display:none} +@media (prefers-color-scheme:dark){ + .shd-btn{background:var(--brand);color:#06231B} +} +@media(min-width:640px){ + .modal.sheet-modal{align-items:center;padding:20px;overflow-y:auto} + .sheet-modal .shd{margin:auto;padding-bottom:22px;animation:up .25s cubic-bezier(.32,.72,0,1)} + .shd-grab{display:none} + .shd h2{font-size:22px} +} +@media (prefers-reduced-motion: reduce){ + .sheet-modal .shd{animation:none} + .shd-status.wait .shd-dot{animation:none} + .shd-btn:active{transform:none} +} diff --git a/static/app.js b/static/app.js new file mode 100644 index 0000000..eb5fd73 --- /dev/null +++ b/static/app.js @@ -0,0 +1,1225 @@ +/* Benzina Abruzzo — front-end. Nessuna dipendenza oltre Leaflet. */ +(function () { + 'use strict'; + + var $ = function (s) { return document.querySelector(s); }; + var $$ = function (s) { return Array.prototype.slice.call(document.querySelectorAll(s)); }; + + var S = { + fuel: 'Benzina', + self: 0, + prov: '', + band: '', + comune: '', + sort: 'value', + pos: null, + rows: [], + meta: null, + sel: null, + vehicle: { type: 'car', cons: 5.8, unit: 'l100', tank: 50, mode: 0 } + }; + + + // Consumi dichiarati (ciclo combinato WLTP, arrotondati) per i modelli piu diffusi. + var MODELS = { + car: [ + ['Fiat Panda 1.0 Hybrid', 5.2, 38], ['Fiat 500 1.0 Hybrid', 5.2, 38], + ['Toyota Yaris Hybrid', 4.2, 36], ['Renault Clio TCe 90', 5.4, 42], + ['Volkswagen Polo 1.0 TSI', 5.6, 40], ['Ford Fiesta 1.0 EcoBoost', 5.6, 42], + ['Peugeot 208 1.2 PureTech', 5.5, 44], ['Citroen C3 1.2', 5.6, 45], + ['Opel Corsa 1.2', 5.5, 44], ['Lancia Ypsilon 1.0', 5.3, 40], + ['Fiat Tipo 1.5 Hybrid', 5.4, 50], ['Volkswagen Golf 1.5 TSI', 5.9, 50], + ['Toyota Corolla Hybrid', 4.5, 43], ['Ford Focus 1.0', 5.9, 52], + ['Skoda Octavia 1.5 TSI', 5.9, 55], ['Audi A3 30 TFSI', 5.9, 50], + ['BMW Serie 1 116i', 6.2, 50], ['Mercedes Classe A 180', 6.2, 51], + ['Fiat 500X 1.5 Hybrid', 6.0, 48], ['Jeep Renegade 1.5', 6.3, 48], + ['Fiat Panda 1.3 Multijet', 4.6, 37], ['Volkswagen Golf 2.0 TDI', 4.9, 50], + ['Audi A4 2.0 TDI', 5.2, 54], ['BMW Serie 3 320d', 5.1, 59], + ['Fiat Ducato 2.3 (camper)', 9.5, 90], + ['Fiat Panda 1.2 GPL', 7.1, 30], ['Dacia Sandero 1.0 GPL', 6.9, 40], + ['Fiat Panda 0.9 Metano', 4.2, 12], ['Volkswagen Polo 1.0 Metano', 4.0, 13] + ], + moto: [ + ['Honda SH 125', 2.7, 7.5], ['Honda SH 150', 2.9, 7.5], + ['Piaggio Beverly 300', 3.4, 12], ['Yamaha XMAX 300', 3.3, 13], + ['Honda NC750X', 3.6, 14], ['Yamaha MT-07', 4.3, 14], + ['Kawasaki Versys 650', 4.5, 21], ['Benelli TRK 502', 4.2, 20], + ['Piaggio Liberty 125', 2.6, 6], ['Vespa GTS 300', 3.4, 8.5], + ['Ducati Monster 937', 5.6, 14], ['BMW R 1250 GS', 4.8, 20] + ], + van: [ + ['Fiat Ducato 2.3 140cv', 8.8, 90], ['Ford Transit Custom', 7.6, 70], + ['Volkswagen Transporter T6.1', 7.4, 70], ['Renault Trafic', 7.2, 66], + ['Iveco Daily 35S', 10.5, 100], ['Peugeot Boxer', 8.6, 90], + ['Citroen Jumper', 8.6, 90], ['Mercedes Sprinter 314', 9.2, 93] + ] + }; + + var LS_VEH = 'benzina.vehicle.v1'; + var LS_PREF = 'benzina.pref.v1'; + + // ---------- helpers ---------- + function eur(n) { return n.toFixed(3).replace('.', ','); } + function eur0(n) { return n.toFixed(2).replace('.', ','); } + function km(n) { return n == null ? '—' : n.toFixed(n < 10 ? 1 : 0).replace('.', ',') + ' km'; } + function toast(msg, ms) { + var t = $('#toast'); t.textContent = msg; t.classList.add('show'); + clearTimeout(toast._t); toast._t = setTimeout(function () { t.classList.remove('show'); }, ms || 2600); + } + function parseNum(v) { return parseFloat(String(v).replace(',', '.')) || 0; } + function consPer100() { + var v = S.vehicle; + if (v.unit === 'kml') return v.cons > 0 ? 100 / v.cons : 0; + return v.cons; + } + function fmtCons() { + var v = S.vehicle; + return v.cons.toFixed(1).replace('.', ',') + (v.unit === 'kml' ? ' km/L' : ' L/100km'); + } + + // ---------- persistence ---------- + function loadPrefs() { + try { + var v = JSON.parse(localStorage.getItem(LS_VEH) || 'null'); + if (v) S.vehicle = Object.assign(S.vehicle, v); + var p = JSON.parse(localStorage.getItem(LS_PREF) || 'null'); + if (p) { + S.fuel = p.fuel || S.fuel; S.self = p.self || 0; S.sort = p.sort || S.sort; + S.band = p.band || ''; S.prov = p.prov || ''; S.comune = p.comune || ''; + } + } catch (e) { /* localStorage può essere bloccato */ } + } + function savePrefs() { + try { + localStorage.setItem(LS_VEH, JSON.stringify(S.vehicle)); + localStorage.setItem(LS_PREF, JSON.stringify({ + fuel: S.fuel, self: S.self, sort: S.sort, band: S.band, prov: S.prov, comune: S.comune + })); + } catch (e) {} + } + + // ---------- map ---------- + var map, markers = {}, meMarker = null, mapReady = false; + + function initMap() { + map = L.map('map', { + zoomControl: false, attributionControl: true, + scrollWheelZoom: false, tap: true, preferCanvas: true, + zoomSnap: 1, fadeAnimation: false, zoomAnimation: false, + markerZoomAnimation: false, inertia: true, inertiaDeceleration: 2600, + maxBoundsViscosity: 0.5, zoomControl: false, attributionControl: true + }).setView([42.35, 13.85], 8); + + // --- Protomaps: vettoriale, tiles self-hosted (una sola richiesta range) --- + var flavor = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; + try { + var layer = protomapsL.leafletLayer({ + url: '/static/tiles/abruzzo.pmtiles', + flavor: flavor, + lang: 'it', + maxDataZoom: 13, + maxZoom: 17, + attribution: '© Protomaps · © OpenStreetMap', + // opzioni GridLayer: non ridisegnare durante pinch/pan, un solo + // buffer di tile. Sono la differenza fra scatti e scorrimento fluido. + updateWhenIdle: true, + updateWhenZooming: false, + keepBuffer: 1, + tileDelay: 1 + }); + layer.addTo(map); + S.basemap = layer; + } catch (e) { + // fallback: raster OSM, ma solo se il renderer vettoriale non parte + L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { + maxZoom: 18, attribution: '© OpenStreetMap' + }).addTo(map); + } + + mapReady = true; + window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function (ev) { + if (!S.basemap) return; + try { + map.removeLayer(S.basemap); + S.basemap = protomapsL.leafletLayer({ + url: '/static/tiles/abruzzo.pmtiles', + flavor: ev.matches ? 'dark' : 'light', lang: 'it', + maxDataZoom: 13, maxZoom: 17, tileDelay: 1, + updateWhenIdle: true, updateWhenZooming: false, keepBuffer: 1, + attribution: '© Protomaps · © OpenStreetMap' + }); + S.basemap.addTo(map); + } catch (e) {} + }); + } + + // cheap / mid / pricey: usati sia dalle righe della lista sia dai pin, + // cosi il colore racconta la stessa cosa in entrambi i posti. + function priceClass(p, min, max) { + var t = (p - min) / Math.max(max - min, 1e-9); + return t < 0.34 ? 'cheap' : t < 0.67 ? 'mid' : 'pricey'; + } + + var MAX_PINS = 25; // solo i migliori: il resto non si disegna + + function drawMarkers(rows) { + if (!mapReady) return; + Object.keys(markers).forEach(function (k) { map.removeLayer(markers[k]); }); + markers = {}; + if (!rows.length) return; + + var ps = rows.map(function (r) { return r.prezzo; }); + var min = Math.min.apply(null, ps), max = Math.max.apply(null, ps); + + var pins = rows.slice(0, MAX_PINS), pts = []; + pins.forEach(function (r, i) { + if (!r.lat || !r.lon) return; + var cls = priceClass(r.prezzo, min, max); + var html = '
' + (i + 1) + '
'; + var icon = L.divIcon({ html: html, className: '', iconSize: [30, 30], iconAnchor: [15, 15] }); + var m = L.marker([r.lat, r.lon], { icon: icon, title: r.bandiera || r.gestore, riseOnHover: true }) + .on('click', function () { openDetail(r); }); + m.addTo(map); + markers[r.id] = m; + pts.push([r.lat, r.lon]); + }); + if (pts.length) map.fitBounds(L.latLngBounds(pts).pad(0.22), { animate: false }); + } + + function drawMe(pos) { + if (!mapReady) return; + if (meMarker) map.removeLayer(meMarker); + var icon = L.divIcon({ html: '
', className: '', iconSize: [16, 16], iconAnchor: [8, 8] }); + meMarker = L.marker([pos.lat, pos.lon], { icon: icon, zIndexOffset: 1000 }).addTo(map); + } + + // ---------- list ---------- + var listEl, sheet; + + function openSheet() { + sheet.classList.add('open'); + document.querySelector('.app').classList.add('sheet-open'); + sheet.setAttribute('aria-hidden', 'false'); + renderChunk(); + } + + function closeSheet() { + sheet.classList.remove('open'); + document.querySelector('.app').classList.remove('sheet-open'); + sheet.setAttribute('aria-hidden', 'true'); + } + + function toggleSheet() { + if (sheet.classList.contains('open')) closeSheet(); else openSheet(); + } + + function badge(r) { + var out = []; + out.push('' + (r.self ? 'self' : 'servito') + ''); + if (r.km != null) out.push('' + km(r.km) + ''); + return out.join(''); + } + + var PAGE_SIZE = 24, rendered = 0, io = null; + var loading = false, pending = false; + + function cardHTML(r, i, min, max) { + var cls = priceClass(r.prezzo, min, max) || 'mid'; + var sub = r.comune; + if (r.km != null) sub = '' + km(r.km) + ' · ' + sub; + else if (r.indirizzo) sub += ' · ' + r.indirizzo.slice(0, 30); + return '
' + + '' + + '
' + (r.bandiera || r.gestore || 'Impianto') + '
' + + '
' + sub + '
' + + '
' + eur(r.prezzo) + '
' + + '
' + (r.self ? 'self' : 'servito') + '
' + + '
'; + } + + function renderChunk() { + if (rendered >= S.rows.length) return; + var ps = S.rows.map(function (r) { return r.prezzo; }); + var min = Math.min.apply(null, ps), max = Math.max.apply(null, ps); + var end = Math.min(rendered + PAGE_SIZE, S.rows.length); + var frag = document.createDocumentFragment(); + var tmp = document.createElement('div'); + var html = ''; + for (var i = rendered; i < end; i++) html += cardHTML(S.rows[i], i, min, max); + tmp.innerHTML = html; + while (tmp.firstChild) frag.appendChild(tmp.firstChild); + if (sentinelEl && sentinelEl.parentNode === listEl) listEl.insertBefore(frag, sentinelEl); + else listEl.appendChild(frag); + rendered = end; + } + + function render() { + var rows = S.rows; + listEl.classList.remove('empty'); + listEl.innerHTML = ''; + rendered = 0; + if (!rows.length) { + listEl.classList.add('empty'); + listEl.textContent = 'Nessun impianto trovato con questi filtri.'; + return; + } + renderChunk(); + renderChunk(); + ensureSentinel(); + } + + var sentinelEl = null; + + function bindInfiniteList() { + if (io) { io.disconnect(); io = null; } + io = new IntersectionObserver(function (entries) { + if (entries[0].isIntersecting) renderChunk(); + }, { root: listEl, rootMargin: '400px' }); + } + + function ensureSentinel() { + if (!sentinelEl) { + sentinelEl = document.createElement('div'); + sentinelEl.id = 'lsentinel'; + sentinelEl.style.height = '1px'; + } + listEl.appendChild(sentinelEl); + if (io) { io.disconnect(); io.observe(sentinelEl); } + } + + function listHint() { + var n = S.rows.length; + var t = $('#listtitle'); + if (S.sort === 'dist' && S.pos) t.textContent = 'Piu vicini'; + else if (S.sort === 'value' && S.pos) t.textContent = 'Miglior scelta'; + else t.textContent = 'Piu economici'; + var hint = n + (n === 1 ? ' impianto' : ' impianti'); + var lb = $('#listbtn-label'); + $('#listhint').textContent = hint; + if (lb) lb.textContent = 'Impianti'; + } + + function apiUrl() { + var q = ['carburante=' + encodeURIComponent(S.fuel), 'self=' + S.self, 'sort=' + S.sort]; + if (S.prov) q.push('provincia=' + S.prov); + if (S.band) q.push('bandiera=' + encodeURIComponent(S.band)); + if (S.pos) q.push('lat=' + S.pos.lat.toFixed(5), 'lon=' + S.pos.lon.toFixed(5)); + q.push('tank=' + S.vehicle.tank, 'cons=' + consPer100().toFixed(2)); + return '/api/data?' + q.join('&'); + } + + var LS_DATA = 'benzina.data.v1'; + var DATA_TTL = 2 * 60 * 60 * 1000; // due ore + + function snapKey() { + return [S.fuel, S.self, S.sort, S.prov, S.band, S.comune, + S.vehicle.tank, consPer100().toFixed(2)].join('|'); + } + + function readSnap() { + try { + var raw = localStorage.getItem(LS_DATA); + if (!raw) return null; + var o = JSON.parse(raw); + if (!o || o.k !== snapKey()) return null; + if (Date.now() - o.t > DATA_TTL) return null; + return o; + } catch (e) { return null; } + } + + function writeSnap(d, etag) { + try { + localStorage.setItem(LS_DATA, JSON.stringify({ + t: Date.now(), k: snapKey(), e: etag || (d && d.__etag) || '', + rows: d.cheapest || [], meta: d.meta, summary: d.summary || [] + })); + } catch (e) {} + } + + function paint(d, fromCache) { + S.rows = d.cheapest || d.rows || []; + if (S.comune) { + var qq = S.comune.trim().toLowerCase(); + S.rows = S.rows.filter(function (r) { return (r.comune || '').toLowerCase().indexOf(qq) === 0; }); + } + S.meta = d.meta; + S.summary = d.summary || []; + listHint(); render(); + drawMarkers(S.rows); + if (S.pos) drawMe(S.pos); + var m = d.meta || {}; + $('#foot').textContent = 'MIMIT ' + (m.fonte || '—') + ' · ' + (m.impianti || 0) + ' impianti'; + if (fromCache) document.body.classList.add('from-cache'); + else document.body.classList.remove('from-cache'); + if (window.__paintMark === undefined) window.__paintMark = Math.round(performance.now()); + } + + function load(force) { + if (loading) { if (force) pending = true; return; } + loading = true; + + // 1) se abbiamo uno snapshot fresco lo disegniamo subito: zero attesa + if (!force) { + var snap = readSnap(); + if (snap) { + paint(snap, true); + // in sottofondo: richiesta condizionale. Se i prezzi non sono cambiati + // il server risponde 304 e non scarichiamo nulla. + var hd = {}; + if (snap.e) hd['If-None-Match'] = snap.e; + fetch(apiUrl(), { headers: hd }).then(function (r) { + if (r.status === 304) return null; + var et = r.headers.get('ETag'); + return r.json().then(function (d) { return { d: d, e: et }; }); + }).then(function (res) { + if (!res) return; + writeSnap(res.d, res.e); + paint(res.d, false); + }).catch(function () {}).then(function () { loading = false; }); + return; + } + } + + slotSkeletons(); + fetch(apiUrl()).then(function (r) { + var et = r.headers.get('ETag'); + return r.json().then(function (d) { return { d: d, e: et }; }); + }).then(function (res) { + writeSnap(res.d, res.e); + paint(res.d, false); + }).catch(function () { + var snap2 = readSnap(); + if (snap2) { paint(snap2, true); toast('Offline — prezzi salvati', 3000); } + else { + listEl.classList.add('empty'); + listEl.textContent = 'Dati non disponibili: sei offline?'; + toast('Connessione assente'); + } + }).then(function () { + loading = false; + if (pending) { pending = false; load(); } + }); + } + + function slotSkeletons() { + listEl.classList.remove('empty'); + listEl.innerHTML = new Array(7).join('
'); + } + + // ---------- detail ---------- + var current = null; + + function navUrl(r) { + var isIOS = /iphone|ipad|ipod/i.test(navigator.userAgent); + if (isIOS) return 'https://maps.apple.com/?daddr=' + r.lat + ',' + r.lon + '&dirflg=d'; + return 'https://www.google.com/maps/dir/?api=1&destination=' + r.lat + ',' + r.lon + '&travelmode=driving'; + } + + function openDetail(r) { + current = r; + S.sel = r.id; + render(); + + $('#d-name').textContent = r.bandiera || r.gestore || 'Impianto'; + var addr = [r.indirizzo, r.comune + ' (' + r.provincia + ')'].filter(Boolean).join(' — '); + $('#d-addr').textContent = addr.replace(/\s*-\s*-$/, ''); + + // tabella carburanti: prima il carburante che stai guardando, poi gli altri + var cur = fuelLabel(); + $('#d-fuels').innerHTML = '
' + + '' + cur + '' + + '' + eur(r.prezzo) + '
' + + '
' + + 'Carico altri carburanti…—
'; + + $('#d-nav').href = navUrl(r); + openModal('#detail'); + + var hid = r.id; + fetch('/api/station?id=' + hid) + .then(function (x) { return x.json(); }) + .then(function (d) { + if (!current || current.id !== hid || !d || !d.fuels) return; + var html = ''; + var others = d.fuels.filter(function (f) { return f.carburante !== cur; }); + var main = d.fuels.filter(function (f) { return f.carburante === cur; })[0]; + var rowFor = function (f, cls) { + var self = f['self'] != null ? eur(f['self']) : '—'; + var serv = f.servito != null ? eur(f.servito) : '—'; + return '
' + + '' + f.carburante + '' + + '' + self + '' + + '' + serv + '
'; + }; + if (main) html += rowFor(main, ' main'); + html += others.map(function (f) { return rowFor(f); }).join(''); + $('#d-fuels').innerHTML = html; + + // provenienza dei dati: sta sotto, in piccolo + var self = main && main['self'] != null ? main['self'] : null; + var serv = main && main.servito != null ? main.servito : null; + var when = (main && main.dt) || d.collected || ''; + $('#d-note').textContent = 'Prezzi MIMIT' + (when ? ' del ' + when : '') + + ' · self ' + (self != null ? eur(self) : 'n.d.') + + ' · servito ' + (serv != null ? eur(serv) : 'n.d.') + + (d.tipo ? ' · ' + d.tipo.toLowerCase() : ''); + }) + .catch(function () {}); + + // il costo del pieno: l'unica riga che serve davvero + var tank = S.vehicle.tank, cons = consPer100(); + var pieno = r.prezzo * tank; + var bits = ['' + eur0(pieno) + ' € per ' + tank + ' L']; + if (r.km != null) { + var viaggio = r.km * 2 * cons / 100 * r.prezzo; + bits.push('' + eur0(viaggio) + ' € di viaggio (' + km(r.km) + ' a/r)'); + } + var avg = provAvg(r); + if (avg) { + var diff = (avg - r.prezzo) * tank; + if (Math.abs(diff) >= 0.5) { + bits.push((diff > 0 ? 'risparmi ' : 'paghi ') + eur0(Math.abs(diff)) + ' € sulla media ' + r.provincia); + } + } + $('#d-meta').innerHTML = bits.join('  ·  '); + $('#d-note').textContent = 'Prezzi comunicati al MIMIT il ' + (r.dt || 'n.d.') + '.'; + $('#d-histlabel').textContent = 'Andamento ' + cur; + drawHistory(null); + fetch('/api/history?id=' + r.id + '&carburante=' + encodeURIComponent(S.fuel)) + .then(function (x) { return x.json(); }) + .then(function (rows) { if (current && current.id === hid) drawHistory(rows); }) + .catch(function () {}); + } + + function fuelLabel() { return S.fuel || 'Benzina'; } + + function provAvg(r) { + if (!S.summary) return null; + var hit = S.summary.filter(function (s) { return s.provincia === r.provincia; })[0]; + return hit ? hit.media : null; + } + + function drawHistory(rows) { + var svg = $('#d-hist'), n = $('#d-histn'), wrap = $('#d-histwrap'); + if (!svg) return; + // con meno di 3 rilevazioni una linea non dice niente: meglio niente + var thin = !rows || rows.length < 3; + if (wrap) wrap.style.display = thin ? 'none' : ''; + if (thin) { svg.innerHTML = ''; n.textContent = ''; return; } + var vals = rows.map(function (r) { return r.p; }); + var mn = Math.min.apply(null, vals), mx = Math.max.apply(null, vals); + var span = Math.max(mx - mn, 0.005); + var pad = 4, W = 300, H = 54; + var pts = rows.map(function (r, i) { + var x = rows.length === 1 ? W / 2 : pad + i * (W - pad * 2) / (rows.length - 1); + var y = H - pad - ((r.p - mn) / span) * (H - pad * 2); + return [x, y]; + }); + var line = pts.map(function (p) { return p[0].toFixed(1) + ',' + p[1].toFixed(1); }).join(' '); + var area = '0,' + H + ' ' + line + ' ' + W + ',' + H; + svg.innerHTML = '' + + pts.map(function (p) { return ''; }).join('') + + '' + eur(mn) + '' + + '' + eur(mx) + ''; + n.textContent = rows.length === 1 ? '(1 rilevazione)' : '(' + rows.length + ' rilevazioni)'; + } + + function closeDetail() { + closeModal('#detail'); + S.sel = null; + render(); + } + + // ---------- geo ---------- + // --- stato del prompt posizione --- + function row(k, v) { + return '
  • ' + k + '' + v + '
  • '; + } + + var geoCurrent = null; + + function geoState(state, extra) { + geoCurrent = state; + var st = $('#geo-state'), ti = $('#geo-title'), + bo = $('#geo-body'), ste = $('#geo-steps'), btn = $('#geo-on'), + lab = $('#geo-on-label'), alt = $('#geo-manual'), skip = $('#geo-skip'), + note = $('#geo-note'); + if (!st) return; + var status = st.parentNode; + status.className = 'shd-status'; + ste.innerHTML = ''; + btn.disabled = false; + btn.style.display = 'flex'; + alt.style.display = 'block'; + alt.textContent = 'Scegli un comune'; + note.textContent = extra || ''; + + if (state === 'idle') { + st.textContent = 'Posizione non attiva'; + ti.textContent = 'Dove ti trovi?'; + bo.innerHTML = 'Serve per mettere in cima i distributori piu vicini e calcolare quanto costa arrivarci.'; + lab.textContent = 'Consenti la posizione'; + skip.textContent = 'Non ora'; + ste.innerHTML = row('1', 'Distanza reale da ogni impianto') + + row('2', 'Costo del viaggio, non solo il prezzo al litro') + + row('3', 'Resta sul telefono, non viene salvata'); + } else if (state === 'asking') { + status.className = 'shd-status wait'; + st.textContent = 'In attesa del permesso'; + ti.textContent = 'Conferma nel browser'; + bo.innerHTML = 'Rispondi Consenti alla richiesta appena comparsa. Se non la vedi, controlla le impostazioni del sito.'; + lab.textContent = 'Riprova'; + skip.textContent = 'Annulla'; + btn.disabled = true; + } else if (state === 'ok') { + status.className = 'shd-status ok'; + st.textContent = 'Posizione attiva'; + ti.textContent = 'Ci siamo'; + bo.innerHTML = 'Lista ordinata per distanza. Tocca un impianto per aprirlo nella mappa.'; + lab.textContent = 'Aggiorna'; + skip.textContent = 'Chiudi'; + } else if (state === 'inapp') { + status.className = 'shd-status bad'; + st.textContent = 'Browser non supportato'; + ti.textContent = 'Aprilo in Chrome o Safari'; + bo.innerHTML = 'Stai usando il browser dentro un\'altra app (Telegram, Instagram, Facebook): qui la posizione e bloccata e la richiesta non puo comparire.'; + lab.textContent = 'Copia il link'; + alt.style.display = 'none'; + skip.textContent = 'Continua senza posizione'; + ste.innerHTML = row('1', 'Copia l\'indirizzo') + + row('2', 'Incollalo in Chrome o Safari') + + row('3', 'Concedi la posizione'); + } else if (state === 'denied') { + status.className = 'shd-status bad'; + st.textContent = 'Permesso negato'; + ti.textContent = 'Riattiva la posizione'; + bo.innerHTML = 'Il browser ha un blocco salvato per questo sito e non mostra piu la richiesta. Si toglie dalle impostazioni, poi ricarica.'; + ste.innerHTML = geoDeniedSteps(); + lab.textContent = 'Ho sistemato, ricarica'; + alt.style.display = 'block'; + $('#geo-manual').textContent = 'Intanto scegli un comune'; + skip.textContent = 'Continua senza posizione'; + } else if (state === 'blocked') { + status.className = 'shd-status bad'; + st.textContent = 'Richiesta soppressa'; + ti.textContent = 'Questa pagina non puo chiedere la posizione'; + bo.innerHTML = 'Il browser non ha nemmeno mostrato la richiesta. Succede nei browser dentro le app (Telegram, Instagram) e in alcune versioni di iOS: li la posizione e bloccata a monte.'; + lab.textContent = 'Copia il link'; + alt.style.display = 'block'; + $('#geo-manual').textContent = 'Scegli un comune'; + skip.textContent = 'Continua senza posizione'; + ste.innerHTML = row('1', 'Copia l\'indirizzo con il pulsante qui sopra') + + row('2', 'Incollalo in Chrome o Safari, non dentro l\'app') + + row('3', 'Tocca di nuovo Consenti la posizione'); + } + } + + function geoDeniedSteps() { + var p = platform(); + if (p === 'ios') { + return row('1', 'Tocca aA a sinistra dell\'indirizzo') + + row('2', 'Impostazioni sito → Posizione') + + row('3', 'Scegli Consenti e ricarica'); + } + if (p === 'android') { + return row('1', 'Tocca il lucchetto accanto all\'indirizzo') + + row('2', 'Autorizzazioni → Posizione') + + row('3', 'Scegli Consenti e ricarica'); + } + return row('1', 'Clicca il lucchetto nella barra degli indirizzi') + + row('2', 'Posizione → Consenti') + + row('3', 'Ricarica la pagina'); + } + + var locWatch = null, locAnswered = false; + + function locate(cb) { + if (!navigator.geolocation) { + toast('Questo browser non supporta la geolocalizzazione'); + geoState('denied', 'Browser senza supporto GPS.'); + return; + } + var inapp = inAppBrowser(); + if (inapp) { + geoState('idle', (inapp === 'telegram' + ? 'Sembra che tu stia usando il browser dentro Telegram: la posizione spesso è bloccata. Apri il link in Chrome o Safari. ' + : 'Sembra un browser dentro un\'altra app: la posizione può essere bloccata. Apri il link in Chrome o Safari. ')); + } + geoState('asking'); + locAnswered = false; + clearTimeout(locWatch); + // se il browser non risponde (capita nei webview), non lasciare l'utente in attesa + locWatch = setTimeout(function () { + if (locAnswered) return; + var btn = $('#geo-on'); + if (btn) btn.disabled = false; + var st = $('#geo-state'); + if (st && st.textContent === 'In attesa del permesso') { + geoState('idle', 'Il browser non ha risposto alla richiesta. Se non vedi nessun avviso, controlla le impostazioni del sito o apri la pagina in Chrome/Safari.'); + } + }, 22000); + + navigator.geolocation.getCurrentPosition(onPos, onErr, + { enableHighAccuracy: true, timeout: 12000, maximumAge: 30000 }); + + function onPos(p) { + locAnswered = true; clearTimeout(locWatch); + S.pos = { lat: p.coords.latitude, lon: p.coords.longitude }; + S.posLabel = 'la tua posizione'; + drawMe(S.pos); + if (mapReady) map.setView([S.pos.lat, S.pos.lon], 11); + $('#locbtn').classList.add('on'); + geoState('ok'); + try { localStorage.setItem('benzina.geoask', '1'); } catch (e) {} + load(true); + if (cb) cb(); + setTimeout(function () { + var st = $('#geo-state'); + if (st && st.textContent === 'Posizione attiva') closeModal('#geoprompt'); + }, 1100); + } + + function onErr(e) { + locAnswered = true; clearTimeout(locWatch); + $('#locbtn').classList.remove('on'); + if (e.code === 1) { + geoDenied(e); + return; + } + if (e.code === 3) { + // timeout: riprovo senza alta precisione, che su desktop e lento + geoState('asking', 'Riprovo con precisione minore…'); + navigator.geolocation.getCurrentPosition(onPos, function (e2) { + locAnswered = true; + if (e2.code === 1) { geoState('denied', 'Permesso negato (codice 1).'); return; } + geoState('idle', 'Non riesco a localizzarti (codice ' + e2.code + '). Scegli un comune: è immediato.'); + }, { enableHighAccuracy: false, timeout: 15000, maximumAge: 300000 }); + return; + } + geoState('idle', 'Posizione non disponibile (codice ' + e.code + '). Scegli un comune.'); + } + } + + // codici: 1 PERMISSION_DENIED, 2 POSITION_UNAVAILABLE, 3 TIMEOUT. + // Distinguere "l'utente ha negato" da "l'ambiente non lascia nemmeno + // chiedere" e' la differenza tra mandarlo nelle impostazioni e mandarlo + // in un altro browser. + function geoDenied(e) { + var detail = 'codice ' + e.code + (e.message ? ' (' + e.message + ')' : ''); + var finish = function (perm) { + if (perm === 'denied') { + geoState('denied', detail + ' · permesso memorizzato: negato'); + } else { + geoState('blocked', detail + ' · permesso memorizzato: ' + perm); + } + try { localStorage.setItem('benzina.geoask', '1'); } catch (err) {} + }; + if (navigator.permissions && navigator.permissions.query) { + navigator.permissions.query({ name: 'geolocation' }) + .then(function (s) { finish(s.state); }) + .catch(function () { finish('non leggibile'); }); + } else { + finish('non leggibile'); + } + } + + function showGeoNote(txt) { + var n = $('#geo-note'); + if (n) n.textContent = txt || ''; + } + + function openModal(sel) { var m = $(sel); if (m) m.classList.add('open'); } + function closeModal(sel) { var m = $(sel); if (m) m.classList.remove('open'); } + + // ---------- setup ---------- + function fillModels() { + var sel = $('#vmodel'); + if (!sel) return; + var list = MODELS[S.vehicle.type] || []; + sel.innerHTML = '' + + list.map(function (m, i) { + return ''; + }).join(''); + } + + function openSetup() { + var v = S.vehicle; + fillModels(); + $$('#vtype button').forEach(function (b) { b.setAttribute('aria-pressed', String(b.dataset.v === v.type)); }); + $$('#vunit button').forEach(function (b) { b.setAttribute('aria-pressed', String(b.dataset.u === v.unit)); }); + $$('#vmode button').forEach(function (b) { b.setAttribute('aria-pressed', String(+b.dataset.m === S.self)); }); + $('#vcons').value = String(v.cons).replace('.', ','); + $('#vtank').value = String(v.tank); + $('#setup').classList.add('open'); + } + + function bindSetup() { + $('#setupclose').onclick = function () { $('#setup').classList.remove('open'); }; + $$('#vtype button').forEach(function (b) { + b.onclick = function () { + $$('#vtype button').forEach(function (x) { x.setAttribute('aria-pressed', 'false'); }); + b.setAttribute('aria-pressed', 'true'); + S.vehicle.type = b.dataset.v; + // valori tipici di partenza + if (b.dataset.v === 'moto') { S.vehicle.cons = 4.0; S.vehicle.tank = 15; } + else if (b.dataset.v === 'van') { S.vehicle.cons = 8.5; S.vehicle.tank = 70; } + else { S.vehicle.cons = 5.8; S.vehicle.tank = 50; } + $('#vcons').value = String(S.vehicle.cons).replace('.', ','); + $('#vtank').value = String(S.vehicle.tank); + fillModels(); + }; + }); + $$('#vunit button').forEach(function (b) { + b.onclick = function () { + $$('#vunit button').forEach(function (x) { x.setAttribute('aria-pressed', 'false'); }); + b.setAttribute('aria-pressed', 'true'); + S.vehicle.unit = b.dataset.u; + }; + }); + $$('#vmode button').forEach(function (b) { + b.onclick = function () { + $$('#vmode button').forEach(function (x) { x.setAttribute('aria-pressed', 'false'); }); + b.setAttribute('aria-pressed', 'true'); + S.self = +b.dataset.m; + }; + }); + var msel = $('#vmodel'); + if (msel) msel.onchange = function () { + var idx = msel.value; + if (idx === '') return; + var m = (MODELS[S.vehicle.type] || [])[+idx]; + if (!m) return; + S.vehicle.cons = m[1]; S.vehicle.tank = m[2]; S.vehicle.unit = 'l100'; + $$('#vunit button').forEach(function (x) { + x.setAttribute('aria-pressed', String(x.dataset.u === 'l100')); + }); + $('#vcons').value = String(m[1]).replace('.', ','); + $('#vtank').value = String(m[2]); + toast(m[0] + ': ' + String(m[1]).replace('.', ',') + ' L/100km, serbatoio ' + m[2] + ' L'); + }; + $('#vsave').onclick = function () { + S.vehicle.cons = parseNum($('#vcons').value) || S.vehicle.cons; + S.vehicle.tank = parseNum($('#vtank').value) || S.vehicle.tank; + savePrefs(); + $('#setup').classList.remove('open'); + toast('Veicolo salvato: ' + fmtCons() + ', ' + S.vehicle.tank + ' L'); + load(); + }; + } + + // ---------- filters ---------- + function bindChips() { + $$('.chip[data-sort]').forEach(function (c) { + c.onclick = function () { + $$('.chip[data-sort]').forEach(function (x) { x.setAttribute('aria-pressed', 'false'); }); + c.setAttribute('aria-pressed', 'true'); + S.sort = c.dataset.sort; + if (S.sort !== 'price' && !S.pos) { locate(); } + savePrefs(); load(); + }; + }); + $('#locbtn').onclick = function () { askPosition(); }; + $('#listbtn').onclick = toggleSheet; + $('#sheetclose').onclick = closeSheet; + $('#grab').onclick = closeSheet; + listEl.addEventListener('click', function (e) { + var card = e.target.closest('.card'); + if (!card) return; + var r = S.rows.filter(function (x) { return String(x.id) === card.dataset.id; })[0]; + if (r) openDetail(r); + }); + $('#detail').addEventListener('click', function (e) { + if (e.target.id === 'detail') closeDetail(); + }); + $('#d-close').onclick = closeDetail; + $('#d-vehicle').onclick = function () { closeDetail(); openSetup(); }; + $('#d-share').onclick = function () { + if (!current) return; + var r = current; + var txt = (r.bandiera || r.gestore) + ' — ' + r.comune + ': ' + eur(r.prezzo) + ' €/L (' + + (r.self ? 'self' : 'servito') + ')\n' + + 'https://benzina.feedme.work/?s=' + r.id; + if (navigator.share) { + navigator.share({ title: 'Benzina Abruzzo', text: txt, url: 'https://benzina.feedme.work/?s=' + r.id }) + .catch(function () {}); + } else if (navigator.clipboard) { + navigator.clipboard.writeText(txt).then(function () { toast('Copiato negli appunti'); }); + } else { toast('Condivisione non disponibile'); } + }; + var vb = $('#vbtn'); + if (vb) vb.onclick = openSetup; + } + + // ---------- PWA / installazione ---------- + var LS_INST = 'benzina.installsnooze'; + var installEvt = null, installCtx = null; + + function isStandalone() { + return window.matchMedia('(display-mode: standalone)').matches || + window.matchMedia('(display-mode: fullscreen)').matches || + navigator.standalone === true; + } + + function inAppBrowser() { + var ua = navigator.userAgent || ''; + if (/FBAN|FBAV|Instagram|Line\/|Twitter|LinkedInApp|Pinterest/i.test(ua)) return 'social'; + if (/Telegram/i.test(ua)) return 'telegram'; + if (/; wv\)/i.test(ua)) return 'webview'; + return ''; + } + + function platform() { + var ua = navigator.userAgent; + if (/iphone|ipad|ipod/i.test(ua)) return 'ios'; + if (/android/i.test(ua)) return 'android'; + if (/windows|macintosh|linux/i.test(ua)) return 'desktop'; + return 'other'; + } + + // 0 = non chiedere piu (solo se ha cliccato "Non ora") + function installSnoozed() { + try { return localStorage.getItem(LS_INST) === '1'; } catch (e) { return false; } + } + function snoozeInstall() { + try { localStorage.setItem(LS_INST, '1'); } catch (e) {} + } + + function installStepsHTML(p, canPrompt) { + if (canPrompt) return ''; + if (p === 'ios') { + return row('1', 'Apri questa pagina in Safari') + + row('2', 'Tocca Condividi in basso') + + row('3', 'Scegli Aggiungi a Home'); + } + if (p === 'android') { + return row('1', 'Apri il menu ⋮ del browser') + + row('2', 'Tocca Installa app') + + row('3', 'Conferma'); + } + return row('1', 'Icona installa nella barra degli indirizzi') + + row('2', 'Oppure menu del browser → Installa'); + } + + function showInstallPrompt(ctx) { + installCtx = ctx || 'auto'; + var p = platform(); + var canPrompt = !!installEvt; + var st = $('#install-state'), ti = $('#install-title'), bo = $('#install-body'), + ste = $('#install-steps'), go = $('#install-go'), + later = $('#install-later'), status = st.parentNode; + + status.className = 'shd-status'; + ste.innerHTML = ''; + go.style.display = 'flex'; + + if (canPrompt) { + st.textContent = 'Pronta da installare'; + ti.textContent = 'Tienila in home'; + bo.innerHTML = 'Un tocco e la trovi tra le app: si apre a schermo intero e funziona anche senza rete.'; + ste.innerHTML = row('1', 'A schermo intero, senza barra del browser') + + row('2', 'Ultimi prezzi anche offline') + + row('3', 'Si disinstalla come qualsiasi app'); + go.textContent = 'Installa l\'app'; + later.textContent = 'Non ora'; + } else { + st.textContent = p === 'ios' ? 'Aggiungi a Home' : 'Installazione manuale'; + ti.textContent = p === 'ios' ? 'Tre tocchi in Safari' : 'Dal menu del browser'; + bo.innerHTML = p === 'ios' + ? 'Safari non mostra un pulsante automatico: si aggiunge dalla schermata di condivisione.' + : 'Il tuo browser non offre il pulsante automatico: si installa dal menu.'; + ste.innerHTML = installStepsHTML(p, false); + go.textContent = 'Ho capito'; + later.textContent = 'Non ora'; + } + openModal('#install'); + } + + function bindInstall() { + var ix = $('#install-x'); + if (ix) ix.onclick = function () { snoozeInstall(); closeModal('#install'); }; + var go = $('#install-go'); + if (go) go.onclick = function () { + if (!installEvt) { snoozeInstall(); closeModal('#install'); return; } + var e = installEvt; + installEvt = null; + e.prompt(); + e.userChoice.then(function (res) { + closeModal('#install'); + if (res.outcome === 'accepted') toast('App installata'); + }).catch(function () { closeModal('#install'); }); + }; + var later = $('#install-later'); + if (later) later.onclick = function () { + snoozeInstall(); + closeModal('#install'); + }; + var m = $('#install'); + if (m) m.addEventListener('click', function (e) { + if (e.target.id === 'install') { snoozeInstall(); closeModal('#install'); } + }); + window.addEventListener('beforeinstallprompt', function (e) { + e.preventDefault(); + installEvt = e; + var steps = $('#install-steps'); + if (steps) steps.innerHTML = ''; + var go = $('#install-go'); + if (go) go.style.display = 'flex'; + var later = $('#install-later'); + if (later) later.textContent = 'Non ora'; + }); + window.addEventListener('appinstalled', function () { + installEvt = null; + closeModal('#install'); + try { localStorage.setItem(LS_INST, '1'); } catch (e) {} + toast('App installata: la trovi nella schermata home'); + }); + } + + function maybeAskInstall() { + if (isStandalone()) return; + if (installSnoozed()) return; + // non sovrapporre al prompt posizione + if (document.querySelector('#geoprompt.open')) { + setTimeout(maybeAskInstall, 4000); + return; + } + showInstallPrompt('auto'); + } + + // ---------- filtri ---------- + function updateFilterBadge() { + var act = (S.band ? 1 : 0) + (S.prov ? 1 : 0) + (S.comune ? 1 : 0) + (S.self ? 1 : 0); + var fc = $('#filterchip'), bd = $('#fcount'); + if (bd) { + bd.textContent = act; + bd.className = act ? 'badge-dot on' : 'badge-dot'; + } + if (fc) fc.setAttribute('aria-pressed', act ? 'true' : 'false'); + } + + function openFilters() { + var f = $('#f-fuel'); + f.innerHTML = (S.carburanti || ['Benzina']).map(function (x) { + return '' + x + ''; + }).join(''); + var b = $('#f-band'); + b.innerHTML = '' + + (S.bandiere || []).map(function (x) { + return ''; + }).join(''); + var p = $('#f-prov'); + p.innerHTML = '' + + ['AQ', 'CH', 'PE', 'TE'].map(function (x) { + return ''; + }).join(''); + $('#f-common').value = S.comune || ''; + $$('#f-mode button').forEach(function (x) { + x.setAttribute('aria-pressed', String(+x.dataset.m === S.self)); + }); + openModal('#filters'); + } + + function bindFilters() { + $('#filterchip').onclick = openFilters; + $('#filtersclose').onclick = function () { closeModal('#filters'); }; + $$('#f-mode button').forEach(function (b) { + b.onclick = function () { + $$('#f-mode button').forEach(function (x) { x.setAttribute('aria-pressed', 'false'); }); + b.setAttribute('aria-pressed', 'true'); + }; + }); + var fi = $('#f-install'); + if (fi) fi.onclick = function () { + closeModal('#filters'); + try { localStorage.removeItem('benzina.installsnooze'); } catch (e) {} + showInstallPrompt('manual'); + }; + $('#f-reset').onclick = function () { + $('#f-fuel').value = 'Benzina'; + $('#f-band').value = ''; + $('#f-prov').value = ''; + $('#f-common').value = ''; + $$('#f-mode button')[0].click(); + }; + $('#f-apply').onclick = function () { + S.fuel = $('#f-fuel').value; + S.band = $('#f-band').value; + S.prov = $('#f-prov').value; + S.comune = $('#f-common').value.trim(); + var on = $$('#f-mode button').filter(function (x) { return x.getAttribute('aria-pressed') === 'true'; })[0]; + S.self = on ? +on.dataset.m : 0; + savePrefs(); + closeModal('#filters'); + updateFilterBadge(); + load(true); + toast(labelFilters()); + }; + $('#filters').addEventListener('click', function (e) { + if (e.target.id === 'filters') closeModal('#filters'); + }); + } + + function labelFilters() { + var bits = [S.fuel]; + if (S.band) bits.push(S.band); + if (S.prov) bits.push(S.prov); + if (S.comune) bits.push(S.comune); + if (S.self) bits.push('solo self'); + return bits.join(' · '); + } + + // ---------- prompt posizione ---------- + function bindGeoPrompt() { + var gx = $('#geo-x'); + if (gx) gx.onclick = function () { + try { localStorage.setItem('benzina.geoask', '1'); } catch (e) {} + closeModal('#geoprompt'); + }; + $('#geo-on').onclick = function () { + showGeoNote(''); + if (geoCurrent === 'inapp' || geoCurrent === 'blocked') { + copyLink(); + return; + } + if (geoCurrent === 'denied') { + location.reload(); + return; + } + // sincrono, stesso frame del click: e' quello che sblocca il prompt iOS + locate(); + }; + $('#geo-manual').onclick = function () { + try { localStorage.setItem('benzina.geoask', '1'); } catch (e) {} + closeModal('#geoprompt'); + openFilters(); + setTimeout(function () { $('#f-common').focus(); }, 400); + }; + $('#geo-skip').onclick = function () { + closeModal('#geoprompt'); + try { localStorage.setItem('benzina.geoask', '1'); } catch (e) {} + }; + $('#geoprompt').addEventListener('click', function (e) { + if (e.target.id === 'geoprompt') closeModal('#geoprompt'); + }); + } + + function copyLink() { + var url = location.origin + location.pathname; + var done = function () { toast('Link copiato: incollalo in Chrome o Safari', 4200); }; + var fallback = function () { window.prompt('Copia il link e aprilo in Chrome o Safari:', url); }; + var ok = false; + try { + if (navigator.clipboard && navigator.clipboard.writeText) { + var p = navigator.clipboard.writeText(url); + // se il browser non risponde (webview/permessi) non aspettiamo in eterno + var guard = new Promise(function (res) { setTimeout(function () { res('timeout'); }, 1500); }); + Promise.race([p.then(function () { ok = true; }), guard]).then(function () { + if (ok) done(); else fallback(); + }).catch(fallback); + return; + } + } catch (e) {} + fallback(); + } + + // ATTENZIONE: getCurrentPosition deve partire DENTRO il gestore del click, + // in modo sincrono. Safari (e iOS in generale) annulla la richiesta se la + // chiamata avviene dopo un await/promise: risponde subito con errore 1 senza + // mostrare il prompt. Per questo qui non si interroga permissions.query. + function askPosition() { + if (inAppBrowser()) { geoState('inapp'); openModal('#geoprompt'); return; } + locate(); + } + + function maybeAskGeo() { + if (!navigator.geolocation) return; + if (inAppBrowser()) { geoState('inapp'); openModal('#geoprompt'); return; } + if (location.protocol !== 'https:' && location.hostname !== 'localhost') { + geoState('denied', 'Serve HTTPS per chiedere la posizione.'); + openModal('#geoprompt'); + return; + } + if (navigator.permissions && navigator.permissions.query) { + navigator.permissions.query({ name: 'geolocation' }).then(function (st) { + if (st.state === 'granted') { locate(); return; } + if (st.state === 'denied') { geoState('denied'); openModal('#geoprompt'); return; } + geoState('idle'); + openModal('#geoprompt'); + }).catch(function () { geoState('idle'); openModal('#geoprompt'); }); + } else { + geoState('idle'); + openModal('#geoprompt'); + } + } + + // ---------- boot ---------- + function boot() { + listEl = $('#list'); sheet = $('#sheet'); + bindInfiniteList(); + loadPrefs(); + initMap(); + bindSetup(); + bindChips(); + $$('.chip[data-sort]').forEach(function (x) { + x.setAttribute('aria-pressed', String(x.dataset.sort === S.sort)); + }); + fetch('/api/meta').then(function (r) { return r.json(); }).then(function (d) { + S.carburanti = d.carburanti || []; + S.bandiere = d.bandiere || []; + var dl = $('#comuni-list'); + if (dl) { + fetch('/api/comuni').then(function (x) { return x.json(); }).then(function (cs) { + dl.innerHTML = cs.map(function (c) { return '