Files
fikakassa/app/main.py
Joakim 9ae513a1b8 N/A
2026-11-01 22:06:14 +01:00

879 lines
34 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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
import qrcode
import yaml
from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse, JSONResponse, HTMLResponse, Response
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
BASE = Path(__file__).resolve().parent.parent
CONFIG = BASE / "config.yaml"
STATIC = Path(__file__).resolve().parent / "static"
TEMPLATES = Path(__file__).resolve().parent / "templates"
with CONFIG.open("r", encoding="utf-8") as f:
cfg = yaml.safe_load(f)
products = {p["id"]: p for p in cfg["products"]}
shop = cfg["shop"]
app = FastAPI(title="Fikakassan")
app.mount("/static", StaticFiles(directory=STATIC), name="static")
# Only the current order is eligible for the on-screen success message.
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())
def make_order(items: list[dict]) -> dict:
total = sum(int(x["price"]) * int(x["quantity"]) for x in items)
order_id = "FK-" + secrets.token_hex(4).upper()
return {
"id": order_id,
"items": items,
"total": total,
"created_at": time.time(),
"expires_at": time.time() + int(shop["payment_timeout_seconds"]),
}
def swish_qr_payload(order: dict) -> str:
# Current Swish QR link format. Omitting `edit` keeps the amount and message fixed.
sw = normalized_swish_number(shop["swish_number"])
msg = quote(order["id"], safe="")
return (
"https://app.swish.nu/1/p/sw/?"
f"sw={sw}&amt={order['total']:.2f}&cur=SEK&msg={msg}&src=qr"
)
def qr_png(payload: str) -> bytes:
qr = qrcode.QRCode(version=None, error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=12, border=4)
qr.add_data(payload)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white").convert("RGBA")
# Add the circular Swish mark in the centre. Error correction H gives the
# QR enough redundancy for the centre logo while keeping it easy to scan.
logo_path = STATIC / "swish-logo.png"
if logo_path.exists():
from PIL import Image, ImageDraw
logo = Image.open(logo_path).convert("RGBA")
target = max(96, img.width // 6)
logo.thumbnail((target, target), Image.Resampling.LANCZOS)
pad = 12
backing_size = max(logo.width, logo.height) + pad * 2
backing = Image.new("RGBA", (backing_size, backing_size), (255, 255, 255, 255))
mask = Image.new("L", (backing_size, backing_size), 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0, backing_size - 1, backing_size - 1), fill=255)
backing.alpha_composite(logo, ((backing_size - logo.width)//2, (backing_size - logo.height)//2))
backing.putalpha(mask)
x = (img.width - backing.width) // 2
y = (img.height - backing.height) // 2
img.alpha_composite(backing, (x, y))
out = io.BytesIO()
img.save(out, format="PNG")
return out.getvalue()
def swish_print_qr_payload() -> str:
# Printable QR: recipient only. The customer enters the amount in Swish.
sw = normalized_swish_number(shop["swish_number"])
return f"https://app.swish.nu/1/p/sw/?sw={sw}&cur=SEK&src=qr"
def print_qr_png() -> bytes:
return qr_png(swish_print_qr_payload())
@app.get("/print", response_class=HTMLResponse)
def print_shop():
"""Printable, always-current version of the configured shop."""
grid = shop.get("grid", {})
columns = max(1, int(grid.get("columns", 5)))
rows = max(1, int(grid.get("rows", 2)))
items = list(products.values())
cards = []
for p in items:
images = p.get("images") or ([p.get("image")] if p.get("image") else [])
rotations = p.get("image_rotations") or [p.get("rotate", 0)] * max(1, len(images))
offsets = p.get("image_x_offsets") or [0] * len(images)
image_html = []
for i, image in enumerate(images):
if not image:
continue
rotation = float(rotations[i] if i < len(rotations) else 0)
offset = float(offsets[i] if i < len(offsets) else 0)
z = 3 if i == 0 else 2
# The shop renders combo images after removing the large white
# margins from the original product photos. Use the same cropped
# assets for the printable version so the overlap and offsets look
# the same as on the touchscreen shop.
image_src = str(image)
if len(images) > 1:
stem = Path(image_src).stem
cropped = STATIC / "products" / "combo" / f"{stem}-cropped.jpg"
if cropped.exists():
image_src = f"combo/{stem}-cropped.jpg"
image_html.append(
f'<img class="print-product-image" src="/static/products/{escape(image_src, quote=True)}" '
f'alt="" style="--x:{offset:g}px;--rot:{rotation:g}deg;z-index:{z}">'
)
if p.get("offer"):
price = f'<div class="print-price offer"><span>{escape(str(p.get("offer_label", "ERBJUDANDE")))}</span>{int(p["price"])} kr</div>'
else:
price = f'<div class="print-price">{int(p["price"])} kr</div>'
cards.append(
'<article class="print-card">'
f'{price}'
f'<div class="print-image-area">{"".join(image_html)}</div>'
f'<div class="print-name">{escape(str(p["name"]))}</div>'
'</article>'
)
cards.append(
'<article class="print-card print-swish-card">'
'<div class="print-swish-poster">'
'<img class="print-qr" src="/print/swish-qr.png" alt="Swish QR-kod">'
f'<div class="print-swish-number">{escape(str(shop["swish_number"]))}</div>'
f'<div class="print-swish-name">{escape(str(shop["swish_name"]))}</div>'
'<div class="print-swish-amount">Ange beloppet själv</div>'
'</div>'
'</article>'
)
total_rows = max(rows, (len(cards) + columns - 1) // columns)
title = escape(str(shop.get("name", "Fikakassan")))
row_gap = max(0, total_rows - 1)
html = f"""<!doctype html>
<html lang="sv">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{title} – utskrift</title>
<style>
@page {{ size:A4 landscape; margin:8mm; }}
* {{ box-sizing:border-box; -webkit-print-color-adjust:exact; print-color-adjust:exact; }}
html,body {{ margin:0; padding:0; background:#fff; color:#111; font-family:Arial,Helvetica,sans-serif; }}
.print-toolbar {{ display:flex; justify-content:flex-end; padding:0 0 8px; }}
.print-toolbar button {{ font-size:16px; padding:8px 16px; cursor:pointer; }}
.print-grid {{ width:100%; display:grid; grid-template-columns:repeat({columns},minmax(0,1fr)); grid-auto-rows:minmax(0,1fr); gap:3mm; }}
.print-card {{ position:relative; min-width:0; min-height:0; border:1.5px solid #222; border-radius:5mm; overflow:hidden; background:#fff; display:flex; flex-direction:column; align-items:center; page-break-inside:avoid; break-inside:avoid; }}
.print-price {{ position:absolute; top:3mm; right:3mm; z-index:10; background:#ff5a00; color:#fff; border:1px solid #ff5a00; font-size:20pt; font-weight:800; line-height:1; padding:2.5mm 4mm; border-radius:999px; -webkit-print-color-adjust:exact; print-color-adjust:exact; }}
.print-price.offer {{ font-size:13pt; display:flex; flex-direction:column; align-items:center; gap:1mm; }}
.print-price.offer span {{ font-size:8pt; letter-spacing:.04em; }}
.print-image-area {{ position:relative; width:100%; flex:1 1 auto; min-height:0; display:flex; align-items:center; justify-content:center; overflow:hidden; padding:4mm 4mm 0; }}
.print-product-image {{ position:absolute; left:50%; top:50%; width:auto; height:94%; max-width:92%; object-fit:contain; transform:translateX(calc(-50% + var(--x,0px))) translateY(-50%) rotate(var(--rot,0deg)); transform-origin:center center; }}
.print-product-image:first-child {{ z-index:3; }}
.print-name {{ flex:0 0 auto; min-height:13mm; padding:1mm 3mm 3mm; width:100%; text-align:center; font-size:15pt; font-weight:700; line-height:1.05; display:flex; align-items:center; justify-content:center; }}
.print-swish-card {{ justify-content:center; padding:0; border:0; background:#fff; overflow:hidden; }}
.print-swish-poster {{ position:relative; width:100%; height:100%; aspect-ratio:625/945; background:url('/static/swish-poster-template.png') center/100% 100% no-repeat; -webkit-print-color-adjust:exact; print-color-adjust:exact; }}
.print-qr {{ position:absolute; left:12.5%; top:7.5%; width:75%; height:auto; aspect-ratio:1; object-fit:contain; }}
.print-swish-number {{ position:absolute; left:10%; top:56%; width:80%; text-align:center; color:#56575a; font-size:clamp(8pt,2.7vw,13pt); font-weight:700; letter-spacing:.1px; white-space:nowrap; }}
.print-swish-name {{ position:absolute; left:10%; top:61%; width:80%; text-align:center; color:#56575a; font-size:clamp(7pt,2vw,10pt); font-weight:700; white-space:nowrap; }}
.print-swish-amount {{ position:absolute; left:8%; top:70.5%; width:84%; text-align:center; color:#fff; font-size:clamp(8pt,2.5vw,12pt); font-weight:900; white-space:nowrap; }}
@media print {{
.print-toolbar {{ display:none; }}
.print-grid {{ min-height:calc(210mm - 16mm); grid-auto-rows:calc((210mm - 16mm - ({row_gap} * 3mm)) / {total_rows}); }}
}}
</style>
</head>
<body>
<div class="print-toolbar"><button onclick="window.print()">Skriv ut</button></div>
<main class="print-grid">{"".join(cards)}</main>
</body>
</html>"""
return HTMLResponse(html)
@app.get("/print/swish-qr.png")
def print_swish_qr():
return Response(content=print_qr_png(), media_type="image/png", headers={"Cache-Control": "no-store"})
@app.get("/")
def index():
return FileResponse(TEMPLATES / "index.html")
@app.get("/api/products")
def get_products():
return {"products": list(products.values())}
@app.get("/api/shop")
def get_shop():
return {
"name": shop["name"],
"swish_number": shop["swish_number"],
"swish_name": shop["swish_name"],
"payment_timeout_seconds": int(shop["payment_timeout_seconds"]),
"thank_you_seconds": int(shop["thank_you_seconds"]),
"grid": {
"columns": int(shop.get("grid", {}).get("columns", 4)),
"rows": int(shop.get("grid", {}).get("rows", 2)),
},
}
class OrderItem(BaseModel):
id: str
quantity: int
class OrderRequest(BaseModel):
items: list[OrderItem]
@app.post("/api/order")
def create_order(req: OrderRequest):
global current_order
# The offer cards are real product bundles. The customer sees the
# individual products in the receipt, while the order total uses the
# discounted bundle price.
display_items: dict[str, dict] = {}
total = 0
for requested in req.items:
if requested.id not in products:
raise HTTPException(400, f"Okänd produkt: {requested.id}")
if requested.quantity < 1:
continue
p = products[requested.id]
qty = int(requested.quantity)
total += int(p["price"]) * qty
components = p.get("components")
if components:
for component in components:
component_id = component["id"]
if component_id not in products:
raise HTTPException(500, f"Ogiltig kombination: {component_id}")
cp = products[component_id]
component_qty = qty * int(component.get("quantity", 1))
if component_id not in display_items:
display_items[component_id] = {
"id": cp["id"],
"name": cp["name"],
"price": int(cp["price"]),
"quantity": 0,
"image": cp.get("image"),
}
display_items[component_id]["quantity"] += component_qty
else:
if p["id"] not in display_items:
display_items[p["id"]] = {
"id": p["id"],
"name": p["name"],
"price": int(p["price"]),
"quantity": 0,
"image": p.get("image"),
}
display_items[p["id"]]["quantity"] += qty
if not display_items:
raise HTTPException(400, "Korgen är tom")
order_id = "FK-" + secrets.token_hex(4).upper()
now = time.time()
current_order = {
"id": order_id,
"items": list(display_items.values()),
"total": total,
"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"]}
@app.get("/api/order/{order_id}/qr.png")
def order_qr(order_id: str):
if not current_order or current_order["id"] != order_id:
raise HTTPException(404, "Ordern finns inte")
return FileResponse(
path=write_temp_qr(order_id),
media_type="image/png",
headers={"Cache-Control": "no-store"},
)
def write_temp_qr(order_id: str) -> str:
qrdir = BASE / "data" / "qr"
qrdir.mkdir(parents=True, exist_ok=True)
path = qrdir / f"{order_id}.png"
path.write_bytes(qr_png(swish_qr_payload(current_order)))
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:
return {"status": "idle"}
return {
"status": "waiting",
"order_id": current_order["id"],
"expires_at": current_order["expires_at"],
"total": current_order["total"],
}
@app.post("/api/payment")
def payment_notification(payment: PaymentNotification):
"""Endpoint for the Android Swish notification bridge.
A payment is accepted only when amount + message match the active order.
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"]
amount_ok = abs(float(payment.amount) - float(current_order["total"])) < 0.001
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",
"expected_amount": current_order["total"],
"expected_message": expected_message,
})
last_payment = {
"order_id": current_order["id"],
"amount": payment.amount,
"message": payment.message,
"sender": payment.sender,
"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"]}
@app.get("/api/payment/event")
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"}