first commit
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>
|
||||