diff --git a/README.md b/README.md
index 66f56e5..68d59f5 100644
--- a/README.md
+++ b/README.md
@@ -43,3 +43,70 @@ Erbjudanden kan definieras som produkter med `offer: true`, `images` och `compon
Sidan byggs direkt från `config.yaml`, så ändringar av produkter, priser, bilder, erbjudanden och grid-layout slår igenom automatiskt nästa gång `/print` öppnas.
Sista kortet är alltid ett Swish-kort med en QR-kod som endast innehåller mottagaren. Beloppet anges manuellt i Swish.
+
+
+## Backoffice
+
+Fikakassan har ett lokalt backoffice på `/backoffice`.
+
+Det sparar historik i `data/fikakassa.db` (SQLite) och innehåller:
+
+- dagens försäljning och antal betalda köp
+- varukostnad för sålda varor
+- registrerat svinn och svinnkostnad
+- resultat efter varukostnad och svinn
+- försäljningshistorik per dag med valfritt antal dagar bakåt från idag
+- lager i **Butik** och **Baklager**
+- inköpspris per produkt
+- påfyllnad, inventeringsjusteringar, svinn och lagerflyttar
+- automatisk lagerminskning när en Swish-betalning godkänns
+- detaljerad betalningsloggning i systemd-journalen
+
+Öppna:
+
+```text
+http://127.0.0.1:8000/backoffice
+```
+
+Från en annan dator på samma nätverk används kioskens IP-adress.
+
+### Inköpspris och känt startlager
+
+Backoffice innehåller de kända startvärdena från inventeringen: Monster Energy 24 st à 11,00 kr, Monster Ultra 24 st à 11,00 kr, Coca-Cola 30 st à 6,23 kr, Coca-Cola Zero 30 st à 6,23 kr, Kexchoklad 40 st à 5,62 kr, Twix 20 st à 4,72 kr och Corny Big 24 st à 6,55 kr.
+
+Kvantiteterna är den kända totalmängden; underlaget anger inte hur många som ligger i Butik respektive Baklager, så applikationen gissar inte den fördelningen. Inköpspriserna kan ändras manuellt i backoffice.
+
+### Lager
+
+`Butik` är lagret som kunden handlar från. När en betalning godkänns dras de faktiska produkterna automatiskt från butikslagret.
+
+`Baklager` används för reservlager. Påfyllnad och flyttar mellan lager registreras manuellt i backoffice.
+
+### Betalningsfelsökning
+
+Backend loggar nu bland annat:
+
+```text
+PAYMENT received: ...
+PAYMENT accepted: ...
+PAYMENT rejected: ...
+PAYMENT event delivered: ...
+```
+
+Se live:
+
+```bash
+sudo journalctl -u fikakassa.service -f
+```
+
+Webbläsarens JavaScript loggar betalningskedjan i Chromium DevTools, bland annat när eventet tas emot och när tackskärmen startar.
+
+### Databas
+
+SQLite-databasen skapas automatiskt:
+
+```text
+/opt/fikakassa/data/fikakassa.db
+```
+
+Den innehåller försäljning, betalningar, lager och lagerrörelser och överlever omstart av Fikakassan.
diff --git a/app/main.py b/app/main.py
index e52a553..2dbab05 100644
--- a/app/main.py
+++ b/app/main.py
@@ -3,6 +3,8 @@ from __future__ import annotations
import io
import secrets
import time
+import sqlite3
+from datetime import datetime, date, timedelta
from pathlib import Path
from urllib.parse import quote
from html import escape
@@ -32,6 +34,199 @@ app.mount("/static", StaticFiles(directory=STATIC), name="static")
current_order: dict | None = None
last_payment: dict | None = None
+DB_PATH = BASE / "data" / "fikakassa.db"
+DB_PATH.parent.mkdir(parents=True, exist_ok=True)
+
+
+def db():
+ conn = sqlite3.connect(DB_PATH, timeout=10)
+ conn.row_factory = sqlite3.Row
+ conn.execute("PRAGMA journal_mode=WAL")
+ conn.execute("PRAGMA foreign_keys=ON")
+ return conn
+
+
+def init_db():
+ conn = db()
+ conn.executescript("""
+ CREATE TABLE IF NOT EXISTS orders (
+ id TEXT PRIMARY KEY,
+ created_at REAL NOT NULL,
+ expires_at REAL NOT NULL,
+ paid_at REAL,
+ total REAL NOT NULL,
+ status TEXT NOT NULL DEFAULT 'pending',
+ sender TEXT,
+ transaction_id TEXT,
+ payment_message TEXT
+ );
+
+ CREATE TABLE IF NOT EXISTS order_lines (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ order_id TEXT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
+ product_id TEXT NOT NULL,
+ product_name TEXT NOT NULL,
+ quantity INTEGER NOT NULL,
+ unit_price REAL NOT NULL,
+ line_total REAL NOT NULL,
+ is_offer INTEGER NOT NULL DEFAULT 0
+ );
+
+ CREATE TABLE IF NOT EXISTS inventory (
+ product_id TEXT PRIMARY KEY,
+ store_qty INTEGER NOT NULL DEFAULT 0,
+ backstock_qty INTEGER NOT NULL DEFAULT 0,
+ cost_price REAL NOT NULL DEFAULT 0,
+ updated_at REAL NOT NULL
+ );
+
+ CREATE TABLE IF NOT EXISTS inventory_movements (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ created_at REAL NOT NULL,
+ product_id TEXT NOT NULL,
+ location TEXT NOT NULL,
+ movement_type TEXT NOT NULL,
+ quantity INTEGER NOT NULL,
+ note TEXT,
+ order_id TEXT,
+ unit_cost REAL
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_orders_paid_at ON orders(paid_at);
+ CREATE INDEX IF NOT EXISTS idx_order_lines_order ON order_lines(order_id);
+ CREATE INDEX IF NOT EXISTS idx_movements_created ON inventory_movements(created_at);
+
+ CREATE TABLE IF NOT EXISTS settings (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL
+ );
+ """)
+ cols = {r[1] for r in conn.execute("PRAGMA table_info(inventory_movements)").fetchall()}
+ if "unit_cost" not in cols:
+ conn.execute("ALTER TABLE inventory_movements ADD COLUMN unit_cost REAL")
+ now = time.time()
+ for p in products.values():
+ conn.execute(
+ """INSERT OR IGNORE INTO inventory
+ (product_id, store_qty, backstock_qty, cost_price, updated_at)
+ VALUES (?, 0, 0, 0, ?)""",
+ (p["id"], now),
+ )
+
+ # Seed the known purchase prices only once. The supplied inventory counts
+ # are totals for shop + backstock, but the source does not specify the
+ # split between those locations, so quantities are not assigned here.
+ # This avoids inventing a store/backstock split.
+ seeded = conn.execute(
+ "SELECT value FROM settings WHERE key='initial_inventory_seeded'"
+ ).fetchone()
+ initial = cfg.get("initial_inventory") or []
+ if not seeded and initial:
+ for item in initial:
+ pid = str(item.get("id", ""))
+ if pid not in products:
+ continue
+ cost = max(0.0, float(item.get("cost_price", 0)))
+ conn.execute(
+ "UPDATE inventory SET cost_price=?, updated_at=? WHERE product_id=? AND cost_price=0",
+ (cost, now, pid),
+ )
+ conn.execute(
+ "INSERT OR REPLACE INTO settings(key,value) VALUES('initial_inventory_seeded',?)",
+ (datetime.now().isoformat(timespec='seconds'),),
+ )
+
+ conn.commit()
+ conn.close()
+
+
+init_db()
+
+
+def local_day_bounds(day: str | None = None):
+ """Return UTC epoch bounds for a Swedish local calendar day.
+
+ The kiosk is intended for Sweden. Using zoneinfo keeps DST correct.
+ """
+ from zoneinfo import ZoneInfo
+ tz = ZoneInfo("Europe/Stockholm")
+ d = date.fromisoformat(day) if day else datetime.now(tz).date()
+ start = datetime(d.year, d.month, d.day, tzinfo=tz)
+ end = start + timedelta(days=1)
+ return start.timestamp(), end.timestamp()
+
+
+def record_order(order: dict, requested_items: list[dict]):
+ conn = db()
+ conn.execute(
+ """INSERT INTO orders(id, created_at, expires_at, total, status)
+ VALUES (?, ?, ?, ?, 'pending')""",
+ (order["id"], order["created_at"], order["expires_at"], order["total"]),
+ )
+ for item in requested_items:
+ p = products[item["id"]]
+ conn.execute(
+ """INSERT INTO order_lines
+ (order_id, product_id, product_name, quantity, unit_price, line_total, is_offer)
+ VALUES (?, ?, ?, ?, ?, ?, ?)""",
+ (
+ order["id"], p["id"], p["name"], int(item["quantity"]),
+ float(p["price"]), float(p["price"]) * int(item["quantity"]),
+ 1 if p.get("components") else 0,
+ ),
+ )
+ conn.commit()
+ conn.close()
+
+
+def mark_order_paid(payment):
+ now = time.time()
+ conn = db()
+ conn.execute(
+ """UPDATE orders
+ SET status='paid', paid_at=?, sender=?, transaction_id=?, payment_message=?
+ WHERE id=?""",
+ (now, payment.sender, payment.transaction_id, payment.message, current_order["id"]),
+ )
+
+ # Consume the actual component products from the shop shelf.
+ for item in current_order["items"]:
+ qty = int(item["quantity"])
+ if qty <= 0:
+ continue
+ row = conn.execute("SELECT cost_price FROM inventory WHERE product_id=?", (item["id"],)).fetchone()
+ unit_cost = float(row["cost_price"]) if row else 0.0
+ conn.execute(
+ """UPDATE inventory SET store_qty=store_qty-?, updated_at=?
+ WHERE product_id=?""",
+ (qty, now, item["id"]),
+ )
+ conn.execute(
+ """INSERT INTO inventory_movements
+ (created_at, product_id, location, movement_type, quantity, note, order_id, unit_cost)
+ VALUES (?, ?, 'store', 'sale', ?, ?, ?, ?)""",
+ (now, item["id"], -qty, "Automatisk försäljning", current_order["id"], unit_cost),
+ )
+ conn.commit()
+ conn.close()
+
+
+def expire_old_orders():
+ conn = db()
+ conn.execute(
+ "UPDATE orders SET status='expired' WHERE status='pending' AND expires_at < ?",
+ (time.time(),),
+ )
+ conn.commit()
+ conn.close()
+
+
+class PaymentNotification(BaseModel):
+ amount: float
+ message: str | None = None
+ sender: str | None = None
+ transaction_id: str | None = None
+
def normalized_swish_number(number: str) -> str:
return "".join(ch for ch in number if ch.isdigit())
@@ -304,6 +499,10 @@ def create_order(req: OrderRequest):
"created_at": now,
"expires_at": now + int(shop["payment_timeout_seconds"]),
}
+ record_order(current_order, [
+ {"id": requested.id, "quantity": int(requested.quantity)}
+ for requested in req.items if requested.quantity >= 1
+ ])
payload = swish_qr_payload(current_order)
return {**current_order, "qr_payload": payload, "swish_number": shop["swish_number"], "swish_name": shop["swish_name"]}
@@ -327,6 +526,276 @@ def write_temp_qr(order_id: str) -> str:
return str(path)
+
+@app.get("/backoffice", response_class=HTMLResponse)
+def backoffice():
+ return FileResponse(TEMPLATES / "backoffice.html")
+
+
+@app.get("/api/backoffice/dashboard")
+def backoffice_dashboard(day: str | None = None):
+ expire_old_orders()
+ start, end = local_day_bounds(day)
+ conn = db()
+
+ totals = conn.execute(
+ """SELECT
+ COALESCE(SUM(CASE WHEN status='paid' THEN total ELSE 0 END),0) AS sales,
+ COUNT(CASE WHEN status='paid' THEN 1 END) AS orders
+ FROM orders WHERE paid_at >= ? AND paid_at < ?""",
+ (start, end),
+ ).fetchone()
+
+ sold = conn.execute(
+ """SELECT ol.product_id, ol.product_name,
+ SUM(ol.quantity) quantity,
+ SUM(ol.line_total) revenue
+ FROM order_lines ol
+ JOIN orders o ON o.id=ol.order_id
+ WHERE o.status='paid' AND o.paid_at >= ? AND o.paid_at < ?
+ GROUP BY ol.product_id, ol.product_name
+ ORDER BY revenue DESC""",
+ (start, end),
+ ).fetchall()
+
+ components = conn.execute(
+ """SELECT ol.product_id, ol.product_name, SUM(ol.quantity) quantity
+ FROM order_lines ol JOIN orders o ON o.id=ol.order_id
+ WHERE o.status='paid' AND o.paid_at >= ? AND o.paid_at < ?
+ GROUP BY ol.product_id, ol.product_name""",
+ (start, end),
+ ).fetchall()
+
+ # Actual consumed quantities include combo components.
+ sold_components = {}
+ for line in conn.execute(
+ """SELECT ol.product_id, ol.quantity, ol.is_offer
+ FROM order_lines ol JOIN orders o ON o.id=ol.order_id
+ WHERE o.status='paid' AND o.paid_at >= ? AND o.paid_at < ?""",
+ (start, end),
+ ):
+ p = products.get(line["product_id"], {})
+ if p.get("components"):
+ for c in p["components"]:
+ sold_components[c["id"]] = sold_components.get(c["id"], 0) + int(line["quantity"]) * int(c.get("quantity", 1))
+ else:
+ sold_components[line["product_id"]] = sold_components.get(line["product_id"], 0) + int(line["quantity"])
+
+ inv_rows = conn.execute(
+ "SELECT * FROM inventory ORDER BY product_id"
+ ).fetchall()
+ inv = {r["product_id"]: r for r in inv_rows}
+
+ sale_rows = conn.execute(
+ """SELECT product_id, SUM(-quantity) qty,
+ SUM((-quantity) * COALESCE(unit_cost, 0)) cost
+ FROM inventory_movements
+ WHERE movement_type='sale' AND created_at >= ? AND created_at < ?
+ GROUP BY product_id""",
+ (start, end),
+ ).fetchall()
+ cogs = sum(float(r["cost"]) for r in sale_rows)
+ product_stats = [{
+ "id": r["product_id"],
+ "name": products.get(r["product_id"], {}).get("name", r["product_id"]),
+ "quantity": int(r["qty"]),
+ "cost": float(r["cost"]),
+ "cost_price": (float(r["cost"]) / int(r["qty"])) if int(r["qty"]) else 0,
+ } for r in sale_rows]
+
+ shrink_rows = conn.execute(
+ """SELECT im.product_id, SUM(-im.quantity) qty,
+ SUM((-im.quantity) * COALESCE(im.unit_cost, 0)) cost
+ FROM inventory_movements im
+ WHERE im.movement_type='shrinkage' AND im.created_at >= ? AND im.created_at < ?
+ GROUP BY im.product_id""",
+ (start, end),
+ ).fetchall()
+ shrink_cost = 0.0
+ shrinkage = []
+ for r in shrink_rows:
+ qty = max(0, int(r["qty"]))
+ cost = float(r["cost"])
+ shrink_cost += cost
+ shrinkage.append({
+ "id": r["product_id"],
+ "name": products.get(r["product_id"], {}).get("name", r["product_id"]),
+ "quantity": qty,
+ "cost": qty * cost,
+ })
+
+ sales = float(totals["sales"])
+ conn.close()
+ return {
+ "day": day or datetime.now().astimezone().date().isoformat(),
+ "sales": sales,
+ "orders": int(totals["orders"]),
+ "cogs": cogs,
+ "shrinkage_cost": shrink_cost,
+ "profit": sales - cogs - shrink_cost,
+ "products": product_stats,
+ "order_lines": [dict(r) for r in sold],
+ "shrinkage": shrinkage,
+ }
+
+
+@app.get("/api/backoffice/history")
+def backoffice_history(days: int = 1, back_days: int | None = None):
+ # `back_days=0` means today only. `back_days=N` means today plus the
+ # previous N calendar days. Keep `days` as a compatibility parameter.
+ if back_days is not None:
+ back_days = max(0, min(int(back_days), 3650))
+ days = back_days + 1
+ else:
+ days = max(1, min(int(days), 3650))
+ from zoneinfo import ZoneInfo
+ tz = ZoneInfo("Europe/Stockholm")
+ today = datetime.now(tz).date()
+ start_date = today - timedelta(days=days - 1)
+ start, _ = local_day_bounds(start_date.isoformat())
+ _, end = local_day_bounds((today + timedelta(days=1)).isoformat())
+ conn = db()
+ rows = conn.execute(
+ """SELECT date(datetime(paid_at, 'unixepoch', 'localtime')) day,
+ COALESCE(SUM(total),0) sales,
+ COUNT(*) orders
+ FROM orders
+ WHERE status='paid' AND paid_at >= ? AND paid_at < ?
+ GROUP BY day ORDER BY day""",
+ (start, end),
+ ).fetchall()
+ movement_rows = conn.execute(
+ """SELECT date(datetime(created_at, 'unixepoch', 'localtime')) day,
+ COALESCE(SUM(CASE WHEN movement_type='sale' THEN (-quantity)*COALESCE(unit_cost,0) ELSE 0 END),0) cogs,
+ COALESCE(SUM(CASE WHEN movement_type='shrinkage' THEN (-quantity)*COALESCE(unit_cost,0) ELSE 0 END),0) shrink
+ FROM inventory_movements
+ WHERE created_at >= ? AND created_at < ?
+ GROUP BY day""",
+ (start, end),
+ ).fetchall()
+ conn.close()
+ by_day = {r["day"]: {"sales": float(r["sales"]), "orders": int(r["orders"])} for r in rows}
+ by_move = {r["day"]: {"cogs": float(r["cogs"]), "shrink": float(r["shrink"])} for r in movement_rows}
+ result = []
+ for i in range(days):
+ d = start_date + timedelta(days=i)
+ x = by_day.get(d.isoformat(), {"sales": 0, "orders": 0})
+ m = by_move.get(d.isoformat(), {"cogs": 0, "shrink": 0})
+ result.append({"day": d.isoformat(), **x, **m, "profit": x["sales"] - m["cogs"] - m["shrink"]})
+ return result
+
+
+@app.get("/api/backoffice/inventory")
+def backoffice_inventory():
+ conn = db()
+ rows = conn.execute("SELECT * FROM inventory ORDER BY product_id").fetchall()
+ conn.close()
+ return {"items": [
+ {
+ "id": r["product_id"],
+ "name": products.get(r["product_id"], {}).get("name", r["product_id"]),
+ "store": int(r["store_qty"]),
+ "backstock": int(r["backstock_qty"]),
+ "cost_price": float(r["cost_price"]),
+ "stock_value": (int(r["store_qty"]) + int(r["backstock_qty"])) * float(r["cost_price"]),
+ } for r in rows
+ ]}
+
+
+class InventoryUpdate(BaseModel):
+ product_id: str
+ location: str
+ movement_type: str
+ quantity: int
+ note: str | None = None
+ cost_price: float | None = None
+
+
+@app.post("/api/backoffice/inventory")
+def update_inventory(req: InventoryUpdate):
+ if req.product_id not in products:
+ raise HTTPException(400, "Okänd produkt")
+ if req.location not in ("store", "backstock"):
+ raise HTTPException(400, "Ogiltig lagerplats")
+ if req.movement_type not in ("purchase", "adjustment", "shrinkage", "transfer"):
+ raise HTTPException(400, "Ogiltig lagerrörelse")
+ if req.quantity <= 0:
+ raise HTTPException(400, "Antal måste vara större än 0")
+ now = time.time()
+ conn = db()
+ col = "store_qty" if req.location == "store" else "backstock_qty"
+ delta = req.quantity if req.movement_type in ("purchase", "adjustment") else -req.quantity
+ if req.movement_type == "transfer":
+ # For transfer, location is the destination; source is inferred by
+ # the note prefix "from:store" or "from:backstock".
+ source = "backstock" if (req.note or "").startswith("from:backstock") else "store"
+ if source == req.location:
+ raise HTTPException(400, "Käll- och destinationslager måste skilja sig")
+ source_col = "backstock_qty" if source == "backstock" else "store_qty"
+ conn.execute(f"UPDATE inventory SET {source_col}={source_col}-?, updated_at=? WHERE product_id=?",
+ (req.quantity, now, req.product_id))
+ conn.execute(f"UPDATE inventory SET {col}={col}+?, updated_at=? WHERE product_id=?",
+ (req.quantity, now, req.product_id))
+ cost_row = conn.execute("SELECT cost_price FROM inventory WHERE product_id=?", (req.product_id,)).fetchone()
+ unit_cost = float(cost_row["cost_price"]) if cost_row else 0.0
+ conn.execute("""INSERT INTO inventory_movements
+ (created_at,product_id,location,movement_type,quantity,note,unit_cost)
+ VALUES (?,?,?,?,?,?,?)""",
+ (now, req.product_id, source, "transfer_out", -req.quantity, req.note, unit_cost))
+ conn.execute("""INSERT INTO inventory_movements
+ (created_at,product_id,location,movement_type,quantity,note,unit_cost)
+ VALUES (?,?,?,?,?,?,?)""",
+ (now, req.product_id, req.location, "transfer_in", req.quantity, req.note, unit_cost))
+ else:
+ cost_row = conn.execute("SELECT cost_price FROM inventory WHERE product_id=?", (req.product_id,)).fetchone()
+ unit_cost = float(cost_row["cost_price"]) if cost_row else 0.0
+ conn.execute(f"UPDATE inventory SET {col}={col}+?, updated_at=? WHERE product_id=?",
+ (delta, now, req.product_id))
+ conn.execute("""INSERT INTO inventory_movements
+ (created_at,product_id,location,movement_type,quantity,note,unit_cost)
+ VALUES (?,?,?,?,?,?,?)""",
+ (now, req.product_id, req.location, req.movement_type, delta, req.note, unit_cost))
+ if req.cost_price is not None:
+ if req.cost_price < 0:
+ raise HTTPException(400, "Inköpspris kan inte vara negativt")
+ conn.execute("UPDATE inventory SET cost_price=?, updated_at=? WHERE product_id=?",
+ (req.cost_price, now, req.product_id))
+ conn.commit()
+ conn.close()
+ return {"ok": True}
+
+
+@app.post("/api/backoffice/product-cost")
+def update_product_cost(payload: dict):
+ product_id = str(payload.get("product_id", ""))
+ try:
+ cost_price = float(payload.get("cost_price", -1))
+ except (TypeError, ValueError):
+ cost_price = -1
+ if product_id not in products or cost_price < 0:
+ raise HTTPException(400, "Ogiltigt produkt eller inköpspris")
+ now = time.time()
+ conn = db()
+ conn.execute("UPDATE inventory SET cost_price=?, updated_at=? WHERE product_id=?", (cost_price, now, product_id))
+ conn.commit()
+ conn.close()
+ return {"ok": True, "product_id": product_id, "cost_price": cost_price}
+
+
+@app.get("/api/backoffice/movements")
+def inventory_movements(limit: int = 100):
+ limit = max(1, min(int(limit), 500))
+ conn = db()
+ rows = conn.execute(
+ """SELECT created_at,product_id,location,movement_type,quantity,note,order_id
+ FROM inventory_movements ORDER BY created_at DESC LIMIT ?""", (limit,)
+ ).fetchall()
+ conn.close()
+ return {"movements": [
+ {**dict(r), "name": products.get(r["product_id"], {}).get("name", r["product_id"])}
+ for r in rows
+ ]}
+
@app.get("/api/payment/status")
def payment_status():
if not current_order:
@@ -339,13 +808,6 @@ def payment_status():
}
-class PaymentNotification(BaseModel):
- amount: float
- message: str | None = None
- sender: str | None = None
- transaction_id: str | None = None
-
-
@app.post("/api/payment")
def payment_notification(payment: PaymentNotification):
"""Endpoint for the Android Swish notification bridge.
@@ -354,10 +816,18 @@ def payment_notification(payment: PaymentNotification):
The sender/transaction id are recorded but are not used as the primary match.
"""
global current_order, last_payment
+ print(
+ f"PAYMENT received: amount={payment.amount:.2f} message={payment.message!r} "
+ f"sender={payment.sender or '-'} transaction_id={payment.transaction_id or '-'} "
+ f"active_order={current_order['id'] if current_order else '-'}",
+ flush=True,
+ )
if not current_order:
+ print("PAYMENT rejected: no_active_order", flush=True)
return JSONResponse({"accepted": False, "reason": "no_active_order"})
if time.time() > current_order["expires_at"]:
+ print(f"PAYMENT rejected: order_expired order={current_order['id']}", flush=True)
return JSONResponse({"accepted": False, "reason": "order_expired"})
expected_message = current_order["id"]
@@ -365,6 +835,12 @@ def payment_notification(payment: PaymentNotification):
message_ok = (payment.message or "").strip().upper() == expected_message.upper()
if not (amount_ok and message_ok):
+ print(
+ f"PAYMENT rejected: mismatch order={current_order['id']} "
+ f"expected_amount={current_order['total']} received_amount={payment.amount} "
+ f"expected_message={expected_message!r} received_message={payment.message!r}",
+ flush=True,
+ )
return JSONResponse({
"accepted": False,
"reason": "amount_or_message_mismatch",
@@ -380,6 +856,12 @@ def payment_notification(payment: PaymentNotification):
"transaction_id": payment.transaction_id,
"received_at": time.time(),
}
+ mark_order_paid(payment)
+ print(
+ f"PAYMENT accepted: order={current_order['id']} amount={payment.amount:.2f} "
+ f"sender={payment.sender or '-'} transaction_id={payment.transaction_id or '-'}",
+ flush=True,
+ )
return {"accepted": True, "order_id": current_order["id"]}
@@ -387,5 +869,10 @@ def payment_notification(payment: PaymentNotification):
def payment_event(after: float = 0):
"""Long-poll-friendly/simple polling endpoint used by the kiosk."""
if last_payment and last_payment["received_at"] > after:
+ print(
+ f"PAYMENT event delivered: order={last_payment['order_id']} after={after:.3f} "
+ f"received_at={last_payment['received_at']:.3f}",
+ flush=True,
+ )
return {"event": "payment", **last_payment}
return {"event": "none"}
diff --git a/app/static/css/backoffice.css b/app/static/css/backoffice.css
new file mode 100644
index 0000000..8b70bde
--- /dev/null
+++ b/app/static/css/backoffice.css
@@ -0,0 +1,44 @@
+*{box-sizing:border-box}
+:root{font-family:system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#171717;background:#f4f5f6}
+body{margin:0}
+.topbar{background:#fff;border-bottom:1px solid #ddd;padding:18px 28px;display:flex;align-items:center;justify-content:space-between}
+.eyebrow{font-size:12px;font-weight:800;letter-spacing:.12em;color:#ff5a00}
+h1,h2{margin:0}
+h1{font-size:28px}.wrap{max-width:1400px;margin:0 auto;padding:22px}
+.shop-link,button{border:0;border-radius:10px;padding:10px 16px;font-weight:700;cursor:pointer}
+.shop-link{background:#ff5a00;color:#fff;text-decoration:none}
+button{background:#ff5a00;color:#fff}
+.toolbar{display:flex;gap:12px;align-items:end;margin-bottom:18px}
+label{display:flex;flex-direction:column;gap:5px;font-size:13px;font-weight:700}
+input,select{font:inherit;border:1px solid #ccc;border-radius:8px;padding:9px;background:#fff}
+#status{font-size:13px;color:#666}
+.cards{display:grid;grid-template-columns:repeat(5,1fr);gap:12px;margin-bottom:18px}
+.metric{background:#fff;border:1px solid #ddd;border-radius:14px;padding:18px;display:flex;flex-direction:column;gap:8px}
+.metric span{font-size:13px;color:#666}.metric strong{font-size:25px}
+.metric.profit{border-color:#ff5a00}
+.panel{background:#fff;border:1px solid #ddd;border-radius:14px;margin:18px 0;padding:18px}
+.panel-head{display:flex;justify-content:space-between;align-items:center;margin-bottom:14px}
+.panel h2{font-size:19px}
+.table-wrap{overflow:auto}
+table{width:100%;border-collapse:collapse}
+th,td{text-align:left;padding:10px 8px;border-bottom:1px solid #eee;white-space:nowrap}
+th{font-size:12px;text-transform:uppercase;color:#666}
+td.num,th.num{text-align:right}
+.history-chart{height:180px;display:flex;align-items:end;gap:3px;border-bottom:1px solid #bbb;padding:10px 0 0;overflow:hidden}
+.bar{min-width:8px;flex:1;background:#ff5a00;border-radius:4px 4px 0 0;position:relative}
+.bar:hover{opacity:.75}.bar span{display:none;position:absolute;bottom:100%;left:50%;transform:translateX(-50%);background:#222;color:#fff;padding:4px 6px;border-radius:5px;font-size:11px;white-space:nowrap}
+.bar:hover span{display:block}
+.hint{font-size:13px;color:#666}
+.movement-form{display:grid;grid-template-columns:1.5fr 1fr 1.5fr .7fr 1fr 2fr auto;gap:10px;align-items:end}
+.movement-form button{height:40px}
+code{background:#eee;padding:2px 5px;border-radius:4px}
+.small-btn{padding:6px 9px;font-size:12px}
+@media(max-width:1000px){.cards{grid-template-columns:repeat(2,1fr)}.movement-form{grid-template-columns:repeat(2,1fr)}}
+@media(max-width:600px){.wrap{padding:12px}.cards{grid-template-columns:1fr}.movement-form{grid-template-columns:1fr}}
+.history-controls{display:flex;align-items:end;gap:8px}
+.history-controls label{min-width:115px}
+.history-controls input{width:100px;text-align:center}
+.history-step{width:42px;height:40px;padding:0;font-size:24px;line-height:1}
+.history-summary{display:flex;flex-wrap:wrap;gap:8px;margin:0 0 14px}
+.history-summary span{background:#f5f5f5;border:1px solid #e2e2e2;border-radius:999px;padding:7px 11px;font-size:13px}
+@media(max-width:600px){.history-controls{flex-wrap:wrap}.history-controls label{min-width:90px}.history-summary{gap:5px}}
diff --git a/app/static/js/app.js b/app/static/js/app.js
index 4da259f..e1433cd 100644
--- a/app/static/js/app.js
+++ b/app/static/js/app.js
@@ -1,4 +1,5 @@
-const state={products:[],quantities:{},paymentTimer:null,pollTimer:null,thankTimer:null,pollSince:0};
+const state={products:[],quantities:{},paymentTimer:null,pollTimer:null,thankTimer:null,pollSince:0,thankYouSeconds:3};
+const debug=(...args)=>console.log('[FIKAKASSA]',new Date().toISOString(),...args);
// Kioskläge: blockera webbläsarens vanliga touch-, markerings- och kontextmenyer.
document.addEventListener('contextmenu',e=>e.preventDefault());
@@ -137,9 +138,58 @@ function renderProducts(){
}
function changeQty(id,d){state.quantities[id]=Math.max(0,(state.quantities[id]||0)+d);renderProducts()}
function clearTimers(){if(state.paymentTimer)clearTimeout(state.paymentTimer);if(state.pollTimer)clearTimeout(state.pollTimer);if(state.thankTimer)clearTimeout(state.thankTimer);state.paymentTimer=state.pollTimer=state.thankTimer=null}
-function resetShop(){clearTimers();state.quantities={};state.pollSince=Date.now()/1000;paymentView.classList.add('hidden');thanksView.classList.add('hidden');shopView.classList.remove('hidden');renderProducts()}
-async function startPayment(){const items=state.products.map(p=>({id:p.id,quantity:state.quantities[p.id]||0})).filter(x=>x.quantity>0);if(!items.length)return;const r=await fetch('/api/order',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({items})});if(!r.ok)return;const order=await r.json();summary.innerHTML=order.items.map(i=>`
${i.quantity} ×${i.name}
`).join('');paymentTotal.textContent=money(order.total);posterAmount.textContent=`Betala ${money(order.total)}`;posterNumber.textContent=formatSwishNumber(order.swish_number);posterName.textContent=order.swish_name||'Joakim Svensson';try{await prepareQr(order.id);}catch(e){console.error(e);return;}shopView.classList.add('hidden');thanksView.classList.add('hidden');paymentView.classList.remove('hidden');timeoutBar.style.transition='none';timeoutBar.style.transform='scaleX(1)';requestAnimationFrame(()=>requestAnimationFrame(()=>{timeoutBar.style.transition='transform 30s linear';timeoutBar.style.transform='scaleX(0)'}));state.pollSince=Date.now()/1000;pollPayment();state.paymentTimer=setTimeout(resetShop,30000)}
-async function pollPayment(){try{const r=await fetch(`/api/payment/event?after=${state.pollSince}`,{cache:'no-store'});if(r.ok){const e=await r.json();if(e.event==='payment'){state.pollSince=e.received_at;showThanks();return}}}catch(e){}if(!paymentView.classList.contains('hidden'))state.pollTimer=setTimeout(pollPayment,700)}
-function showThanks(){clearTimers();paymentView.classList.add('hidden');shopView.classList.add('hidden');thanksView.classList.remove('hidden');state.thankTimer=setTimeout(resetShop,3000)}
+function resetShop(){
+ debug('resetShop()');
+ clearTimers();state.quantities={};state.pollSince=Date.now()/1000;
+ paymentView.classList.add('hidden');thanksView.classList.add('hidden');shopView.classList.remove('hidden');renderProducts()
+}
+async function startPayment(){
+ const items=state.products.map(p=>({id:p.id,quantity:state.quantities[p.id]||0})).filter(x=>x.quantity>0);
+ if(!items.length)return;
+ debug('startPayment()',items);
+ const r=await fetch('/api/order',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({items})});
+ if(!r.ok){debug('POST /api/order failed',r.status);return}
+ const order=await r.json();
+ debug('order created',order.id,'total=',order.total,'created_at=',order.created_at);
+ summary.innerHTML=order.items.map(i=>`${i.quantity} ×${i.name}
`).join('');
+ paymentTotal.textContent=money(order.total);posterAmount.textContent=`Betala ${money(order.total)}`;
+ posterNumber.textContent=formatSwishNumber(order.swish_number);posterName.textContent=order.swish_name||'Joakim Svensson';
+ try{await prepareQr(order.id)}catch(e){debug('QR failed',e);console.error(e);return}
+ shopView.classList.add('hidden');thanksView.classList.add('hidden');paymentView.classList.remove('hidden');
+ timeoutBar.style.transition='none';timeoutBar.style.transform='scaleX(1)';
+ requestAnimationFrame(()=>requestAnimationFrame(()=>{timeoutBar.style.transition='transform 30s linear';timeoutBar.style.transform='scaleX(0)'}));
+ // Use order.created_at rather than "now". A fast payment can arrive while the QR is loading.
+ state.pollSince=Math.max(0,Number(order.created_at)-0.01);
+ debug('payment polling started, after=',state.pollSince);
+ pollPayment();
+ state.paymentTimer=setTimeout(()=>{debug('payment timeout');resetShop()},30000)
+}
+async function pollPayment(){
+ try{
+ const after=state.pollSince;
+ const r=await fetch(`/api/payment/event?after=${after}`,{cache:'no-store'});
+ if(r.ok){
+ const e=await r.json();
+ debug('payment event poll',e);
+ if(e.event==='payment'){
+ state.pollSince=e.received_at;
+ showThanks();
+ return
+ }
+ }else debug('payment event HTTP',r.status);
+ }catch(e){debug('payment poll error',e)}
+ if(!paymentView.classList.contains('hidden'))state.pollTimer=setTimeout(pollPayment,700)
+}
+function showThanks(){
+ debug('showThanks(): payment accepted, switching to thanks screen');
+ clearTimers();
+ paymentView.classList.add('hidden');shopView.classList.add('hidden');thanksView.classList.remove('hidden');
+ debug('thanks timer started',state.thankYouSeconds*1000,'ms');
+ state.thankTimer=setTimeout(()=>{debug('thanks timer expired');resetShop()},state.thankYouSeconds*1000)
+}
nextCustomer.onclick=resetShop;cancelPurchase.onclick=resetShop;
-Promise.all([fetch('/api/products').then(r=>r.json()),fetch('/api/shop').then(r=>r.json())]).then(([pd,sd])=>{state.products=pd.products;applyGridConfig(sd.grid);state.products.forEach(p=>state.quantities[p.id]=0);renderProducts()});
+Promise.all([fetch('/api/products').then(r=>r.json()),fetch('/api/shop').then(r=>r.json())]).then(([pd,sd])=>{
+ state.products=pd.products;applyGridConfig(sd.grid);state.thankYouSeconds=Number(sd.thank_you_seconds)||3;
+ debug('shop config loaded',sd);
+ state.products.forEach(p=>state.quantities[p.id]=0);renderProducts()
+}).catch(e=>debug('initial load failed',e));
diff --git a/app/static/js/backoffice.js b/app/static/js/backoffice.js
new file mode 100644
index 0000000..08fc094
--- /dev/null
+++ b/app/static/js/backoffice.js
@@ -0,0 +1,59 @@
+const $=id=>document.getElementById(id);
+const money=v=>`${Number(v||0).toFixed(2).replace('.00','')} kr`;
+const fmtTime=ts=>new Date(Number(ts)*1000).toLocaleString('sv-SE',{dateStyle:'short',timeStyle:'short'});
+const dayInput=$('day');
+dayInput.value=new Date().toLocaleDateString('sv-SE',{year:'numeric',month:'2-digit',day:'2-digit'}).split('/').reverse().join('-');
+
+async function get(url,opts){const r=await fetch(url,opts);if(!r.ok)throw new Error(await r.text());return r.json()}
+async function loadDashboard(){
+ const d=await get(`/api/backoffice/dashboard?day=${encodeURIComponent(dayInput.value)}`);
+ $('sales').textContent=money(d.sales); $('orders').textContent=d.orders;
+ $('cogs').textContent=money(d.cogs); $('shrink').textContent=money(d.shrinkage_cost); $('profit').textContent=money(d.profit);
+ $('salesTable').querySelector('tbody').innerHTML=d.order_lines.map(x=>`| ${x.product_name} | ${x.quantity} | ${money(x.line_total)} |
`).join('')||'| Ingen försäljning. |
';
+}
+async function loadHistory(){
+ const back=Math.max(0,Math.min(3650,Number($('daysBack').value)||0));
+ $('daysBack').value=back;
+ $('historyRange').textContent=back===0?'Idag':`Idag − ${back} dagar`;
+ const rows=await get(`/api/backoffice/history?back_days=${back}`);
+ const max=Math.max(1,...rows.map(x=>x.sales));
+ $('historyChart').innerHTML=rows.map(x=>`${x.day}: ${money(x.sales)}
`).join('');
+ $('historyTable').querySelector('tbody').innerHTML=[...rows].reverse().map(x=>`| ${x.day} | ${x.orders} | ${money(x.sales)} | ${money(x.shrink)} | ${money(x.profit)} |
`).join('');
+ const totals=rows.reduce((a,x)=>({orders:a.orders+x.orders,sales:a.sales+x.sales,cogs:a.cogs+x.cogs,shrink:a.shrink+x.shrink,profit:a.profit+x.profit}),{orders:0,sales:0,cogs:0,shrink:0,profit:0});
+ $('historySummary').innerHTML=`${rows.length} dagar${totals.orders} köp${money(totals.sales)} försäljning${money(totals.cogs)} varukostnad${money(totals.shrink)} svinn${money(totals.profit)} resultat`;
+}
+
+async function loadInventory(){
+ const d=await get('/api/backoffice/inventory');
+ $('inventoryTable').querySelector('tbody').innerHTML=d.items.map(x=>`
+| ${x.name} | ${x.store} | ${x.backstock} | ${x.store+x.backstock} |
+${money(x.cost_price)} | ${money(x.stock_value)} |
+ |
`).join('');
+ $('mProduct').innerHTML=d.items.map(x=>``).join('');
+}
+async function loadMovements(){
+ const d=await get('/api/backoffice/movements');
+ const labels={purchase:'Påfyllnad',shrinkage:'Svinn',adjustment:'Justering',transfer_in:'Flytt in',transfer_out:'Flytt ut',sale:'Försäljning'};
+ $('movementTable').querySelector('tbody').innerHTML=d.movements.map(x=>`| ${fmtTime(x.created_at)} | ${x.name} | ${x.location==='store'?'Butik':'Baklager'} | ${labels[x.movement_type]||x.movement_type} | ${x.quantity>0?'+':''}${x.quantity} | ${x.note||''} |
`).join('');
+}
+async function refresh(){
+ $('status').textContent='Uppdaterar…';
+ try{await Promise.all([loadDashboard(),loadHistory(),loadInventory(),loadMovements()]);$('status').textContent='Uppdaterad '+new Date().toLocaleTimeString('sv-SE')}catch(e){$('status').textContent='Fel: '+e.message}
+}
+async function setCost(id,current){
+ const v=prompt('Nytt inköpspris per styck (kr):',current);
+ if(v===null)return;
+ const n=Number(v);if(!Number.isFinite(n)||n<0)return alert('Ogiltigt pris.');
+ await get('/api/backoffice/product-cost',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({product_id:id,cost_price:n})});
+ refresh();
+}
+$('movementForm').addEventListener('submit',async e=>{
+ e.preventDefault();
+ const type=$('mType').value;
+ const note=$('mNote').value;
+ const payload={product_id:$('mProduct').value,location:$('mLocation').value,movement_type:type,quantity:Number($('mQty').value),note,cost_price:$('mCost').value===''?null:Number($('mCost').value)};
+ if(type==='transfer'&&!/^from:(store|backstock)/i.test(note)){alert('Ange källa i noteringen: from:store eller from:backstock');return}
+ try{await get('/api/backoffice/inventory',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});e.target.reset();await refresh()}catch(err){alert(err.message)}
+});
+$('refresh').onclick=refresh;$('reloadInventory').onclick=loadInventory;$('daysBack').oninput=loadHistory;$('historyMinus').onclick=()=>{const e=$('daysBack');e.value=Math.max(0,(Number(e.value)||0)-1);loadHistory()};$('historyPlus').onclick=()=>{const e=$('daysBack');e.value=Math.min(3650,(Number(e.value)||0)+1);loadHistory()};
+refresh();
diff --git a/app/templates/backoffice.html b/app/templates/backoffice.html
new file mode 100644
index 0000000..5caeb24
--- /dev/null
+++ b/app/templates/backoffice.html
@@ -0,0 +1,88 @@
+
+
+
+
+
+Fikakassan – Backoffice
+
+
+
+
+
+
+
+
+
+ Försäljning0 kr
+ Betalda köp0
+ Varukostnad0 kr
+ Svinnkostnad0 kr
+ Resultat efter svinn0 kr
+
+
+
+
+
+
+
Historik
+
+
+
+
+ Idag
+
+
+
+
+ | Datum | Köp | Försäljning | Svinn | Resultat |
|---|
+
+
+
+ Lager
+ Butik = det som finns ute i kassan. Baklager = reservlager. Inköpspris används för varukostnad och svinnkostnad.
+
+ | Produkt | Butik | Baklager | Totalt | Inköpspris | Lager värde | Åtgärd |
+
+
+
+
+
+ Registrera lagerhändelse
+
+ Vid "Flytta till detta lager" används noteringen from:backstock eller from:store för att ange källan.
+
+
+
+ Senaste lagerhändelser
+ | Tid | Produkt | Plats | Händelse | Antal | Notering |
|---|
+
+
+
+
+
diff --git a/config.yaml b/config.yaml
index 1a5cd3a..2d6dd53 100644
--- a/config.yaml
+++ b/config.yaml
@@ -5,7 +5,7 @@ shop:
payment_timeout_seconds: 30
thank_you_seconds: 3
grid:
- columns: 4
+ columns: 5
rows: 2
products:
- id: monster-energy
@@ -16,6 +16,25 @@ products:
name: Monster Ultra
price: 20
image: monster-ultra.jpg
+- id: combo-monster-corny
+ name: Monster Ultra + Corny Big
+ price: 33
+ offer: true
+ offer_label: ERBJUDANDE
+ images:
+ - monster-ultra.jpg
+ - corny-large.jpg
+ image_rotations:
+ - 0
+ - 90
+ image_x_offsets:
+ - -28
+ - 28
+ components:
+ - id: monster-ultra
+ quantity: 1
+ - id: corny-big
+ quantity: 1
- id: coca-cola
name: Coca-Cola
price: 15
@@ -29,6 +48,25 @@ products:
price: 15
image: twix.jpg
rotate: 0
+- id: combo-twix-cola
+ name: Twix + Coca-Cola
+ price: 29
+ offer: true
+ offer_label: ERBJUDANDE
+ images:
+ - twix.jpg
+ - coca-cola.jpg
+ image_rotations:
+ - 0
+ - 0
+ image_x_offsets:
+ - -28
+ - 28
+ components:
+ - id: twix
+ quantity: 1
+ - id: coca-cola
+ quantity: 1
- id: kexchoklad
name: Kexchoklad
price: 15
@@ -39,3 +77,28 @@ products:
price: 15
image: corny-large.jpg
rotate: 90
+
+# Kända startvärden från inventeringsunderlaget.
+# Kvantiteterna är total lagerhållning; butik/baklager-fördelningen är inte angiven.
+initial_inventory:
+- id: monster-energy
+ quantity: 24
+ cost_price: 11.00
+- id: monster-ultra
+ quantity: 24
+ cost_price: 11.00
+- id: coca-cola
+ quantity: 30
+ cost_price: 6.23
+- id: coca-cola-zero
+ quantity: 30
+ cost_price: 6.23
+- id: kexchoklad
+ quantity: 40
+ cost_price: 5.62
+- id: twix
+ quantity: 20
+ cost_price: 4.72
+- id: corny-big
+ quantity: 24
+ cost_price: 6.55