Merge remote-tracking branch 'refs/remotes/origin/main'
All checks were successful
Build and Deploy citti / build-and-deploy (push) Successful in 48s

This commit is contained in:
Henrik Jess Nielsen
2026-10-30 14:23:54 +01:00
16 changed files with 1843 additions and 22 deletions

View File

@@ -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 ./
@@ -21,6 +26,7 @@ RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
COPY templates/ templates/
COPY static/ static/
ENV DATA_DIR=/app/instance \
PORT=9756 \

719
app.py
View File

@@ -1,10 +1,16 @@
import sqlite3
import os
import re
import json
import time
import hashlib
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 +19,31 @@ 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"))
# German→Danish translation of offer headings via Claude (BlaaAi uses the same
# ANTHROPIC_API_KEY + Haiku pattern). Cached per heading, so only new headings
# cost a call. Without a key, offers simply stay in German.
TRANSLATE_MODEL = os.environ.get("TRANSLATE_MODEL", "claude-haiku-5-5")
# Moderate batches keep each request's max_tokens small. OAuth/subscription
# tokens have a tight output-tokens-per-minute limit, and the API reserves
# max_tokens against it — big requests 429 fast. ~22 output tokens/item, so
# 100 items fit in max_tokens=4000 with margin. Paced + retried below.
TRANSLATE_BATCH = int(os.environ.get("TRANSLATE_BATCH", "100"))
CLAUDE_MAX_RETRIES = int(os.environ.get("CLAUDE_MAX_RETRIES", "8"))
# AI matching of the fixed list against offers (more precise than the token
# heuristic). Bump to claude-sonnet-5-5 via env for harder cases.
MATCH_MODEL = os.environ.get("MATCH_MODEL", "claude-haiku-5-5")
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 +120,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 +157,26 @@ 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)""")
c.execute("""CREATE TABLE IF NOT EXISTS translations (
de TEXT PRIMARY KEY, da TEXT, created TEXT)""")
c.execute("""CREATE TABLE IF NOT EXISTS offer_matches (
item_key TEXT PRIMARY KEY, offer_id TEXT, updated TEXT)""")
try:
c.execute("ALTER TABLE extras ADD COLUMN section_key TEXT")
except Exception:
@@ -121,17 +187,445 @@ 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', '')
translated = translate_missing() # own short transactions, outside the write above
matched = match_offers_ai()
return {'catalogs': cat_count, 'offers_seen': len(seen),
'offers_total': total, 'translated': translated, 'matched': matched}
def _claude_mode():
"""'key' for an API key, 'oauth' for a Bearer auth token, else None."""
if os.environ.get("ANTHROPIC_API_KEY"):
return "key"
if os.environ.get("ANTHROPIC_AUTH_TOKEN"):
return "oauth"
return None
def _claude_json(client, model, max_tokens, prompt):
"""One Claude call returning text. Thinking is disabled (these are mechanical
JSON tasks and thinking would eat the token budget); if a model rejects the
disabled flag we retry without it, and the large max_tokens still fits the
output alongside thinking. OAuth tokens require the oauth beta header on
/v1/messages, so add it when authenticating with a token."""
extra = {"anthropic-beta": "oauth-2025-04-20"} if _claude_mode() == "oauth" else {}
kwargs = dict(model=model, max_tokens=max_tokens,
messages=[{"role": "user", "content": prompt}],
extra_headers=extra)
try:
msg = client.messages.create(thinking={"type": "disabled"}, **kwargs)
except Exception as e:
app.logger.info("citti: thinking=disabled rejected (%s); retrying plain", e)
msg = client.messages.create(**kwargs)
return "".join(b.text for b in msg.content if b.type == "text")
def _translate_batch(client, headings):
"""Translate a list of German headings to short Danish names. Returns list
aligned to input (falls back to the German text on any parse gap)."""
numbered = "\n".join(f"{i}. {h}" for i, h in enumerate(headings))
prompt = (
"Oversæt disse tyske dagligvare-tilbudsoverskrifter til korte, naturlige "
"danske produktnavne. Behold mærke-/egennavne uændret. Svar KUN med et JSON-"
'array på formen [{"i":0,"da":"..."}], ét element per linje, intet andet.\n\n'
+ numbered)
text = _claude_json(client, TRANSLATE_MODEL, 4000, prompt)
m = re.search(r"\[.*\]", text, re.DOTALL)
out = list(headings)
if not m:
app.logger.warning("citti translate: unparseable response: %s", text[:200])
return out
for item in json.loads(m.group(0)):
idx, da = item.get("i"), (item.get("da") or "").strip()
if isinstance(idx, int) and 0 <= idx < len(out) and da:
out[idx] = da
return out
def translate_missing():
"""Translate offer headings that have no Danish cache entry yet. Needs a
Claude credential (ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN); without one,
headings stay German."""
if not _claude_mode():
return 0
with get_db() as c:
todo = [r['heading'] for r in c.execute(
"SELECT DISTINCT heading FROM offers WHERE heading IS NOT NULL "
"AND heading NOT IN (SELECT de FROM translations)")]
if not todo:
return 0
try:
import anthropic
except Exception as e:
app.logger.warning("citti translate: anthropic SDK unavailable: %s", e)
return 0
client = anthropic.Anthropic(max_retries=CLAUDE_MAX_RETRIES)
now = datetime.now(timezone.utc).isoformat()
done = 0
batches = range(0, len(todo), TRANSLATE_BATCH)
for n, i in enumerate(batches):
batch = todo[i:i + TRANSLATE_BATCH]
try:
das = _translate_batch(client, batch)
except Exception as e:
# Rate limit or transient error: skip this batch, keep what's done
# (translations are cached), and let the next refresh pick up the
# rest. Never abort the whole refresh over it.
app.logger.warning("citti translate batch failed: %s", e)
continue
with get_db() as c:
for de, da in zip(batch, das):
c.execute("INSERT OR REPLACE INTO translations(de,da,created) "
"VALUES(?,?,?)", (de, da, now))
done += len(batch)
if n + 1 < len(batches):
time.sleep(1.5) # pace to stay under the rate limit
app.logger.info("citti translate: %d headings translated", done)
return done
def load_translations(c):
return {r['de']: r['da'] for r in c.execute("SELECT de,da FROM translations")}
def attach_da(tmap, *offer_lists):
"""Set heading_da on each offer dict (falls back to German heading)."""
for lst in offer_lists:
for o in lst:
o['heading_da'] = tmap.get(o.get('heading')) or o.get('heading')
# --- AI matching: fixed list ↔ offers (more precise than the token heuristic) -
def match_offers_ai():
"""Ask Claude which offer (if any) is the same product as each fixed item.
Stores results in offer_matches. Needs a Claude credential; on none or
failure the heuristic matcher remains the fallback."""
if not _claude_mode():
return 0
with get_db() as c:
offers = [dict(r) for r in c.execute(
"SELECT id, heading, catalog FROM offers")]
if not offers:
return 0
# Skip the (daily) match call when the offer set hasn't changed since the
# last successful match — the avis only turns over weekly, so this avoids a
# pointless Claude call most days.
sig = hashlib.md5(
"\n".join(sorted(o['id'] + '|' + (o.get('heading') or '') for o in offers))
.encode('utf-8')).hexdigest()
with get_db() as c:
if _meta_get(c, 'last_match_sig') == sig and \
c.execute("SELECT COUNT(*) FROM offer_matches").fetchone()[0]:
return 0
try:
import anthropic
except Exception as e:
app.logger.warning("citti match: anthropic SDK unavailable: %s", e)
return 0
items = "\n".join(
f"{it['key']} | {it['name']} | {it.get('de') or ''}"
for it in ITEM_BY_KEY.values())
offer_lines = "\n".join(
f"{o['id']} | {o['heading']} | {o['catalog']}" for o in offers)
prompt = (
"Du matcher en fast dansk indkøbsliste mod aktuelle tyske "
"supermarkeds-tilbud.\n\n"
"VARER (key | dansk navn | tysk navn):\n" + items +
"\n\nTILBUD (offer_id | tysk overskrift | katalog):\n" + offer_lines +
"\n\nFind for hver vare det tilbud der er SAMME slags produkt, hvis et "
"findes. Vær striks: match kun når det tydeligt er samme varetype "
"(fx entrecôte↔entrecôte-tilbud). Match IKKE blot på mærke eller løst "
"beslægtede varer (fx 'Nutella 1kg glas' må IKKE matche 'Nutella "
"julekalender'). Vælg det billigste ved flere ens. Returnér KUN et "
'JSON-array [{"item_key":"...","offer_id":"..."}] med de sikre match, '
"intet andet.")
client = anthropic.Anthropic(max_retries=CLAUDE_MAX_RETRIES)
try:
text = _claude_json(client, MATCH_MODEL, 2000, prompt)
except Exception as e:
# Rate limit or transient error: keep the existing matches and move on,
# never fail the whole refresh over matching.
app.logger.warning("citti match failed: %s", e)
return 0
m = re.search(r"\[.*\]", text, re.DOTALL)
if not m:
app.logger.warning("citti match: unparseable response: %s", text[:200])
return 0
valid_items = set(ITEM_BY_KEY)
valid_offers = {o['id'] for o in offers}
pairs = []
for row in json.loads(m.group(0)):
ik, oid = row.get("item_key"), row.get("offer_id")
if ik in valid_items and oid in valid_offers:
pairs.append((ik, oid))
now = datetime.now(timezone.utc).isoformat()
with get_db() as c:
c.execute("DELETE FROM offer_matches")
for ik, oid in pairs:
c.execute("INSERT OR REPLACE INTO offer_matches(item_key,offer_id,updated) "
"VALUES(?,?,?)", (ik, oid, now))
_meta_set(c, 'last_match_sig', sig) # remember this offer set as matched
app.logger.info("citti match: %d AI matches", len(pairs))
return len(pairs)
def load_deals(c, offers):
"""Return {item_key: offer_dict}. Prefer stored AI matches; fall back to the
token heuristic when there are none (e.g. no API key yet)."""
by_id = {o['id']: o for o in offers}
ai = {r['item_key']: by_id[r['offer_id']]
for r in c.execute("SELECT item_key, offer_id FROM offer_matches")
if r['offer_id'] in by_id}
if ai:
return ai
return match_catalog_offers(offers) if offers else {}
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
_refreshing = threading.Lock()
def refresh_offers_async():
"""Run a refresh in the background. Translation/matching can be slow under
rate limits, so the manual Opdater button must not block the HTTP request
(and time out the browser). Returns True if a run was started, False if one
is already in progress."""
if not _refreshing.acquire(blocking=False):
return False
def _run():
try:
refresh_offers_safe()
finally:
_refreshing.release()
threading.Thread(target=_run, name="offer-refresh", daemon=True).start()
return True
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('/')
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")]
tmap = load_translations(c)
deals = load_deals(c, all_offers)
by_sec = {}
for e in extras:
by_sec.setdefault(e.get('section_key') or '', []).append(e)
attach_da(tmap, picks, list(deals.values()))
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'])
@@ -201,6 +695,36 @@ def health():
return jsonify({'status': 'healthy', 'service': 'citti'})
# --- PWA / offline: served from root so the service worker scope is '/' -------
@app.route('/sw.js')
def service_worker():
resp = send_from_directory(app.static_folder, 'sw.js')
resp.headers['Service-Worker-Allowed'] = '/'
resp.headers['Cache-Control'] = 'no-cache'
resp.headers['Content-Type'] = 'application/javascript'
return resp
@app.route('/offline.js')
def offline_js():
resp = send_from_directory(app.static_folder, 'offline.js')
resp.headers['Content-Type'] = 'application/javascript'
return resp
@app.route('/manifest.webmanifest')
def manifest():
resp = send_from_directory(app.static_folder, 'manifest.webmanifest')
resp.headers['Content-Type'] = 'application/manifest+json'
return resp
@app.route('/icon.svg')
def icon():
return send_from_directory(app.static_folder, 'icon.svg')
@app.route('/api/category', methods=['POST'])
def add_category():
d = request.json
@@ -229,6 +753,196 @@ 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/<int:trip_id>')
def historik_trip(trip_id):
with get_db() as c:
row = c.execute("SELECT * FROM trips WHERE id=?", (trip_id,)).fetchone()
if not row:
return "Tur ikke fundet", 404
trip = dict(row)
snap = json.loads(trip['snapshot'])
saved = {p['key']: p for p in snap.get('prices', [])}
extras = snap.get('extras', [])
by_sec = {}
for e in extras:
by_sec.setdefault(e.get('section_key') or '', []).append(e)
sections = []
for sec in SECTIONS:
items = []
for item in sec['varer']:
s = saved.get(item['key'])
if s and s.get('checked'):
items.append({'item': item, 'saved': s})
if items or by_sec.get(sec['id']):
sections.append({'sec': sec, 'picked': items,
'extras': by_sec.get(sec['id'], [])})
return render_template('trip.html', trip=trip, sections=sections,
custom_secs=snap.get('custom_sections', []),
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')
attach_da(load_translations(c), offers)
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():
started = refresh_offers_async()
return jsonify(ok=True, started=started)
@app.route('/koeb-nu')
def koeb_nu():
with get_db() as c:
saved = {r['key']: dict(r) for r in c.execute("SELECT * FROM prices")}
offers = [dict(r) for r in c.execute("SELECT * FROM offers")]
picks = [dict(r) for r in c.execute(
"SELECT * FROM offers WHERE picked=1 ORDER BY catalog, heading")]
tmap = load_translations(c)
deals = load_deals(c, offers)
attach_da(tmap, offers, picks)
# 1) Your fixed items currently on offer. No "saving vs estimate" — the
# estimate is the whole line (e.g. 6 × ½ kg) while the offer price is per
# unit (e.g. per 100 g), so a kr-diff would be misleading. Show the honest
# offer price + unit instead.
on_offer = []
for sec in SECTIONS:
for item in sec['varer']:
d = deals.get(item['key'])
if not d:
continue
on_offer.append({
'item': item, 'sec': sec, 'offer': d,
'offer_dkk': (d.get('price_eur') or 0) * EUR_DKK,
'bought': bool(saved.get(item['key'], {}).get('checked')),
})
on_offer.sort(key=lambda r: (r['bought'], -(r['offer'].get('price_eur') or 0)))
# 2) What still needs to be ticked off (fixed items + picked offers)
remaining = []
for sec in SECTIONS:
items = [it for it in sec['varer']
if not saved.get(it['key'], {}).get('checked')]
if items:
remaining.append({'sec': sec, 'varer': items})
picks_remaining = [p for p in picks if not saved.get(p['id'], {}).get('checked')]
# 3) A taste of this week's headline "Tilbud" specials not already on the
# list (the source carries no pre-price, so there is no discount % to rank
# by; show the cheapest finds and link to the full Tilbud page).
on_list_ids = set(deals[k]['id'] for k in deals) | set(p['id'] for p in picks)
other = []
for o in offers:
if o.get('catalog') == 'Tilbud' and o['id'] not in on_list_ids and o.get('price_eur'):
o = dict(o)
o['dkk'] = o['price_eur'] * EUR_DKK
other.append(o)
other.sort(key=lambda o: o['price_eur'])
other = other[:25]
total = sum(len(sec['varer']) for sec in SECTIONS) + len(picks)
bought = sum(1 for sec in SECTIONS for it in sec['varer']
if saved.get(it['key'], {}).get('checked')) \
+ sum(1 for p in picks if saved.get(p['id'], {}).get('checked'))
return render_template('koeb_nu.html', on_offer=on_offer, remaining=remaining,
picks_remaining=picks_remaining, other=other,
eur_dkk=EUR_DKK, total=total, bought=bought,
has_offers=bool(offers))
@app.route('/analyse')
def analyse():
with get_db() as c:
@@ -265,6 +979,7 @@ def analyse():
if __name__ == '__main__':
init_db()
start_offer_scheduler()
port = int(os.environ.get('PORT', 9756))
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

View File

@@ -97,6 +97,26 @@ job "citti" {
HOST = "0.0.0.0"
}
# Claude credential for DA translation + AI offer matching.
# Prefer a dedicated API key (citti/anthropic_api_key) — its own rate
# budget, so citti doesn't compete with interactive Claude Code sessions
# on the same subscription. Else fall back to the OAuth token, set as
# ANTHROPIC_AUTH_TOKEN (the app adds the oauth-2025-04-20 beta header).
# Only ONE var is written: an empty ANTHROPIC_API_KEY would shadow the
# token, so we never emit it unless the key actually exists. If neither
# is set the token var is empty and offers stay German (heuristic match).
template {
data = <<EOT
{{ if keyExists "citti/anthropic_api_key" -}}
ANTHROPIC_API_KEY={{ key "citti/anthropic_api_key" }}
{{- else -}}
ANTHROPIC_AUTH_TOKEN={{ keyOrDefault "citti/claude_oauth_token" "" }}
{{- end }}
EOT
destination = "secrets/app.env"
env = true
}
resources {
cpu = 200
memory = 256

View File

@@ -1 +1,2 @@
flask>=3.0
anthropic>=0.40

BIN
static/icon-192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

BIN
static/icon-512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

9
static/icon.svg Normal file
View File

@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
<rect width="512" height="512" rx="96" fill="#c84b2f"/>
<g fill="none" stroke="#fff" stroke-width="26" stroke-linecap="round" stroke-linejoin="round">
<path d="M120 150h40l40 190h170l34-130H190"/>
<circle cx="214" cy="386" r="22" fill="#fff" stroke="none"/>
<circle cx="360" cy="386" r="22" fill="#fff" stroke="none"/>
</g>
<text x="256" y="250" font-family="DM Sans, Arial, sans-serif" font-size="150" font-weight="700" fill="#fff" text-anchor="middle">C</text>
</svg>

After

Width:  |  Height:  |  Size: 578 B

View File

@@ -0,0 +1,17 @@
{
"name": "Citti Indkøbsseddel",
"short_name": "Citti",
"description": "Indkøbsseddel og Lübeck-tilbud — virker offline i butikken.",
"start_url": "/",
"scope": "/",
"display": "standalone",
"orientation": "portrait",
"background_color": "#f5f2ed",
"theme_color": "#c84b2f",
"icons": [
{ "src": "/static/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },
{ "src": "/static/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" },
{ "src": "/static/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" },
{ "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" }
]
}

110
static/offline.js Normal file
View File

@@ -0,0 +1,110 @@
// citti offline support: register the SW, and make mutations survive no-net.
// window.cittiFetch(url, opts) tries the network; if it fails (offline), it
// queues the POST in localStorage, resolves optimistically, and replays the
// queue in order when the connection returns.
(function () {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').catch(function (e) {
console.warn('[citti] SW registration failed', e);
});
}
var QKEY = 'citti_queue_v1';
function getQ() { try { return JSON.parse(localStorage.getItem(QKEY) || '[]'); } catch (e) { return []; } }
function setQ(q) { try { localStorage.setItem(QKEY, JSON.stringify(q)); } catch (e) {} }
window.cittiFetch = function (url, opts) {
opts = opts || {};
var method = (opts.method || 'GET').toUpperCase();
return fetch(url, opts).then(function (r) {
if (!r.ok) throw new Error('status ' + r.status);
return r;
}).catch(function () {
if (method !== 'GET') {
var q = getQ();
q.push({
url: url, method: method,
headers: opts.headers || {},
body: typeof opts.body === 'string' ? opts.body : null
});
setQ(q);
render();
}
// optimistic: let the UI proceed as if saved
return new Response(JSON.stringify({ ok: true, queued: true }),
{ status: 200, headers: { 'Content-Type': 'application/json' } });
});
};
var flushing = false;
function flush() {
if (flushing || !navigator.onLine) { render(); return; }
var q = getQ();
if (!q.length) { render(); return; }
flushing = true;
var next = q[0];
fetch(next.url, { method: next.method, headers: next.headers, body: next.body })
.then(function (r) {
if (!r.ok) throw new Error('status ' + r.status);
var qq = getQ(); qq.shift(); setQ(qq);
flushing = false; render();
if (getQ().length) flush();
})
.catch(function () { flushing = false; render(); });
}
function render() {
var n = getQ().length;
var el = document.getElementById('citti-sync');
if (!el) {
el = document.createElement('div');
el.id = 'citti-sync';
el.style.cssText = 'position:fixed;left:50%;transform:translateX(-50%);bottom:14px;z-index:9999;'
+ 'padding:8px 16px;border-radius:20px;font:600 13px/1 system-ui,-apple-system,sans-serif;'
+ 'color:#fff;box-shadow:0 2px 10px rgba(0,0,0,.25);transition:opacity .3s;pointer-events:none';
document.body.appendChild(el);
}
var offline = !navigator.onLine;
if (offline && n) { el.textContent = '📴 Offline · ' + n + ' gemmes når du er online'; el.style.background = '#92580a'; el.style.opacity = '1'; }
else if (offline) { el.textContent = '📴 Offline'; el.style.background = '#5a5550'; el.style.opacity = '1'; }
else if (n) { el.textContent = '↻ Synkroniserer ' + n + '…'; el.style.background = '#2d6a4f'; el.style.opacity = '1'; }
else { el.style.opacity = '0'; }
}
// ---- Install ("Add to home screen") prompt ----
var deferredPrompt = null;
function showInstall() {
if (!document.body) { document.addEventListener('DOMContentLoaded', showInstall); return; }
var b = document.getElementById('citti-install');
if (!b) {
b = document.createElement('button');
b.id = 'citti-install';
b.type = 'button';
b.textContent = '⬇ Installér app';
b.style.cssText = 'position:fixed;left:14px;bottom:14px;z-index:9999;padding:9px 15px;'
+ 'border:none;border-radius:20px;background:#1a1814;color:#fff;cursor:pointer;'
+ 'font:600 13px/1 system-ui,-apple-system,sans-serif;box-shadow:0 2px 10px rgba(0,0,0,.25)';
b.addEventListener('click', function () {
if (!deferredPrompt) return;
deferredPrompt.prompt();
deferredPrompt.userChoice.finally(function () { deferredPrompt = null; b.remove(); });
});
document.body.appendChild(b);
}
}
window.addEventListener('beforeinstallprompt', function (e) {
e.preventDefault(); // keep the event so we can trigger it from our button
deferredPrompt = e;
showInstall();
});
window.addEventListener('appinstalled', function () {
deferredPrompt = null;
var b = document.getElementById('citti-install');
if (b) b.remove();
});
window.addEventListener('online', function () { render(); flush(); });
window.addEventListener('offline', render);
if (document.readyState !== 'loading') { render(); flush(); }
else document.addEventListener('DOMContentLoaded', function () { render(); flush(); });
})();

51
static/sw.js Normal file
View File

@@ -0,0 +1,51 @@
// citti service worker — offline shell + asset caching.
// Pages: network-first (fresh when online, cached copy in the store).
// Assets: cache-first. POSTs are never touched here — the page queues them.
const CACHE = 'citti-v2';
const CORE = ['/', '/tilbud', '/koeb-nu', '/offline.js', '/manifest.webmanifest',
'/icon.svg', '/static/icon-192.png', '/static/icon-512.png'];
self.addEventListener('install', (e) => {
e.waitUntil(
caches.open(CACHE)
.then((c) => Promise.allSettled(CORE.map((u) => c.add(u))))
.then(() => self.skipWaiting())
);
});
self.addEventListener('activate', (e) => {
e.waitUntil(
caches.keys()
.then((ks) => Promise.all(ks.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
.then(() => self.clients.claim())
);
});
self.addEventListener('fetch', (e) => {
const req = e.request;
if (req.method !== 'GET') return; // POSTs go straight to network; the page queues failures
const url = new URL(req.url);
if (url.origin !== location.origin) return;
const isAsset = /\.(js|css|svg|png|jpe?g|webp|webmanifest)$/.test(url.pathname)
|| url.pathname.startsWith('/uploads/');
if (isAsset) {
e.respondWith(
caches.match(req).then((hit) => hit || fetch(req).then((r) => {
const copy = r.clone();
caches.open(CACHE).then((c) => c.put(req, copy));
return r;
}))
);
} else {
// pages (navigations): network-first, fall back to the cached copy, then to '/'
e.respondWith(
fetch(req).then((r) => {
const copy = r.clone();
caches.open(CACHE).then((c) => c.put(req, copy));
return r;
}).catch(() => caches.match(req).then((hit) => hit || caches.match('/')))
);
}
});

View File

@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Citti Analyse — Uge 23-25</title>
<title>Citti Analyse</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 {
@@ -85,7 +85,7 @@
<header>
<div>
<h1>Citti <span>Analyse</span></h1>
<div style="font-size:12px;color:var(--muted);margin-top:4px">Uge 23–25 · 03.06–23.06.2026</div>
<div style="font-size:12px;color:var(--muted);margin-top:4px">CITTI Lübeck · Herrenholz 14</div>
</div>
<a href="/" class="btn-back">← Indkøbsseddel</a>
</header>

74
templates/historik.html Normal file
View File

@@ -0,0 +1,74 @@
<!DOCTYPE html>
<html lang="da">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Citti Historik</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;
--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: 1.5rem; 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); }
.btn-back { background: var(--text); color: white; border: none; border-radius: 8px; padding: 8px 14px; font-size: 13px; font-family: var(--sans); cursor: pointer; text-decoration: none; display: inline-block; font-weight: 500; }
.trip-list { display: flex; flex-direction: column; gap: 10px; }
.trip-card { display: flex; align-items: center; justify-content: space-between; gap: 1rem; background: var(--card); border: 1px solid var(--border); border-radius: 10px; padding: 1rem 1.25rem; text-decoration: none; color: inherit; transition: border-color 0.15s ease; }
.trip-card:active { border-color: var(--accent); }
.trip-label { font-size: 1.1rem; font-weight: 600; }
.trip-meta { font-size: 12px; color: var(--muted); margin-top: 2px; }
.trip-totals { text-align: right; white-space: nowrap; }
.trip-actual { font-size: 1.25rem; font-weight: 600; font-family: var(--mono); color: var(--green); letter-spacing: -0.02em; }
.trip-est { font-size: 12px; color: var(--muted); font-family: var(--mono); margin-top: 2px; }
.chev { color: var(--muted); font-size: 20px; margin-left: 4px; }
.empty-state { padding: 3rem 2rem; text-align: center; color: var(--muted); font-size: 14px; background: var(--card); border: 1px solid var(--border); border-radius: 10px; }
</style>
</head>
<body>
<div class="page">
<header>
<div>
<h1>Citti <span>Historik</span></h1>
<div style="font-size:12px;color:var(--muted);margin-top:4px">Gemte indkøbsture</div>
</div>
<a href="/" class="btn-back">← Indkøbsseddel</a>
</header>
{% if trips %}
<div class="trip-list">
{% for t in trips %}
<a href="/historik/{{ t.id }}" class="trip-card">
<div>
<div class="trip-label">{{ t.label }}</div>
<div class="trip-meta">{{ t.item_count }} varer</div>
</div>
<div style="display:flex;align-items:center">
<div class="trip-totals">
{% if t.total_actual %}
<div class="trip-actual">{{ "{:,.0f}".format(t.total_actual).replace(",",".") }} kr.</div>
{% else %}
<div class="trip-actual" style="color:var(--muted)">—</div>
{% endif %}
<div class="trip-est">est. {{ "{:,.0f}".format(t.total_est or 0).replace(",",".") }} kr.</div>
</div>
<span class="chev">›</span>
</div>
</a>
{% endfor %}
</div>
{% else %}
<div class="empty-state">Ingen gemte ture endnu. Tryk "🗂 Arkivér &amp; ny liste" på indkøbssedlen for at gemme en tur her.</div>
{% endif %}
</div>
</body>
</html>

View File

@@ -3,7 +3,14 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Citti Indkøbsseddel — Uge 23-25</title>
<meta name="theme-color" content="#c84b2f">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="Citti">
<link rel="manifest" href="/manifest.webmanifest">
<link rel="apple-touch-icon" href="/icon.svg">
<link rel="icon" href="/icon.svg">
<script src="/offline.js" defer></script>
<title>Citti Indkøbsseddel</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 {
@@ -35,6 +42,13 @@
.stat .s-label { font-size: 10px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 3px; }
.stat .s-val { font-size: 1.35rem; font-weight: 600; font-family: var(--mono); letter-spacing: -0.02em; }
.stat .s-sub { font-size: 10px; color: var(--muted); margin-top: 1px; }
.budget-block { display: flex; align-items: center; justify-content: space-between; gap: 1rem; background: var(--green-light); border: 1px solid #a8d5bc; border-radius: 10px; padding: 0.8rem 1.1rem; margin-bottom: 1.5rem; }
.bb-label { font-size: 13px; font-weight: 600; color: var(--text); }
.bb-status { font-size: 11px; color: var(--green); margin-top: 2px; font-weight: 500; }
.bb-val { font-size: 1.75rem; font-weight: 600; font-family: var(--mono); color: var(--green); letter-spacing: -0.02em; white-space: nowrap; }
.bb-val.over { color: var(--accent); }
.budget-block:has(.bb-val.over) { background: var(--accent-light); border-color: #f0b8a8; }
.budget-block:has(.bb-val.over) .bb-status { color: var(--accent); }
.section { margin-bottom: 1.25rem; }
.section-header { display: flex; align-items: center; gap: 8px; padding: 0.55rem 0.875rem; background: var(--text); color: white; border-radius: 8px 8px 0 0; font-size: 12px; font-weight: 500; letter-spacing: 0.04em; text-transform: uppercase; }
@@ -60,10 +74,11 @@
.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-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 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.modified { color: var(--accent); font-weight: 500; border-color: #f0b8ab; background: var(--accent-light); }
.item-qty input.modified { color: var(--green); font-weight: 500; border-color: #a8d5bc; background: var(--green-light); }
.item-est { padding: 0.7rem 0.5rem; font-size: 12px; font-family: var(--mono); color: var(--muted); text-align: right; }
.item-actual { padding: 0.45rem 0.75rem 0.45rem 0.5rem; }
.item-actual input { width: 100%; border: 1px solid var(--border); border-radius: 6px; padding: 5px 8px; font-size: 13px; font-family: var(--mono); background: var(--bg); color: var(--text); text-align: right; outline: none; transition: border-color 0.15s, background 0.15s; }
@@ -92,6 +107,8 @@
/* Rema */
.rema-section { background: var(--card); border: 1px solid var(--border); border-radius: 8px; padding: 1rem 1.1rem; margin-bottom: 1.25rem; }
.rema-title { font-size: 12px; font-weight: 500; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); margin-bottom: 0.75rem; }
.basis-group { font-size: 11px; font-weight: 600; color: var(--text); margin: 0.85rem 0 0.4rem; }
.basis-group:first-of-type { margin-top: 0; }
.rema-items { display: flex; flex-wrap: wrap; gap: 6px; }
.rema-item { display: flex; align-items: center; gap: 6px; font-size: 13px; background: var(--bg); border: 1px solid var(--border); border-radius: 6px; padding: 5px 10px; cursor: pointer; transition: background 0.15s; }
.rema-item:hover { background: #eae6e0; }
@@ -165,16 +182,19 @@
<div class="header-left">
<h1>Citti <span>Indkøbsseddel</span></h1>
<div class="header-meta">
<span><strong>Uge 23–25</strong> · 03.06–23.06.2026</span>
<span>Man–lør 08–20</span>
<span>Langberger Weg 4, Flensburg</span>
<span>CITTI Lübeck · Herrenholz 14</span>
<span>1 EUR ≈ 7,46 DKK</span>
</div>
</div>
<div class="header-actions">
<div style="display:flex;gap:8px">
<div style="display:flex;gap:8px;flex-wrap:wrap">
<button class="btn btn-cat" onclick="openCatModal()">+ Kategori</button>
<a href="/tilbud" class="btn">🏷 Tilbud</a>
<a href="/koeb-nu" class="btn">🛒 Køb nu</a>
<a href="/analyse" class="btn">📊 Analyse</a>
<a href="/historik" class="btn">🕑 Historik</a>
<button class="btn" onclick="openArchiveModal()">🗂 Arkivér & ny liste</button>
</div>
<div class="savings-card">
<div class="label">Estimeret besparelse</div>
@@ -187,18 +207,18 @@
<div class="stats-row">
<div class="stat">
<div class="s-label">Aftensmadsdage</div>
<div class="s-val">~40</div>
<div class="s-sub">fra én tur</div>
<div class="s-val" id="stat-days">—</div>
<div class="s-sub">kød + pasta-retter</div>
</div>
<div class="stat">
<div class="s-label">Kødportioner</div>
<div class="s-val">24</div>
<div class="s-val" id="stat-portions">—</div>
<div class="s-sub">à 500g i fryseren</div>
</div>
<div class="stat">
<div class="s-label">Estimeret total</div>
<div class="s-val" style="font-size:1.15rem">~4.400</div>
<div class="s-sub">kr. inkl. Rema</div>
<div class="s-val" style="font-size:1.15rem" id="stat-est">—</div>
<div class="s-sub">kr. for listen</div>
</div>
<div class="stat">
<div class="s-label">Faktisk betalt</div>
@@ -207,6 +227,15 @@
</div>
</div>
<!-- BUDGET-TJEK -->
<div class="budget-block">
<div class="bb-left">
<div class="bb-label">📊 Pris pr. aftensmadsdag</div>
<div class="bb-status" id="budget-status">Budget ~200 kr./dag</div>
</div>
<div class="bb-val" id="budget-per-day">—</div>
</div>
<!-- FASTE SEKTIONER -->
{% for sec in sections %}
<div class="section">
@@ -225,13 +254,16 @@
<div class="items-table" id="sec-{{ sec.id }}">
{% for item in sec.varer %}
{% set s = saved.get(item.key, {}) %}
<div class="item-row{% if s.get('checked') %} checked{% endif %}" data-key="{{ item.key }}" data-est="{{ item.est }}">
{% set od = deals.get(item.key) %}
<div class="item-row{% if s.get('checked') %} checked{% endif %}" data-key="{{ item.key }}" data-est="{{ item.est }}"{% if od and od.unit %} data-offer-eur="{{ od.price_eur }}" data-offer-unit="{{ od.unit }}" data-offer-size="{{ od.size_from or '' }}"{% endif %}>
<div class="item-check"><input type="checkbox" {% if s.get('checked') %}checked{% endif %} onchange="toggleRow(this)"></div>
<div class="item-name">
{{ item.name }}
{% 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('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_da or d.heading }}</a>{% endif %}
</div>
<div class="item-qty">
<input type="text" value="{{ s.get('qty') or item.qty }}" placeholder="{{ item.qty }}"
@@ -245,7 +277,7 @@
</div>
{% endfor %}
{% for e in by_sec.get(sec.id, []) %}
<div class="extra-item-row" id="extra-{{ e.id }}">
<div class="extra-item-row" id="extra-{{ e.id }}" data-est="{{ e.price or 0 }}">
<div></div>
<div class="item-name">
{{ e.name }}
@@ -259,6 +291,35 @@
</div>
{% 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 }}" data-est="{{ (o.price_eur * eur_dkk)|round(2) }}" 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_da or o.heading }}
{% if o.heading_da and o.heading_da != o.heading %}<span class="de">🇩🇪 {{ o.heading }}</span>{% endif %}
<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 -->
<div id="custom-sections">
{% for cs in custom_secs %}
@@ -274,7 +335,7 @@
{% set sk_extras = by_sec.get(sk, []) %}
{% if sk_extras %}
{% for e in sk_extras %}
<div class="extra-item-row" id="extra-{{ e.id }}">
<div class="extra-item-row" id="extra-{{ e.id }}" data-est="{{ e.price or 0 }}">
<div></div>
<div class="item-name">{{ e.name }}{% if e.note %}<span class="note">{{ e.note }}</span>{% endif %}</div>
<div class="eir-price">{% if e.price %}{{ "{:.2f}".format(e.price).replace(".",",") }}{% else %}—{% endif %}</div>
@@ -289,6 +350,59 @@
{% endfor %}
</div>
<!-- BASISVARER (grabbes ved CITTI) -->
<div class="rema-section">
<div class="rema-title">🧺 Basisvarer — husk ved CITTI</div>
{% set basis_groups = [
{"g":"Grundvarer", "items":[
{"key":"basis-ris","name":"Ris (stor pose)","de":"Reis (Großpackung)"},
{"key":"basis-rugbroed","name":"Rugbrød","de":"Roggenbrot"},
{"key":"basis-havregryn","name":"Havregryn","de":"Haferflocken"},
{"key":"basis-mel","name":"Mel","de":"Mehl"},
{"key":"basis-sukker","name":"Sukker","de":"Zucker"}]},
{"g":"Protein", "items":[
{"key":"basis-aeg","name":"Æg","de":"Eier"},
{"key":"basis-boenner","name":"Kidneybønner","de":"Kidneybohnen"},
{"key":"basis-linser","name":"Linser","de":"Linsen"}]},
{"g":"Grønt & frugt", "items":[
{"key":"basis-bananer","name":"Bananer","de":"Bananen"},
{"key":"basis-tomater","name":"Tomater","de":"Tomaten"},
{"key":"basis-guleroedder","name":"Gulerødder","de":"Karotten"},
{"key":"basis-loeg","name":"Løg","de":"Zwiebeln"},
{"key":"basis-hvidloeg","name":"Hvidløg","de":"Knoblauch"},
{"key":"basis-kartofler","name":"Kartofler","de":"Kartoffeln"},
{"key":"basis-aebler","name":"Æbler","de":"Äpfel"},
{"key":"basis-appelsiner","name":"Appelsiner","de":"Orangen"}]},
{"g":"Mejeri", "items":[
{"key":"basis-maelk","name":"Mælk","de":"Milch"},
{"key":"basis-smoer","name":"Smør","de":"Butter"},
{"key":"basis-yoghurt","name":"Yoghurt","de":"Joghurt"},
{"key":"basis-ost","name":"Ost","de":"Käse"}]},
{"g":"Køl & frys", "items":[
{"key":"basis-frossen-frugt","name":"Frossen frugt","de":"TK-Obst"}]},
{"g":"Husholdning", "items":[
{"key":"basis-koekkenruller","name":"Køkkenruller","de":"Küchenrolle"},
{"key":"basis-fryseposer","name":"Fryseposer","de":"Gefrierbeutel"},
{"key":"basis-toiletpapir","name":"Toiletpapir","de":"Toilettenpapier"}]},
{"g":"Krydderier", "items":[
{"key":"basis-salt","name":"Salt","de":"Salz"},
{"key":"basis-peber","name":"Peber","de":"Pfeffer"},
{"key":"basis-bouillon","name":"Bouillon","de":"Brühe"}]}
] %}
{% for grp in basis_groups %}
<div class="basis-group">{{ grp.g }}</div>
<div class="rema-items">
{% for b in grp['items'] %}
{% set bs = saved.get(b.key, {}) %}
<label class="rema-item{% if bs.get('checked') %} checked{% endif %}">
<input type="checkbox" {% if bs.get('checked') %}checked{% endif %} onchange="toggleBasis(this, '{{ b.key }}')">
{{ b.name }} <span style="color:var(--muted);font-size:11px">· 🇩🇪 {{ b.de }}</span>
</label>
{% endfor %}
</div>
{% endfor %}
</div>
<!-- REMA -->
<div class="rema-section">
<div class="rema-title">🛒 Køb i Rema1000 / Netto</div>
@@ -309,7 +423,7 @@
</div>
<div class="items-table" id="sec-table-loose">
{% for e in loose %}
<div class="extra-item-row" id="extra-{{ e.id }}">
<div class="extra-item-row" id="extra-{{ e.id }}" data-est="{{ e.price or 0 }}">
<div></div>
<div class="item-name">{{ e.name }}{% if e.note %}<span class="note">{{ e.note }}</span>{% endif %}</div>
<div class="eir-price">{% if e.price %}{{ "{:.2f}".format(e.price).replace(".",",") }}{% else %}—{% endif %}</div>
@@ -351,7 +465,7 @@
</div>
</div>
<footer>Citti Flensborg · Langberger Weg 4 · Tilbud 03.06–23.06.2026</footer>
<footer>CITTI Lübeck · Herrenholz 14</footer>
</div><!-- /page -->
@@ -415,9 +529,42 @@
</div>
</div>
<!-- ARKIVÉR MODAL -->
<div class="modal-overlay" id="archive-modal" onclick="if(event.target===this)closeArchiveModal()">
<div class="modal">
<div class="modal-title">
Arkivér & ny liste
<button class="modal-close" onclick="closeArchiveModal()">×</button>
</div>
<p style="margin:0 0 1.25rem;color:var(--muted);line-height:1.5">
Den nuværende tur gemmes i <strong>Historik</strong>, og listen nulstilles til en frisk
udgave: afkrydsninger og priser fjernes, og dine tilføjede varer og egne kategorier ryddes.
</p>
<button class="btn-submit" id="archive-confirm" onclick="doArchive()">Arkivér & nulstil</button>
<button class="btn-submit" style="background:transparent;color:var(--muted);margin-top:4px" onclick="closeArchiveModal()">Annullér</button>
</div>
</div>
<script>
const SEC_IDS = ['koed','frost','mejeri','pasta','groent','konserves','indisk','mex','drikke','hus'];
const DK_SAVINGS_RATIO = 0.35;
const EUR_DKK = {{ eur_dkk }};
// For a catalog row that matches a current Lübeck offer, work out the real line
// price from the offer: offer price is per unit (e.g. per 100 g), so multiply by
// the item's quantity. Only weight-based offers (g/kg) are converted reliably;
// everything else keeps the hardcoded estimate.
function offerLineDkk(row) {
const eur = parseFloat(row.dataset.offerEur);
const unit = (row.dataset.offerUnit || '').toLowerCase();
const size = parseFloat(row.dataset.offerSize);
if (isNaN(eur) || !(unit === 'g' || unit === 'kg')) return null;
const kg = qtyToKg(row.querySelector('.item-qty input')
? (row.querySelector('.item-qty input').value.trim() || row.querySelector('.item-qty input').placeholder) : '');
if (kg <= 0) return null;
const offerKg = unit === 'kg' ? (size || 1) : (size || 100) / 1000; // offer priced per `size` units
return kg * (eur / offerKg) * EUR_DKK;
}
let saveTimer = null;
function showSaved() {
@@ -450,13 +597,18 @@ function saveToServer(key, price, checked) {
const row = document.querySelector(`.item-row[data-key="${key}"]`);
const qtyInput = row ? row.querySelector('.item-qty input') : null;
const qty = qtyInput ? qtyInput.value.trim() || null : null;
fetch('/api/price', {
(window.cittiFetch || fetch)('/api/price', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({key, price, checked, qty})
}).then(() => showSaved());
}
function toggleBasis(cb, key) {
cb.closest('.rema-item').classList.toggle('checked', cb.checked);
saveToServer(key, null, cb.checked ? 1 : 0); // persists in prices, offline-safe
}
function updateQty(input) {
const row = input.closest('.item-row');
const key = row.dataset.key;
@@ -464,10 +616,73 @@ function updateQty(input) {
input.classList.toggle('modified', input.value.trim() !== '' && input.value.trim() !== defaultQty);
const price = parseFloat(row.querySelector('.item-actual input').value);
const checked = row.querySelector('input[type=checkbox]').checked ? 1 : 0;
recalcAll(); // meal stats + estimate (offer prices) react to qty
clearTimeout(debounceTimers[key + '_qty']);
debounceTimers[key + '_qty'] = setTimeout(() => saveToServer(key, isNaN(price) ? null : price, checked), 600);
}
// Parse a Danish quantity string ("6 × ½ kg", "3 kg", "~700g", "2 stk.") into
// kilograms / pack count, for the meat-portions and dinner-days estimates.
function qtyToKg(s) {
if (!s) return 0;
s = s.toLowerCase().replace(/~/g, '').replace(',', '.')
.replace(/½/g, '0.5').replace(/¼/g, '0.25').replace(/¾/g, '0.75');
let m = s.match(/([\d.]+)\s*[×x]\s*([\d.]+)\s*kg/);
if (m) return parseFloat(m[1]) * parseFloat(m[2]);
m = s.match(/([\d.]+)\s*[×x]\s*([\d.]+)\s*g\b/);
if (m) return parseFloat(m[1]) * parseFloat(m[2]) / 1000;
m = s.match(/([\d.]+)\s*kg/);
if (m) return parseFloat(m[1]);
m = s.match(/([\d.]+)\s*g\b/);
if (m) return parseFloat(m[1]) / 1000;
return 0;
}
function qtyToPacks(s) {
const m = (s || '').match(/([\d.]+)\s*stk/i);
return m ? parseFloat(m[1]) : 0;
}
// Leading number of a quantity string ("6 × ½ kg" -> 6, "8 dåser" -> 8), used to
// scale a fixed line estimate when the quantity changes.
function qtyNum(s) {
const m = (s || '').replace(',', '.').replace(/~/g, '').replace(/½/g, '0.5').match(/([\d.]+)/);
return m ? parseFloat(m[1]) : null;
}
function curQty(row) {
const inp = row.querySelector('.item-qty input');
return inp ? (inp.value.trim() || inp.placeholder) : '';
}
let mealsDinners = 0;
const DAY_BUDGET = 200; // ~200 kr/dag budget
function computeMeals() {
let meatKg = 0;
document.querySelectorAll('#sec-koed .item-row').forEach(r => { meatKg += qtyToKg(curQty(r)); });
let packs = 0;
document.querySelectorAll('#sec-pasta .item-row').forEach(r => { packs += qtyToPacks(curQty(r)); });
const portions = Math.round(meatKg / 0.5);
mealsDinners = portions + Math.round(packs);
const dp = document.getElementById('stat-portions');
const dd = document.getElementById('stat-days');
if (dp) dp.textContent = portions > 0 ? portions : '—';
if (dd) dd.textContent = mealsDinners > 0 ? mealsDinners : '—';
}
function updateBudget(est) {
const el = document.getElementById('budget-per-day');
const st = document.getElementById('budget-status');
if (!el) return;
if (est > 0 && mealsDinners > 0) {
const perDay = Math.round(est / mealsDinners);
el.textContent = perDay.toLocaleString('da-DK') + ' kr.';
const ok = perDay <= DAY_BUDGET;
st.textContent = 'Budget ~' + DAY_BUDGET + ' kr./dag · ' + (ok ? 'holder ✓' : 'over budget ⚠');
el.classList.toggle('over', !ok);
} else {
el.textContent = '—';
st.textContent = 'Budget ~' + DAY_BUDGET + ' kr./dag';
el.classList.remove('over');
}
}
function recalcAll() {
const sections = document.querySelectorAll('.items-table');
let totalActual = 0; let hasAny = false;
@@ -483,11 +698,34 @@ function recalcAll() {
document.getElementById('s-total-citti').textContent = Math.round(totalActual).toLocaleString('da-DK');
document.getElementById('s-total-all').textContent = Math.round(totalActual + 350).toLocaleString('da-DK');
document.getElementById('stat-actual').textContent = Math.round(totalActual).toLocaleString('da-DK');
document.getElementById('total-savings').textContent = Math.round(totalActual * DK_SAVINGS_RATIO).toLocaleString('da-DK');
} else {
['s-total-citti','s-total-all','stat-actual'].forEach(id => document.getElementById(id).textContent = '—');
document.getElementById('total-savings').textContent = '~1.800';
}
// Estimeret total = whole current list (fixed catalog + added items +
// picked offers), live from each row's data-est. Reflects add/remove/pick.
let est = 0;
document.querySelectorAll('[data-est]').forEach(r => {
const offer = offerLineDkk(r); // real offer price if matched
if (offer != null) { est += offer; return; }
let base = parseFloat(r.dataset.est) || 0;
const qi = r.querySelector('.item-qty input'); // scale estimate with quantity
if (qi) {
const cur = qtyNum(qi.value.trim() || qi.placeholder);
const def = qtyNum(qi.placeholder);
if (cur != null && def != null && def > 0) base = base * (cur / def);
}
est += base;
});
document.getElementById('stat-est').textContent = est > 0 ? Math.round(est).toLocaleString('da-DK') : '—';
// Estimeret besparelse = 35% of actual spend once entered, else of the estimate.
const savingsBase = hasAny ? totalActual : est;
document.getElementById('total-savings').textContent =
savingsBase > 0 ? Math.round(savingsBase * DK_SAVINGS_RATIO).toLocaleString('da-DK') : '~1.800';
computeMeals();
updateBudget(est);
}
// Item modal
@@ -557,14 +795,17 @@ function appendExtraToSection(data) {
const noteHtml = data.note ? `<span class="note">${data.note}</span>` : '';
const row = document.createElement('div');
row.className = 'extra-item-row'; row.id = `extra-${data.id}`;
row.dataset.est = data.price || 0;
row.innerHTML = `<div></div><div class="item-name">${data.name}${noteHtml}</div><div class="eir-price">${priceStr}</div><div class="eir-del"><button onclick="deleteExtra(${data.id}, this)" title="Slet">×</button></div>`;
table.appendChild(row);
recalcAll();
}
async function deleteExtra(id, btn) {
if (!confirm('Slet denne vare?')) return;
await fetch(`/api/item/${id}`, {method: 'DELETE'});
document.getElementById(`extra-${id}`).remove();
recalcAll();
}
// Category modal
@@ -621,6 +862,53 @@ async function deleteCategory(id) {
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 (window.cittiFetch || 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';
}
recalcAll();
showSaved();
}
function openArchiveModal() {
document.getElementById('archive-modal').classList.add('open');
}
function closeArchiveModal() {
document.getElementById('archive-modal').classList.remove('open');
}
async function doArchive() {
const btn = document.getElementById('archive-confirm');
btn.textContent = 'Arkiverer...'; btn.disabled = true;
try {
const res = await fetch('/api/archive', {method: 'POST'});
const data = await res.json();
if (data.ok) {
window.location.reload();
return;
}
if (data.empty) alert('Listen er allerede tom — intet at arkivere.');
else alert('Kunne ikke arkivere. Prøv igen.');
} catch (e) {
alert('Kunne ikke arkivere. Prøv igen.');
}
btn.textContent = 'Arkivér & nulstil'; btn.disabled = false;
closeArchiveModal();
}
recalcAll();
</script>
</body>

167
templates/koeb_nu.html Normal file
View File

@@ -0,0 +1,167 @@
<!DOCTYPE html>
<html lang="da">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#c84b2f">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="Citti">
<link rel="manifest" href="/manifest.webmanifest">
<link rel="apple-touch-icon" href="/icon.svg">
<link rel="icon" href="/icon.svg">
<script src="/offline.js" defer></script>
<title>Citti · Køb nu</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: 1.25rem; 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-back { background: var(--text); color: white; border: none; border-radius: 8px; padding: 8px 14px; font-size: 13px; font-family: var(--sans); cursor: pointer; text-decoration: none; display: inline-block; font-weight: 500; }
.kpi-row { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 1.5rem; }
.kpi { background: var(--card); border: 1px solid var(--border); border-radius: 10px; padding: 1rem; }
.kpi-label { font-size: 11px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 4px; }
.kpi-val { font-size: 1.75rem; font-weight: 600; font-family: var(--mono); letter-spacing: -0.02em; }
.kpi-val.green { color: var(--green); }
.kpi-sub { font-size: 11px; color: var(--muted); margin-top: 2px; }
.card { background: var(--card); border: 1px solid var(--border); border-radius: 10px; overflow: hidden; margin-bottom: 1.25rem; }
.card-title { background: var(--text); color: white; padding: 0.6rem 1rem; font-size: 12px; font-weight: 500; text-transform: uppercase; letter-spacing: 0.05em; }
.card-title.green { background: var(--green); }
.row { display: flex; align-items: center; justify-content: space-between; gap: 1rem; padding: 0.6rem 1rem; border-bottom: 1px solid var(--border); }
.row:last-child { border-bottom: none; }
.row.bought { opacity: 0.45; }
.row.bought .r-name { text-decoration: line-through; }
.r-name { font-size: 14px; font-weight: 500; }
.r-meta { font-size: 11px; color: var(--muted); margin-top: 1px; }
.r-right { text-align: right; white-space: nowrap; }
.r-price { font-family: var(--mono); font-weight: 600; }
.r-pre { font-family: var(--mono); font-size: 12px; color: var(--muted); text-decoration: line-through; margin-right: 4px; }
.r-save { font-size: 11px; color: var(--green); font-weight: 600; }
.r-dkk { font-size: 11px; color: var(--muted); font-family: var(--mono); }
.pill { display: inline-block; font-size: 10px; font-weight: 600; background: var(--accent); color: #fff; border-radius: 4px; padding: 1px 6px; margin-left: 6px; }
.sec-group { padding: 0.5rem 1rem; border-bottom: 1px solid var(--border); }
.sec-group:last-child { border-bottom: none; }
.sec-h { font-size: 12px; font-weight: 600; color: var(--muted); margin-bottom: 4px; }
.chips { display: flex; flex-wrap: wrap; gap: 6px; }
.chip { font-size: 12px; background: var(--bg); border: 1px solid var(--border); border-radius: 6px; padding: 3px 9px; }
.empty-state { padding: 2rem; text-align: center; color: var(--muted); font-size: 14px; }
@media (max-width: 600px) { .kpi-val { font-size: 1.35rem; } }
</style>
</head>
<body>
<div class="page">
<header>
<div>
<h1>Citti <span>Køb nu</span></h1>
<div class="sub">Status for din seddel · tilbud fra CITTI Lübeck · mængder uændret</div>
</div>
<a href="/" class="btn-back">← Indkøbsseddel</a>
</header>
{% if not has_offers %}
<div class="card"><div class="empty-state">Ingen tilbud hentet endnu — åbn <a href="/tilbud">Tilbud</a> og tryk Opdater først.</div></div>
{% endif %}
<div class="kpi-row">
<div class="kpi">
<div class="kpi-label">Krydset af</div>
<div class="kpi-val">{{ bought }}<span style="font-size:1rem;color:var(--muted)">/{{ total }}</span></div>
<div class="kpi-sub">varer købt</div>
</div>
<div class="kpi">
<div class="kpi-label">Mangler</div>
<div class="kpi-val">{{ total - bought }}</div>
<div class="kpi-sub">ikke krydset af endnu</div>
</div>
<div class="kpi">
<div class="kpi-label">På tilbud</div>
<div class="kpi-val green">{{ on_offer|length }}</div>
<div class="kpi-sub">af dine varer lige nu</div>
</div>
</div>
<!-- 1) DINE VARER PÅ TILBUD -->
<div class="card">
<div class="card-title green">🏷 Dine varer på tilbud nu</div>
{% if on_offer %}
{% for r in on_offer %}
<div class="row{% if r.bought %} bought{% endif %}">
<div>
<div class="r-name">{{ r.sec.emoji }} {{ r.item.name }}{% if r.bought %} ✓{% endif %}</div>
<div class="r-meta">🏷 {{ r.offer.heading_da or r.offer.heading }} · {{ r.offer.catalog }}{% if r.offer.page %} · s. {{ r.offer.page }}{% endif %}</div>
</div>
<div class="r-right">
<div class="r-price">{{ "{:.2f}".format(r.offer.price_eur).replace(".",",") }} € <span class="r-dkk">≈ {{ "{:.0f}".format(r.offer_dkk) }} kr.</span></div>
{% if r.offer.unit and r.offer.size_from %}<div class="r-dkk">pr. {{ r.offer.size_from|int }}{% if r.offer.size_to and r.offer.size_to != r.offer.size_from %}–{{ r.offer.size_to|int }}{% endif %} {{ r.offer.unit }}</div>{% endif %}
</div>
</div>
{% endfor %}
{% else %}
<div class="empty-state">Ingen af dine faste varer er på tilbud lige nu.</div>
{% endif %}
</div>
<!-- 2) MANGLER AT KØBE -->
<div class="card">
<div class="card-title">🛒 Mangler at krydse af</div>
{% if remaining or picks_remaining %}
{% for g in remaining %}
<div class="sec-group">
<div class="sec-h">{{ g.sec.emoji }} {{ g.sec.title }}</div>
<div class="chips">
{% for it in g.varer %}<span class="chip">{{ it.name }}</span>{% endfor %}
</div>
</div>
{% endfor %}
{% if picks_remaining %}
<div class="sec-group">
<div class="sec-h">🏷 Lübeck-tilbud</div>
<div class="chips">
{% for p in picks_remaining %}<span class="chip">{{ p.heading_da or p.heading }}</span>{% endfor %}
</div>
</div>
{% endif %}
{% else %}
<div class="empty-state">Alt er krydset af — godt gået! 🎉</div>
{% endif %}
</div>
<!-- 3) UGENS TILBUD — UDVALG -->
{% if other %}
<div class="card">
<div class="card-title">✨ Ugens tilbud — billige fund (ikke på din liste)</div>
{% for o in other %}
<div class="row">
<div>
<div class="r-name">{{ o.heading_da or o.heading }}</div>
<div class="r-meta">{% if o.heading_da and o.heading_da != o.heading %}🇩🇪 {{ o.heading }} · {% endif %}{{ o.catalog }}{% if o.page %} · s. {{ o.page }}{% endif %}{% if o.unit and o.size_from %} · {{ o.size_from|int }} {{ o.unit }}{% endif %}</div>
</div>
<div class="r-right">
<div class="r-price">{{ "{:.2f}".format(o.price_eur).replace(".",",") }} €</div>
<div class="r-dkk">≈ {{ "{:.0f}".format(o.dkk) }} kr.</div>
</div>
</div>
{% endfor %}
<div class="row" style="justify-content:center">
<a href="/tilbud" style="color:var(--accent);font-size:13px;font-weight:600;text-decoration:none">Se alle tilbud →</a>
</div>
</div>
{% endif %}
</div>
</body>
</html>

201
templates/tilbud.html Normal file
View File

@@ -0,0 +1,201 @@
<!DOCTYPE html>
<html lang="da">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#c84b2f">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="Citti">
<link rel="manifest" href="/manifest.webmanifest">
<link rel="apple-touch-icon" href="/icon.svg">
<link rel="icon" href="/icon.svg">
<script src="/offline.js" defer></script>
<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.picked { box-shadow: inset 3px 0 0 var(--green); }
.on-list { display: none; font-size: 10px; font-weight: 700; color: #fff; background: var(--green); border-radius: 4px; padding: 1px 6px; vertical-align: middle; white-space: nowrap; }
.offer.picked .on-list { display: inline-block; }
.btn.only-picked.active { background: var(--green); color: #fff; border-color: var(--green); }
.offer input[type=checkbox] { width: 20px; height: 20px; accent-color: var(--green); cursor: pointer; }
.o-name { font-size: 14px; }
.o-de { font-size: 10px; color: #b0aba3; font-style: italic; margin-top: 1px; }
.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<br>
<a href="https://www.cittimarkt.de/angebote" target="_blank" rel="noopener" style="color:var(--accent);font-weight:600;text-decoration:none">📄 Se hele avisen hos CITTI Lübeck →</a>
</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()">
<button class="btn only-picked" id="only-picked-btn" onclick="toggleOnlyPicked()">✓ Kun valgte</button>
<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_da or o.heading }} <span class="on-list">✓ på seddel</span></div>
{% if o.heading_da and o.heading_da != o.heading %}<div class="o-de">🇩🇪 {{ o.heading }}</div>{% endif %}
<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>
<a class="golist" id="golist" href="/"
style="display:none;position:fixed;right:14px;bottom:14px;z-index:9999;padding:11px 18px;border-radius:24px;background:#2d6a4f;color:#fff;text-decoration:none;font:600 14px/1 var(--sans);box-shadow:0 3px 12px rgba(0,0,0,.28)">🛒 <b id="golist-n">0</b> valgt · Gå til seddel →</a>
<script>
let pickCount = {{ picked_count }};
// Picking is instant — a tick adds the offer to the shopping list right away
// (it shows in the "Lübeck-tilbud" section there). This just mirrors the count
// and the "go to list" button.
function updatePick() {
document.getElementById('pick-count').textContent = pickCount + ' på seddel';
document.getElementById('golist-n').textContent = pickCount;
document.getElementById('golist').style.display = pickCount > 0 ? 'block' : 'none';
}
async function togglePick(cb, id) {
const picked = cb.checked;
cb.closest('.offer').classList.toggle('picked', picked);
pickCount += picked ? 1 : -1;
updatePick();
if (onlyPicked) filterOffers(); // keep the "only selected" view in sync
try {
await (window.cittiFetch || 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;
updatePick();
}
}
let onlyPicked = false;
function toggleOnlyPicked() {
onlyPicked = !onlyPicked;
document.getElementById('only-picked-btn').classList.toggle('active', onlyPicked);
filterOffers();
}
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))
&& (!onlyPicked || o.classList.contains('picked'));
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 {
// The refresh runs in the background (translation can be slow under rate
// limits), so we just kick it off and reload a little later to show
// progress — the page fills in as batches complete.
await fetch('/api/offers/refresh', {method: 'POST'});
btn.textContent = '⟳ Opdaterer i baggrunden…';
setTimeout(function () { window.location.reload(); }, 12000);
} catch (e) {
btn.textContent = '⟳ Opdater'; btn.disabled = false;
}
}
updatePick();
</script>
</body>
</html>

162
templates/trip.html Normal file
View File

@@ -0,0 +1,162 @@
<!DOCTYPE html>
<html lang="da">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Citti · {{ trip.label }}</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;
--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: 1.5rem; 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); }
.btn-back { background: var(--text); color: white; border: none; 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.ghost { background: transparent; color: var(--muted); border: 1px solid var(--border); }
.kpi-row { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 1.5rem; }
.kpi { background: var(--card); border: 1px solid var(--border); border-radius: 10px; padding: 1rem; }
.kpi-label { font-size: 11px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 4px; }
.kpi-val { font-size: 1.75rem; font-weight: 600; font-family: var(--mono); letter-spacing: -0.02em; }
.kpi-val.green { color: var(--green); }
.kpi-val.red { color: var(--accent); }
.kpi-sub { font-size: 11px; color: var(--muted); margin-top: 2px; }
.card { background: var(--card); border: 1px solid var(--border); border-radius: 10px; overflow: hidden; margin-bottom: 1.25rem; }
.card-title { background: var(--text); color: white; padding: 0.6rem 1rem; font-size: 12px; font-weight: 500; text-transform: uppercase; letter-spacing: 0.05em; }
.row { display: flex; align-items: center; justify-content: space-between; gap: 1rem; padding: 0.6rem 1rem; border-bottom: 1px solid var(--border); }
.row:last-child { border-bottom: none; }
.row-name { font-size: 14px; }
.row-qty { font-size: 12px; color: var(--muted); font-family: var(--mono); }
.row-price { font-family: var(--mono); font-weight: 600; color: var(--green); white-space: nowrap; }
.row-price.none { color: var(--muted); font-weight: 400; }
.extra-thumb { width: 28px; height: 28px; border-radius: 6px; object-fit: cover; vertical-align: middle; margin-right: 8px; }
.tag { font-size: 10px; color: var(--muted); border: 1px solid var(--border); border-radius: 4px; padding: 1px 5px; margin-left: 6px; text-transform: uppercase; letter-spacing: 0.04em; }
.empty-state { padding: 2rem; text-align: center; color: var(--muted); font-size: 14px; }
@media (max-width: 600px) { .kpi-row { grid-template-columns: repeat(3, 1fr); } .kpi-val { font-size: 1.3rem; } }
</style>
</head>
<body>
<div class="page">
<header>
<div>
<h1>Citti <span>{{ trip.label }}</span></h1>
<div style="font-size:12px;color:var(--muted);margin-top:4px">{{ trip.item_count }} varer · arkiveret</div>
</div>
<div style="display:flex;gap:8px">
<a href="/historik" class="btn-back ghost">← Historik</a>
</div>
</header>
{% set total_actual = trip.total_actual or 0 %}
{% set total_est = trip.total_est or 0 %}
{% set diff = (total_actual - total_est) if total_actual else 0 %}
<div class="kpi-row">
<div class="kpi">
<div class="kpi-label">Faktisk betalt</div>
{% if total_actual %}
<div class="kpi-val">{{ "{:,.0f}".format(total_actual).replace(",",".") }}</div>
<div class="kpi-sub">kr. registreret</div>
{% else %}
<div class="kpi-val" style="color:var(--muted)">—</div>
<div class="kpi-sub">ingen priser</div>
{% endif %}
</div>
<div class="kpi">
<div class="kpi-label">Estimeret</div>
<div class="kpi-val">{{ "{:,.0f}".format(total_est).replace(",",".") }}</div>
<div class="kpi-sub">kr. planlagt</div>
</div>
<div class="kpi">
<div class="kpi-label">Difference</div>
{% if total_actual %}
<div class="kpi-val {% if diff > 0 %}red{% else %}green{% endif %}">{% if diff > 0 %}+{% endif %}{{ "{:,.0f}".format(diff).replace(",",".") }}</div>
<div class="kpi-sub">kr.</div>
{% else %}
<div class="kpi-val" style="color:var(--muted)">—</div>
<div class="kpi-sub">-</div>
{% endif %}
</div>
</div>
{% if not sections and not custom_secs and not loose_extras %}
<div class="card"><div class="empty-state">Denne tur blev gemt uden afkrydsede varer.</div></div>
{% endif %}
{% for block in sections %}
<div class="card">
<div class="card-title">{{ block.sec.emoji }} {{ block.sec.title }}</div>
{% for row in block.picked %}
<div class="row">
<div>
<span class="row-name">{{ row.item.name }}</span>
{% set q = row.saved.qty or row.item.qty %}
{% if q and q != '—' %}<span class="row-qty"> · {{ q }}</span>{% endif %}
</div>
{% if row.saved.price %}
<span class="row-price">{{ "{:.2f}".format(row.saved.price).replace(".",",") }} kr.</span>
{% else %}
<span class="row-price none">✓</span>
{% endif %}
</div>
{% endfor %}
{% for e in block.extras %}
<div class="row">
<div>
{% if e.photo %}<img class="extra-thumb" src="/uploads/{{ e.photo }}" alt="">{% endif %}
<span class="row-name">{{ e.name }}</span><span class="tag">ekstra</span>
{% if e.note %}<span class="row-qty"> · {{ e.note }}</span>{% endif %}
</div>
{% if e.price %}<span class="row-price">{{ "{:.2f}".format(e.price).replace(".",",") }} kr.</span>{% else %}<span class="row-price none">—</span>{% endif %}
</div>
{% endfor %}
</div>
{% endfor %}
{% for cs in custom_secs %}
{% set cs_extras = by_sec.get('custom-' ~ cs.id, []) %}
{% if cs_extras %}
<div class="card">
<div class="card-title">{{ cs.emoji }} {{ cs.title }}</div>
{% for e in cs_extras %}
<div class="row">
<div>
{% if e.photo %}<img class="extra-thumb" src="/uploads/{{ e.photo }}" alt="">{% endif %}
<span class="row-name">{{ e.name }}</span>
{% if e.note %}<span class="row-qty"> · {{ e.note }}</span>{% endif %}
</div>
{% if e.price %}<span class="row-price">{{ "{:.2f}".format(e.price).replace(".",",") }} kr.</span>{% else %}<span class="row-price none">—</span>{% endif %}
</div>
{% endfor %}
</div>
{% endif %}
{% endfor %}
{% if loose_extras %}
<div class="card">
<div class="card-title">📦 Øvrige ekstra varer</div>
{% for e in loose_extras %}
<div class="row">
<div>
{% if e.photo %}<img class="extra-thumb" src="/uploads/{{ e.photo }}" alt="">{% endif %}
<span class="row-name">{{ e.name }}</span>
{% if e.note %}<span class="row-qty"> · {{ e.note }}</span>{% endif %}
</div>
{% if e.price %}<span class="row-price">{{ "{:.2f}".format(e.price).replace(".",",") }} kr.</span>{% else %}<span class="row-price none">—</span>{% endif %}
</div>
{% endfor %}
</div>
{% endif %}
</div>
</body>
</html>