This commit is contained in:
Joakim
2026-11-01 22:06:14 +01:00
parent f247cd69bf
commit 9ae513a1b8
7 changed files with 872 additions and 14 deletions

View File

@@ -1,4 +1,5 @@
const state={products:[],quantities:{},paymentTimer:null,pollTimer:null,thankTimer:null,pollSince:0};
const state={products:[],quantities:{},paymentTimer:null,pollTimer:null,thankTimer:null,pollSince:0,thankYouSeconds:3};
const debug=(...args)=>console.log('[FIKAKASSA]',new Date().toISOString(),...args);
// Kioskläge: blockera webbläsarens vanliga touch-, markerings- och kontextmenyer.
document.addEventListener('contextmenu',e=>e.preventDefault());
@@ -137,9 +138,58 @@ function renderProducts(){
}
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)}
function resetShop(){
debug('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;
debug('startPayment()',items);
const r=await fetch('/api/order',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({items})});
if(!r.ok){debug('POST /api/order failed',r.status);return}
const order=await r.json();
debug('order created',order.id,'total=',order.total,'created_at=',order.created_at);
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){debug('QR failed',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)'}));
// Use order.created_at rather than "now". A fast payment can arrive while the QR is loading.
state.pollSince=Math.max(0,Number(order.created_at)-0.01);
debug('payment polling started, after=',state.pollSince);
pollPayment();
state.paymentTimer=setTimeout(()=>{debug('payment timeout');resetShop()},30000)
}
async function pollPayment(){
try{
const after=state.pollSince;
const r=await fetch(`/api/payment/event?after=${after}`,{cache:'no-store'});
if(r.ok){
const e=await r.json();
debug('payment event poll',e);
if(e.event==='payment'){
state.pollSince=e.received_at;
showThanks();
return
}
}else debug('payment event HTTP',r.status);
}catch(e){debug('payment poll error',e)}
if(!paymentView.classList.contains('hidden'))state.pollTimer=setTimeout(pollPayment,700)
}
function showThanks(){
debug('showThanks(): payment accepted, switching to thanks screen');
clearTimers();
paymentView.classList.add('hidden');shopView.classList.add('hidden');thanksView.classList.remove('hidden');
debug('thanks timer started',state.thankYouSeconds*1000,'ms');
state.thankTimer=setTimeout(()=>{debug('thanks timer expired');resetShop()},state.thankYouSeconds*1000)
}
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()});
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.thankYouSeconds=Number(sd.thank_you_seconds)||3;
debug('shop config loaded',sd);
state.products.forEach(p=>state.quantities[p.id]=0);renderProducts()
}).catch(e=>debug('initial load failed',e));

View File

@@ -0,0 +1,59 @@
const $=id=>document.getElementById(id);
const money=v=>`${Number(v||0).toFixed(2).replace('.00','')} kr`;
const fmtTime=ts=>new Date(Number(ts)*1000).toLocaleString('sv-SE',{dateStyle:'short',timeStyle:'short'});
const dayInput=$('day');
dayInput.value=new Date().toLocaleDateString('sv-SE',{year:'numeric',month:'2-digit',day:'2-digit'}).split('/').reverse().join('-');
async function get(url,opts){const r=await fetch(url,opts);if(!r.ok)throw new Error(await r.text());return r.json()}
async function loadDashboard(){
const d=await get(`/api/backoffice/dashboard?day=${encodeURIComponent(dayInput.value)}`);
$('sales').textContent=money(d.sales); $('orders').textContent=d.orders;
$('cogs').textContent=money(d.cogs); $('shrink').textContent=money(d.shrinkage_cost); $('profit').textContent=money(d.profit);
$('salesTable').querySelector('tbody').innerHTML=d.order_lines.map(x=>`<tr><td>${x.product_name}</td><td>${x.quantity}</td><td>${money(x.line_total)}</td></tr>`).join('')||'<tr><td colspan="3">Ingen försäljning.</td></tr>';
}
async function loadHistory(){
const back=Math.max(0,Math.min(3650,Number($('daysBack').value)||0));
$('daysBack').value=back;
$('historyRange').textContent=back===0?'Idag':`Idag − ${back} dagar`;
const rows=await get(`/api/backoffice/history?back_days=${back}`);
const max=Math.max(1,...rows.map(x=>x.sales));
$('historyChart').innerHTML=rows.map(x=>`<div class="bar" style="height:${Math.max(2,(x.sales/max)*100)}%"><span>${x.day}: ${money(x.sales)}</span></div>`).join('');
$('historyTable').querySelector('tbody').innerHTML=[...rows].reverse().map(x=>`<tr><td>${x.day}</td><td>${x.orders}</td><td>${money(x.sales)}</td><td>${money(x.shrink)}</td><td>${money(x.profit)}</td></tr>`).join('');
const totals=rows.reduce((a,x)=>({orders:a.orders+x.orders,sales:a.sales+x.sales,cogs:a.cogs+x.cogs,shrink:a.shrink+x.shrink,profit:a.profit+x.profit}),{orders:0,sales:0,cogs:0,shrink:0,profit:0});
$('historySummary').innerHTML=`<span><strong>${rows.length}</strong> dagar</span><span><strong>${totals.orders}</strong> köp</span><span><strong>${money(totals.sales)}</strong> försäljning</span><span><strong>${money(totals.cogs)}</strong> varukostnad</span><span><strong>${money(totals.shrink)}</strong> svinn</span><span><strong>${money(totals.profit)}</strong> resultat</span>`;
}
async function loadInventory(){
const d=await get('/api/backoffice/inventory');
$('inventoryTable').querySelector('tbody').innerHTML=d.items.map(x=>`<tr>
<td>${x.name}</td><td>${x.store}</td><td>${x.backstock}</td><td>${x.store+x.backstock}</td>
<td>${money(x.cost_price)}</td><td>${money(x.stock_value)}</td>
<td><button class="small-btn" onclick="setCost('${x.id}',${x.cost_price})">Ändra inköpspris</button></td></tr>`).join('');
$('mProduct').innerHTML=d.items.map(x=>`<option value="${x.id}">${x.name}</option>`).join('');
}
async function loadMovements(){
const d=await get('/api/backoffice/movements');
const labels={purchase:'Påfyllnad',shrinkage:'Svinn',adjustment:'Justering',transfer_in:'Flytt in',transfer_out:'Flytt ut',sale:'Försäljning'};
$('movementTable').querySelector('tbody').innerHTML=d.movements.map(x=>`<tr><td>${fmtTime(x.created_at)}</td><td>${x.name}</td><td>${x.location==='store'?'Butik':'Baklager'}</td><td>${labels[x.movement_type]||x.movement_type}</td><td>${x.quantity>0?'+':''}${x.quantity}</td><td>${x.note||''}</td></tr>`).join('');
}
async function refresh(){
$('status').textContent='Uppdaterar…';
try{await Promise.all([loadDashboard(),loadHistory(),loadInventory(),loadMovements()]);$('status').textContent='Uppdaterad '+new Date().toLocaleTimeString('sv-SE')}catch(e){$('status').textContent='Fel: '+e.message}
}
async function setCost(id,current){
const v=prompt('Nytt inköpspris per styck (kr):',current);
if(v===null)return;
const n=Number(v);if(!Number.isFinite(n)||n<0)return alert('Ogiltigt pris.');
await get('/api/backoffice/product-cost',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({product_id:id,cost_price:n})});
refresh();
}
$('movementForm').addEventListener('submit',async e=>{
e.preventDefault();
const type=$('mType').value;
const note=$('mNote').value;
const payload={product_id:$('mProduct').value,location:$('mLocation').value,movement_type:type,quantity:Number($('mQty').value),note,cost_price:$('mCost').value===''?null:Number($('mCost').value)};
if(type==='transfer'&&!/^from:(store|backstock)/i.test(note)){alert('Ange källa i noteringen: from:store eller from:backstock');return}
try{await get('/api/backoffice/inventory',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});e.target.reset();await refresh()}catch(err){alert(err.message)}
});
$('refresh').onclick=refresh;$('reloadInventory').onclick=loadInventory;$('daysBack').oninput=loadHistory;$('historyMinus').onclick=()=>{const e=$('daysBack');e.value=Math.max(0,(Number(e.value)||0)-1);loadHistory()};$('historyPlus').onclick=()=>{const e=$('daysBack');e.value=Math.min(3650,(Number(e.value)||0)+1);loadHistory()};
refresh();