N/A
This commit is contained in:
44
app/static/css/backoffice.css
Normal file
44
app/static/css/backoffice.css
Normal file
@@ -0,0 +1,44 @@
|
||||
*{box-sizing:border-box}
|
||||
:root{font-family:system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#171717;background:#f4f5f6}
|
||||
body{margin:0}
|
||||
.topbar{background:#fff;border-bottom:1px solid #ddd;padding:18px 28px;display:flex;align-items:center;justify-content:space-between}
|
||||
.eyebrow{font-size:12px;font-weight:800;letter-spacing:.12em;color:#ff5a00}
|
||||
h1,h2{margin:0}
|
||||
h1{font-size:28px}.wrap{max-width:1400px;margin:0 auto;padding:22px}
|
||||
.shop-link,button{border:0;border-radius:10px;padding:10px 16px;font-weight:700;cursor:pointer}
|
||||
.shop-link{background:#ff5a00;color:#fff;text-decoration:none}
|
||||
button{background:#ff5a00;color:#fff}
|
||||
.toolbar{display:flex;gap:12px;align-items:end;margin-bottom:18px}
|
||||
label{display:flex;flex-direction:column;gap:5px;font-size:13px;font-weight:700}
|
||||
input,select{font:inherit;border:1px solid #ccc;border-radius:8px;padding:9px;background:#fff}
|
||||
#status{font-size:13px;color:#666}
|
||||
.cards{display:grid;grid-template-columns:repeat(5,1fr);gap:12px;margin-bottom:18px}
|
||||
.metric{background:#fff;border:1px solid #ddd;border-radius:14px;padding:18px;display:flex;flex-direction:column;gap:8px}
|
||||
.metric span{font-size:13px;color:#666}.metric strong{font-size:25px}
|
||||
.metric.profit{border-color:#ff5a00}
|
||||
.panel{background:#fff;border:1px solid #ddd;border-radius:14px;margin:18px 0;padding:18px}
|
||||
.panel-head{display:flex;justify-content:space-between;align-items:center;margin-bottom:14px}
|
||||
.panel h2{font-size:19px}
|
||||
.table-wrap{overflow:auto}
|
||||
table{width:100%;border-collapse:collapse}
|
||||
th,td{text-align:left;padding:10px 8px;border-bottom:1px solid #eee;white-space:nowrap}
|
||||
th{font-size:12px;text-transform:uppercase;color:#666}
|
||||
td.num,th.num{text-align:right}
|
||||
.history-chart{height:180px;display:flex;align-items:end;gap:3px;border-bottom:1px solid #bbb;padding:10px 0 0;overflow:hidden}
|
||||
.bar{min-width:8px;flex:1;background:#ff5a00;border-radius:4px 4px 0 0;position:relative}
|
||||
.bar:hover{opacity:.75}.bar span{display:none;position:absolute;bottom:100%;left:50%;transform:translateX(-50%);background:#222;color:#fff;padding:4px 6px;border-radius:5px;font-size:11px;white-space:nowrap}
|
||||
.bar:hover span{display:block}
|
||||
.hint{font-size:13px;color:#666}
|
||||
.movement-form{display:grid;grid-template-columns:1.5fr 1fr 1.5fr .7fr 1fr 2fr auto;gap:10px;align-items:end}
|
||||
.movement-form button{height:40px}
|
||||
code{background:#eee;padding:2px 5px;border-radius:4px}
|
||||
.small-btn{padding:6px 9px;font-size:12px}
|
||||
@media(max-width:1000px){.cards{grid-template-columns:repeat(2,1fr)}.movement-form{grid-template-columns:repeat(2,1fr)}}
|
||||
@media(max-width:600px){.wrap{padding:12px}.cards{grid-template-columns:1fr}.movement-form{grid-template-columns:1fr}}
|
||||
.history-controls{display:flex;align-items:end;gap:8px}
|
||||
.history-controls label{min-width:115px}
|
||||
.history-controls input{width:100px;text-align:center}
|
||||
.history-step{width:42px;height:40px;padding:0;font-size:24px;line-height:1}
|
||||
.history-summary{display:flex;flex-wrap:wrap;gap:8px;margin:0 0 14px}
|
||||
.history-summary span{background:#f5f5f5;border:1px solid #e2e2e2;border-radius:999px;padding:7px 11px;font-size:13px}
|
||||
@media(max-width:600px){.history-controls{flex-wrap:wrap}.history-controls label{min-width:90px}.history-summary{gap:5px}}
|
||||
@@ -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));
|
||||
|
||||
59
app/static/js/backoffice.js
Normal file
59
app/static/js/backoffice.js
Normal 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();
|
||||
Reference in New Issue
Block a user