Compare commits

..

22 Commits

Author SHA1 Message Date
Henrik Jess Nielsen
298f90812d feat(mobile): show estimate + ½kg price per item on phones
The estimate column is hidden on phones, so add a small 'est X kr · ½kg Y kr'
line under each item name, shown only on mobile. The ½kg (per-500g) price is
computed for weight items (line price ÷ kg × 0.5). The est column (desktop)
and this line now show the *computed* per-row price (offer price × quantity,
or quantity-scaled estimate), so each row matches what the total adds up.
2026-10-30 16:17:57 +01:00
Henrik Jess Nielsen
925174d80e fix(match): prefer standard/cheapest variant, not premium, for truthful estimates
A generic catalog item (e.g. 'Entrecote ½ kg') could match a premium offer
(Wagyu 250 €/kg, US-Beef), inflating the estimate — correct math, wrong
product. Tell the matcher to pick the ordinary/standard variant at the lowest
price and avoid premium/luxury (Wagyu, Dry-Aged, US-Beef, øko-premium) unless
the item names it. No price caps (that would be guesswork) — the estimate
stays raw offer price × quantity. Version marker in the match signature forces
a re-match so the new logic takes effect.
2026-10-30 14:51:18 +01:00
Henrik Jess Nielsen
b32a9a9fcb feat(add-item): photo → Claude vision suggests name + category
In 'Tilføj vare', taking/choosing a photo now sends it (downscaled client-
side) to Claude vision, which identifies the product and returns a Danish
name, German name, best-fit catalog section and a short note. The form is
prefilled and the suggested category shown — you just confirm and type the
price. Full photo is still uploaded on submit. Degrades gracefully: no
credential or a failed call just falls back to manual entry.

- /api/item/analyze (vision via _claude_json, now accepts image content)
- VISION_MODEL (Haiku by default; bump to sonnet via env for harder photos)
2026-10-30 14:27:30 +01:00
Henrik Jess Nielsen
b2390c4495 chore(header): Lübeck store, drop stale dates, link the Lübeck avis
- Remove the outdated 'Uge 23–25 · 03.06–23.06.2026' from the header, title,
  footer and analyse page
- Change the store from Langberger Weg 4, Flensburg to CITTI Lübeck
  (Herrenholz 14) across index/analyse/footer
- Add a '📄 Se hele avisen hos CITTI Lübeck' link on /tilbud to
  cittimarkt.de/angebote — the real German/Lübeck offers page, not the Danish
  Flensburg booklet that misled which offers apply in Lübeck
2026-10-30 14:13:13 +01:00
Henrik Jess Nielsen
97e420df2f fix(stats): estimate + budget now react to quantity changes
Estimeret total used each row's fixed line estimate, so changing a quantity
(6 → 8) didn't move the price or the per-day budget unless the item matched a
weight offer. Now scale an unmatched item's estimate by the quantity ratio
(current number ÷ default number via qtyNum), so doubling the amount ~doubles
its estimate. Combined with updateQty→recalcAll, price and budget update live
on every quantity edit.
2026-10-30 13:58:26 +01:00
Henrik Jess Nielsen
d2f6746557 fix(qty): edited quantity shows green 'changed', not an alarming red
Editing a quantity always saved, but the 'modified' class painted the field
accent-red, which read as a validation error ('can't change it'). Recolor it
to the green success style used by the actual-price field. Also make updateQty
call recalcAll so the estimate/budget react to quantity changes too, not just
the meal stats.
2026-10-30 13:55:32 +01:00
Henrik Jess Nielsen
b688fa491a feat(stats): Estimeret total uses real offer prices for matched items
When a catalog item matches a current Lübeck offer, compute its line cost
from the offer instead of the hardcoded estimate: offer price is per unit
(e.g. per 100 g), so multiply by the item's quantity (qtyToKg × €/kg × rate).
Only weight-based offers (g/kg) are converted — units that can't be matched
cleanly keep the estimate, so the total never goes garbage. Data-offer-*
attrs on matched rows; recalcAll prefers the offer line price. The total (and
the budget-per-day) now move toward actual prices as matches land.
2026-10-30 13:45:25 +01:00
Henrik Jess Nielsen
abd50a7569 feat(stats): budget-per-day block + computed savings
- New budget block: 'Pris pr. aftensmadsdag' = Estimeret total ÷
  Aftensmadsdage, checked against a ~200 kr/day budget (green 'holder ✓',
  red 'over budget' with accent background). Updates live with the list.
- Estimeret besparelse is no longer a hardcoded ~1.800: it's 35% of actual
  spend once prices are entered, else 35% of the live estimate.
2026-10-30 13:42:59 +01:00
Henrik Jess Nielsen
786ee368e5 feat(tilbud): clearly show which offers are already on the list
Picked offers were only marked by a checked box + faint green bg, easy to
miss while scrolling 467 offers (so you'd try to re-add them). Add a green
'✓ på seddel' badge + green left border on picked offers, and a '✓ Kun
valgte' filter button to show only what's already on the list. Driven by the
existing .picked class, so it updates instantly on pick/unpick.
2026-10-30 13:34:29 +01:00
Henrik Jess Nielsen
92d1ab62a0 feat(list): grouped Basisvarer staples, deduped against the catalog
Expand 'Basisvarer — husk ved CITTI' into 7 categories (Grundvarer, Protein,
Grønt & frugt, Mejeri, Køl & frys, Husholdning, Krydderier) with German names
for in-store navigation. Compared against the existing CITTI catalog so
nothing is duplicated (ris/pasta/konserves/tun/olier/frozen veg/soya/
cleaning already covered). Added 'Ris (stor pose)' by request; skipped items
the user already keeps at home (sennep/honning/eddike/sølvpapir) and fresh
veg (frozen veg covers it). Checkoffs persist and are offline-safe.
2026-10-30 13:17:44 +01:00
Henrik Jess Nielsen
9dc431ebd5 feat(list): Basisvarer checklist to grab at CITTI
Add a 'Basisvarer — husk ved CITTI' checklist for everyday staples the user
wants to buy at CITTI rather than in DK: Rugbrød, Bananer, Havregryn,
Tomater, Toiletpapir — each with a German name for in-store navigation.
Checkoffs persist (prices table, keyed basis-*) and are offline-safe via
saveToServer/cittiFetch. Skips Kyllingebryst/Kaffe/Opvasketabs, which are
already in the CITTI catalog.
2026-10-30 13:07:54 +01:00
Henrik Jess Nielsen
dc53fbfb9b feat(stats): compute Kødportioner and Aftensmadsdage from the list
Both tiles were hardcoded. Parse the quantity strings (6 × ½ kg, 3 kg,
~700g, 2 stk.) live: Kødportioner = total Kød & fisk weight / 500g;
Aftensmadsdage = meat portions + pasta/tortelloni packs. Recomputed on
load and whenever a quantity changes, so the trip's food volume is
visible while editing. Defaults now read ~30 portions / ~36 dinners.
2026-10-30 12:51:24 +01:00
Henrik Jess Nielsen
32e6841b8c feat(stats): live 'Estimeret total' reflecting the actual list
Estimeret total was a hardcoded ~4.400. Make it dynamic: every list row
(fixed catalog, added extras, picked Lübeck offers) carries data-est in DKK,
and recalcAll sums them, so the tile updates live when you add/remove items
or pick/unpick offers. 'Faktisk betalt' was already live; the Aftensmadsdage
and Kødportioner tiles stay as illustrative figures.
2026-10-30 12:45:55 +01:00
Henrik Jess Nielsen
a5279bb01d feat(tilbud): 'Gå til seddel' button showing how many offers are selected
Ticking an offer already adds it to the shopping list instantly (it shows in
the Lübeck-tilbud section), but that wasn't visible. Add a fixed 'N valgt ·
Gå til seddel' button that appears once anything is selected, so the link
between the checklist and the list is obvious and you can jump straight to it.
2026-10-30 12:41:28 +01:00
Henrik Jess Nielsen
c5e4a326e0 chore(deploy): prefer a dedicated API key over the shared OAuth token
The OAuth token shares one rate budget across everything on the subscription
(incl. interactive Claude Code sessions), so citti's translation is almost
always throttled while coding — hence the page staying German. Template now
emits ANTHROPIC_API_KEY from citti/anthropic_api_key when set (its own rate
budget, no contention), else the OAuth token. Only one var is written so an
empty key can't shadow the token.
2026-10-30 12:19:45 +01:00
Henrik Jess Nielsen
67ffc07a04 fix(offers): background refresh + skip unchanged matching
Two things made Opdater show 'Opdatering fejlede': the refresh ran
synchronously (so a slow, rate-limited translate timed out the browser)
and a 429 returned 502. Now:
- /api/offers/refresh starts the work in a background thread and returns
  immediately; the button says 'Opdaterer i baggrunden' and reloads a bit
  later as batches land. A lock prevents overlapping runs.
- match_offers_ai skips the Claude call when the offer set is unchanged
  since the last successful match (hashed), so it runs ~weekly (when the
  avis turns over), not every daily refresh — fewer calls, less cost, less
  rate pressure.
2026-10-30 12:16:30 +01:00
Henrik Jess Nielsen
bf5439f7ad fix(offers): survive Claude rate limits (429)
The OAuth token works (429 = authenticated but throttled); subscription
tokens have a tight output-tokens/min limit and the API reserves max_tokens
against it, so the big translate calls 429'd and the error surfaced as a
failed refresh.

- Smaller requests: translate max_tokens 16000->4000, batch 250->100; match
  max_tokens 8000->2000 (less reserved OTPM per call)
- Client max_retries=8 so the SDK waits out 429s (respects retry-after)
- Pace 1.5s between translate batches
- Matching no longer fails the whole refresh on a 429 — it keeps the existing
  matches; translations are cached per batch, so progress persists and the
  next refresh finishes the rest
2026-10-30 12:07:01 +01:00
Henrik Jess Nielsen
66031345d2 feat(pwa): installable — PNG icons + beforeinstallprompt button
Chrome's install prompt needs 192 and 512 PNG icons (SVG-only often isn't
enough, especially on Android). Add them and reference them in the manifest
(any + maskable). offline.js captures beforeinstallprompt and shows an
'Installér app' button that triggers the native prompt, and clears it on
appinstalled. Bump SW cache to v2 so the new manifest/icons take effect.
2026-10-30 11:58:46 +01:00
Henrik Jess Nielsen
b640d9950c feat(pwa): offline support so the list works in-store with no net
No signal inside the store made the server-rendered app unusable. Make it
an installable PWA:
- service worker (static/sw.js) caches pages (network-first, cache fallback)
  and assets, served from root so scope is /
- offline.js: cittiFetch() queues check-off / price / qty / pick POSTs in
  localStorage when offline and replays them in order on reconnect, with an
  optimistic response and an Offline/Syncing status badge
- manifest + icon for add-to-home-screen; PWA meta tags on the in-store pages
- in-store mutations (saveToServer, pick/unpick) go through cittiFetch;
  archive/refresh/add still need net by design
- Dockerfile copies static/
Open once online first so the SW can cache; then it works offline.
2026-10-30 11:54:38 +01:00
Henrik Jess Nielsen
1dec3b7bd8 fix(offers): support Claude OAuth token (citti/claude_oauth_token)
The key was provisioned as an OAuth token, not an API key. Read it from
Consul into ANTHROPIC_AUTH_TOKEN (the SDK uses it as a Bearer credential)
and add the required anthropic-beta: oauth-2025-04-20 header on the
messages calls. Credential guards now accept a key or a token. The job no
longer sets ANTHROPIC_API_KEY, since even an empty value would shadow the
token.
2026-10-30 11:46:57 +01:00
Henrik Jess Nielsen
06656ffd4f fix(deploy): reuse blaaai Consul key so citti gets a Claude key
Prod container had no ANTHROPIC_API_KEY (refresh returned 0/0 instantly;
homepage showed only the 9 heuristic matches), so offers stayed German.
The template read citti/anthropic_api_key, a path never set. Fall back to
the existing blaaai Consul key via or(), reusing BlaaAi's key with no new
secret to provision.
2026-10-30 11:28:19 +01:00
Henrik Jess Nielsen
f374088211 fix(offers): DE→DA translation returned nothing — disable thinking, batch big
Prod showed 0 of 467 headings translated while AI matching worked. Cause:
Haiku 5.5 defaults thinking on, which consumed the 4000-token budget on the
40-item translation batches and truncated the JSON, so every batch fell back
to German. Matching (one small response) slipped through.

- Disable thinking on both Claude calls (mechanical JSON tasks), via a shared
  _claude_json helper that retries without the flag if a model rejects it
- Raise max_tokens (16000 translate / 8000 match) so output fits even if
  thinking stays on
- Batch ~all headings in 1-2 calls (250) instead of 40, so the preamble isn't
  repeated per batch and we don't hammer the rate limit (cheaper, as suggested)
2026-10-30 11:19:40 +01:00
13 changed files with 732 additions and 62 deletions

View File

@@ -26,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 \

204
app.py
View File

@@ -3,6 +3,7 @@ import os
import re
import json
import time
import hashlib
import threading
import unicodedata
import socket
@@ -33,10 +34,17 @@ OFFERS_REFRESH_HOURS = float(os.environ.get("OFFERS_REFRESH_HOURS", "20"))
# 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")
TRANSLATE_BATCH = int(os.environ.get("TRANSLATE_BATCH", "40"))
# 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")
# Vision: identify + categorise a product from a photo in "Tilføj vare".
VISION_MODEL = os.environ.get("VISION_MODEL", "claude-haiku-5-5")
SECTIONS = [
{"id": "koed", "emoji": "🥩", "title": "Kød & fisk", "est": 1580, "varer": [
@@ -297,6 +305,33 @@ def fetch_offers():
'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, content):
"""One Claude call returning text. `content` is a prompt string or a list of
content blocks (e.g. an image + text for vision). 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. 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": content}],
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)."""
@@ -306,12 +341,7 @@ def _translate_batch(client, headings):
"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)
msg = client.messages.create(
model=TRANSLATE_MODEL,
max_tokens=4000,
messages=[{"role": "user", "content": prompt}],
)
text = "".join(b.text for b in msg.content if b.type == "text")
text = _claude_json(client, TRANSLATE_MODEL, 4000, prompt)
m = re.search(r"\[.*\]", text, re.DOTALL)
out = list(headings)
if not m:
@@ -325,9 +355,10 @@ def _translate_batch(client, headings):
def translate_missing():
"""Translate offer headings that have no Danish cache entry yet. Needs
ANTHROPIC_API_KEY (as in BlaaAi); without it, headings stay German."""
if not os.environ.get("ANTHROPIC_API_KEY"):
"""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(
@@ -340,14 +371,18 @@ def translate_missing():
except Exception as e:
app.logger.warning("citti translate: anthropic SDK unavailable: %s", e)
return 0
client = anthropic.Anthropic()
client = anthropic.Anthropic(max_retries=CLAUDE_MAX_RETRIES)
now = datetime.now(timezone.utc).isoformat()
done = 0
for i in range(0, len(todo), TRANSLATE_BATCH):
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:
@@ -355,6 +390,8 @@ def translate_missing():
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
@@ -374,15 +411,30 @@ def attach_da(tmap, *offer_lists):
def match_offers_ai():
"""Ask Claude which offer (if any) is the same product as each fixed item.
Stores results in offer_matches. Needs ANTHROPIC_API_KEY; on no key or
Stores results in offer_matches. Needs a Claude credential; on none or
failure the heuristic matcher remains the fallback."""
if not os.environ.get("ANTHROPIC_API_KEY"):
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. The leading version forces a re-match
# whenever the matching logic/prompt changes (bump it when editing them).
MATCH_VERSION = "v2-standard-not-premium"
sig = hashlib.md5(
(MATCH_VERSION + "\n" + "\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:
@@ -403,14 +455,20 @@ def match_offers_ai():
"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 "
"julekalender'). Når varen er generisk (fx 'Entrecote ½ kg'), vælg den "
"ALMINDELIGE/standard variant til den LAVESTE pris — undgå premium-/"
"luksus-varianter (Wagyu, Dry-Aged, US-Beef, øko-premium) medmindre varen "
"selv nævner det, da de giver et urealistisk højt estimat. Returnér KUN et "
'JSON-array [{"item_key":"...","offer_id":"..."}] med de sikre match, '
"intet andet.")
client = anthropic.Anthropic()
msg = client.messages.create(
model=MATCH_MODEL, max_tokens=4000,
messages=[{"role": "user", "content": prompt}])
text = "".join(b.text for b in msg.content if b.type == "text")
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])
@@ -428,6 +486,7 @@ def match_offers_ai():
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)
@@ -459,6 +518,27 @@ def refresh_offers_safe():
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')
@@ -601,6 +681,54 @@ def add_item():
name=name, section_key=section_key, price=price, note=note)
@app.route('/api/item/analyze', methods=['POST'])
def analyze_item():
"""Identify + categorise a product from a photo via Claude vision. Returns
suggestions {name, de, section, note}; price is always entered manually."""
if not _claude_mode():
return jsonify(ok=False, error='no-credential'), 503
f = request.files.get('photo')
if not f or not f.filename:
return jsonify(ok=False, error='no-photo'), 400
import base64
ext = (os.path.splitext(f.filename)[1] or '.jpg').lower()
media = {'png': 'image/png', 'webp': 'image/webp', 'gif': 'image/gif'}.get(
ext.lstrip('.'), 'image/jpeg')
b64 = base64.standard_b64encode(f.read()).decode()
secs = "; ".join(f"{s['id']}={s['title']}" for s in SECTIONS)
prompt = (
"Billedet viser én dagligvare fra et tysk supermarked (CITTI). "
"Identificér varen og returnér KUN JSON, intet andet:\n"
'{"name":"kort dansk produktnavn","de":"tysk navn hvis synligt ellers null",'
'"section":"bedst passende sektions-id fra listen, ellers null",'
'"note":"kort note, fx mærke eller størrelse, ellers null"}\n'
"Sektioner: " + secs)
content = [
{"type": "image", "source": {"type": "base64", "media_type": media, "data": b64}},
{"type": "text", "text": prompt},
]
try:
import anthropic
client = anthropic.Anthropic(max_retries=2)
text = _claude_json(client, VISION_MODEL, 1000, content)
except Exception as e:
app.logger.warning("citti analyze failed: %s", e)
return jsonify(ok=False, error='analyze-failed'), 502
m = re.search(r"\{.*\}", text, re.DOTALL)
if not m:
return jsonify(ok=True, name=None, section=None, note=None, de=None)
try:
d = json.loads(m.group(0))
except Exception:
return jsonify(ok=True, name=None, section=None, note=None, de=None)
sec = d.get('section')
if sec not in {s['id'] for s in SECTIONS}:
sec = None
return jsonify(ok=True, name=d.get('name'), de=d.get('de'),
section=sec, note=d.get('note'))
@app.route('/api/item/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
with get_db() as c:
@@ -623,6 +751,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
@@ -776,10 +934,8 @@ def offer_pick():
@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)
started = refresh_offers_async()
return jsonify(ok=True, started=started)
@app.route('/koeb-nu')

View File

@@ -97,12 +97,21 @@ job "citti" {
HOST = "0.0.0.0"
}
# Claude key for DA translation + AI offer matching (same account as
# BlaaAi). keyOrDefault so a missing KV never blocks deploy — without it
# offers simply stay German and the token heuristic handles matching.
# 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
ANTHROPIC_API_KEY={{ keyOrDefault "citti/anthropic_api_key" "" }}
{{ 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

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>

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; }
@@ -57,6 +71,7 @@
.item-name { padding: 0.7rem 0.5rem; font-size: 14px; }
.item-name .note { font-size: 11px; color: var(--muted); display: block; margin-top: 1px; }
.item-name .de { font-size: 10px; color: #b0aba3; display: block; margin-top: 0; font-style: italic; }
.item-name .row-est-m { display: none; font-size: 10px; color: var(--muted); font-family: var(--mono); margin-top: 2px; }
.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); }
@@ -64,7 +79,7 @@
.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; }
@@ -93,6 +108,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; }
@@ -141,6 +158,8 @@
.btn-submit { width: 100%; background: var(--accent); color: white; border: none; border-radius: 10px; padding: 14px; font-size: 16px; font-weight: 600; font-family: var(--sans); cursor: pointer; margin-top: 0.5rem; }
.btn-submit:active { opacity: 0.85; }
.modal-context { background: var(--accent-light); border-radius: 8px; padding: 8px 12px; font-size: 13px; color: var(--accent); font-weight: 500; margin-bottom: 1rem; }
.ai-suggest { background: var(--green-light); border: 1px solid #a8d5bc; border-radius: 8px; padding: 9px 12px; font-size: 13px; color: var(--green); margin-bottom: 1rem; line-height: 1.4; }
.ai-suggest.loading { background: var(--bg); color: var(--muted); border-color: var(--border); }
.saving-indicator { position: fixed; top: 0.75rem; right: 0.75rem; background: var(--green); color: white; border-radius: 6px; padding: 4px 10px; font-size: 12px; font-family: var(--mono); opacity: 0; transition: opacity 0.3s; z-index: 50; pointer-events: none; }
.saving-indicator.show { opacity: 1; }
@@ -151,6 +170,7 @@
.header-actions { flex-direction: row; align-items: center; }
.item-row { grid-template-columns: 28px 1fr 64px 78px; }
.item-est { display: none; }
.item-name .row-est-m { display: block; }
.col-headers { grid-template-columns: 28px 1fr 64px 78px; }
.col-h:nth-child(4) { display: none; }
.extra-item-row { grid-template-columns: 28px 1fr auto auto; }
@@ -166,9 +186,8 @@
<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>
@@ -192,18 +211,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>
@@ -212,6 +231,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">
@@ -230,7 +258,8 @@
<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 }}
@@ -239,6 +268,7 @@
{% 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 %}
<span class="row-est-m"></span>
</div>
<div class="item-qty">
<input type="text" value="{{ s.get('qty') or item.qty }}" placeholder="{{ item.qty }}"
@@ -252,7 +282,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 }}
@@ -275,7 +305,7 @@
<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-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 }}
@@ -310,7 +340,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>
@@ -325,6 +355,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>
@@ -345,7 +428,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>
@@ -387,7 +470,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 -->
@@ -404,6 +487,7 @@
<button class="modal-close" onclick="closeItemModal()">×</button>
</div>
<div class="modal-context" id="item-modal-ctx" style="display:none"></div>
<div id="ai-suggest" class="ai-suggest" style="display:none"></div>
<form id="add-form" onsubmit="submitItem(event)">
<input type="hidden" name="section_key" id="item-section-key">
<div class="form-group">
@@ -470,6 +554,23 @@
<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() {
@@ -502,13 +603,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;
@@ -516,10 +622,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;
@@ -535,11 +704,52 @@ 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 qi = r.querySelector('.item-qty input');
const offer = offerLineDkk(r); // real offer price if matched
let line;
if (offer != null) {
line = offer;
} else {
line = parseFloat(r.dataset.est) || 0;
if (qi) { // scale estimate with quantity
const cur = qtyNum(qi.value.trim() || qi.placeholder);
const def = qtyNum(qi.placeholder);
if (cur != null && def != null && def > 0) line = line * (cur / def);
}
}
est += line;
// Per-row display: computed estimate + ½kg price (for weight items). The
// est column is hidden on phones, so also fill the mobile sub-line.
if (qi) {
const col = r.querySelector('.item-est');
if (col) col.textContent = line > 0 ? Math.round(line).toLocaleString('da-DK') : '—';
const sub = r.querySelector('.row-est-m');
if (sub) {
const kg = qtyToKg(qi.value.trim() || qi.placeholder);
const per500 = (kg > 0 && line > 0) ? Math.round(line / kg * 0.5) : null;
sub.textContent = (line > 0 ? 'est ' + Math.round(line).toLocaleString('da-DK') + ' kr' : '')
+ (per500 ? ' · ½kg ' + per500 + ' kr' : '');
}
}
});
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
@@ -564,11 +774,69 @@ function closeItemModal() {
document.getElementById('item-modal').classList.remove('open');
document.getElementById('add-form').reset();
document.getElementById('photo-preview').style.display = 'none';
document.getElementById('ai-suggest').style.display = 'none';
}
function previewPhoto(input) {
const p = document.getElementById('photo-preview');
if (input.files && input.files[0]) { p.src = URL.createObjectURL(input.files[0]); p.style.display = 'block'; }
if (input.files && input.files[0]) {
p.src = URL.createObjectURL(input.files[0]); p.style.display = 'block';
analyzePhoto(input.files[0]);
}
}
const SEC_NAMES = {koed:'🥩 Kød & fisk', frost:'🧊 Frostgrønt', mejeri:'🧀 Mejeri & ost',
pasta:'🍝 Pasta', groent:'🥗 Grønt & tørvarer', konserves:'🥫 Konserves',
indisk:'🌶️ Indisk & karry', mex:'🌮 Mexicansk & asiatisk', drikke:'🍺 Drikkevarer', hus:'🏠 Husholdning'};
// Downscale for the AI call only (fast/cheap, avoids size limits); the full
// photo is still uploaded on submit.
function downscaleImage(file, maxDim) {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
const scale = Math.min(1, maxDim / Math.max(img.width, img.height));
const w = Math.round(img.width * scale), h = Math.round(img.height * scale);
const c = document.createElement('canvas');
c.width = w; c.height = h;
c.getContext('2d').drawImage(img, 0, 0, w, h);
c.toBlob((b) => resolve(b || file), 'image/jpeg', 0.85);
};
img.onerror = () => resolve(file);
img.src = URL.createObjectURL(file);
});
}
async function analyzePhoto(file) {
const box = document.getElementById('ai-suggest');
box.style.display = 'block';
box.className = 'ai-suggest loading';
box.textContent = '🪄 Analyserer billede…';
try {
const small = await downscaleImage(file, 1024);
const fd = new FormData(); fd.append('photo', small, 'photo.jpg');
const res = await fetch('/api/item/analyze', {method: 'POST', body: fd});
if (!res.ok) throw new Error('fail');
const d = await res.json();
const form = document.getElementById('add-form');
const skInput = document.getElementById('item-section-key');
if (d.name && !form.name.value.trim()) form.name.value = d.name;
if (!form.note.value.trim()) {
const parts = [];
if (d.note) parts.push(d.note);
if (d.de) parts.push('🇩🇪 ' + d.de);
if (parts.length) form.note.value = parts.join(' · ');
}
if (d.section && !skInput.value) skInput.value = d.section; // keep an explicitly chosen section
const eff = skInput.value;
const cat = eff ? (SEC_NAMES[eff] || eff) : 'Diverse (ingen kategori)';
box.className = 'ai-suggest done';
box.innerHTML = '🪄 Forslag: <b>' + (d.name || '?') + '</b> · ' + cat
+ ' <span style="color:var(--muted)">— ret hvis forkert, og tast prisen</span>';
} catch (e) {
box.className = 'ai-suggest';
box.innerHTML = '<span style="color:var(--muted)">Kunne ikke analysere billedet — udfyld manuelt.</span>';
}
}
async function submitItem(e) {
@@ -609,14 +877,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
@@ -680,7 +951,7 @@ function toggleOffer(cb) {
}
async function removeOffer(id) {
await fetch('/api/offers/pick', {
await (window.cittiFetch || fetch)('/api/offers/pick', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({id, picked: false})
@@ -690,6 +961,7 @@ async function removeOffer(id) {
if (!document.querySelectorAll('#picks-table .item-row').length) {
document.getElementById('sec-picks').style.display = 'none';
}
recalcAll();
showSaved();
}

View File

@@ -3,6 +3,13 @@
<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>

View File

@@ -3,6 +3,13 @@
<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>
@@ -33,6 +40,10 @@
.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; }
@@ -58,7 +69,8 @@
<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
{% 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">
@@ -71,6 +83,7 @@
<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>
@@ -88,7 +101,7 @@
<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 }}</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 %}
@@ -110,16 +123,30 @@
{% 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;
document.getElementById('pick-count').textContent = pickCount + ' på seddel';
updatePick();
if (onlyPicked) filterOffers(); // keep the "only selected" view in sync
try {
await fetch('/api/offers/pick', {
await (window.cittiFetch || fetch)('/api/offers/pick', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({id, picked})
@@ -128,16 +155,24 @@ async function togglePick(cb, id) {
cb.checked = !picked;
cb.closest('.offer').classList.toggle('picked', !picked);
pickCount += picked ? -1 : 1;
document.getElementById('pick-count').textContent = pickCount + ' på seddel';
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);
const match = (!q || o.dataset.name.includes(q))
&& (!onlyPicked || o.classList.contains('picked'));
o.classList.toggle('hidden', !match);
if (match) any = true;
});
@@ -149,15 +184,18 @@ 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.');
// 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) {
alert('Opdatering fejlede. Prøv igen om lidt.');
}
btn.textContent = '⟳ Opdater'; btn.disabled = false;
}
}
updatePick();
</script>
</body>
</html>