diff --git a/Dockerfile b/Dockerfile
index 53f50a8..8da08c5 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -14,6 +14,11 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
WORKDIR /app
+# ca-certificates: urllib needs them to reach the Tjek API over HTTPS
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends ca-certificates \
+ && rm -rf /var/lib/apt/lists/*
+
RUN pip install --upgrade --no-cache-dir pip
COPY requirements.txt ./
diff --git a/app.py b/app.py
index 2badd70..22167a3 100644
--- a/app.py
+++ b/app.py
@@ -1,10 +1,15 @@
import sqlite3
import os
import re
+import json
+import time
+import threading
import unicodedata
import socket
+import urllib.request
+import urllib.error
from pathlib import Path
-from datetime import datetime
+from datetime import datetime, timezone
from flask import Flask, render_template, request, jsonify, send_from_directory
app = Flask(__name__)
@@ -13,6 +18,17 @@ UPLOAD_DIR = DATA_DIR / "uploads"
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
DB = str(DATA_DIR / "data.db")
+# --- Tjek (ShopGun) API: live CITTI offer prices ------------------------------
+# Only Lübeck: the German dealer 3czmZx (cittimarkt.de) covers Flensburg/Kiel/
+# Lübeck with all_stores catalogs, so its EUR prices ARE the Lübeck prices.
+# The Danish dealer 9f097g (citti.dk "Fordelshæfte") is deliberately NOT used.
+TJEK_API = "https://squid-api.tjek.com/v2"
+TJEK_DEALER = os.environ.get("TJEK_DEALER_ID", "3czmZx")
+TJEK_UA = ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
+ "(KHTML, like Gecko) Chrome/120.0 Safari/537.36")
+EUR_DKK = float(os.environ.get("EUR_DKK", "7.46"))
+OFFERS_REFRESH_HOURS = float(os.environ.get("OFFERS_REFRESH_HOURS", "20"))
+
SECTIONS = [
{"id": "koed", "emoji": "🥩", "title": "Kød & fisk", "est": 1580, "varer": [
{"key": "entrecote", "name": "Entrecote ½ kg", "de": "Entrecôte ½ kg", "note": "Frisk sydamerikansk", "qty": "6 × ½ kg", "est": 605.94, "badges": ["card"]},
@@ -89,6 +105,21 @@ SECTIONS = [
]
+ITEM_BY_KEY = {v['key']: v for sec in SECTIONS for v in sec['varer']}
+
+
+def compute_totals(saved):
+ """Sum af katalogets estimater og indtastede faktiske priser."""
+ total_est = total_actual = 0
+ for sec in SECTIONS:
+ for item in sec['varer']:
+ total_est += item['est']
+ actual = saved.get(item['key'], {}).get('price')
+ if actual:
+ total_actual += actual
+ return total_est, total_actual
+
+
def slugify(text):
text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode()
return re.sub(r'[-\s]+', '-', re.sub(r'[^\w\s-]', '', text.lower())).strip('-')
@@ -111,6 +142,22 @@ def init_db():
c.execute("""CREATE TABLE IF NOT EXISTS custom_sections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
emoji TEXT DEFAULT '📦', title TEXT, created TEXT)""")
+ c.execute("""CREATE TABLE IF NOT EXISTS trips (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ label TEXT, archived TEXT,
+ total_est REAL, total_actual REAL, item_count INTEGER,
+ snapshot TEXT)""")
+ c.execute("""CREATE TABLE IF NOT EXISTS offers (
+ id TEXT PRIMARY KEY,
+ catalog TEXT, catalog_id TEXT, heading TEXT,
+ price_eur REAL, pre_price_eur REAL,
+ unit TEXT, size_from REAL, size_to REAL,
+ pieces_from INTEGER, pieces_to INTEGER,
+ page INTEGER, run_from TEXT, run_till TEXT,
+ fetched_at TEXT,
+ picked INTEGER DEFAULT 0)""")
+ c.execute("""CREATE TABLE IF NOT EXISTS offer_meta (
+ k TEXT PRIMARY KEY, v TEXT)""")
try:
c.execute("ALTER TABLE extras ADD COLUMN section_key TEXT")
except Exception:
@@ -121,17 +168,227 @@ def init_db():
pass
+# --- Offer fetching -----------------------------------------------------------
+
+def _meta_get(c, k, default=None):
+ row = c.execute("SELECT v FROM offer_meta WHERE k=?", (k,)).fetchone()
+ return row['v'] if row else default
+
+
+def _meta_set(c, k, v):
+ c.execute("INSERT INTO offer_meta(k,v) VALUES(?,?) "
+ "ON CONFLICT(k) DO UPDATE SET v=excluded.v", (k, str(v)))
+
+
+def _tjek_get(path):
+ url = f"{TJEK_API}{path}"
+ req = urllib.request.Request(url, headers={
+ 'User-Agent': TJEK_UA, 'Accept': 'application/json'})
+ with urllib.request.urlopen(req, timeout=20) as resp:
+ return json.loads(resp.read().decode('utf-8'))
+
+
+def _parse_offer(h):
+ """Map one hotspot dict to our offers row, defensively."""
+ o = h.get('offer') or {}
+ pricing = o.get('pricing') or {}
+ qty = o.get('quantity') or {}
+ unit = ((qty.get('unit') or {}).get('symbol'))
+ size = qty.get('size') or {}
+ pieces = qty.get('pieces') or {}
+ locations = h.get('locations') or {}
+ page = None
+ if locations:
+ try:
+ page = min(int(k) for k in locations.keys())
+ except (ValueError, TypeError):
+ page = None
+ oid = o.get('id') or h.get('id')
+ if not oid or pricing.get('price') is None:
+ return None
+ return {
+ 'id': oid,
+ 'heading': o.get('heading') or h.get('heading'),
+ 'price_eur': pricing.get('price'),
+ 'pre_price_eur': pricing.get('pre_price'),
+ 'unit': unit,
+ 'size_from': size.get('from'), 'size_to': size.get('to'),
+ 'pieces_from': pieces.get('from'), 'pieces_to': pieces.get('to'),
+ 'page': page,
+ 'run_from': o.get('run_from'), 'run_till': o.get('run_till'),
+ }
+
+
+def fetch_offers():
+ """Fetch current Lübeck (dealer 3czmZx) catalogs + offers. Returns summary."""
+ now_iso = datetime.now(timezone.utc).isoformat()
+ catalogs = _tjek_get(
+ f"/catalogs?dealer_id={TJEK_DEALER}"
+ "&order_by=-publication_date&limit=24&types=paged,incito")
+ seen = set()
+ fetched_cats = set()
+ cat_count = 0
+ with get_db() as c:
+ for cat in catalogs:
+ cat_id = cat.get('id')
+ if not cat_id:
+ continue
+ label = cat.get('label') or cat_id
+ try:
+ hotspots = _tjek_get(f"/catalogs/{cat_id}/hotspots")
+ except Exception as e:
+ app.logger.warning("citti offers: hotspots failed for %s: %s", cat_id, e)
+ continue
+ fetched_cats.add(cat_id)
+ cat_count += 1
+ for h in hotspots:
+ if h.get('type') != 'offer':
+ continue
+ row = _parse_offer(h)
+ if not row:
+ continue
+ seen.add(row['id'])
+ c.execute("""INSERT INTO offers(
+ id,catalog,catalog_id,heading,price_eur,pre_price_eur,
+ unit,size_from,size_to,pieces_from,pieces_to,page,
+ run_from,run_till,fetched_at)
+ VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
+ ON CONFLICT(id) DO UPDATE SET
+ catalog=excluded.catalog, catalog_id=excluded.catalog_id,
+ heading=excluded.heading, price_eur=excluded.price_eur,
+ pre_price_eur=excluded.pre_price_eur, unit=excluded.unit,
+ size_from=excluded.size_from, size_to=excluded.size_to,
+ pieces_from=excluded.pieces_from, pieces_to=excluded.pieces_to,
+ page=excluded.page, run_from=excluded.run_from,
+ run_till=excluded.run_till, fetched_at=excluded.fetched_at""",
+ (row['id'], label, cat_id, row['heading'], row['price_eur'],
+ row['pre_price_eur'], row['unit'], row['size_from'], row['size_to'],
+ row['pieces_from'], row['pieces_to'], row['page'],
+ row['run_from'], row['run_till'], now_iso))
+ # Prune offers that vanished from a catalog we actually re-fetched, but
+ # keep picked ones (never silently empty an in-progress list) and never
+ # touch catalogs whose fetch failed this run.
+ if seen and fetched_cats:
+ sp = ','.join('?' * len(seen))
+ cp = ','.join('?' * len(fetched_cats))
+ c.execute(
+ f"DELETE FROM offers WHERE picked=0 AND catalog_id IN ({cp}) "
+ f"AND id NOT IN ({sp})",
+ tuple(fetched_cats) + tuple(seen))
+ total = c.execute("SELECT COUNT(*) FROM offers").fetchone()[0]
+ _meta_set(c, 'last_refresh', now_iso)
+ _meta_set(c, 'last_error', '')
+ return {'catalogs': cat_count, 'offers_seen': len(seen), 'offers_total': total}
+
+
+def refresh_offers_safe():
+ try:
+ summary = fetch_offers()
+ app.logger.info("citti offers refreshed: %s", summary)
+ return summary
+ except Exception as e:
+ app.logger.warning("citti offers refresh failed: %s", e)
+ try:
+ with get_db() as c:
+ _meta_set(c, 'last_error', f"{datetime.now(timezone.utc).isoformat()}: {e}")
+ except Exception:
+ pass
+ return None
+
+
+def _offers_stale():
+ with get_db() as c:
+ last = _meta_get(c, 'last_refresh')
+ if not last:
+ return True
+ try:
+ dt = datetime.fromisoformat(last)
+ age = (datetime.now(timezone.utc) - dt).total_seconds()
+ return age > OFFERS_REFRESH_HOURS * 3600
+ except Exception:
+ return True
+
+
+def _offer_scheduler():
+ """Daily in-process refresh. The app's data.db lives on its own Nomad alloc
+ disk, so the job must run inside this process rather than as a separate job."""
+ while True:
+ if _offers_stale():
+ refresh_offers_safe()
+ time.sleep(3600)
+
+
+def start_offer_scheduler():
+ t = threading.Thread(target=_offer_scheduler, name="offer-scheduler", daemon=True)
+ t.start()
+
+
+# --- Match fixed catalog items against current offers -------------------------
+
+_MATCH_STOP = {
+ 'kg', 'g', 'l', 'ml', 'cl', 'stk', 'stck', 'stuck', 'dose', 'dosen',
+ 'glas', 'premium', 'frisch', 'frische', 'frisches', 'frischer', 'original',
+ 'extra', 'vergine', 'qualitatswein', 'und', 'mit', 'der', 'die', 'das',
+ 'natur', 'oder', 'variant', 'blandede', 'hvad', 'ellers', 'frister',
+ 'skiver', 'frost', 'frisk', 'nach', 'wahl', 'sonst', 'verlockend', 'mild',
+}
+
+
+def _norm(s):
+ s = (s or '').lower().replace('ß', 'ss')
+ return unicodedata.normalize('NFKD', s).encode('ascii', 'ignore').decode()
+
+
+def _match_tokens(s):
+ return [t for t in re.split(r'[^a-z0-9]+', _norm(s))
+ if len(t) >= 4 and not t.isdigit() and t not in _MATCH_STOP]
+
+
+def _wb(token, text):
+ return re.search(r'(?=2 tokens for multi-word names."""
+ prepped = [(o, _norm(o.get('heading'))) for o in offers]
+ deals = {}
+ for item in ITEM_BY_KEY.values():
+ toks = _match_tokens(item.get('de') or item['name'])
+ if not toks:
+ continue
+ need = 2 if len(toks) >= 2 else 1
+ if need == 1 and len(toks[0]) < 5:
+ continue
+ best = None
+ best_rank = None
+ for o, h in prepped:
+ n = sum(1 for t in toks if _wb(t, h))
+ if n >= need:
+ rank = (-n, o.get('price_eur') or 1e9)
+ if best_rank is None or rank < best_rank:
+ best, best_rank = o, rank
+ if best:
+ deals[item['key']] = best
+ return deals
+
+
@app.route('/')
def index():
with get_db() as c:
saved = {r['key']: dict(r) for r in c.execute("SELECT * FROM prices")}
extras = [dict(r) for r in c.execute("SELECT * FROM extras ORDER BY created DESC")]
custom_secs = [dict(r) for r in c.execute("SELECT * FROM custom_sections ORDER BY created")]
+ picks = [dict(r) for r in c.execute(
+ "SELECT * FROM offers WHERE picked=1 ORDER BY catalog, heading")]
+ all_offers = [dict(r) for r in c.execute("SELECT * FROM offers")]
by_sec = {}
for e in extras:
by_sec.setdefault(e.get('section_key') or '', []).append(e)
+ deals = match_catalog_offers(all_offers) if all_offers else {}
return render_template('index.html', sections=SECTIONS, saved=saved,
- by_sec=by_sec, custom_secs=custom_secs)
+ by_sec=by_sec, custom_secs=custom_secs,
+ picks=picks, eur_dkk=EUR_DKK, deals=deals)
@app.route('/api/price', methods=['POST'])
@@ -229,6 +486,195 @@ def delete_category(cat_id):
return jsonify(ok=True)
+MONTHS_DA = ['jan', 'feb', 'mar', 'apr', 'maj', 'jun',
+ 'jul', 'aug', 'sep', 'okt', 'nov', 'dec']
+
+
+def _trip_label(dt):
+ return f"{dt.day}. {MONTHS_DA[dt.month - 1]} {dt.year}"
+
+
+@app.route('/api/archive', methods=['POST'])
+def archive_trip():
+ with get_db() as c:
+ prices = [dict(r) for r in c.execute("SELECT * FROM prices")]
+ extras = [dict(r) for r in c.execute("SELECT * FROM extras ORDER BY created DESC")]
+ custom_secs = [dict(r) for r in c.execute("SELECT * FROM custom_sections ORDER BY created")]
+
+ checked = [p for p in prices if p.get('checked')]
+ touched = [p for p in prices if p.get('checked') or p.get('price') or p.get('qty')]
+ if not touched and not extras and not custom_secs:
+ return jsonify(ok=False, empty=True)
+
+ for p in prices:
+ item = ITEM_BY_KEY.get(p['key'])
+ if item:
+ p['name'] = item['name']
+ p['de'] = item.get('de')
+ p['est'] = item['est']
+
+ saved = {p['key']: p for p in prices}
+ total_est, total_actual = compute_totals(saved)
+ total_actual += sum(e['price'] for e in extras if e.get('price'))
+ item_count = len(checked) + len(extras)
+
+ now = datetime.now()
+ snapshot = json.dumps({
+ 'prices': prices, 'extras': extras, 'custom_sections': custom_secs})
+ row = c.execute(
+ """INSERT INTO trips(label,archived,total_est,total_actual,item_count,snapshot)
+ VALUES(?,?,?,?,?,?)""",
+ (_trip_label(now), now.isoformat(), total_est,
+ total_actual or None, item_count, snapshot))
+ trip_id = row.lastrowid
+
+ c.execute("DELETE FROM prices")
+ c.execute("DELETE FROM extras")
+ c.execute("DELETE FROM custom_sections")
+
+ return jsonify(ok=True, trip_id=trip_id)
+
+
+@app.route('/historik')
+def historik():
+ with get_db() as c:
+ trips = [dict(r) for r in c.execute(
+ "SELECT id,label,archived,total_est,total_actual,item_count "
+ "FROM trips ORDER BY id DESC")]
+ return render_template('historik.html', trips=trips)
+
+
+@app.route('/historik/Citti Historik
+
diff --git a/templates/koeb_nu.html b/templates/koeb_nu.html new file mode 100644 index 0000000..e862d45 --- /dev/null +++ b/templates/koeb_nu.html @@ -0,0 +1,160 @@ + + +
+ + +
+ + + +
+