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.
917 lines
42 KiB
Python
917 lines
42 KiB
Python
import sqlite3
|
||
import os
|
||
import re
|
||
import json
|
||
import time
|
||
import threading
|
||
import unicodedata
|
||
import socket
|
||
import urllib.request
|
||
import urllib.error
|
||
from pathlib import Path
|
||
from datetime import datetime, timezone
|
||
from flask import Flask, render_template, request, jsonify, send_from_directory
|
||
|
||
app = Flask(__name__)
|
||
DATA_DIR = Path(os.environ.get("DATA_DIR", "."))
|
||
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")
|
||
# Big batches: ~all headings in 1-2 calls, so the instruction preamble isn't
|
||
# repeated per 40 and we don't hammer the rate limit. ~22 output tokens/item,
|
||
# so 250 stays well under max_tokens=16000.
|
||
TRANSLATE_BATCH = int(os.environ.get("TRANSLATE_BATCH", "250"))
|
||
# 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"]},
|
||
{"key": "nakkekoteletter", "name": "Nakkekoteletter ½ kg", "de": "Schweinenackenkoteletten ½ kg", "note": "Med/uden krydderi", "qty": "6 × ½ kg", "est": 191.94},
|
||
{"key": "kyllingebryst", "name": "Kyllingebryst ½ kg", "de": "Hähnchenbrustfilet ½ kg", "note": "Texas-marinade", "qty": "6 × ½ kg", "est": 359.94},
|
||
{"key": "hakket-oksekoed", "name": "Hakket oksekød", "de": "Rinderhackfleisch", "note": "Køddisk — spørg personalet", "qty": "3 kg", "est": 240},
|
||
{"key": "rumpsteak", "name": "Rumpsteak ½ kg", "de": "Rumpsteak ½ kg", "note": "Modnet, tyske kvier", "qty": "1 × ½ kg", "est": 167.99},
|
||
{"key": "lakseside", "name": "Lakseside premium", "de": "Lachsseite premium", "note": "15,99/100g · tag ~700g", "qty": "~700g", "est": 112},
|
||
{"key": "grillpoelser", "name": "Gerstand grillpølser", "de": "Gerstand Grillwürste", "note": "10 stk. à 100g", "qty": "1 kg", "est": 74.99},
|
||
{"key": "bacon", "name": "Steinemann bacon i skiver","de": "Steinemann Bauchspeck in Scheiben", "note": "Røget · fryseegnet", "qty": "1 kg", "est": 74.99},
|
||
]},
|
||
{"id": "frost", "emoji": "🧊", "title": "Frostgrønt · 3 kg poser", "est": 100, "varer": [
|
||
{"key": "wok-mix", "name": "Wok-mix blandede grøntsager", "de": "Wok-Mix Gemüsemischung", "qty": "3 kg", "est": 40},
|
||
{"key": "aerter", "name": "Ærter", "de": "Erbsen", "qty": "3 kg", "est": 30},
|
||
{"key": "broccoli", "name": "Broccoli", "de": "Brokkoli", "qty": "3 kg", "est": 35},
|
||
{"key": "frost-andet", "name": "Hvad der ellers frister", "de": "Was sonst verlockend ist", "note": "Tjek frysedisken", "qty": "—", "est": 0},
|
||
]},
|
||
{"id": "mejeri", "emoji": "🧀", "title": "Mejeri, ost & frost", "est": 185, "varer": [
|
||
{"key": "feta", "name": "Greco Schaffeta feta 150g", "de": "Greco Schaffeta Feta 150g", "note": "70% fåremælk", "qty": "3 stk.", "est": 44.97},
|
||
{"key": "frutti-mare", "name": "Frutti di Mare", "de": "Frutti di Mare", "note": "Rejer, muslinger, blæksprutte", "qty": "1 kg", "est": 59.99},
|
||
{"key": "tigerrejer", "name": "Sorte tigerrejer frost", "de": "Schwarze Tigergarnelen TK", "note": "Rå, pillede · wok/grill", "qty": "1 kg", "est": 79.99},
|
||
]},
|
||
{"id": "pasta", "emoji": "🍝", "title": "Pasta frisk køl · Gut & Günstig ~800g", "est": 160, "varer": [
|
||
{"key": "tortelloni-skinke", "name": "Tortelloni Skinke", "de": "Tortelloni Schinken", "qty": "2 stk.", "est": 55},
|
||
{"key": "tortelloni-spinat", "name": "Tortelloni Spinat & ricotta", "de": "Tortelloni Spinat & Ricotta", "qty": "2 stk.", "est": 55},
|
||
{"key": "tortelloni-valg", "name": "Tortelloni valgfri variant", "de": "Tortelloni nach Wahl", "note": "Svampe, tomat-mozzarella o.l.", "qty": "2 stk.", "est": 55},
|
||
]},
|
||
{"id": "groent", "emoji": "🥗", "title": "Grønt, olier & tørvarer", "est": 245, "varer": [
|
||
{"key": "avocado", "name": "Avocado Hass", "de": "Avocado Hass", "note": "Fra Peru, SanLucar", "qty": "5 stk.", "est": 74.95},
|
||
{"key": "olivenolie", "name": "Bertolli olivenolie extra vergine", "de": "Bertolli Olivenöl extra vergine", "qty": "1L", "est": 99.99},
|
||
{"key": "mutti", "name": "Mutti passata", "de": "Mutti Passata", "note": "Natur eller basilikum", "qty": "3 × 700g", "est": 44.97},
|
||
{"key": "rustichella", "name": "Rustichella d'Abruzzo pasta", "de": "Rustichella d'Abruzzo Pasta", "qty": "4 × 500g", "est": 75.96},
|
||
]},
|
||
{"id": "konserves", "emoji": "🥫", "title": "Konserves — tomat & basis", "est": 185, "varer": [
|
||
{"key": "hakkede-tomater", "name": "Hakkede tomater 400g", "de": "Gehackte Tomaten 400g", "qty": "8 dåser", "est": 50},
|
||
{"key": "flaede-tomater", "name": "Flåede tomater 400g", "de": "Geschälte Tomaten 400g", "qty": "4 dåser", "est": 25},
|
||
{"key": "tomatpure", "name": "Tomatpuré / koncentrat", "de": "Tomatenmark / -konzentrat", "qty": "4 stk.", "est": 35},
|
||
{"key": "tun", "name": "Tun i olie 80g", "de": "Thunfisch in Öl 80g", "qty": "6 dåser", "est": 47},
|
||
{"key": "majs", "name": "Majs 340g", "de": "Mais 340g", "qty": "4 dåser", "est": 28},
|
||
]},
|
||
{"id": "indisk", "emoji": "🌶️", "title": "Indisk & karry", "est": 160, "varer": [
|
||
{"key": "tikka-masala", "name": "Tikka masala sauce", "de": "Tikka Masala Sauce", "note": "350–500g · Taste of India", "qty": "5 stk.", "est": 70},
|
||
{"key": "karrypasta-roed", "name": "Karrypasta rød 50g", "de": "Rote Currypaste 50g", "qty": "2 stk.", "est": 20},
|
||
{"key": "karrypasta-groen", "name": "Karrypasta grøn 50g", "de": "Grüne Currypaste 50g", "qty": "2 stk.", "est": 20},
|
||
{"key": "karrypasta-gul", "name": "Karrypasta gul/mild", "de": "Gelbe Currypaste/mild", "qty": "2 stk.", "est": 20},
|
||
{"key": "mango-chutney", "name": "Mango chutney 300g", "de": "Mango-Chutney 300g", "qty": "2 stk.", "est": 24},
|
||
{"key": "basmatiris", "name": "Basmatiris 1 kg", "de": "Basmatireis 1 kg", "qty": "2 stk.", "est": 28},
|
||
]},
|
||
{"id": "mex", "emoji": "🌮", "title": "Mexicansk & asiatisk", "est": 185, "varer": [
|
||
{"key": "tacokrydderi", "name": "Tacokrydderi pakke", "de": "Taco-Gewürzmischung", "qty": "6 stk.", "est": 33},
|
||
{"key": "jalapenos", "name": "Jalapeños på glas 200g", "de": "Jalapeños im Glas 200g", "qty": "2 stk.", "est": 16},
|
||
{"key": "salsa", "name": "Salsa / tomatdip 300g", "de": "Salsa / Tomaten-Dip 300g", "qty": "2 stk.", "est": 19},
|
||
{"key": "tacoshells", "name": "Tacoshells / tortilla wraps","de": "Taco-Shells / Tortilla-Wraps","qty": "2 stk.", "est": 24},
|
||
{"key": "kokosmalk", "name": "Kokosmælk 400ml", "de": "Kokosmilch 400ml", "qty": "6 dåser", "est": 47},
|
||
{"key": "sojasauce", "name": "Sojasauce 250ml", "de": "Sojasoße 250ml", "qty": "1 stk.", "est": 10},
|
||
{"key": "bambusskud", "name": "Bambusskud / vandkastanjer","de": "Bambussprossen / Wasserkastanien","qty": "2 dåser", "est": 14},
|
||
]},
|
||
{"id": "drikke", "emoji": "🍺", "title": "Drikkevarer", "est": 530, "varer": [
|
||
{"key": "carlsberg", "name": "Carlsberg / Carls Special 0,33L", "de": "Carlsberg / Carls Special 0,33L", "qty": "24 stk.", "est": 79, "badges": ["kasse"]},
|
||
{"key": "pepsi-max", "name": "Pepsi Max 1,5L", "de": "Pepsi Max 1,5L", "qty": "6 stk.", "est": 49.99, "badges": ["kasse"]},
|
||
{"key": "faxe-kondi", "name": "Faxe Kondi Appelsin 0,33L", "de": "Faxe Kondi Orange 0,33L", "qty": "24 stk.", "est": 54.99, "badges": ["kasse"]},
|
||
{"key": "kuehling-vin", "name": "Kühling hvid-/rosévin 0,75L", "de": "Kühling Weiß-/Roséwein 0,75L", "qty": "4 stk.", "est": 159.96, "badges": ["card"]},
|
||
{"key": "grauburgunder", "name": "Grauburgunder hvidvin 1,5L", "de": "Grauburgunder Weißwein 1,5L", "qty": "1 stk.", "est": 59.99, "badges": ["card"]},
|
||
{"key": "kaffe", "name": "Eduscho Caffè Crema hele bønner", "de": "Eduscho Caffè Crema ganze Bohnen", "qty": "1 kg", "est": 104.99},
|
||
]},
|
||
{"id": "hus", "emoji": "🏠", "title": "Husholdning & skafferi", "est": 535, "varer": [
|
||
{"key": "ariel", "name": "Ariel vaskemiddel", "de": "Ariel Waschmittel", "note": "100–111 vaske", "qty": "1 stk.", "est": 199.90},
|
||
{"key": "finish", "name": "Finish opvasketabs", "de": "Finish Spülmaschinentabs", "note": "64 stk.", "qty": "1 stk.", "est": 59.99},
|
||
{"key": "cashew", "name": "BASE Culinar cashewnødder", "de": "BASE Culinar Cashewkerne", "qty": "1 kg", "est": 79.99},
|
||
{"key": "nutella", "name": "Nutella 1 kg glas", "de": "Nutella 1 kg Glas", "qty": "1 stk.", "est": 49.99, "badges": ["card"]},
|
||
{"key": "biscoff", "name": "Lotus Biscoff smørepålæg 1,6 kg", "de": "Lotus Biscoff Brotaufstrich 1,6 kg", "qty": "1 stk.", "est": 99.99, "badges": ["card"]},
|
||
{"key": "haribo", "name": "Haribo vingummi / lakrids", "de": "Haribo Weingummi / Lakritz", "note": "800–1000g", "qty": "1 stk.", "est": 44.99},
|
||
]},
|
||
]
|
||
|
||
|
||
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('-')
|
||
|
||
|
||
def get_db():
|
||
conn = sqlite3.connect(DB)
|
||
conn.row_factory = sqlite3.Row
|
||
return conn
|
||
|
||
|
||
def init_db():
|
||
with get_db() as c:
|
||
c.execute("""CREATE TABLE IF NOT EXISTS prices (
|
||
key TEXT PRIMARY KEY, price REAL, checked INT DEFAULT 0, qty TEXT, updated TEXT)""")
|
||
c.execute("""CREATE TABLE IF NOT EXISTS extras (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
name TEXT, section_key TEXT, price REAL,
|
||
photo TEXT, note TEXT, created TEXT)""")
|
||
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:
|
||
pass
|
||
try:
|
||
c.execute("ALTER TABLE prices ADD COLUMN qty TEXT")
|
||
except Exception:
|
||
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, 16000, 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()
|
||
now = datetime.now(timezone.utc).isoformat()
|
||
done = 0
|
||
for i in range(0, len(todo), TRANSLATE_BATCH):
|
||
batch = todo[i:i + TRANSLATE_BATCH]
|
||
try:
|
||
das = _translate_batch(client, batch)
|
||
except Exception as e:
|
||
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)
|
||
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
|
||
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()
|
||
text = _claude_json(client, MATCH_MODEL, 8000, prompt)
|
||
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))
|
||
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
|
||
|
||
|
||
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,
|
||
picks=picks, eur_dkk=EUR_DKK, deals=deals)
|
||
|
||
|
||
@app.route('/api/price', methods=['POST'])
|
||
def save_price():
|
||
d = request.json
|
||
key = d.get('key')
|
||
price = d.get('price')
|
||
checked = int(d.get('checked', 0))
|
||
qty = d.get('qty') or None
|
||
if not key:
|
||
return jsonify(error='missing key'), 400
|
||
with get_db() as c:
|
||
c.execute("""INSERT INTO prices(key,price,checked,qty,updated) VALUES(?,?,?,?,?)
|
||
ON CONFLICT(key) DO UPDATE SET price=excluded.price,
|
||
checked=excluded.checked, qty=excluded.qty, updated=excluded.updated""",
|
||
(key, price, checked, qty, datetime.now().isoformat()))
|
||
return jsonify(ok=True)
|
||
|
||
|
||
@app.route('/api/item', methods=['POST'])
|
||
def add_item():
|
||
name = request.form.get('name', '').strip()
|
||
if not name:
|
||
return jsonify(error='name required'), 400
|
||
price_s = request.form.get('price', '').strip().replace(',', '.')
|
||
price = float(price_s) if price_s else None
|
||
section_key = request.form.get('section_key', '').strip() or None
|
||
note = request.form.get('note', '').strip()
|
||
|
||
photo = None
|
||
f = request.files.get('photo')
|
||
if f and f.filename:
|
||
ext = (os.path.splitext(f.filename)[1] or '.jpg').lower()
|
||
fname = f"{slugify(name)}-{int(datetime.now().timestamp())}{ext}"
|
||
f.save(UPLOAD_DIR / fname)
|
||
photo = fname
|
||
|
||
with get_db() as c:
|
||
row = c.execute(
|
||
"INSERT INTO extras(name,section_key,price,photo,note,created) VALUES(?,?,?,?,?,?)",
|
||
(name, section_key, price, photo, note, datetime.now().isoformat()))
|
||
item_id = row.lastrowid
|
||
|
||
return jsonify(ok=True, id=item_id, photo=photo,
|
||
name=name, section_key=section_key, price=price, note=note)
|
||
|
||
|
||
@app.route('/api/item/<int:item_id>', methods=['DELETE'])
|
||
def delete_item(item_id):
|
||
with get_db() as c:
|
||
row = c.execute("SELECT photo FROM extras WHERE id=?", (item_id,)).fetchone()
|
||
if row and row['photo']:
|
||
p = UPLOAD_DIR / row['photo']
|
||
if p.exists():
|
||
p.unlink()
|
||
c.execute("DELETE FROM extras WHERE id=?", (item_id,))
|
||
return jsonify(ok=True)
|
||
|
||
|
||
@app.route('/uploads/<path:filename>')
|
||
def serve_upload(filename):
|
||
return send_from_directory(UPLOAD_DIR, filename)
|
||
|
||
|
||
@app.route('/health')
|
||
def health():
|
||
return jsonify({'status': 'healthy', 'service': 'citti'})
|
||
|
||
|
||
@app.route('/api/category', methods=['POST'])
|
||
def add_category():
|
||
d = request.json
|
||
emoji = (d.get('emoji') or '📦').strip() or '📦'
|
||
title = (d.get('title') or '').strip()
|
||
if not title:
|
||
return jsonify(error='title required'), 400
|
||
with get_db() as c:
|
||
row = c.execute("INSERT INTO custom_sections(emoji,title,created) VALUES(?,?,?)",
|
||
(emoji, title, datetime.now().isoformat()))
|
||
cat_id = row.lastrowid
|
||
return jsonify(ok=True, id=cat_id, key=f"custom-{cat_id}", emoji=emoji, title=title)
|
||
|
||
|
||
@app.route('/api/category/<int:cat_id>', methods=['DELETE'])
|
||
def delete_category(cat_id):
|
||
key = f"custom-{cat_id}"
|
||
with get_db() as c:
|
||
for r in c.execute("SELECT photo FROM extras WHERE section_key=?", (key,)).fetchall():
|
||
if r['photo']:
|
||
p = UPLOAD_DIR / r['photo']
|
||
if p.exists():
|
||
p.unlink()
|
||
c.execute("DELETE FROM extras WHERE section_key=?", (key,))
|
||
c.execute("DELETE FROM custom_sections WHERE id=?", (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():
|
||
summary = refresh_offers_safe()
|
||
if summary is None:
|
||
return jsonify(ok=False, error='refresh failed'), 502
|
||
return jsonify(ok=True, **summary)
|
||
|
||
|
||
@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:
|
||
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 price DESC NULLS LAST")]
|
||
custom_secs = [dict(r) for r in c.execute("SELECT * FROM custom_sections ORDER BY created")]
|
||
|
||
rows = []
|
||
total_est = total_actual = 0
|
||
for sec in SECTIONS:
|
||
sec_est = sec_actual = 0
|
||
for item in sec['varer']:
|
||
s = saved.get(item['key'], {})
|
||
actual = s.get('price')
|
||
sec_est += item['est']
|
||
if actual:
|
||
sec_actual += actual
|
||
rows.append({
|
||
'title': sec['title'],
|
||
'emoji': sec['emoji'],
|
||
'est': sec_est,
|
||
'actual': sec_actual or None,
|
||
'diff': (sec_actual - sec_est) if sec_actual else None,
|
||
})
|
||
total_est += sec_est
|
||
if sec_actual:
|
||
total_actual += sec_actual
|
||
|
||
return render_template('analyse.html', sections=SECTIONS, saved=saved,
|
||
extras=extras, rows=rows, custom_secs=custom_secs,
|
||
total_est=total_est,
|
||
total_actual=total_actual or None)
|
||
|
||
|
||
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)
|
||
s.connect(("8.8.8.8", 80))
|
||
local_ip = s.getsockname()[0]
|
||
s.close()
|
||
except Exception:
|
||
local_ip = "127.0.0.1"
|
||
print(f"\n Computer: http://localhost:{port}")
|
||
print(f" Telefon (samme WiFi): http://{local_ip}:{port}\n")
|
||
app.run(host='0.0.0.0', port=port, debug=False)
|