feat(trips): archive current list and start a fresh one

Add a "Arkivér & ny liste" button that snapshots the current trip
(checked items, prices, quantities, extras and custom categories)
into a new trips table, then clears the mutable state so the list
resets to the fresh catalog.

- New trips table in init_db() storing a self-contained JSON snapshot
  plus computed totals and item count
- POST /api/archive with a no-op guard against archiving an empty list
- /historik list view and /historik/<id> read-only detail view
- Photo files are kept so archived trips can still show them
This commit is contained in:
Henrik Jess Nielsen
2026-10-30 10:15:27 +01:00
parent 7e5ef3c4b5
commit cf999ae228
4 changed files with 391 additions and 1 deletions

110
app.py
View File

@@ -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/<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('/analyse')
def analyse():
with get_db() as c: