commit fdeeb26e8688ecede235c1c8253b6ef72364cbb7 Author: Joakim Date: Sun Nov 1 16:20:49 2026 +0100 first commit diff --git a/README.md b/README.md new file mode 100644 index 0000000..66f56e5 --- /dev/null +++ b/README.md @@ -0,0 +1,45 @@ +# Fikakassan + +Kiosk-anpassad självbetjäningskassa med Swish-betalning. + +## Innehåll +- 5x2 produktlayout: 7 ordinarie produkter + 2 erbjudanden + totalsida. +- Erbjudanden: Monster Ultra + Corny Large för 33 kr och Coca-Cola + Twix för 29 kr. +- Produktnamn centreras under bilderna. +- Kexchoklad, Twix och Corny roteras 90 grader. +- Swish QR med Joakim Svensson och dynamiskt orderbelopp/order-ID. +- Betalningsbekräftelse via `POST /api/payment`. +- Kioskbegränsningar i webbsidan: zoom, markering, högerklick och touch-gester blockeras. + +## Start +```bash +python3 -m venv .venv +. .venv/bin/activate +pip install -r requirements.txt +uvicorn app.main:app --host 0.0.0.0 --port 8000 +``` + + +### Erbjudanden +Erbjudandekorten är rabatterade kombinationer av riktiga produkter. Vid betalning expanderas de till de ingående produkterna i köpsammanställningen, medan det rabatterade kombopriset används för totalsumman. + + +## Konfigurerbart produktgaller + +Rutnätet styrs i `config.yaml` under `shop.grid`: + +```yaml +grid: + columns: 5 + rows: 2 +``` + +Erbjudanden kan definieras som produkter med `offer: true`, `images` och `components`. `components` är de verkliga produkterna som hamnar var för sig i betalningssammanställningen, medan kombinationen använder sitt rabatterade pris. + +## Utskrift + +Öppna `http://:8000/print` för en utskriftsvänlig version av aktuellt sortiment. + +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. diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..3d97853 --- /dev/null +++ b/README.txt @@ -0,0 +1,16 @@ +Fikakassan V9 – screensaver + lokal rörelsedetektering + +Testkörning på Debian: + cd fikakassa-v9 + python3 -m http.server 8080 + öppna http://127.0.0.1:8080/ + +Webbläsaren behöver kameratillstånd. Kameran används endast lokalt för lågupplöst rörelsedetektering; inga bilder sparas eller skickas. + +Screensaver efter 20 sekunder. Rörelse framför kameran eller touch väcker kassan. + +Produktlayouten räknas automatiskt ut från antal produkter + totalslot. Exempel: + 7 produkter -> 4x2 + 17 produkter -> 6x3 + 18 produkter -> 6x3 +Det finns alltså ingen hårdkodad 4x2-layout. diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..e52a553 --- /dev/null +++ b/app/main.py @@ -0,0 +1,391 @@ +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"} diff --git a/app/static/css/style.css b/app/static/css/style.css new file mode 100644 index 0000000..62c084d --- /dev/null +++ b/app/static/css/style.css @@ -0,0 +1,6 @@ +:root{--orange:#ff5a00;--ink:#17191d;--muted:#68707a;--bg:#f3f4f6}*{box-sizing:border-box;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}html,body{margin:0;width:100%;height:100%;overflow:hidden;touch-action:none;overscroll-behavior:none}body{font-family:Arial,Helvetica,sans-serif;background:var(--bg);color:var(--ink)}button{font:inherit;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;touch-action:manipulation}.hidden{display:none!important}.shop-view{width:100vw;height:100vh;padding:10px}.product-grid{width:100%;height:100%;display:grid;grid-template-columns:repeat(var(--grid-columns,4),minmax(0,1fr));grid-template-rows:repeat(var(--grid-rows,2),minmax(0,1fr));gap:10px}.product-card,.total-card{position:relative;min-width:0;min-height:0;background:#fff;border-radius:18px;box-shadow:0 2px 12px rgba(0,0,0,.08);overflow:hidden}.product-card{padding:10px 10px 9px;display:flex;flex-direction:column}.product-image-wrap{flex:1 1 0;height:0;min-height:0;display:flex;align-items:center;justify-content:center;padding:2px 12px 0;overflow:hidden}.product-image{max-width:100%;max-height:100%;object-fit:contain;-webkit-user-drag:none;user-drag:none;pointer-events:none}.product-canvas{display:block;max-width:100%;max-height:100%;width:auto;height:100%;object-fit:contain;pointer-events:none}.combo-images{position:relative;width:100%;height:100%;display:block;overflow:visible}.combo-canvas{position:absolute;top:50%;left:50%;width:auto;height:100%;max-width:88%;transform:translate(calc(-50% + var(--combo-x, 0px)),-50%)}.combo-canvas:first-child{z-index:3}.combo-canvas:not(:first-child){z-index:2}.product-name{flex:0 0 34px;height:34px;font-size:clamp(16px,1.3vw,23px);font-weight:700;line-height:30px;margin:2px 0 5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-align:center;width:100%}.price{position:absolute;top:8px;right:8px;z-index:100;background:var(--orange);color:#fff;font-weight:800;font-size:clamp(21px,2vw,34px);line-height:1;padding:8px 12px;border-radius:999px;border:4px solid #fff;box-shadow:none;transform:none}.offer-price{border-radius:16px;padding:6px 12px 7px;display:flex;flex-direction:column;align-items:center;gap:1px}.offer-label{font-size:clamp(10px,0.8vw,14px);font-weight:900;letter-spacing:.8px;line-height:1}.offer-value{font-size:clamp(21px,2vw,34px);line-height:1.05}.qty{align-self:center;display:flex;align-items:center;justify-content:center;gap:15px;min-width:132px;height:47px;padding:4px 11px;border-radius:999px;background:#eef0f2;font-size:22px;font-weight:800;transition:.12s ease}.qty.selected{background:var(--orange);color:#fff}.qty button{border:0;background:transparent;color:inherit;cursor:pointer;width:31px;height:39px;font-size:28px;line-height:1}.qty button:active{transform:scale(.88)}.qty-value{min-width:20px;text-align:center}.total-card{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:18px}.total-label{color:var(--muted);font-size:25px;font-weight:700}.total-value{font-size:clamp(40px,4.2vw,66px);font-weight:900;margin:5px 0 18px}.pay-button{width:100%;max-width:340px;min-height:64px;border:0;border-radius:16px;background:var(--orange);color:#fff;font-size:21px;font-weight:900;cursor:pointer}.pay-button:disabled{background:#ffc9a7;cursor:default}.clear-button{margin-top:10px;border:0;background:transparent;text-decoration:underline;color:var(--muted);cursor:pointer;font-size:15px} + +.payment-view{width:100vw;height:100vh;display:flex;flex-direction:column;padding:24px 28px 0;background:var(--bg)}.payment-content{flex:1 1 auto;min-height:0;display:grid;grid-template-columns:minmax(0,1fr) minmax(420px,46vw);gap:28px;align-items:center}.payment-summary-card{height:100%;min-height:0;background:#fff;border-radius:28px;box-shadow:0 2px 15px rgba(0,0,0,.08);display:flex;flex-direction:column;justify-content:center;padding:42px clamp(30px,4vw,70px);overflow:hidden}.payment-heading{font-size:clamp(34px,3vw,52px);font-weight:900;margin-bottom:24px}.summary{width:100%;font-size:clamp(21px,1.8vw,30px);color:#30343a}.summary-row{display:flex;align-items:center;justify-content:space-between;gap:20px;padding:11px 0;border-bottom:1px solid #e7e9eb}.summary-row strong{font-size:1em;white-space:nowrap}.summary-row span{font-weight:700;text-align:right}.summary-divider{height:2px;background:#eceef0;margin:22px 0 18px}.summary-total-label{font-size:20px;font-weight:700;color:var(--muted)}.payment-total{font-size:clamp(58px,6vw,94px);font-weight:900;color:var(--orange);line-height:1;margin:7px 0 26px}.poster-area{height:100%;min-height:0;display:flex;align-items:center;justify-content:center}.swish-poster{position:relative;height:min(84vh,920px);width:auto;aspect-ratio:625/945;background:url('/static/swish-poster-template.png') center/100% 100% no-repeat;flex:0 1 auto}.poster-qr{position:absolute;left:12.5%;top:7.5%;width:75%;height:auto;aspect-ratio:1;object-fit:contain}.poster-number{position:absolute;left:10%;top:56.0%;width:80%;text-align:center;color:#56575a;font-size:clamp(21px,3.15vh,43px);font-weight:700;letter-spacing:.5px;white-space:nowrap}.poster-name{position:absolute;left:10%;top:61.0%;width:80%;text-align:center;color:#56575a;font-size:clamp(16px,2.2vh,31px);font-weight:700;white-space:nowrap}.poster-amount{position:absolute;left:8%;top:70.5%;width:84%;text-align:center;color:#fff;font-size:clamp(22px,3.25vh,45px);font-weight:900;white-space:nowrap}.timeout-bar-wrap{height:68px;flex:0 0 68px;position:relative;display:flex;align-items:flex-end;justify-content:space-between;background:var(--bg);padding-bottom:8px}.next-customer{order:3;margin:0;border:0;background:var(--orange);color:#fff;font-size:19px;font-weight:800;border-radius:12px;padding:15px 22px;cursor:pointer}.cancel-purchase{order:1;margin:0;border:0;background:#fff;color:var(--ink);font-size:19px;font-weight:800;border-radius:12px;padding:15px 22px;cursor:pointer;box-shadow:0 2px 10px rgba(0,0,0,.08)}.timeout-bar{order:2;position:absolute;left:0;bottom:0;flex:0 0 8px;width:100%;height:8px;background:var(--orange);transform-origin:right center}.thanks-view{width:100vw;height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;background:#fff}.thanks-icon{width:110px;height:110px;border-radius:50%;background:var(--orange);color:#fff;display:grid;place-items:center;font-size:70px;font-weight:900}.thanks-view h1{font-size:clamp(40px,5vw,72px);margin:24px 0 8px}.thanks-view p{color:var(--muted);font-size:26px;margin:0} + +@media(max-width:1050px){.shop-view{padding:7px}.product-grid{gap:7px}.product-card{padding:7px 7px 8px}.price{top:7px;right:7px;font-size:20px;padding:6px 9px;border-width:3px;transform:none;box-shadow:none}.offer-price{padding:5px 8px 6px}.offer-label{font-size:9px}.qty{min-width:116px;height:43px;gap:10px}.product-name{flex-basis:30px;height:30px;font-size:15px;line-height:27px;margin:2px 0 3px}.payment-view{padding:12px 12px 0}.payment-content{grid-template-columns:minmax(0,1fr) minmax(330px,43vw);gap:14px}.payment-summary-card{padding:28px 24px}.payment-heading{margin-bottom:16px}.summary-row{padding:8px 0}.payment-total{margin-bottom:18px}.swish-poster{height:min(82vh,760px)}} +@media(max-width:760px){.payment-content{grid-template-columns:1fr;grid-template-rows:auto 1fr;overflow:hidden}.payment-summary-card{height:auto;min-height:0;padding:16px 20px}.payment-heading{font-size:28px;margin-bottom:8px}.summary{font-size:18px}.summary-row{padding:5px 0}.summary-divider{margin:10px 0 8px}.summary-total-label{font-size:15px}.payment-total{font-size:46px;margin:4px 0 10px}.poster-area{min-height:0}.swish-poster{height:min(57vh,620px)}} diff --git a/app/static/index.html b/app/static/index.html new file mode 100644 index 0000000..22c6f85 --- /dev/null +++ b/app/static/index.html @@ -0,0 +1,220 @@ + + + + + +Fikakassan + + + +
+
+
Välkommen till Fikakassan
+ + +
+
Inväntar betalning
0 kr
Genomför betalningen med Swish.
+ + + + diff --git a/app/static/js/app.js b/app/static/js/app.js new file mode 100644 index 0000000..4da259f --- /dev/null +++ b/app/static/js/app.js @@ -0,0 +1,145 @@ +const state={products:[],quantities:{},paymentTimer:null,pollTimer:null,thankTimer:null,pollSince:0}; + +// Kioskläge: blockera webbläsarens vanliga touch-, markerings- och kontextmenyer. +document.addEventListener('contextmenu',e=>e.preventDefault()); +document.addEventListener('selectstart',e=>e.preventDefault()); +document.addEventListener('dragstart',e=>e.preventDefault()); +document.addEventListener('gesturestart',e=>e.preventDefault(),{passive:false}); +document.addEventListener('gesturechange',e=>e.preventDefault(),{passive:false}); +document.addEventListener('gestureend',e=>e.preventDefault(),{passive:false}); +document.addEventListener('wheel',e=>{if(e.ctrlKey)e.preventDefault()},{passive:false}); +document.addEventListener('keydown',e=>{ + if((e.ctrlKey||e.metaKey)&&(['+','-','=','0'].includes(e.key)))e.preventDefault(); +}); + +const shopView=document.getElementById('shopView'),paymentView=document.getElementById('paymentView'),thanksView=document.getElementById('thanksView'),productGrid=document.getElementById('productGrid'),summary=document.getElementById('summary'),paymentTotal=document.getElementById('paymentTotal'),qr=document.getElementById('qr'),posterAmount=document.getElementById('posterAmount'),posterNumber=document.getElementById('posterNumber'),posterName=document.getElementById('posterName'),timeoutBar=document.getElementById('timeoutBar'),nextCustomer=document.getElementById('nextCustomer'),cancelPurchase=document.getElementById('cancelPurchase'); +const money=v=>`${v} kr`; +function formatSwishNumber(v){const d=String(v||'').replace(/\D/g,'');if(d.startsWith('46')&&d.length===11){const n='0'+d.slice(2);return `${n.slice(0,3)}-${n.slice(3,6)} ${n.slice(6,8)} ${n.slice(8,10)}`}return v||''} +function total(){return state.products.reduce((s,p)=>s+(state.quantities[p.id]||0)*p.price,0)} +const imageCache=new Map(); +let qrObjectUrl=null; + +async function prepareQr(orderId){ + const response=await fetch(`/api/order/${encodeURIComponent(orderId)}/qr.png?ts=${Date.now()}`,{cache:'no-store'}); + if(!response.ok)throw new Error('Kunde inte hämta QR-koden'); + const blob=await response.blob(); + if(qrObjectUrl)URL.revokeObjectURL(qrObjectUrl); + qrObjectUrl=URL.createObjectURL(blob); + qr.src=qrObjectUrl; + if(qr.decode){ + try{await qr.decode();}catch(e){ + await new Promise((resolve,reject)=>{qr.onload=resolve;qr.onerror=reject;}); + } + }else{ + await new Promise((resolve,reject)=>{qr.onload=resolve;qr.onerror=reject;}); + } +} + + +function productImages(p){ + const images=p.images||[p.image]; + const rotations=p.image_rotations||[p.rotate||0]; + const xOffsets=p.image_x_offsets||[]; + if(images.length>1){ + return `
${images.map((img,i)=>``).join('')}
`; + } + return ``; +} + +async function loadTransparentImage(src){ + if(imageCache.has(src))return imageCache.get(src); + const promise=new Promise((resolve,reject)=>{ + const img=new Image(); + img.onload=()=>{ + const scale=Math.min(1,900/Math.max(img.naturalWidth,img.naturalHeight)); + const w=Math.max(1,Math.round(img.naturalWidth*scale)); + const h=Math.max(1,Math.round(img.naturalHeight*scale)); + const c=document.createElement('canvas'); c.width=w; c.height=h; + const ctx=c.getContext('2d',{willReadFrequently:true}); + ctx.drawImage(img,0,0,w,h); + const data=ctx.getImageData(0,0,w,h); + const px=data.data, seen=new Uint8Array(w*h), queue=new Int32Array(w*h); + let head=0,tail=0; + const nearWhite=i=>px[i]>=244&&px[i+1]>=244&&px[i+2]>=244&&px[i+3]>0; + const push=(x,y)=>{const n=y*w+x;if(!seen[n]){seen[n]=1;queue[tail++]=n}}; + for(let x=0;x0)push(x-1,y); if(x0)push(x,y-1); if(y8){if(xmaxX)maxX=x;if(ymaxY)maxY=y}} + if(maxX<0){resolve(null);return} + const pad=8; minX=Math.max(0,minX-pad); minY=Math.max(0,minY-pad); maxX=Math.min(w-1,maxX+pad); maxY=Math.min(h-1,maxY+pad); + const out=document.createElement('canvas'); out.width=maxX-minX+1; out.height=maxY-minY+1; + out.getContext('2d').drawImage(c,minX,minY,out.width,out.height,0,0,out.width,out.height); + resolve(out); + }; + img.onerror=reject; img.src=src; + }); + imageCache.set(src,promise); + return promise; +} + +async function hydrateProductCanvases(){ + const canvases=[...document.querySelectorAll('.product-canvas')]; + await Promise.all(canvases.map(async canvas=>{ + try{ + const source=await loadTransparentImage(canvas.dataset.src); + if(!source)return; + const rotation=(Number(canvas.dataset.rotation)||0)*Math.PI/180; + const sin=Math.abs(Math.sin(rotation)),cos=Math.abs(Math.cos(rotation)); + const rw=Math.max(1,Math.round(source.width*cos+source.height*sin)); + const rh=Math.max(1,Math.round(source.width*sin+source.height*cos)); + canvas.width=rw; canvas.height=rh; + if(canvas.classList.contains('combo-canvas')) canvas.style.setProperty('--combo-x', `${Number(canvas.dataset.xOffset)||0}px`); + const ctx=canvas.getContext('2d'); + ctx.clearRect(0,0,rw,rh); ctx.translate(rw/2,rh/2); ctx.rotate(rotation); + ctx.drawImage(source,-source.width/2,-source.height/2); + }catch(e){console.error('Kunde inte behandla produktbild',canvas.dataset.src,e)} + })); +} +function applyGridConfig(grid){ + const columns=Math.max(1,Number(grid?.columns)||4); + const rows=Math.max(1,Number(grid?.rows)||2); + productGrid.style.setProperty('--grid-columns',columns); + productGrid.style.setProperty('--grid-rows',rows); +} +function priceMarkup(p){ + if(p.offer){ + return `
${p.offer_label||'ERBJUDANDE'}${money(p.price)}
`; + } + return `
${money(p.price)}
`; +} +function renderProducts(){ + productGrid.innerHTML=''; + state.products.forEach(p=>{ + const q=state.quantities[p.id]||0; + const c=document.createElement('article'); + c.className=`product-card${p.offer?' offer-card':''}`; + c.innerHTML=`${priceMarkup(p)}
${productImages(p)}
${p.name}
${q}
`; + c.querySelector('.minus').onclick=()=>changeQty(p.id,-1); + c.querySelector('.plus').onclick=()=>changeQty(p.id,1); + productGrid.appendChild(c); + }); + const t=document.createElement('article'); + t.className='total-card'; + const amount=total(); + t.innerHTML=`
Totalt
${money(amount)}
`; + t.querySelector('.pay-button').onclick=startPayment; + t.querySelector('.clear-button').onclick=resetShop; + productGrid.appendChild(t); + hydrateProductCanvases(); +} +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)} +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()}); diff --git a/app/static/products/coca-cola-zero.jpg b/app/static/products/coca-cola-zero.jpg new file mode 100644 index 0000000..af7a28e Binary files /dev/null and b/app/static/products/coca-cola-zero.jpg differ diff --git a/app/static/products/coca-cola.jpg b/app/static/products/coca-cola.jpg new file mode 100644 index 0000000..4e1a1b4 Binary files /dev/null and b/app/static/products/coca-cola.jpg differ diff --git a/app/static/products/combo/coca-cola-cropped.jpg b/app/static/products/combo/coca-cola-cropped.jpg new file mode 100644 index 0000000..3252df7 Binary files /dev/null and b/app/static/products/combo/coca-cola-cropped.jpg differ diff --git a/app/static/products/combo/corny-large-cropped.jpg b/app/static/products/combo/corny-large-cropped.jpg new file mode 100644 index 0000000..8b60fd5 Binary files /dev/null and b/app/static/products/combo/corny-large-cropped.jpg differ diff --git a/app/static/products/combo/monster-ultra-cropped.jpg b/app/static/products/combo/monster-ultra-cropped.jpg new file mode 100644 index 0000000..9561856 Binary files /dev/null and b/app/static/products/combo/monster-ultra-cropped.jpg differ diff --git a/app/static/products/combo/twix-cropped.jpg b/app/static/products/combo/twix-cropped.jpg new file mode 100644 index 0000000..5f75df8 Binary files /dev/null and b/app/static/products/combo/twix-cropped.jpg differ diff --git a/app/static/products/corny-large.jpg b/app/static/products/corny-large.jpg new file mode 100644 index 0000000..c2e8652 Binary files /dev/null and b/app/static/products/corny-large.jpg differ diff --git a/app/static/products/kexchoklad.jpg b/app/static/products/kexchoklad.jpg new file mode 100644 index 0000000..8c7979c Binary files /dev/null and b/app/static/products/kexchoklad.jpg differ diff --git a/app/static/products/monster-energy.jpg b/app/static/products/monster-energy.jpg new file mode 100644 index 0000000..e78e4d4 Binary files /dev/null and b/app/static/products/monster-energy.jpg differ diff --git a/app/static/products/monster-ultra.jpg b/app/static/products/monster-ultra.jpg new file mode 100644 index 0000000..fe2cfca Binary files /dev/null and b/app/static/products/monster-ultra.jpg differ diff --git a/app/static/products/twix.jpg b/app/static/products/twix.jpg new file mode 100644 index 0000000..2016da9 Binary files /dev/null and b/app/static/products/twix.jpg differ diff --git a/app/static/swish-logo.png b/app/static/swish-logo.png new file mode 100644 index 0000000..1520486 Binary files /dev/null and b/app/static/swish-logo.png differ diff --git a/app/static/swish-poster-template.png b/app/static/swish-poster-template.png new file mode 100644 index 0000000..09d3968 Binary files /dev/null and b/app/static/swish-poster-template.png differ diff --git a/app/templates/index.html b/app/templates/index.html new file mode 100644 index 0000000..f355f8a --- /dev/null +++ b/app/templates/index.html @@ -0,0 +1,48 @@ + + + + + + Fikakassan + + + +
+
+
+ + + + + + + + diff --git a/config.yaml b/config.yaml new file mode 100644 index 0000000..1a5cd3a --- /dev/null +++ b/config.yaml @@ -0,0 +1,41 @@ +shop: + name: Fikakassan + swish_number: +46 73 441 37 87 + swish_name: Joakim Svensson + payment_timeout_seconds: 30 + thank_you_seconds: 3 + grid: + columns: 4 + rows: 2 +products: +- id: monster-energy + name: Monster Energy + price: 20 + image: monster-energy.jpg +- id: monster-ultra + name: Monster Ultra + price: 20 + image: monster-ultra.jpg +- id: coca-cola + name: Coca-Cola + price: 15 + image: coca-cola.jpg +- id: coca-cola-zero + name: Coca-Cola Zero + price: 15 + image: coca-cola-zero.jpg +- id: twix + name: Twix + price: 15 + image: twix.jpg + rotate: 0 +- id: kexchoklad + name: Kexchoklad + price: 15 + image: kexchoklad.jpg + rotate: 0 +- id: corny-big + name: Corny Big + price: 15 + image: corny-large.jpg + rotate: 90 diff --git a/config4x2.yaml b/config4x2.yaml new file mode 100644 index 0000000..1a5cd3a --- /dev/null +++ b/config4x2.yaml @@ -0,0 +1,41 @@ +shop: + name: Fikakassan + swish_number: +46 73 441 37 87 + swish_name: Joakim Svensson + payment_timeout_seconds: 30 + thank_you_seconds: 3 + grid: + columns: 4 + rows: 2 +products: +- id: monster-energy + name: Monster Energy + price: 20 + image: monster-energy.jpg +- id: monster-ultra + name: Monster Ultra + price: 20 + image: monster-ultra.jpg +- id: coca-cola + name: Coca-Cola + price: 15 + image: coca-cola.jpg +- id: coca-cola-zero + name: Coca-Cola Zero + price: 15 + image: coca-cola-zero.jpg +- id: twix + name: Twix + price: 15 + image: twix.jpg + rotate: 0 +- id: kexchoklad + name: Kexchoklad + price: 15 + image: kexchoklad.jpg + rotate: 0 +- id: corny-big + name: Corny Big + price: 15 + image: corny-large.jpg + rotate: 90 diff --git a/config5x2.yaml b/config5x2.yaml new file mode 100644 index 0000000..af986a1 --- /dev/null +++ b/config5x2.yaml @@ -0,0 +1,79 @@ +shop: + name: Fikakassan + swish_number: +46 73 441 37 87 + swish_name: Joakim Svensson + payment_timeout_seconds: 30 + thank_you_seconds: 3 + grid: + columns: 5 + rows: 2 +products: +- id: monster-energy + name: Monster Energy + price: 20 + image: monster-energy.jpg +- id: monster-ultra + 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: + - -38 + - 38 + components: + - id: monster-ultra + quantity: 1 + - id: corny-big + quantity: 1 +- id: coca-cola + name: Coca-Cola + price: 15 + image: coca-cola.jpg +- id: coca-cola-zero + name: Coca-Cola Zero + price: 15 + image: coca-cola-zero.jpg +- id: twix + name: Twix + 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: + - -38 + - 38 + components: + - id: twix + quantity: 1 + - id: coca-cola + quantity: 1 +- id: kexchoklad + name: Kexchoklad + price: 15 + image: kexchoklad.jpg + rotate: 0 +- id: corny-big + name: Corny Big + price: 15 + image: corny-large.jpg + rotate: 90 diff --git a/data/qr/FK-0306AB64.png b/data/qr/FK-0306AB64.png new file mode 100644 index 0000000..a05584c Binary files /dev/null and b/data/qr/FK-0306AB64.png differ diff --git a/data/qr/FK-0B1395B1.png b/data/qr/FK-0B1395B1.png new file mode 100644 index 0000000..a1c8ba9 Binary files /dev/null and b/data/qr/FK-0B1395B1.png differ diff --git a/data/qr/FK-0EF4F0E0.png b/data/qr/FK-0EF4F0E0.png new file mode 100644 index 0000000..c7e4110 Binary files /dev/null and b/data/qr/FK-0EF4F0E0.png differ diff --git a/data/qr/FK-15FA20B6.png b/data/qr/FK-15FA20B6.png new file mode 100644 index 0000000..979bbbd Binary files /dev/null and b/data/qr/FK-15FA20B6.png differ diff --git a/data/qr/FK-174AD3DD.png b/data/qr/FK-174AD3DD.png new file mode 100644 index 0000000..24b588a Binary files /dev/null and b/data/qr/FK-174AD3DD.png differ diff --git a/data/qr/FK-1ED734E1.png b/data/qr/FK-1ED734E1.png new file mode 100644 index 0000000..8cbd77f Binary files /dev/null and b/data/qr/FK-1ED734E1.png differ diff --git a/data/qr/FK-1F52E29C.png b/data/qr/FK-1F52E29C.png new file mode 100644 index 0000000..4748a64 Binary files /dev/null and b/data/qr/FK-1F52E29C.png differ diff --git a/data/qr/FK-24280D4D.png b/data/qr/FK-24280D4D.png new file mode 100644 index 0000000..8875982 Binary files /dev/null and b/data/qr/FK-24280D4D.png differ diff --git a/data/qr/FK-3134F4D4.png b/data/qr/FK-3134F4D4.png new file mode 100644 index 0000000..733905c Binary files /dev/null and b/data/qr/FK-3134F4D4.png differ diff --git a/data/qr/FK-3356A3A6.png b/data/qr/FK-3356A3A6.png new file mode 100644 index 0000000..534790a Binary files /dev/null and b/data/qr/FK-3356A3A6.png differ diff --git a/data/qr/FK-37BF74C0.png b/data/qr/FK-37BF74C0.png new file mode 100644 index 0000000..a3d7e56 Binary files /dev/null and b/data/qr/FK-37BF74C0.png differ diff --git a/data/qr/FK-3D394FB2.png b/data/qr/FK-3D394FB2.png new file mode 100644 index 0000000..162d71d Binary files /dev/null and b/data/qr/FK-3D394FB2.png differ diff --git a/data/qr/FK-40F60424.png b/data/qr/FK-40F60424.png new file mode 100644 index 0000000..8aba2ae Binary files /dev/null and b/data/qr/FK-40F60424.png differ diff --git a/data/qr/FK-5AE78EBB.png b/data/qr/FK-5AE78EBB.png new file mode 100644 index 0000000..fa9f619 Binary files /dev/null and b/data/qr/FK-5AE78EBB.png differ diff --git a/data/qr/FK-5F8D3164.png b/data/qr/FK-5F8D3164.png new file mode 100644 index 0000000..3955a85 Binary files /dev/null and b/data/qr/FK-5F8D3164.png differ diff --git a/data/qr/FK-6CB4F03E.png b/data/qr/FK-6CB4F03E.png new file mode 100644 index 0000000..6e8629d Binary files /dev/null and b/data/qr/FK-6CB4F03E.png differ diff --git a/data/qr/FK-726EC95C.png b/data/qr/FK-726EC95C.png new file mode 100644 index 0000000..3969921 Binary files /dev/null and b/data/qr/FK-726EC95C.png differ diff --git a/data/qr/FK-7C967EDA.png b/data/qr/FK-7C967EDA.png new file mode 100644 index 0000000..6e6631a Binary files /dev/null and b/data/qr/FK-7C967EDA.png differ diff --git a/data/qr/FK-7CA3F695.png b/data/qr/FK-7CA3F695.png new file mode 100644 index 0000000..5a6d085 Binary files /dev/null and b/data/qr/FK-7CA3F695.png differ diff --git a/data/qr/FK-809D12B8.png b/data/qr/FK-809D12B8.png new file mode 100644 index 0000000..a234f6b Binary files /dev/null and b/data/qr/FK-809D12B8.png differ diff --git a/data/qr/FK-85D9AEDE.png b/data/qr/FK-85D9AEDE.png new file mode 100644 index 0000000..18bc27f Binary files /dev/null and b/data/qr/FK-85D9AEDE.png differ diff --git a/data/qr/FK-88172ECB.png b/data/qr/FK-88172ECB.png new file mode 100644 index 0000000..62d67fd Binary files /dev/null and b/data/qr/FK-88172ECB.png differ diff --git a/data/qr/FK-8E764160.png b/data/qr/FK-8E764160.png new file mode 100644 index 0000000..5e60447 Binary files /dev/null and b/data/qr/FK-8E764160.png differ diff --git a/data/qr/FK-9408A2D3.png b/data/qr/FK-9408A2D3.png new file mode 100644 index 0000000..9aa54fb Binary files /dev/null and b/data/qr/FK-9408A2D3.png differ diff --git a/data/qr/FK-9B0EFDF1.png b/data/qr/FK-9B0EFDF1.png new file mode 100644 index 0000000..0cefd76 Binary files /dev/null and b/data/qr/FK-9B0EFDF1.png differ diff --git a/data/qr/FK-A2D5DC16.png b/data/qr/FK-A2D5DC16.png new file mode 100644 index 0000000..ff6785e Binary files /dev/null and b/data/qr/FK-A2D5DC16.png differ diff --git a/data/qr/FK-AAEBF5D8.png b/data/qr/FK-AAEBF5D8.png new file mode 100644 index 0000000..0151129 Binary files /dev/null and b/data/qr/FK-AAEBF5D8.png differ diff --git a/data/qr/FK-B3257FB0.png b/data/qr/FK-B3257FB0.png new file mode 100644 index 0000000..de8e669 Binary files /dev/null and b/data/qr/FK-B3257FB0.png differ diff --git a/data/qr/FK-B710F056.png b/data/qr/FK-B710F056.png new file mode 100644 index 0000000..e9fb226 Binary files /dev/null and b/data/qr/FK-B710F056.png differ diff --git a/data/qr/FK-BB7A5831.png b/data/qr/FK-BB7A5831.png new file mode 100644 index 0000000..00d475b Binary files /dev/null and b/data/qr/FK-BB7A5831.png differ diff --git a/data/qr/FK-CD6D26B3.png b/data/qr/FK-CD6D26B3.png new file mode 100644 index 0000000..94727da Binary files /dev/null and b/data/qr/FK-CD6D26B3.png differ diff --git a/data/qr/FK-D83AA5DA.png b/data/qr/FK-D83AA5DA.png new file mode 100644 index 0000000..1d31476 Binary files /dev/null and b/data/qr/FK-D83AA5DA.png differ diff --git a/data/qr/FK-E0B63FDA.png b/data/qr/FK-E0B63FDA.png new file mode 100644 index 0000000..22f8110 Binary files /dev/null and b/data/qr/FK-E0B63FDA.png differ diff --git a/data/qr/FK-E91F6472.png b/data/qr/FK-E91F6472.png new file mode 100644 index 0000000..8801618 Binary files /dev/null and b/data/qr/FK-E91F6472.png differ diff --git a/data/qr/FK-EDEBDD7F.png b/data/qr/FK-EDEBDD7F.png new file mode 100644 index 0000000..6a323db Binary files /dev/null and b/data/qr/FK-EDEBDD7F.png differ diff --git a/data/qr/FK-F026BA85.png b/data/qr/FK-F026BA85.png new file mode 100644 index 0000000..149cd0b Binary files /dev/null and b/data/qr/FK-F026BA85.png differ diff --git a/data/qr/FK-FA07C6BF.png b/data/qr/FK-FA07C6BF.png new file mode 100644 index 0000000..0404c41 Binary files /dev/null and b/data/qr/FK-FA07C6BF.png differ diff --git a/data/qr/FK-FF14070E.png b/data/qr/FK-FF14070E.png new file mode 100644 index 0000000..1628b4f Binary files /dev/null and b/data/qr/FK-FF14070E.png differ diff --git a/index.html b/index.html new file mode 100644 index 0000000..05b0734 --- /dev/null +++ b/index.html @@ -0,0 +1,59 @@ + + + + + +Fikakassan + + + +
+
+
Välkommen till Fikakassan
+ +
+ + + diff --git a/kiosk.sh b/kiosk.sh new file mode 100644 index 0000000..0d69678 --- /dev/null +++ b/kiosk.sh @@ -0,0 +1,2 @@ +#!/bin/sh +exec chromium --kiosk --start-fullscreen --disable-pinch http://127.0.0.1:8000 diff --git a/products.yaml b/products.yaml new file mode 100644 index 0000000..e1090e0 --- /dev/null +++ b/products.yaml @@ -0,0 +1,35 @@ +products: + - id: monster-energy + name: Monster Energy + price: 20 + image: products/monster-energy.jpg + + - id: monster-ultra + name: Monster Ultra + price: 20 + image: products/monster-ultra.jpg + + - id: coca-cola + name: Coca-Cola + price: 15 + image: products/coca-cola.jpg + + - id: coca-cola-zero + name: Coca-Cola Zero + price: 15 + image: products/coca-cola-zero.jpg + + - id: kexchoklad + name: Kexchoklad + price: 15 + image: products/kexchoklad.jpg + + - id: twix + name: Twix + price: 15 + image: products/twix.jpg + + - id: corny-large + name: Corny Large + price: 15 + image: products/corny-large.jpg diff --git a/products/coca-cola-zero.jpg b/products/coca-cola-zero.jpg new file mode 100644 index 0000000..af7a28e Binary files /dev/null and b/products/coca-cola-zero.jpg differ diff --git a/products/coca-cola-zero.png b/products/coca-cola-zero.png new file mode 100644 index 0000000..29fdf06 Binary files /dev/null and b/products/coca-cola-zero.png differ diff --git a/products/coca-cola.jpg b/products/coca-cola.jpg new file mode 100644 index 0000000..4e1a1b4 Binary files /dev/null and b/products/coca-cola.jpg differ diff --git a/products/coca-cola.png b/products/coca-cola.png new file mode 100644 index 0000000..c62035c Binary files /dev/null and b/products/coca-cola.png differ diff --git a/products/corny-large.jpg b/products/corny-large.jpg new file mode 100644 index 0000000..c2e8652 Binary files /dev/null and b/products/corny-large.jpg differ diff --git a/products/corny-large.png b/products/corny-large.png new file mode 100644 index 0000000..e08e729 Binary files /dev/null and b/products/corny-large.png differ diff --git a/products/kexchoklad.jpg b/products/kexchoklad.jpg new file mode 100644 index 0000000..b95f543 Binary files /dev/null and b/products/kexchoklad.jpg differ diff --git a/products/kexchoklad.png b/products/kexchoklad.png new file mode 100644 index 0000000..a6f237e Binary files /dev/null and b/products/kexchoklad.png differ diff --git a/products/monster-energy.jpg b/products/monster-energy.jpg new file mode 100644 index 0000000..e78e4d4 Binary files /dev/null and b/products/monster-energy.jpg differ diff --git a/products/monster-energy.png b/products/monster-energy.png new file mode 100644 index 0000000..ff28ad9 Binary files /dev/null and b/products/monster-energy.png differ diff --git a/products/monster-ultra.jpg b/products/monster-ultra.jpg new file mode 100644 index 0000000..fe2cfca Binary files /dev/null and b/products/monster-ultra.jpg differ diff --git a/products/monster-ultra.png b/products/monster-ultra.png new file mode 100644 index 0000000..01f82c9 Binary files /dev/null and b/products/monster-ultra.png differ diff --git a/products/twix.jpg b/products/twix.jpg new file mode 100644 index 0000000..3f1606d Binary files /dev/null and b/products/twix.jpg differ diff --git a/products/twix.png b/products/twix.png new file mode 100644 index 0000000..2a389bd Binary files /dev/null and b/products/twix.png differ diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..6d74cc1 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +fastapi>=0.115,<1 +uvicorn[standard]>=0.30,<1 +PyYAML>=6,<7 +qrcode[pil]>=8,<9 diff --git a/run.sh b/run.sh new file mode 100755 index 0000000..3adaab9 --- /dev/null +++ b/run.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")" +exec .venv/bin/uvicorn app.main:app --host 0.0.0.0 --port 8000 diff --git a/setup-fikakassa-kioskmode.sh b/setup-fikakassa-kioskmode.sh new file mode 100755 index 0000000..cc472f4 --- /dev/null +++ b/setup-fikakassa-kioskmode.sh @@ -0,0 +1,392 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +# Fikakassan kiosk setup +# Debian 13 / X11 / Openbox / Chromium / NetworkManager +# +# Run as root: +# sudo ./setup-kiosk.sh +# +# The script: +# - installs the kiosk stack and Python runtime +# - creates a non-admin kiosk user +# - installs the Fikakassan app from the directory containing this script +# - starts FastAPI automatically at boot +# - configures Wi-Fi through NetworkManager +# - autologins the kiosk user +# - starts Chromium in true kiosk mode +# - disables suspend/blanking and common escape routes +# - limits outbound traffic so the kiosk does not use the phone's +# mobile data for normal Internet traffic; DNS/NTP are still allowed +# +# Before running, put this script in the root of the Fikakassan project. + +KIOSK_USER="${KIOSK_USER:-joakim}" +APP_DIR="${APP_DIR:-/opt/fikakassa}" +KIOSK_URL="${KIOSK_URL:-http://127.0.0.1:8000/}" + +WIFI_CONNECTION="${WIFI_CONNECTION:-Fikakassan-WiFi}" +WIFI_SSID="${WIFI_SSID:-}" +WIFI_PASSWORD="${WIFI_PASSWORD:-}" + +# Set to 0 if you explicitly want ordinary Internet access from the kiosk. +LOCK_DOWN_INTERNET="${LOCK_DOWN_INTERNET:-1}" + +log() { printf '\n\033[1;32m==> %s\033[0m\n' "$*"; } +warn() { printf '\n\033[1;33mWARNING: %s\033[0m\n' "$*" >&2; } +die() { printf '\n\033[1;31mERROR: %s\033[0m\n' "$*" >&2; exit 1; } + +[[ $EUID -eq 0 ]] || die "Kör skriptet som root eller med sudo." +command -v apt-get >/dev/null || die "Det här skriptet är avsett för Debian/derivat med apt." + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" + +[[ -f "$SCRIPT_DIR/app/main.py" ]] || die "app/main.py saknas. Kör skriptet från Fikakassans projektkatalog." +[[ -f "$SCRIPT_DIR/requirements.txt" ]] || die "requirements.txt saknas." + +if [[ -z "$WIFI_SSID" ]]; then + read -r -p "Wi-Fi SSID för Samsung A50-hotspot: " WIFI_SSID +fi +if [[ -z "$WIFI_PASSWORD" ]]; then + read -r -s -p "Wi-Fi-lösenord: " WIFI_PASSWORD + echo +fi + +log "Installerar systempaket" + +export DEBIAN_FRONTEND=noninteractive +apt-get update +apt-get install -y \ + network-manager \ + openssh-server \ + python3 \ + python3-venv \ + python3-pip \ + xorg \ + xinit \ + openbox \ + chromium \ + unclutter \ + x11-xserver-utils \ + fonts-dejavu \ + fonts-liberation \ + nftables \ + rsync + +systemctl enable NetworkManager.service +systemctl enable ssh.service +systemctl enable nftables.service + +log "Skapar kiosk-användare" + +if ! id "$KIOSK_USER" >/dev/null 2>&1; then + useradd --create-home --shell /bin/bash --user-group "$KIOSK_USER" +fi + +# Use the existing Debian user for the kiosk session. Existing sudo/group +# memberships are preserved. +usermod -s /bin/bash "$KIOSK_USER" + +log "Installerar Fikakassan i $APP_DIR" + +install -d -o root -g root "$APP_DIR" +rsync -a --delete \ + --exclude='.venv/' \ + --exclude='__pycache__/' \ + --exclude='*.pyc' \ + "$SCRIPT_DIR/" "$APP_DIR/" + +# The kiosk user needs to read the application, but not modify it. +chown -R root:root "$APP_DIR" +find "$APP_DIR" -type d -exec chmod 755 {} + +find "$APP_DIR" -type f -exec chmod 644 {} + + +log "Skapar Python virtualenv" + +python3 -m venv "$APP_DIR/.venv" +"$APP_DIR/.venv/bin/pip" install --disable-pip-version-check --no-cache-dir -r "$APP_DIR/requirements.txt" + +log "Skapar systemd-tjänst för Fikakassan" + +cat > /etc/systemd/system/fikakassa.service </dev/null 2>&1 || true + +nmcli radio wifi on +nmcli device wifi connect "$WIFI_SSID" \ + password "$WIFI_PASSWORD" \ + name "$WIFI_CONNECTION" + +nmcli connection modify "$WIFI_CONNECTION" \ + connection.autoconnect yes \ + connection.autoconnect-retries 0 \ + connection.mdns 0 \ + ipv4.never-default yes \ + ipv4.route-metric 600 \ + ipv6.method disabled \ + ipv6.never-default yes + +# Give the hotspot connection high priority if several Wi-Fi networks are known. +nmcli connection modify "$WIFI_CONNECTION" connection.autoconnect-priority 100 + +nmcli connection up "$WIFI_CONNECTION" || true + +log "Konfigurerar lokal brandvägg" + +if [[ "$LOCK_DOWN_INTERNET" == "1" ]]; then + # The kiosk needs: + # - local LAN traffic to the A50/kiosk + # - DNS for NTP hostname resolution + # - UDP/123 for NTP + # - DHCP + # - established traffic + # + # It must NOT be able to browse the Internet through the phone. + # A wired Ethernet connection (interface names en*) is intentionally + # exempted from the outbound lockdown, so plugging in a cable gives + # normal Internet access for updates and development while Wi-Fi remains + # available for the A50/local kiosk network. + # + # All RFC1918 traffic is permitted so the Android bridge can talk to the + # kiosk even if Samsung changes the hotspot subnet. + + cat > /etc/nftables.conf <<'EOF' +#!/usr/sbin/nft -f + +flush ruleset + +table inet kiosk_filter { + chain input { + type filter hook input priority filter; policy drop; + + iifname "lo" accept + ct state established,related accept + + # ICMP is useful for diagnostics and does not provide Internet browsing. + ip protocol icmp accept + + # DHCP client traffic. + udp sport 67 udp dport 68 accept + + # SSH and Fikakassan are available from the local network only. + ip saddr 10.0.0.0/8 tcp dport 22 accept + ip saddr 172.16.0.0/12 tcp dport 22 accept + ip saddr 192.168.0.0/16 tcp dport 22 accept + + ip saddr 10.0.0.0/8 tcp dport 8000 accept + ip saddr 172.16.0.0/12 tcp dport 8000 accept + ip saddr 192.168.0.0/16 tcp dport 8000 accept + } + + chain forward { + type filter hook forward priority filter; policy drop; + } + + chain output { + type filter hook output priority filter; policy drop; + + oifname "lo" accept + ct state established,related accept + + # DHCP client. + udp sport 68 udp dport 67 accept + + # A wired Ethernet connection is the maintenance/Internet path. + # Allow normal outbound traffic there; Wi-Fi remains locked to local + # networks plus DNS/NTP. + oifname "en*" accept + + # DNS and NTP are explicitly allowed. + udp dport 53 accept + tcp dport 53 accept + udp dport 123 accept + + # Permit local/private networks only. + ip daddr 10.0.0.0/8 accept + ip daddr 172.16.0.0/12 accept + ip daddr 192.168.0.0/16 accept + + # ICMP for local diagnostics. + ip daddr 10.0.0.0/8 ip protocol icmp accept + ip daddr 172.16.0.0/12 ip protocol icmp accept + ip daddr 192.168.0.0/16 ip protocol icmp accept + } +} +EOF + + nft -f /etc/nftables.conf +else + warn "Internet-lockdown är avstängt (LOCK_DOWN_INTERNET=0)." +fi + +log "Stänger av automatisk sleep/blanking" + +mkdir -p /etc/systemd/logind.conf.d +cat > /etc/systemd/logind.conf.d/90-fikakassa.conf <<'EOF' +[Login] +HandlePowerKey=ignore +HandleSuspendKey=ignore +HandleHibernateKey=ignore +HandleLidSwitch=ignore +HandleLidSwitchExternalPower=ignore +IdleAction=ignore +EOF + +systemctl restart systemd-logind.service || true + +log "Konfigurerar X11/Openbox" + +KIOSK_HOME="/home/$KIOSK_USER" +install -d -o "$KIOSK_USER" -g "$KIOSK_USER" \ + "$KIOSK_HOME/.config/openbox" \ + "$KIOSK_HOME/.config" + +cat > "$KIOSK_HOME/.xinitrc" <<'EOF' +#!/bin/sh +exec openbox-session +EOF +chown "$KIOSK_USER:$KIOSK_USER" "$KIOSK_HOME/.xinitrc" +chmod 755 "$KIOSK_HOME/.xinitrc" + +cat > "$KIOSK_HOME/.config/openbox/autostart" < /etc/systemd/system/getty@tty1.service.d/override.conf < "$KIOSK_HOME/.bash_profile" <<'EOF' +# Start graphical kiosk session automatically. +if [ -z "$DISPLAY" ] && [ "$(tty 2>/dev/null)" = "/dev/tty1" ]; then + exec startx +fi +EOF +chown "$KIOSK_USER:$KIOSK_USER" "$KIOSK_HOME/.bash_profile" +chmod 644 "$KIOSK_HOME/.bash_profile" + +systemctl daemon-reload +systemctl enable getty@tty1.service +systemctl restart getty@tty1.service || true + +log "Sätter systemtid/NTP" + +# systemd-timesyncd is enough; no Internet browsing is required. +apt-get install -y systemd-timesyncd +systemctl enable --now systemd-timesyncd.service || true + +log "Aktiverar automatisk omstart av Chromium om X-sessionen kraschar" + +# Xorg/startx returns to tty1 if Chromium/Openbox dies. systemd getty will +# respawn the session. This keeps the kiosk self-healing after crashes. +systemctl restart getty@tty1.service || true + +cat < Xorg -> Openbox -> Chromium + +Internet-lockdown: + $([[ "$LOCK_DOWN_INTERNET" == "1" ]] && echo "AKTIV: endast lokalt nät + DNS/NTP" || echo "AVSTÄNGD") + +Starta om maskinen nu: + reboot + +OBS: + "Power on efter strömavbrott" är en BIOS/UEFI-inställning och kan inte + garanteras av Linux. På X1 Yoga behöver "Power on with AC attach" / + motsvarande BIOS-inställning aktiveras om maskinen ska starta automatiskt + efter ett strömavbrott. + +EOF