diff --git a/app.py b/app.py index 2badd70..8831f4c 100644 --- a/app.py +++ b/app.py @@ -1,6 +1,7 @@ import sqlite3 import os import re +import json import unicodedata import socket from pathlib import Path @@ -89,6 +90,21 @@ SECTIONS = [ ] +ITEM_BY_KEY = {v['key']: v for sec in SECTIONS for v in sec['varer']} + + +def compute_totals(saved): + """Sum af katalogets estimater og indtastede faktiske priser.""" + total_est = total_actual = 0 + for sec in SECTIONS: + for item in sec['varer']: + total_est += item['est'] + actual = saved.get(item['key'], {}).get('price') + if actual: + total_actual += actual + return total_est, total_actual + + def slugify(text): text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode() return re.sub(r'[-\s]+', '-', re.sub(r'[^\w\s-]', '', text.lower())).strip('-') @@ -111,6 +127,11 @@ def init_db(): c.execute("""CREATE TABLE IF NOT EXISTS custom_sections ( id INTEGER PRIMARY KEY AUTOINCREMENT, emoji TEXT DEFAULT '📦', title TEXT, created TEXT)""") + c.execute("""CREATE TABLE IF NOT EXISTS trips ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + label TEXT, archived TEXT, + total_est REAL, total_actual REAL, item_count INTEGER, + snapshot TEXT)""") try: c.execute("ALTER TABLE extras ADD COLUMN section_key TEXT") except Exception: @@ -229,6 +250,95 @@ def delete_category(cat_id): return jsonify(ok=True) +MONTHS_DA = ['jan', 'feb', 'mar', 'apr', 'maj', 'jun', + 'jul', 'aug', 'sep', 'okt', 'nov', 'dec'] + + +def _trip_label(dt): + return f"{dt.day}. {MONTHS_DA[dt.month - 1]} {dt.year}" + + +@app.route('/api/archive', methods=['POST']) +def archive_trip(): + with get_db() as c: + prices = [dict(r) for r in c.execute("SELECT * FROM prices")] + extras = [dict(r) for r in c.execute("SELECT * FROM extras ORDER BY created DESC")] + custom_secs = [dict(r) for r in c.execute("SELECT * FROM custom_sections ORDER BY created")] + + checked = [p for p in prices if p.get('checked')] + touched = [p for p in prices if p.get('checked') or p.get('price') or p.get('qty')] + if not touched and not extras and not custom_secs: + return jsonify(ok=False, empty=True) + + for p in prices: + item = ITEM_BY_KEY.get(p['key']) + if item: + p['name'] = item['name'] + p['de'] = item.get('de') + p['est'] = item['est'] + + saved = {p['key']: p for p in prices} + total_est, total_actual = compute_totals(saved) + total_actual += sum(e['price'] for e in extras if e.get('price')) + item_count = len(checked) + len(extras) + + now = datetime.now() + snapshot = json.dumps({ + 'prices': prices, 'extras': extras, 'custom_sections': custom_secs}) + row = c.execute( + """INSERT INTO trips(label,archived,total_est,total_actual,item_count,snapshot) + VALUES(?,?,?,?,?,?)""", + (_trip_label(now), now.isoformat(), total_est, + total_actual or None, item_count, snapshot)) + trip_id = row.lastrowid + + c.execute("DELETE FROM prices") + c.execute("DELETE FROM extras") + c.execute("DELETE FROM custom_sections") + + return jsonify(ok=True, trip_id=trip_id) + + +@app.route('/historik') +def historik(): + with get_db() as c: + trips = [dict(r) for r in c.execute( + "SELECT id,label,archived,total_est,total_actual,item_count " + "FROM trips ORDER BY id DESC")] + return render_template('historik.html', trips=trips) + + +@app.route('/historik/') +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('/analyse') def analyse(): with get_db() as c: diff --git a/templates/historik.html b/templates/historik.html new file mode 100644 index 0000000..68ae970 --- /dev/null +++ b/templates/historik.html @@ -0,0 +1,74 @@ + + + + + +Citti Historik + + + + +
+ +
+
+

Citti Historik

+
Gemte indkøbsture
+
+ ← Indkøbsseddel +
+ +{% if trips %} + +{% else %} +
Ingen gemte ture endnu. Tryk "🗂 Arkivér & ny liste" på indkøbssedlen for at gemme en tur her.
+{% endif %} + +
+ + diff --git a/templates/index.html b/templates/index.html index 22557a4..04976d7 100644 --- a/templates/index.html +++ b/templates/index.html @@ -172,9 +172,11 @@
-
+
📊 Analyse + 🕑 Historik +
Estimeret besparelse
@@ -415,6 +417,22 @@
+ + + diff --git a/templates/trip.html b/templates/trip.html new file mode 100644 index 0000000..4ef87ce --- /dev/null +++ b/templates/trip.html @@ -0,0 +1,162 @@ + + + + + +Citti · {{ trip.label }} + + + + +
+ +
+
+

Citti {{ trip.label }}

+
{{ trip.item_count }} varer · arkiveret
+
+
+ ← Historik +
+
+ +{% set total_actual = trip.total_actual or 0 %} +{% set total_est = trip.total_est or 0 %} +{% set diff = (total_actual - total_est) if total_actual else 0 %} + +
+
+
Faktisk betalt
+ {% if total_actual %} +
{{ "{:,.0f}".format(total_actual).replace(",",".") }}
+
kr. registreret
+ {% else %} +
—
+
ingen priser
+ {% endif %} +
+
+
Estimeret
+
{{ "{:,.0f}".format(total_est).replace(",",".") }}
+
kr. planlagt
+
+
+
Difference
+ {% if total_actual %} +
{% if diff > 0 %}+{% endif %}{{ "{:,.0f}".format(diff).replace(",",".") }}
+
kr.
+ {% else %} +
—
+
-
+ {% endif %} +
+
+ +{% if not sections and not custom_secs and not loose_extras %} +
Denne tur blev gemt uden afkrydsede varer.
+{% endif %} + +{% for block in sections %} +
+
{{ block.sec.emoji }} {{ block.sec.title }}
+ {% for row in block.picked %} +
+
+ {{ row.item.name }} + {% set q = row.saved.qty or row.item.qty %} + {% if q and q != '—' %} · {{ q }}{% endif %} +
+ {% if row.saved.price %} + {{ "{:.2f}".format(row.saved.price).replace(".",",") }} kr. + {% else %} + ✓ + {% endif %} +
+ {% endfor %} + {% for e in block.extras %} +
+
+ {% if e.photo %}{% endif %} + {{ e.name }}ekstra + {% if e.note %} · {{ e.note }}{% endif %} +
+ {% if e.price %}{{ "{:.2f}".format(e.price).replace(".",",") }} kr.{% else %}—{% endif %} +
+ {% endfor %} +
+{% endfor %} + +{% for cs in custom_secs %} +{% set cs_extras = by_sec.get('custom-' ~ cs.id, []) %} +{% if cs_extras %} +
+
{{ cs.emoji }} {{ cs.title }}
+ {% for e in cs_extras %} +
+
+ {% if e.photo %}{% endif %} + {{ e.name }} + {% if e.note %} · {{ e.note }}{% endif %} +
+ {% if e.price %}{{ "{:.2f}".format(e.price).replace(".",",") }} kr.{% else %}—{% endif %} +
+ {% endfor %} +
+{% endif %} +{% endfor %} + +{% if loose_extras %} +
+
📦 Øvrige ekstra varer
+ {% for e in loose_extras %} +
+
+ {% if e.photo %}{% endif %} + {{ e.name }} + {% if e.note %} · {{ e.note }}{% endif %} +
+ {% if e.price %}{{ "{:.2f}".format(e.price).replace(".",",") }} kr.{% else %}—{% endif %} +
+ {% endfor %} +
+{% endif %} + +
+ +