first commit
45
README.md
Normal file
@@ -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://<kassans-adress>: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.
|
||||||
16
README.txt
Normal file
@@ -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.
|
||||||
0
app/__init__.py
Normal file
391
app/main.py
Normal file
@@ -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'<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"]),
|
||||||
|
}
|
||||||
|
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"}
|
||||||
6
app/static/css/style.css
Normal file
@@ -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)}}
|
||||||
220
app/static/index.html
Normal file
@@ -0,0 +1,220 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="sv">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||||
|
<title>Fikakassan</title>
|
||||||
|
<style>
|
||||||
|
:root{--orange:#ff6600;--bg:#f2f3f5;--card:#fff;--text:#20242a;--muted:#68707a}
|
||||||
|
*{box-sizing:border-box}
|
||||||
|
html,body{margin:0;width:100%;height:100%;overflow:hidden;font-family:system-ui,-apple-system,"Segoe UI",sans-serif;background:var(--bg);color:var(--text)}
|
||||||
|
button{font:inherit}
|
||||||
|
#app{width:100vw;height:100vh;padding:12px}
|
||||||
|
#grid{width:100%;height:100%;display:grid;gap:12px;grid-template-columns:repeat(var(--cols),minmax(0,1fr));grid-template-rows:repeat(var(--rows),minmax(0,1fr))}
|
||||||
|
.card{position:relative;min-width:0;min-height:0;background:var(--card);border-radius:20px;box-shadow:0 2px 12px #00000012;overflow:hidden;padding:14px 16px 10px;display:flex;flex-direction:column}
|
||||||
|
.price{position:absolute;right:14px;top:14px;background:var(--orange);color:#fff;font-size:clamp(1.25rem,2.7vw,2.2rem);font-weight:850;padding:.16em .45em;border-radius:999px;box-shadow:0 6px 16px #ff660033;z-index:2}
|
||||||
|
.image-wrap{flex:1;min-height:0;display:flex;align-items:center;justify-content:center;padding:4px 20px 0}
|
||||||
|
.image-wrap img{max-width:100%;max-height:100%;object-fit:contain;display:block}
|
||||||
|
.name{font-size:clamp(1rem,1.7vw,1.5rem);font-weight:700;margin:4px 0 8px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||||
|
.qty{height:50px;align-self:center;display:flex;align-items:center;justify-content:center;gap:20px;padding:4px 13px;border-radius:999px;background:#eef0f2;font-size:1.35rem;font-weight:800;min-width:148px;transition:background .12s,color .12s}
|
||||||
|
.qty.active{background:var(--orange);color:#fff}
|
||||||
|
.qty button{border:0;background:transparent;color:inherit;font:inherit;width:38px;height:38px;border-radius:50%;cursor:pointer;touch-action:manipulation}
|
||||||
|
.qty button:active{transform:scale(.9)}
|
||||||
|
.total{justify-content:center;align-items:center;text-align:center;padding:24px}
|
||||||
|
.total-label{font-size:clamp(1.4rem,2.5vw,2.2rem);font-weight:700;color:var(--muted)}
|
||||||
|
.total-value{font-size:clamp(2.8rem,6vw,5rem);font-weight:850;margin:4px 0 22px}
|
||||||
|
.pay{border:0;background:var(--orange);color:#fff;font-weight:850;font-size:clamp(1rem,1.8vw,1.4rem);border-radius:16px;padding:18px 28px;width:100%;cursor:pointer}
|
||||||
|
.pay:disabled{opacity:.35;cursor:not-allowed}
|
||||||
|
.clear{margin-top:14px;border:0;background:transparent;text-decoration:underline;color:var(--muted);font-size:1rem;cursor:pointer}
|
||||||
|
#screensaver{position:fixed;inset:0;background:#f7f7f5;z-index:20;display:none;overflow:hidden;cursor:pointer}
|
||||||
|
.ss-title{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);font-size:clamp(2rem,5vw,5rem);font-weight:850;color:#222;white-space:nowrap;z-index:2;animation:titleDrift 7s ease-in-out infinite alternate}
|
||||||
|
.ss-title span{color:var(--orange)}
|
||||||
|
.ss-return{position:absolute;left:50%;bottom:6%;transform:translateX(-50%);z-index:3;border:0;border-radius:999px;background:var(--orange);color:#fff;font-weight:800;font-size:clamp(1rem,1.8vw,1.4rem);padding:14px 28px;box-shadow:0 8px 24px #ff660044;animation:returnPulse 2.4s ease-in-out infinite}
|
||||||
|
@keyframes titleDrift{from{transform:translate(calc(-50% - 45px),calc(-50% - 18px)) rotate(-1deg)}to{transform:translate(calc(-50% + 45px),calc(-50% + 18px)) rotate(1deg)}}
|
||||||
|
@keyframes returnPulse{0%,100%{transform:translateX(-50%) scale(1)}50%{transform:translateX(-50%) scale(1.04)}}
|
||||||
|
.float{position:absolute;width:clamp(100px,12vw,190px);height:clamp(100px,12vw,190px);object-fit:contain;filter:drop-shadow(0 12px 18px #00000015);animation:drift 18s ease-in-out infinite alternate}
|
||||||
|
.f1{left:8%;top:14%;animation-delay:-2s}.f2{right:9%;top:18%;animation-delay:-8s}.f3{left:14%;bottom:10%;animation-delay:-5s}.f4{right:14%;bottom:12%;animation-delay:-11s}.f5{left:43%;top:8%;width:clamp(80px,9vw,140px);animation-delay:-14s}.f6{right:38%;bottom:7%;width:clamp(80px,9vw,140px);animation-delay:-17s}
|
||||||
|
@keyframes drift{from{transform:translate3d(-12px,-8px,0) rotate(-3deg)}to{transform:translate3d(18px,14px,0) rotate(4deg)}}
|
||||||
|
#camera{position:fixed;width:1px;height:1px;opacity:0;pointer-events:none;left:-10px;top:-10px}#motionCanvas{display:none}
|
||||||
|
#payment{position:fixed;inset:0;background:#fff;z-index:30;display:none;align-items:center;justify-content:center;text-align:center;padding:30px}
|
||||||
|
.payment-box{width:min(700px,92vw);padding:35px;border-radius:28px;box-shadow:0 10px 40px #0002;background:#fff}
|
||||||
|
.payment-title{font-size:clamp(1.8rem,4vw,3rem);font-weight:850}.payment-total{font-size:clamp(3rem,8vw,6rem);font-weight:900;color:var(--orange);margin:10px 0 18px}.payment-text{font-size:clamp(1.1rem,2vw,1.5rem);color:var(--muted)}
|
||||||
|
@media(max-width:900px){#app{padding:8px}.card{border-radius:14px;padding:10px}.qty{height:44px;min-width:130px;gap:12px}.price{right:10px;top:10px}.name{margin-bottom:4px}}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"><main id="grid"></main></div>
|
||||||
|
<div id="screensaver" aria-label="Välkomstskärm">
|
||||||
|
<div class="ss-title">Välkommen till <span>Fikakassan</span></div>
|
||||||
|
<button class="ss-return" type="button">Tillbaka till försäljning</button>
|
||||||
|
<img class="float f1" data-product="monster-energy"><img class="float f2" data-product="coca-cola"><img class="float f3" data-product="twix"><img class="float f4" data-product="kexchoklad"><img class="float f5" data-product="monster-ultra"><img class="float f6" data-product="corny-large">
|
||||||
|
</div>
|
||||||
|
<div id="payment"><div class="payment-box"><div class="payment-title">Inväntar betalning</div><div class="payment-total" id="paymentTotal">0 kr</div><div class="payment-text" id="paymentText">Genomför betalningen med Swish.</div></div></div>
|
||||||
|
<video id="camera" autoplay muted playsinline></video><canvas id="motionCanvas" width="160" height="120"></canvas>
|
||||||
|
<script>
|
||||||
|
const grid=document.querySelector('#grid');
|
||||||
|
const saver=document.querySelector('#screensaver');
|
||||||
|
const payment=document.querySelector('#payment');
|
||||||
|
const paymentTotal=document.querySelector('#paymentTotal');
|
||||||
|
const paymentText=document.querySelector('#paymentText');
|
||||||
|
let products=[];
|
||||||
|
let qty={};
|
||||||
|
let idleTimer;
|
||||||
|
let saverOn=false;
|
||||||
|
let orderPolling=null;
|
||||||
|
|
||||||
|
function layout(){
|
||||||
|
const slots=products.length+1;
|
||||||
|
const ratio=1.78;
|
||||||
|
let best={cols:1,rows:slots,score:Infinity};
|
||||||
|
for(let cols=1;cols<=slots;cols++){
|
||||||
|
const rows=Math.ceil(slots/cols);
|
||||||
|
const score=Math.abs((cols/rows)-ratio)+(rows*cols-slots)*0.025;
|
||||||
|
if(score<best.score) best={cols,rows,score};
|
||||||
|
}
|
||||||
|
grid.style.setProperty('--cols',best.cols);
|
||||||
|
grid.style.setProperty('--rows',best.rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
function total(){return products.reduce((sum,p)=>sum+(qty[p.id]||0)*Number(p.price),0)}
|
||||||
|
|
||||||
|
function render(){
|
||||||
|
layout();
|
||||||
|
grid.innerHTML='';
|
||||||
|
for(const p of products){
|
||||||
|
const n=qty[p.id]||0;
|
||||||
|
const card=document.createElement('article');
|
||||||
|
card.className='card';
|
||||||
|
card.innerHTML=`<div class="price">${p.price} kr</div><div class="image-wrap"><img src="/static/${p.image}" alt="${p.name}"></div><div class="name">${p.name}</div><div class="qty ${n?'active':''}"><button data-act="minus" aria-label="Minska">−</button><span>${n}</span><button data-act="plus" aria-label="Öka">+</button></div>`;
|
||||||
|
card.querySelector('[data-act=minus]').onclick=()=>change(p.id,-1);
|
||||||
|
card.querySelector('[data-act=plus]').onclick=()=>change(p.id,1);
|
||||||
|
grid.appendChild(card);
|
||||||
|
}
|
||||||
|
const sum=total();
|
||||||
|
const t=document.createElement('article');
|
||||||
|
t.className='card total';
|
||||||
|
t.innerHTML=`<div class="total-label">Totalt</div><div class="total-value">${sum} kr</div><button class="pay" ${sum?'':'disabled'}>BETALA MED SWISH</button><button class="clear">Töm köp</button>`;
|
||||||
|
t.querySelector('.clear').onclick=clearCart;
|
||||||
|
t.querySelector('.pay').onclick=createOrder;
|
||||||
|
grid.appendChild(t);
|
||||||
|
}
|
||||||
|
|
||||||
|
function change(id,d){qty[id]=Math.max(0,(qty[id]||0)+d);render();wake()}
|
||||||
|
function clearCart(){for(const p of products)qty[p.id]=0;render();wake()}
|
||||||
|
function wake(){
|
||||||
|
saverOn=false;saver.style.display='none';
|
||||||
|
clearTimeout(idleTimer);
|
||||||
|
idleTimer=setTimeout(showSaver,20000);
|
||||||
|
}
|
||||||
|
function showSaver(){
|
||||||
|
if(payment.style.display==='flex'||total()!==0)return;
|
||||||
|
saverOn=true;saver.style.display='block';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadProducts(){
|
||||||
|
const r=await fetch('/api/products',{cache:'no-store'});
|
||||||
|
if(!r.ok)throw new Error('Kunde inte läsa produktregistret');
|
||||||
|
const data=await r.json();
|
||||||
|
products=data.products||[];
|
||||||
|
qty=Object.fromEntries(products.map(p=>[p.id,0]));
|
||||||
|
for(const img of document.querySelectorAll('[data-product]')){
|
||||||
|
const p=products.find(x=>x.id===img.dataset.product);
|
||||||
|
if(p)img.src='/static/'+p.image;
|
||||||
|
}
|
||||||
|
render();
|
||||||
|
wake();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createOrder(){
|
||||||
|
const items=products.filter(p=>(qty[p.id]||0)>0).map(p=>({product_id:p.id,quantity:qty[p.id]}));
|
||||||
|
if(!items.length)return;
|
||||||
|
const r=await fetch('/api/orders',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({items})});
|
||||||
|
if(!r.ok){alert('Kunde inte skapa köpet.');return}
|
||||||
|
const order=await r.json();
|
||||||
|
paymentTotal.textContent=order.total+' kr';
|
||||||
|
paymentText.textContent='Genomför betalningen med Swish. Vi väntar på bekräftelse.';
|
||||||
|
payment.style.display='flex';
|
||||||
|
clearTimeout(idleTimer);
|
||||||
|
pollOrder(order.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
function pollOrder(id){
|
||||||
|
clearInterval(orderPolling);
|
||||||
|
orderPolling=setInterval(async()=>{
|
||||||
|
try{
|
||||||
|
const r=await fetch('/api/orders/'+encodeURIComponent(id),{cache:'no-store'});
|
||||||
|
if(!r.ok)return;
|
||||||
|
const order=await r.json();
|
||||||
|
if(order.status==='paid'){
|
||||||
|
clearInterval(orderPolling);
|
||||||
|
paymentText.textContent='Betalningen är genomförd. Tack!';
|
||||||
|
setTimeout(()=>{payment.style.display='none';clearCart()},1800);
|
||||||
|
}
|
||||||
|
}catch(e){console.warn(e)}
|
||||||
|
},1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
['pointerdown','touchstart','keydown'].forEach(e=>document.addEventListener(e,wake,{passive:true}));
|
||||||
|
saver.addEventListener('pointerdown',wake);
|
||||||
|
|
||||||
|
const video=document.querySelector('#camera'),canvas=document.querySelector('#motionCanvas'),ctx=canvas.getContext('2d',{willReadFrequently:true});
|
||||||
|
let previous=null,lastMotion=0,motionFrames=0,baselineFrames=0;
|
||||||
|
|
||||||
|
function frameBrightness(data){
|
||||||
|
let total=0;
|
||||||
|
for(let i=0;i<data.length;i+=12) total += data[i]*0.299 + data[i+1]*0.587 + data[i+2]*0.114;
|
||||||
|
return total/(data.length/12);
|
||||||
|
}
|
||||||
|
|
||||||
|
function motionLoop(){
|
||||||
|
if(video.readyState>=2){
|
||||||
|
ctx.drawImage(video,0,0,160,120);
|
||||||
|
const data=ctx.getImageData(0,0,160,120).data;
|
||||||
|
if(previous){
|
||||||
|
let changed=0, sum=0;
|
||||||
|
// Compare small blocks rather than individual pixels to reduce camera noise.
|
||||||
|
for(let y=2;y<118;y+=4){
|
||||||
|
for(let x=2;x<158;x+=4){
|
||||||
|
const i=(y*160+x)*4;
|
||||||
|
const old=previous[i]*0.299+previous[i+1]*0.587+previous[i+2]*0.114;
|
||||||
|
const cur=data[i]*0.299+data[i+1]*0.587+data[i+2]*0.114;
|
||||||
|
const d=Math.abs(cur-old);
|
||||||
|
sum+=d;
|
||||||
|
if(d>22) changed++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const avg=sum/((156/4)*(116/4));
|
||||||
|
if(saverOn){
|
||||||
|
// A noticeable movement over two consecutive frames wakes the kiosk.
|
||||||
|
if(changed>70 && avg>3.0) motionFrames++; else motionFrames=0;
|
||||||
|
if(motionFrames>=2 && Date.now()-lastMotion>800){
|
||||||
|
lastMotion=Date.now(); motionFrames=0; wake();
|
||||||
|
}
|
||||||
|
}else{
|
||||||
|
motionFrames=0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
previous=data;
|
||||||
|
baselineFrames++;
|
||||||
|
}
|
||||||
|
requestAnimationFrame(motionLoop);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startCamera(){
|
||||||
|
try{
|
||||||
|
// Do not force a camera direction: this works with more USB/webcam drivers.
|
||||||
|
const stream=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:320},height:{ideal:240}},audio:false});
|
||||||
|
video.srcObject=stream;
|
||||||
|
await video.play().catch(()=>{});
|
||||||
|
requestAnimationFrame(motionLoop);
|
||||||
|
}catch(e){console.warn('Kameran för närvarodetektering kunde inte startas:',e)}
|
||||||
|
}
|
||||||
|
|
||||||
|
saver.addEventListener('pointerdown',wake);
|
||||||
|
document.querySelector('.ss-return').addEventListener('click',wake);
|
||||||
|
loadProducts().catch(err=>{grid.innerHTML='<div style="padding:40px;font-size:2rem">Kunde inte läsa produktregistret.</div>';console.error(err)});
|
||||||
|
if(navigator.mediaDevices?.getUserMedia)startCamera();
|
||||||
|
window.addEventListener('resize',layout);
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
145
app/static/js/app.js
Normal file
@@ -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 `<div class="combo-images">${images.map((img,i)=>`<canvas class="product-canvas combo-canvas" data-src="/static/products/${img}" data-rotation="${rotations[i]||0}" data-x-offset="${Number(xOffsets[i])||0}" aria-hidden="true"></canvas>`).join('')}</div>`;
|
||||||
|
}
|
||||||
|
return `<canvas class="product-canvas" data-src="/static/products/${images[0]}" data-rotation="${rotations[0]||0}" aria-label="${p.name}"></canvas>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;x<w;x++){push(x,0);push(x,h-1)}
|
||||||
|
for(let y=1;y<h-1;y++){push(0,y);push(w-1,y)}
|
||||||
|
while(head<tail){
|
||||||
|
const n=queue[head++], x=n%w, y=(n-x)/w, i=n*4;
|
||||||
|
if(!nearWhite(i))continue;
|
||||||
|
px[i+3]=0;
|
||||||
|
if(x>0)push(x-1,y); if(x<w-1)push(x+1,y); if(y>0)push(x,y-1); if(y<h-1)push(x,y+1);
|
||||||
|
}
|
||||||
|
ctx.putImageData(data,0,0);
|
||||||
|
let minX=w,minY=h,maxX=-1,maxY=-1;
|
||||||
|
for(let y=0;y<h;y++)for(let x=0;x<w;x++){if(px[(y*w+x)*4+3]>8){if(x<minX)minX=x;if(x>maxX)maxX=x;if(y<minY)minY=y;if(y>maxY)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 `<div class="price offer-price"><span class="offer-label">${p.offer_label||'ERBJUDANDE'}</span><span class="offer-value">${money(p.price)}</span></div>`;
|
||||||
|
}
|
||||||
|
return `<div class="price">${money(p.price)}</div>`;
|
||||||
|
}
|
||||||
|
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)}<div class="product-image-wrap">${productImages(p)}</div><div class="product-name">${p.name}</div><div class="qty ${q>0?'selected':''}"><button class="minus">−</button><span class="qty-value">${q}</span><button class="plus">+</button></div>`;
|
||||||
|
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=`<div class="total-label">Totalt</div><div class="total-value">${money(amount)}</div><button class="pay-button" ${amount===0?'disabled':''}>BETALA MED SWISH</button><button class="clear-button">Töm köp</button>`;
|
||||||
|
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=>`<div class="summary-row"><strong>${i.quantity} ×</strong><span>${i.name}</span></div>`).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()});
|
||||||
BIN
app/static/products/coca-cola-zero.jpg
Normal file
|
After Width: | Height: | Size: 138 KiB |
BIN
app/static/products/coca-cola.jpg
Normal file
|
After Width: | Height: | Size: 132 KiB |
BIN
app/static/products/combo/coca-cola-cropped.jpg
Normal file
|
After Width: | Height: | Size: 163 KiB |
BIN
app/static/products/combo/corny-large-cropped.jpg
Normal file
|
After Width: | Height: | Size: 132 KiB |
BIN
app/static/products/combo/monster-ultra-cropped.jpg
Normal file
|
After Width: | Height: | Size: 185 KiB |
BIN
app/static/products/combo/twix-cropped.jpg
Normal file
|
After Width: | Height: | Size: 142 KiB |
BIN
app/static/products/corny-large.jpg
Normal file
|
After Width: | Height: | Size: 108 KiB |
BIN
app/static/products/kexchoklad.jpg
Normal file
|
After Width: | Height: | Size: 245 KiB |
BIN
app/static/products/monster-energy.jpg
Normal file
|
After Width: | Height: | Size: 101 KiB |
BIN
app/static/products/monster-ultra.jpg
Normal file
|
After Width: | Height: | Size: 148 KiB |
BIN
app/static/products/twix.jpg
Normal file
|
After Width: | Height: | Size: 159 KiB |
BIN
app/static/swish-logo.png
Normal file
|
After Width: | Height: | Size: 4.3 KiB |
BIN
app/static/swish-poster-template.png
Normal file
|
After Width: | Height: | Size: 18 KiB |
48
app/templates/index.html
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="sv">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, viewport-fit=cover">
|
||||||
|
<title>Fikakassan</title>
|
||||||
|
<link rel="stylesheet" href="/static/css/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main id="shopView" class="shop-view">
|
||||||
|
<section id="productGrid" class="product-grid"></section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<section id="paymentView" class="payment-view hidden">
|
||||||
|
<div class="payment-content">
|
||||||
|
<div class="payment-summary-card">
|
||||||
|
<div class="payment-heading">Ditt köp</div>
|
||||||
|
<div id="summary" class="summary"></div>
|
||||||
|
<div class="summary-total-label">Att betala</div>
|
||||||
|
<div class="payment-total" id="paymentTotal">0 kr</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="poster-area">
|
||||||
|
<div class="swish-poster">
|
||||||
|
<img id="qr" class="poster-qr" alt="Swish QR-kod">
|
||||||
|
<div id="posterNumber" class="poster-number">073-441 37 87</div>
|
||||||
|
<div id="posterName" class="poster-name">Joakim Svensson</div>
|
||||||
|
<div class="poster-amount" id="posterAmount">Betala 15 kr</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="timeout-bar-wrap">
|
||||||
|
<button id="cancelPurchase" class="cancel-purchase">Avbryt köp</button>
|
||||||
|
<div id="timeoutBar" class="timeout-bar"></div>
|
||||||
|
<button id="nextCustomer" class="next-customer">Nästa kund</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="thanksView" class="thanks-view hidden">
|
||||||
|
<div class="thanks-icon">✓</div>
|
||||||
|
<h1>Tack för din betalning!</h1>
|
||||||
|
<p>Välkommen åter.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<script src="/static/js/app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
41
config.yaml
Normal file
@@ -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
|
||||||
41
config4x2.yaml
Normal file
@@ -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
|
||||||
79
config5x2.yaml
Normal file
@@ -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
|
||||||
BIN
data/qr/FK-0306AB64.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
data/qr/FK-0B1395B1.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-0EF4F0E0.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-15FA20B6.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
data/qr/FK-174AD3DD.png
Normal file
|
After Width: | Height: | Size: 1.4 KiB |
BIN
data/qr/FK-1ED734E1.png
Normal file
|
After Width: | Height: | Size: 1.5 KiB |
BIN
data/qr/FK-1F52E29C.png
Normal file
|
After Width: | Height: | Size: 1.4 KiB |
BIN
data/qr/FK-24280D4D.png
Normal file
|
After Width: | Height: | Size: 1.4 KiB |
BIN
data/qr/FK-3134F4D4.png
Normal file
|
After Width: | Height: | Size: 1.4 KiB |
BIN
data/qr/FK-3356A3A6.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-37BF74C0.png
Normal file
|
After Width: | Height: | Size: 1.4 KiB |
BIN
data/qr/FK-3D394FB2.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-40F60424.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-5AE78EBB.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-5F8D3164.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-6CB4F03E.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-726EC95C.png
Normal file
|
After Width: | Height: | Size: 1.4 KiB |
BIN
data/qr/FK-7C967EDA.png
Normal file
|
After Width: | Height: | Size: 1.4 KiB |
BIN
data/qr/FK-7CA3F695.png
Normal file
|
After Width: | Height: | Size: 1.5 KiB |
BIN
data/qr/FK-809D12B8.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-85D9AEDE.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-88172ECB.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-8E764160.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-9408A2D3.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-9B0EFDF1.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-A2D5DC16.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-AAEBF5D8.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-B3257FB0.png
Normal file
|
After Width: | Height: | Size: 1.4 KiB |
BIN
data/qr/FK-B710F056.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-BB7A5831.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-CD6D26B3.png
Normal file
|
After Width: | Height: | Size: 1.4 KiB |
BIN
data/qr/FK-D83AA5DA.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
data/qr/FK-E0B63FDA.png
Normal file
|
After Width: | Height: | Size: 1.4 KiB |
BIN
data/qr/FK-E91F6472.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-EDEBDD7F.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-F026BA85.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
data/qr/FK-FA07C6BF.png
Normal file
|
After Width: | Height: | Size: 1.4 KiB |
BIN
data/qr/FK-FF14070E.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
59
index.html
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="sv">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||||
|
<title>Fikakassan</title>
|
||||||
|
<style>
|
||||||
|
:root{--orange:#ff6600;--bg:#f3f4f6;--card:#fff;--text:#20242a;--muted:#6b7280}
|
||||||
|
*{box-sizing:border-box}html,body{margin:0;width:100%;height:100%;overflow:hidden;font-family:system-ui,-apple-system,"Segoe UI",sans-serif;background:var(--bg);color:var(--text)}
|
||||||
|
#app{width:100vw;height:100vh;padding:12px}
|
||||||
|
#grid{width:100%;height:100%;display:grid;gap:12px;grid-template-columns:repeat(var(--cols),minmax(0,1fr));grid-template-rows:repeat(var(--rows),minmax(0,1fr))}
|
||||||
|
.card{position:relative;min-width:0;min-height:0;background:var(--card);border-radius:20px;box-shadow:0 2px 12px #00000012;overflow:hidden;padding:14px 16px 10px;display:flex;flex-direction:column}
|
||||||
|
.price{position:absolute;right:14px;top:14px;background:var(--orange);color:#fff;font-size:clamp(1.2rem,2.7vw,2.2rem);font-weight:800;padding:.18em .45em;border-radius:999px;box-shadow:0 6px 16px #ff660033}
|
||||||
|
.image-wrap{flex:1;min-height:0;display:flex;align-items:center;justify-content:center;padding:4px 20px 0}
|
||||||
|
.image-wrap img{max-width:100%;max-height:100%;object-fit:contain;display:block}
|
||||||
|
.name{font-size:clamp(1rem,1.7vw,1.5rem);font-weight:700;margin:4px 0 8px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||||
|
.qty{height:50px;align-self:center;display:flex;align-items:center;justify-content:center;gap:22px;padding:4px 14px;border-radius:999px;background:#eef0f2;font-size:1.35rem;font-weight:800;min-width:148px;transition:.15s}
|
||||||
|
.qty.active{background:var(--orange);color:#fff}.qty button{border:0;background:transparent;color:inherit;font:inherit;width:38px;height:38px;border-radius:50%;cursor:pointer;touch-action:manipulation}.qty button:active{transform:scale(.9)}
|
||||||
|
.total{justify-content:center;align-items:center;text-align:center;padding:24px}.total-label{font-size:clamp(1.4rem,2.5vw,2.2rem);font-weight:700;color:var(--muted)}.total-value{font-size:clamp(2.8rem,6vw,5rem);font-weight:850;margin:4px 0 22px}.pay{border:0;background:var(--orange);color:#fff;font-weight:800;font-size:clamp(1rem,1.8vw,1.4rem);border-radius:16px;padding:18px 28px;width:100%;cursor:pointer}.pay:disabled{opacity:.35;cursor:not-allowed}.clear{margin-top:14px;border:0;background:transparent;text-decoration:underline;color:var(--muted);font-size:1rem;cursor:pointer}
|
||||||
|
#screensaver{position:fixed;inset:0;background:#f7f7f5;z-index:20;display:none;overflow:hidden;cursor:pointer}.ss-title{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);font-size:clamp(2rem,5vw,5rem);font-weight:850;color:#222;white-space:nowrap}.ss-title span{color:var(--orange)}.float{position:absolute;width:clamp(100px,12vw,190px);height:clamp(100px,12vw,190px);object-fit:contain;filter:drop-shadow(0 12px 18px #00000015);animation:drift 18s ease-in-out infinite alternate}.f1{left:8%;top:14%;animation-delay:-2s}.f2{right:9%;top:18%;animation-delay:-8s}.f3{left:14%;bottom:10%;animation-delay:-5s}.f4{right:14%;bottom:12%;animation-delay:-11s}.f5{left:43%;top:8%;width:clamp(80px,9vw,140px);animation-delay:-14s}.f6{right:38%;bottom:7%;width:clamp(80px,9vw,140px);animation-delay:-17s}
|
||||||
|
@keyframes drift{from{transform:translate3d(-12px,-8px,0) rotate(-3deg)}to{transform:translate3d(18px,14px,0) rotate(4deg)}}
|
||||||
|
#camera{position:fixed;width:1px;height:1px;opacity:0;pointer-events:none;left:-10px;top:-10px}#motionCanvas{display:none}
|
||||||
|
@media(max-width:900px){#app{padding:8px}.card{border-radius:14px;padding:10px}.qty{height:44px;min-width:130px;gap:12px}.price{right:10px;top:10px}.name{margin-bottom:4px}}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"><main id="grid"></main></div>
|
||||||
|
<div id="screensaver" aria-label="Välkomstskärm">
|
||||||
|
<div class="ss-title">Välkommen till <span>Fikakassan</span></div>
|
||||||
|
<img class="float f1" src="products/monster-energy.jpg"><img class="float f2" src="products/coca-cola.jpg"><img class="float f3" src="products/twix.jpg"><img class="float f4" src="products/kexchoklad.jpg"><img class="float f5" src="products/monster-ultra.jpg"><img class="float f6" src="products/corny-large.jpg">
|
||||||
|
</div>
|
||||||
|
<video id="camera" autoplay muted playsinline></video><canvas id="motionCanvas" width="160" height="120"></canvas>
|
||||||
|
<script>
|
||||||
|
const 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'}
|
||||||
|
];
|
||||||
|
const qty=Object.fromEntries(products.map(p=>[p.id,0]));
|
||||||
|
const grid=document.querySelector('#grid');const saver=document.querySelector('#screensaver');let idleTimer;let saverOn=false;
|
||||||
|
function layout(){const slots=products.length+1;let cols=Math.max(1,Math.ceil(Math.sqrt(slots*1.8)));let rows=Math.ceil(slots/cols);while((cols-1)>0&&Math.ceil(slots/(cols-1))<=rows+1&&Math.abs((cols-1)/Math.ceil(slots/(cols-1))-1.8)<Math.abs(cols/rows-1.8))cols--;grid.style.setProperty('--cols',cols);grid.style.setProperty('--rows',rows)}
|
||||||
|
function render(){layout();grid.innerHTML='';products.forEach(p=>{const n=qty[p.id];const card=document.createElement('article');card.className='card';card.innerHTML=`<div class="price">${p.price} kr</div><div class="image-wrap"><img src="${p.image}" alt="${p.name}"></div><div class="name">${p.name}</div><div class="qty ${n?'active':''}"><button data-act="minus" aria-label="Minska">−</button><span>${n}</span><button data-act="plus" aria-label="Öka">+</button></div>`;card.querySelector('[data-act=minus]').onclick=()=>change(p.id,-1);card.querySelector('[data-act=plus]').onclick=()=>change(p.id,1);grid.appendChild(card)});const total=products.reduce((s,p)=>s+qty[p.id]*p.price,0);const t=document.createElement('article');t.className='card total';t.innerHTML=`<div class="total-label">Totalt</div><div class="total-value">${total} kr</div><button class="pay" ${total?'':'disabled'}>BETALA MED SWISH</button><button class="clear">Töm köp</button>`;t.querySelector('.clear').onclick=()=>{products.forEach(p=>qty[p.id]=0);render()};grid.appendChild(t)}
|
||||||
|
function change(id,d){qty[id]=Math.max(0,qty[id]+d);render();wake()}
|
||||||
|
function wake(){saverOn=false;saver.style.display='none';clearTimeout(idleTimer);idleTimer=setTimeout(showSaver,20000)}
|
||||||
|
function showSaver(){if(document.querySelector('.pay:disabled')){saverOn=true;saver.style.display='block'}}
|
||||||
|
['pointerdown','touchstart','keydown'].forEach(e=>document.addEventListener(e,wake,{passive:true}));saver.addEventListener('pointerdown',wake);render();wake();
|
||||||
|
|
||||||
|
// Local, non-recording motion detector. Only low-resolution frames are compared in memory.
|
||||||
|
const video=document.querySelector('#camera'),canvas=document.querySelector('#motionCanvas'),ctx=canvas.getContext('2d',{willReadFrequently:true});let previous=null,lastMotion=0;
|
||||||
|
async function startCamera(){try{const stream=await navigator.mediaDevices.getUserMedia({video:{facingMode:'user',width:{ideal:320},height:{ideal:240}},audio:false});video.srcObject=stream;requestAnimationFrame(motionLoop)}catch(e){console.warn('Kamera för närvarodetektering kunde inte startas:',e)}}
|
||||||
|
function motionLoop(){if(video.readyState>=2){ctx.drawImage(video,0,0,160,120);const data=ctx.getImageData(0,0,160,120).data;if(previous){let changed=0;for(let i=0;i<data.length;i+=16){const d=Math.abs(data[i]-previous[i])+Math.abs(data[i+1]-previous[i+1])+Math.abs(data[i+2]-previous[i+2]);if(d>55)changed++}if(changed>180&&Date.now()-lastMotion>1200){lastMotion=Date.now();wake()}}previous=data}requestAnimationFrame(motionLoop)}
|
||||||
|
if(navigator.mediaDevices?.getUserMedia)startCamera();
|
||||||
|
window.addEventListener('resize',layout);
|
||||||
|
</script>
|
||||||
|
</body></html>
|
||||||
2
kiosk.sh
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
exec chromium --kiosk --start-fullscreen --disable-pinch http://127.0.0.1:8000
|
||||||
35
products.yaml
Normal file
@@ -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
|
||||||
BIN
products/coca-cola-zero.jpg
Normal file
|
After Width: | Height: | Size: 138 KiB |
BIN
products/coca-cola-zero.png
Normal file
|
After Width: | Height: | Size: 763 KiB |
BIN
products/coca-cola.jpg
Normal file
|
After Width: | Height: | Size: 132 KiB |
BIN
products/coca-cola.png
Normal file
|
After Width: | Height: | Size: 715 KiB |
BIN
products/corny-large.jpg
Normal file
|
After Width: | Height: | Size: 108 KiB |
BIN
products/corny-large.png
Normal file
|
After Width: | Height: | Size: 589 KiB |
BIN
products/kexchoklad.jpg
Normal file
|
After Width: | Height: | Size: 182 KiB |
BIN
products/kexchoklad.png
Normal file
|
After Width: | Height: | Size: 1.1 MiB |
BIN
products/monster-energy.jpg
Normal file
|
After Width: | Height: | Size: 101 KiB |
BIN
products/monster-energy.png
Normal file
|
After Width: | Height: | Size: 431 KiB |
BIN
products/monster-ultra.jpg
Normal file
|
After Width: | Height: | Size: 148 KiB |
BIN
products/monster-ultra.png
Normal file
|
After Width: | Height: | Size: 552 KiB |
BIN
products/twix.jpg
Normal file
|
After Width: | Height: | Size: 113 KiB |
BIN
products/twix.png
Normal file
|
After Width: | Height: | Size: 690 KiB |
4
requirements.txt
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
fastapi>=0.115,<1
|
||||||
|
uvicorn[standard]>=0.30,<1
|
||||||
|
PyYAML>=6,<7
|
||||||
|
qrcode[pil]>=8,<9
|
||||||
4
run.sh
Executable file
@@ -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
|
||||||
392
setup-fikakassa-kioskmode.sh
Executable file
@@ -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 <<EOF
|
||||||
|
[Unit]
|
||||||
|
Description=Fikakassan FastAPI
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=root
|
||||||
|
Group=root
|
||||||
|
WorkingDirectory=$APP_DIR
|
||||||
|
Environment=PYTHONUNBUFFERED=1
|
||||||
|
ExecStart=$APP_DIR/.venv/bin/uvicorn app.main:app --host 0.0.0.0 --port 8000
|
||||||
|
Restart=always
|
||||||
|
RestartSec=2
|
||||||
|
NoNewPrivileges=true
|
||||||
|
PrivateTmp=true
|
||||||
|
ProtectSystem=full
|
||||||
|
ProtectHome=true
|
||||||
|
ReadWritePaths=$APP_DIR/data
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOF
|
||||||
|
|
||||||
|
install -d -m 755 "$APP_DIR/data"
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl enable --now fikakassa.service
|
||||||
|
|
||||||
|
log "Konfigurerar Wi-Fi"
|
||||||
|
|
||||||
|
systemctl enable --now NetworkManager.service
|
||||||
|
|
||||||
|
# Remove an old profile with the same name, then create a clean one.
|
||||||
|
nmcli connection delete "$WIFI_CONNECTION" >/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" <<EOF
|
||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
# Disable screen blanking and DPMS.
|
||||||
|
xset s off
|
||||||
|
xset -dpms
|
||||||
|
xset s noblank
|
||||||
|
|
||||||
|
# Hide mouse cursor after a short delay.
|
||||||
|
unclutter --timeout 2 --jitter 5 --ignore-scrolling &
|
||||||
|
|
||||||
|
# Start the kiosk browser.
|
||||||
|
exec chromium \\
|
||||||
|
--kiosk \\
|
||||||
|
--start-fullscreen \\
|
||||||
|
--no-first-run \\
|
||||||
|
--no-default-browser-check \\
|
||||||
|
--disable-session-crashed-bubble \\
|
||||||
|
--disable-infobars \\
|
||||||
|
--disable-translate \\
|
||||||
|
--disable-features=TranslateUI \\
|
||||||
|
--password-store=basic \\
|
||||||
|
--disable-pinch \\
|
||||||
|
--overscroll-history-navigation=0 \\
|
||||||
|
--disable-background-networking \\
|
||||||
|
--disable-component-update \\
|
||||||
|
--disable-domain-reliability \\
|
||||||
|
--disable-sync \\
|
||||||
|
--metrics-recording-only \\
|
||||||
|
--noerrdialogs \\
|
||||||
|
"$KIOSK_URL"
|
||||||
|
EOF
|
||||||
|
chown -R "$KIOSK_USER:$KIOSK_USER" "$KIOSK_HOME/.config"
|
||||||
|
chmod 755 "$KIOSK_HOME/.config/openbox/autostart"
|
||||||
|
|
||||||
|
log "Konfigurerar automatisk inloggning på tty1"
|
||||||
|
|
||||||
|
mkdir -p /etc/systemd/system/getty@tty1.service.d
|
||||||
|
cat > /etc/systemd/system/getty@tty1.service.d/override.conf <<EOF
|
||||||
|
[Service]
|
||||||
|
ExecStart=
|
||||||
|
ExecStart=-/sbin/agetty --autologin $KIOSK_USER --noclear %I \$TERM
|
||||||
|
Type=idle
|
||||||
|
EOF
|
||||||
|
|
||||||
|
# Start X only on tty1 for the kiosk account.
|
||||||
|
cat > "$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 <<EOF
|
||||||
|
|
||||||
|
========================================
|
||||||
|
FIKAKASSAN KIOSK ÄR KONFIGURERAD
|
||||||
|
========================================
|
||||||
|
|
||||||
|
Kiosk-användare: $KIOSK_USER
|
||||||
|
Applikation: $APP_DIR
|
||||||
|
Webbapp: $KIOSK_URL
|
||||||
|
Wi-Fi: $WIFI_SSID
|
||||||
|
Wi-Fi-profil: $WIFI_CONNECTION
|
||||||
|
|
||||||
|
FastAPI:
|
||||||
|
systemctl status fikakassa
|
||||||
|
journalctl -u fikakassa -f
|
||||||
|
|
||||||
|
SSH:
|
||||||
|
systemctl status ssh
|
||||||
|
|
||||||
|
Nätverk:
|
||||||
|
nmcli device status
|
||||||
|
nmcli connection show
|
||||||
|
|
||||||
|
Kiosk:
|
||||||
|
tty1 autologin -> 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
|
||||||