first commit

This commit is contained in:
Joakim
2026-11-01 16:20:49 +01:00
commit fdeeb26e86
82 changed files with 1528 additions and 0 deletions

6
app/static/css/style.css Normal file
View 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
View 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
View 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()});

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 185 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 245 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 148 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 159 KiB

BIN
app/static/swish-logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB