from __future__ import annotations import io import secrets import time 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 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'' else: price = f'' cards.append( '' ) cards.append( '' ) 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""" {title} – utskrift
{"".join(cards)}
""" 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"]), } 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("/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"], } 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. 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 if not current_order: return JSONResponse({"accepted": False, "reason": "no_active_order"}) if time.time() > current_order["expires_at"]: 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): 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(), } 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: return {"event": "payment", **last_payment} return {"event": "none"}