feat(offers): live Lübeck offer prices with pick-to-list and deal matching

Fetch CITTI Lübeck offers from the Tjek API (German dealer 3czmZx only —
never the Danish Flensburg booklet) and surface them in the app.

- New offers + offer_meta tables; defensive hotspots parser; upsert by
  offer id, prune per re-fetched catalog while preserving picked rows
- Daily in-process refresh scheduler (data.db lives on the app's own
  Nomad alloc disk, so a separate periodic job can't share it) plus a
  manual POST /api/offers/refresh and an "Opdater" button
- /tilbud page: browse all offers by catalog, search, EUR + DKK, and tick
  offers onto the shopping list; picks appear in a Lübeck-tilbud section
  on the main list and check off as bought via the existing /api/price
- Match the fixed catalog items against current offers and show a
  "på tilbud" badge with the matched offer name (conservative word-
  boundary token match, >=2 tokens for multi-word names)
- Dockerfile: add ca-certificates for urllib HTTPS to the Tjek API
This commit is contained in:
Henrik Jess Nielsen
2026-10-30 10:35:43 +01:00
parent cf999ae228
commit 65a99d2138
4 changed files with 498 additions and 2 deletions

View File

@@ -14,6 +14,11 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
WORKDIR /app 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 RUN pip install --upgrade --no-cache-dir pip
COPY requirements.txt ./ COPY requirements.txt ./

282
app.py
View File

@@ -2,10 +2,14 @@ import sqlite3
import os import os
import re import re
import json import json
import time
import threading
import unicodedata import unicodedata
import socket import socket
import urllib.request
import urllib.error
from pathlib import Path from pathlib import Path
from datetime import datetime from datetime import datetime, timezone
from flask import Flask, render_template, request, jsonify, send_from_directory from flask import Flask, render_template, request, jsonify, send_from_directory
app = Flask(__name__) app = Flask(__name__)
@@ -14,6 +18,17 @@ UPLOAD_DIR = DATA_DIR / "uploads"
UPLOAD_DIR.mkdir(parents=True, exist_ok=True) UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
DB = str(DATA_DIR / "data.db") 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 = [ SECTIONS = [
{"id": "koed", "emoji": "🥩", "title": "Kød & fisk", "est": 1580, "varer": [ {"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"]}, {"key": "entrecote", "name": "Entrecote ½ kg", "de": "Entrecôte ½ kg", "note": "Frisk sydamerikansk", "qty": "6 × ½ kg", "est": 605.94, "badges": ["card"]},
@@ -132,6 +147,17 @@ def init_db():
label TEXT, archived TEXT, label TEXT, archived TEXT,
total_est REAL, total_actual REAL, item_count INTEGER, total_est REAL, total_actual REAL, item_count INTEGER,
snapshot TEXT)""") 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: try:
c.execute("ALTER TABLE extras ADD COLUMN section_key TEXT") c.execute("ALTER TABLE extras ADD COLUMN section_key TEXT")
except Exception: except Exception:
@@ -142,17 +168,227 @@ def init_db():
pass 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'(?<![a-z0-9])' + re.escape(token) + r'(?![a-z0-9])', text) is not None
def match_catalog_offers(offers):
"""Return {item_key: offer} for fixed catalog items currently on offer.
Conservative: word-boundary token match, >=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('/') @app.route('/')
def index(): def index():
with get_db() as c: with get_db() as c:
saved = {r['key']: dict(r) for r in c.execute("SELECT * FROM prices")} 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")] 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")] 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 = {} by_sec = {}
for e in extras: for e in extras:
by_sec.setdefault(e.get('section_key') or '', []).append(e) 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, 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']) @app.route('/api/price', methods=['POST'])
@@ -339,6 +575,47 @@ def historik_trip(trip_id):
by_sec=by_sec, loose_extras=by_sec.get('', [])) by_sec=by_sec, loose_extras=by_sec.get('', []))
@app.route('/tilbud')
def tilbud():
with get_db() as c:
offers = [dict(r) for r in c.execute(
"SELECT * FROM offers ORDER BY catalog, heading")]
last_refresh = _meta_get(c, 'last_refresh')
last_error = _meta_get(c, 'last_error')
by_cat = {}
for o in offers:
by_cat.setdefault(o.get('catalog') or 'Øvrige', []).append(o)
picked_count = sum(1 for o in offers if o.get('picked'))
return render_template('tilbud.html', by_cat=by_cat, eur_dkk=EUR_DKK,
last_refresh=last_refresh, last_error=last_error,
total=len(offers), picked_count=picked_count)
@app.route('/api/offers/pick', methods=['POST'])
def offer_pick():
d = request.json or {}
oid = d.get('id')
picked = 1 if d.get('picked') else 0
if not oid:
return jsonify(error='missing id'), 400
with get_db() as c:
cur = c.execute("UPDATE offers SET picked=? WHERE id=?", (picked, oid))
if cur.rowcount == 0:
return jsonify(error='unknown offer'), 404
# Dropping from the list also clears any bought-state on it.
if not picked:
c.execute("DELETE FROM prices WHERE key=?", (oid,))
return jsonify(ok=True)
@app.route('/api/offers/refresh', methods=['POST'])
def offer_refresh():
summary = refresh_offers_safe()
if summary is None:
return jsonify(ok=False, error='refresh failed'), 502
return jsonify(ok=True, **summary)
@app.route('/analyse') @app.route('/analyse')
def analyse(): def analyse():
with get_db() as c: with get_db() as c:
@@ -375,6 +652,7 @@ def analyse():
if __name__ == '__main__': if __name__ == '__main__':
init_db() init_db()
start_offer_scheduler()
port = int(os.environ.get('PORT', 9756)) port = int(os.environ.get('PORT', 9756))
try: try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

View File

@@ -60,6 +60,7 @@
.badge { display: inline-block; font-size: 9px; padding: 1px 5px; border-radius: 3px; margin-left: 5px; vertical-align: middle; font-weight: 500; } .badge { display: inline-block; font-size: 9px; padding: 1px 5px; border-radius: 3px; margin-left: 5px; vertical-align: middle; font-weight: 500; }
.badge-card { background: var(--blue-light); color: var(--blue); } .badge-card { background: var(--blue-light); color: var(--blue); }
.badge-kasse { background: var(--amber-light); color: var(--amber); } .badge-kasse { background: var(--amber-light); color: var(--amber); }
.item-name .deal { font-size: 11px; color: var(--green); background: var(--green-light); display: inline-block; margin-top: 3px; padding: 2px 7px; border-radius: 5px; font-weight: 600; text-decoration: none; line-height: 1.3; }
.item-qty { padding: 0.35rem 0.4rem; } .item-qty { padding: 0.35rem 0.4rem; }
.item-qty input { width: 100%; border: 1px solid var(--border); border-radius: 5px; padding: 6px 5px; font-size: 11px; font-family: var(--mono); background: var(--bg); color: var(--muted); text-align: center; outline: none; transition: border-color 0.15s, background 0.15s; cursor: text; min-height: 32px; } .item-qty input { width: 100%; border: 1px solid var(--border); border-radius: 5px; padding: 6px 5px; font-size: 11px; font-family: var(--mono); background: var(--bg); color: var(--muted); text-align: center; outline: none; transition: border-color 0.15s, background 0.15s; cursor: text; min-height: 32px; }
.item-qty input:focus { border-color: var(--accent); background: white; color: var(--text); } .item-qty input:focus { border-color: var(--accent); background: white; color: var(--text); }
@@ -174,6 +175,7 @@
<div class="header-actions"> <div class="header-actions">
<div style="display:flex;gap:8px;flex-wrap:wrap"> <div style="display:flex;gap:8px;flex-wrap:wrap">
<button class="btn btn-cat" onclick="openCatModal()">+ Kategori</button> <button class="btn btn-cat" onclick="openCatModal()">+ Kategori</button>
<a href="/tilbud" class="btn">🏷 Tilbud</a>
<a href="/analyse" class="btn">📊 Analyse</a> <a href="/analyse" class="btn">📊 Analyse</a>
<a href="/historik" class="btn">🕑 Historik</a> <a href="/historik" class="btn">🕑 Historik</a>
<button class="btn" onclick="openArchiveModal()">🗂 Arkivér & ny liste</button> <button class="btn" onclick="openArchiveModal()">🗂 Arkivér & ny liste</button>
@@ -234,6 +236,8 @@
{% if item.get('badges') %}{% for b in item.badges %}{% if b == 'card' %}<span class="badge badge-card">CITTI CARD</span>{% endif %}{% if b == 'kasse' %}<span class="badge badge-kasse">Hel kasse</span>{% endif %}{% endfor %}{% endif %} {% if item.get('badges') %}{% for b in item.badges %}{% if b == 'card' %}<span class="badge badge-card">CITTI CARD</span>{% endif %}{% if b == 'kasse' %}<span class="badge badge-kasse">Hel kasse</span>{% endif %}{% endfor %}{% endif %}
{% if item.get('de') %}<span class="de">🇩🇪 {{ item.de }}</span>{% endif %} {% if item.get('de') %}<span class="de">🇩🇪 {{ item.de }}</span>{% endif %}
{% if item.get('note') %}<span class="note">{{ item.note }}</span>{% endif %} {% if item.get('note') %}<span class="note">{{ item.note }}</span>{% endif %}
{% set d = deals.get(item.key) %}
{% if d %}<a class="deal" href="/tilbud" title="{{ d.heading }} ({{ d.catalog }})">🏷 på tilbud: {{ "{:.2f}".format(d.price_eur).replace(".",",") }} € ≈ {{ "{:.0f}".format(d.price_eur * eur_dkk) }} kr. · {{ d.heading }}</a>{% endif %}
</div> </div>
<div class="item-qty"> <div class="item-qty">
<input type="text" value="{{ s.get('qty') or item.qty }}" placeholder="{{ item.qty }}" <input type="text" value="{{ s.get('qty') or item.qty }}" placeholder="{{ item.qty }}"
@@ -261,6 +265,34 @@
</div> </div>
{% endfor %} {% endfor %}
<!-- LÜBECK-TILBUD (valgt på Tilbud-siden) -->
<div class="section" id="sec-picks"{% if not picks %} style="display:none"{% endif %}>
<div class="section-header" style="background:#2d6a4f">
<span class="emoji">🏷</span> Lübeck-tilbud
<span class="est"><a href="/tilbud" style="color:#fff;text-decoration:underline">vælg flere →</a></span>
</div>
<div class="items-table" id="picks-table">
{% for o in picks %}
{% set ps = saved.get(o.id, {}) %}
<div class="item-row{% if ps.get('checked') %} checked{% endif %}" data-key="{{ o.id }}" id="pick-{{ o.id }}">
<div class="item-check"><input type="checkbox" {% if ps.get('checked') %}checked{% endif %} onchange="toggleOffer(this)"></div>
<div class="item-name">
{{ o.heading }}
<span class="note">{{ o.catalog }}{% if o.page %} · s. {{ o.page }}{% endif %}{% if o.unit %} · {{ o.size_from|int if o.size_from else '' }}{{ o.unit }}{% endif %}</span>
</div>
<div class="item-qty" style="display:flex;align-items:center;color:var(--muted);font-size:12px">
{% if o.pre_price_eur %}<s>{{ "{:.2f}".format(o.pre_price_eur).replace(".",",") }}</s>{% endif %}
</div>
<div class="item-est">{{ "{:.2f}".format(o.price_eur).replace(".",",") }} €</div>
<div class="item-actual" style="display:flex;align-items:center;gap:6px;justify-content:flex-end">
<span style="font-family:var(--mono)">≈ {{ "{:.0f}".format(o.price_eur * eur_dkk) }} kr.</span>
<button class="eir-del" onclick="removeOffer('{{ o.id }}')" title="Fjern fra seddel" style="border:none;background:none;cursor:pointer">×</button>
</div>
</div>
{% endfor %}
</div>
</div>
<!-- DYNAMISKE SEKTIONER --> <!-- DYNAMISKE SEKTIONER -->
<div id="custom-sections"> <div id="custom-sections">
{% for cs in custom_secs %} {% for cs in custom_secs %}
@@ -639,6 +671,26 @@ async function deleteCategory(id) {
document.getElementById(`csec-${id}`).remove(); document.getElementById(`csec-${id}`).remove();
} }
function toggleOffer(cb) {
const row = cb.closest('.item-row');
row.classList.toggle('checked', cb.checked);
saveToServer(row.dataset.key, null, cb.checked ? 1 : 0);
}
async function removeOffer(id) {
await fetch('/api/offers/pick', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({id, picked: false})
});
const row = document.getElementById('pick-' + id);
if (row) row.remove();
if (!document.querySelectorAll('#picks-table .item-row').length) {
document.getElementById('sec-picks').style.display = 'none';
}
showSaved();
}
function openArchiveModal() { function openArchiveModal() {
document.getElementById('archive-modal').classList.add('open'); document.getElementById('archive-modal').classList.add('open');
} }

161
templates/tilbud.html Normal file
View File

@@ -0,0 +1,161 @@
<!DOCTYPE html>
<html lang="da">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Citti Tilbud — Lübeck</title>
<link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=DM+Sans:wght@300;400;500;600&display=swap" rel="stylesheet">
<style>
:root {
--bg: #f5f2ed; --card: #ffffff; --border: #e2ddd6; --text: #1a1814;
--muted: #8a857c; --accent: #c84b2f; --green: #2d6a4f; --green-light: #e8f4ee;
--mono: 'DM Mono', monospace; --sans: 'DM Sans', sans-serif;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: var(--sans); background: var(--bg); color: var(--text); font-size: 15px; line-height: 1.5; padding: 1.5rem 1rem 4rem; }
.page { max-width: 860px; margin: 0 auto; }
header { display: flex; align-items: flex-start; justify-content: space-between; gap: 1rem; margin-bottom: 1rem; padding-bottom: 1.25rem; border-bottom: 2px solid var(--text); }
h1 { font-size: 1.75rem; font-weight: 600; letter-spacing: -0.03em; }
h1 span { color: var(--accent); }
.sub { font-size: 12px; color: var(--muted); margin-top: 4px; }
.btn { background: var(--card); color: var(--text); border: 1px solid var(--border); border-radius: 8px; padding: 8px 14px; font-size: 13px; font-family: var(--sans); cursor: pointer; text-decoration: none; display: inline-block; font-weight: 500; }
.btn-back { background: var(--text); color: white; border: none; }
.btn-refresh { background: var(--green); color: white; border: none; }
.btn:active { opacity: 0.85; }
.toolbar { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-bottom: 1.25rem; }
.search { flex: 1; min-width: 180px; padding: 10px 12px; border: 1px solid var(--border); border-radius: 8px; font-family: var(--sans); font-size: 14px; background: var(--card); }
.pick-count { font-size: 13px; color: var(--green); font-weight: 600; white-space: nowrap; }
.cat { margin-bottom: 1.5rem; }
.cat-title { background: var(--text); color: white; padding: 0.5rem 1rem; font-size: 12px; font-weight: 500; text-transform: uppercase; letter-spacing: 0.05em; border-radius: 8px 8px 0 0; }
.cat-body { background: var(--card); border: 1px solid var(--border); border-top: none; border-radius: 0 0 8px 8px; overflow: hidden; }
.offer { display: grid; grid-template-columns: 34px 1fr auto; align-items: center; gap: 10px; padding: 0.55rem 1rem; border-bottom: 1px solid var(--border); }
.offer:last-child { border-bottom: none; }
.offer.picked { background: var(--green-light); }
.offer input[type=checkbox] { width: 20px; height: 20px; accent-color: var(--green); cursor: pointer; }
.o-name { font-size: 14px; }
.o-meta { font-size: 11px; color: var(--muted); margin-top: 1px; }
.o-price { text-align: right; white-space: nowrap; }
.o-eur { font-family: var(--mono); font-weight: 600; font-size: 15px; }
.o-pre { font-family: var(--mono); font-size: 12px; color: var(--muted); text-decoration: line-through; margin-right: 4px; }
.o-dkk { font-family: var(--mono); font-size: 11px; color: var(--muted); }
.empty-state { padding: 2.5rem 2rem; text-align: center; color: var(--muted); font-size: 14px; background: var(--card); border: 1px solid var(--border); border-radius: 10px; }
.err { background: #fde8e3; color: var(--accent); font-size: 12px; padding: 8px 12px; border-radius: 8px; margin-bottom: 1rem; }
.cat.hidden, .offer.hidden { display: none; }
@media (max-width: 600px) {
.offer { grid-template-columns: 30px 1fr auto; }
}
</style>
</head>
<body>
<div class="page">
<header>
<div>
<h1>Citti <span>Tilbud</span></h1>
<div class="sub">
CITTI Lübeck · Herrenholz 14 · priser i EUR (≈ ×{{ "{:.2f}".format(eur_dkk).replace(".",",") }} kr.)<br>
{% if last_refresh %}Opdateret {{ last_refresh[:16].replace("T"," ") }} · {% endif %}{{ total }} tilbud
</div>
</div>
<div style="display:flex;flex-direction:column;gap:8px;align-items:flex-end">
<a href="/" class="btn btn-back">← Indkøbsseddel</a>
<button class="btn btn-refresh" id="refresh-btn" onclick="refreshOffers()">⟳ Opdater</button>
</div>
</header>
{% if last_error %}<div class="err">Sidste opdatering fejlede: {{ last_error }}</div>{% endif %}
<div class="toolbar">
<input class="search" id="search" type="search" placeholder="Søg i tilbud (tysk navn)…" oninput="filterOffers()">
<span class="pick-count" id="pick-count">{{ picked_count }} på seddel</span>
</div>
{% if total == 0 %}
<div class="empty-state">
Ingen tilbud hentet endnu. Tryk <strong>⟳ Opdater</strong> for at hente ugens tilbud fra CITTI Lübeck.
</div>
{% endif %}
{% for cat, offers in by_cat.items() %}
<div class="cat" data-cat>
<div class="cat-title">{{ cat }} ({{ offers|length }})</div>
<div class="cat-body">
{% for o in offers %}
<label class="offer{% if o.picked %} picked{% endif %}" data-name="{{ o.heading|lower }}">
<input type="checkbox" {% if o.picked %}checked{% endif %} onchange="togglePick(this, '{{ o.id }}')">
<div>
<div class="o-name">{{ o.heading }}</div>
<div class="o-meta">
{% if o.page %}s. {{ o.page }}{% endif %}
{% if o.unit and o.size_from %} · {{ o.size_from|int }}{% if o.size_to and o.size_to != o.size_from %}–{{ o.size_to|int }}{% endif %} {{ o.unit }}{% endif %}
{% if o.run_till %} · t.o.m. {{ o.run_till[:10] }}{% endif %}
</div>
</div>
<div class="o-price">
<div>
{% if o.pre_price_eur %}<span class="o-pre">{{ "{:.2f}".format(o.pre_price_eur).replace(".",",") }}</span>{% endif %}
<span class="o-eur">{{ "{:.2f}".format(o.price_eur).replace(".",",") }} €</span>
</div>
<div class="o-dkk">≈ {{ "{:.0f}".format(o.price_eur * eur_dkk) }} kr.</div>
</div>
</label>
{% endfor %}
</div>
</div>
{% endfor %}
</div>
<script>
let pickCount = {{ picked_count }};
async function togglePick(cb, id) {
const picked = cb.checked;
cb.closest('.offer').classList.toggle('picked', picked);
pickCount += picked ? 1 : -1;
document.getElementById('pick-count').textContent = pickCount + ' på seddel';
try {
await fetch('/api/offers/pick', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({id, picked})
});
} catch (e) {
cb.checked = !picked;
cb.closest('.offer').classList.toggle('picked', !picked);
pickCount += picked ? -1 : 1;
document.getElementById('pick-count').textContent = pickCount + ' på seddel';
}
}
function filterOffers() {
const q = document.getElementById('search').value.trim().toLowerCase();
document.querySelectorAll('[data-cat]').forEach(cat => {
let any = false;
cat.querySelectorAll('.offer').forEach(o => {
const match = !q || o.dataset.name.includes(q);
o.classList.toggle('hidden', !match);
if (match) any = true;
});
cat.classList.toggle('hidden', !any);
});
}
async function refreshOffers() {
const btn = document.getElementById('refresh-btn');
btn.textContent = '⟳ Henter…'; btn.disabled = true;
try {
const res = await fetch('/api/offers/refresh', {method: 'POST'});
const data = await res.json();
if (data.ok) { window.location.reload(); return; }
alert('Opdatering fejlede. Prøv igen om lidt.');
} catch (e) {
alert('Opdatering fejlede. Prøv igen om lidt.');
}
btn.textContent = '⟳ Opdater'; btn.disabled = false;
}
</script>
</body>
</html>