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 sqlite3
import os import os
import re import re
import json
import unicodedata import unicodedata
import socket import socket
from pathlib import Path 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): def slugify(text):
text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode() text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode()
return re.sub(r'[-\s]+', '-', re.sub(r'[^\w\s-]', '', text.lower())).strip('-') 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 ( c.execute("""CREATE TABLE IF NOT EXISTS custom_sections (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
emoji TEXT DEFAULT '📦', title TEXT, created TEXT)""") 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: try:
c.execute("ALTER TABLE extras ADD COLUMN section_key TEXT") c.execute("ALTER TABLE extras ADD COLUMN section_key TEXT")
except Exception: except Exception:
@@ -229,6 +250,95 @@ def delete_category(cat_id):
return jsonify(ok=True) 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') @app.route('/analyse')
def analyse(): def analyse():
with get_db() as c: with get_db() as c:

74
templates/historik.html Normal file
View File

@@ -0,0 +1,74 @@
<!DOCTYPE html>
<html lang="da">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Citti Historik</title>
<link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=DM+Sans:wght@300;400;500;600&display=swap" rel="stylesheet">
<style>
:root {
--bg: #f5f2ed; --card: #ffffff; --border: #e2ddd6; --text: #1a1814;
--muted: #8a857c; --accent: #c84b2f; --green: #2d6a4f;
--mono: 'DM Mono', monospace; --sans: 'DM Sans', sans-serif;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: var(--sans); background: var(--bg); color: var(--text); font-size: 15px; line-height: 1.5; padding: 1.5rem 1rem 4rem; }
.page { max-width: 860px; margin: 0 auto; }
header { display: flex; align-items: flex-start; justify-content: space-between; gap: 1rem; margin-bottom: 1.5rem; padding-bottom: 1.25rem; border-bottom: 2px solid var(--text); }
h1 { font-size: 1.75rem; font-weight: 600; letter-spacing: -0.03em; }
h1 span { color: var(--accent); }
.btn-back { background: var(--text); color: white; border: none; border-radius: 8px; padding: 8px 14px; font-size: 13px; font-family: var(--sans); cursor: pointer; text-decoration: none; display: inline-block; font-weight: 500; }
.trip-list { display: flex; flex-direction: column; gap: 10px; }
.trip-card { display: flex; align-items: center; justify-content: space-between; gap: 1rem; background: var(--card); border: 1px solid var(--border); border-radius: 10px; padding: 1rem 1.25rem; text-decoration: none; color: inherit; transition: border-color 0.15s ease; }
.trip-card:active { border-color: var(--accent); }
.trip-label { font-size: 1.1rem; font-weight: 600; }
.trip-meta { font-size: 12px; color: var(--muted); margin-top: 2px; }
.trip-totals { text-align: right; white-space: nowrap; }
.trip-actual { font-size: 1.25rem; font-weight: 600; font-family: var(--mono); color: var(--green); letter-spacing: -0.02em; }
.trip-est { font-size: 12px; color: var(--muted); font-family: var(--mono); margin-top: 2px; }
.chev { color: var(--muted); font-size: 20px; margin-left: 4px; }
.empty-state { padding: 3rem 2rem; text-align: center; color: var(--muted); font-size: 14px; background: var(--card); border: 1px solid var(--border); border-radius: 10px; }
</style>
</head>
<body>
<div class="page">
<header>
<div>
<h1>Citti <span>Historik</span></h1>
<div style="font-size:12px;color:var(--muted);margin-top:4px">Gemte indkøbsture</div>
</div>
<a href="/" class="btn-back">← Indkøbsseddel</a>
</header>
{% if trips %}
<div class="trip-list">
{% for t in trips %}
<a href="/historik/{{ t.id }}" class="trip-card">
<div>
<div class="trip-label">{{ t.label }}</div>
<div class="trip-meta">{{ t.item_count }} varer</div>
</div>
<div style="display:flex;align-items:center">
<div class="trip-totals">
{% if t.total_actual %}
<div class="trip-actual">{{ "{:,.0f}".format(t.total_actual).replace(",",".") }} kr.</div>
{% else %}
<div class="trip-actual" style="color:var(--muted)">—</div>
{% endif %}
<div class="trip-est">est. {{ "{:,.0f}".format(t.total_est or 0).replace(",",".") }} kr.</div>
</div>
<span class="chev">›</span>
</div>
</a>
{% endfor %}
</div>
{% else %}
<div class="empty-state">Ingen gemte ture endnu. Tryk "🗂 Arkivér &amp; ny liste" på indkøbssedlen for at gemme en tur her.</div>
{% endif %}
</div>
</body>
</html>

View File

@@ -172,9 +172,11 @@
</div> </div>
</div> </div>
<div class="header-actions"> <div class="header-actions">
<div style="display:flex;gap:8px"> <div style="display:flex;gap:8px;flex-wrap:wrap">
<button class="btn btn-cat" onclick="openCatModal()">+ Kategori</button> <button class="btn btn-cat" onclick="openCatModal()">+ Kategori</button>
<a href="/analyse" class="btn">📊 Analyse</a> <a href="/analyse" class="btn">📊 Analyse</a>
<a href="/historik" class="btn">🕑 Historik</a>
<button class="btn" onclick="openArchiveModal()">🗂 Arkivér & ny liste</button>
</div> </div>
<div class="savings-card"> <div class="savings-card">
<div class="label">Estimeret besparelse</div> <div class="label">Estimeret besparelse</div>
@@ -415,6 +417,22 @@
</div> </div>
</div> </div>
<!-- ARKIVÉR MODAL -->
<div class="modal-overlay" id="archive-modal" onclick="if(event.target===this)closeArchiveModal()">
<div class="modal">
<div class="modal-title">
Arkivér & ny liste
<button class="modal-close" onclick="closeArchiveModal()">×</button>
</div>
<p style="margin:0 0 1.25rem;color:var(--muted);line-height:1.5">
Den nuværende tur gemmes i <strong>Historik</strong>, og listen nulstilles til en frisk
udgave: afkrydsninger og priser fjernes, og dine tilføjede varer og egne kategorier ryddes.
</p>
<button class="btn-submit" id="archive-confirm" onclick="doArchive()">Arkivér & nulstil</button>
<button class="btn-submit" style="background:transparent;color:var(--muted);margin-top:4px" onclick="closeArchiveModal()">Annullér</button>
</div>
</div>
<script> <script>
const SEC_IDS = ['koed','frost','mejeri','pasta','groent','konserves','indisk','mex','drikke','hus']; const SEC_IDS = ['koed','frost','mejeri','pasta','groent','konserves','indisk','mex','drikke','hus'];
const DK_SAVINGS_RATIO = 0.35; const DK_SAVINGS_RATIO = 0.35;
@@ -621,6 +639,32 @@ async function deleteCategory(id) {
document.getElementById(`csec-${id}`).remove(); document.getElementById(`csec-${id}`).remove();
} }
function openArchiveModal() {
document.getElementById('archive-modal').classList.add('open');
}
function closeArchiveModal() {
document.getElementById('archive-modal').classList.remove('open');
}
async function doArchive() {
const btn = document.getElementById('archive-confirm');
btn.textContent = 'Arkiverer...'; btn.disabled = true;
try {
const res = await fetch('/api/archive', {method: 'POST'});
const data = await res.json();
if (data.ok) {
window.location.reload();
return;
}
if (data.empty) alert('Listen er allerede tom — intet at arkivere.');
else alert('Kunne ikke arkivere. Prøv igen.');
} catch (e) {
alert('Kunne ikke arkivere. Prøv igen.');
}
btn.textContent = 'Arkivér & nulstil'; btn.disabled = false;
closeArchiveModal();
}
recalcAll(); recalcAll();
</script> </script>
</body> </body>

162
templates/trip.html Normal file
View File

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