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''
)
if p.get("offer"):
price = f'