feat: products and prices from the database, edited in the Kanban's Site tab (front 8.1)

Gestão and the administrators switch each product on and off and set its
price from a start date; a price that has started is history and cannot
change, a scheduled one can be cancelled. The Site and the server read
the current price; with no row the code's prices and TREATMENT_CENTS
still apply, so nothing changes until someone sets one. A switched-off
product disappears from the Site and new quotes with it are refused.
Approved quotes and paid orders keep their price.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-09 13:50:45 -03:00
parent 4219db8215
commit c88d81588e
20 changed files with 550 additions and 35 deletions

View File

@@ -9,6 +9,8 @@
let shownCart = null;
let pixClock = null;
let busy = false;
// Every product switched off in the Kanban's Site tab (front 8).
let semPedidos = false;
let draftId = localStorage.getItem('dtf-quote');
let requestKey = localStorage.getItem('dtf-request-key');
let requestBody = localStorage.getItem('dtf-request-body');
@@ -84,6 +86,25 @@
if(preco)preco.textContent=TAXA_TRATAMENTO>0?rs(TAXA_TRATAMENTO):'';
if(!(TAXA_TRATAMENTO>0)&&document.getElementById('fTratamento'))document.getElementById('fTratamento').checked=false;
}
// What the Site sells and at what price, from the database (front 8). An
// older server sends no `products`: the page keeps PRECO.
if(session.products){
for(const [mode,product] of Object.entries(session.products)){
PRECO[mode]=product.unit_cents/100;
const card=document.querySelector('button.ec[data-modo="'+mode+'"]');
if(card&&!product.enabled)card.hidden=true;
}
document.querySelectorAll('[data-preco]').forEach(el=>{
const product=session.products[el.dataset.preco];
el.textContent=product&&!product.enabled?'Indisponível':rs(PRECO[el.dataset.preco]);
});
window.dtfProducts=session.products;
if(typeof folhas!=='undefined'&&folhas.length&&typeof pintaFolha==='function')pintaFolha();
if(typeof itemAtual!=='undefined'&&itemAtual&&typeof carrinho==='function')carrinho();
if(typeof pintaTipoEnvio==='function')pintaTipoEnvio();
semPedidos=!Object.values(session.products).some(product=>product.enabled);
if(semPedidos)message('No momento não estamos recebendo pedidos pelo site.','warn');
}
if(typeof pintaPedido==='function')pintaPedido();
}).catch(()=>{});
window.dtfSessionReady=ready;
@@ -719,6 +740,7 @@
window.addEventListener('dtf-page-changed',()=>{
if (naPagina()) refresh();
else if (!busy) { refreshVersion++; clearInterval(pixClock); message(''); actions.replaceChildren(); pintaResumo(null); }
if (!naPagina() && semPedidos) message('No momento não estamos recebendo pedidos pelo site.','warn');
});
refresh();
})();

116
web/kanban-site.js Normal file
View File

@@ -0,0 +1,116 @@
/* Kanban DTF: the Site tab. What the Site sells and at what price, edited by
Gestão and the administrators (Fase 2, front 8). Loaded after kanban.js,
which defines api, may, money, when, say, node and button.
A price is history: one that has started is never changed or deleted, so
only a scheduled (future) price may be cancelled. */
const SITE_UNIT_LABEL={metro:' /m',pedido:' por pedido'};
// Reais with a comma, as the Site shows them: "19,90" is 1990 cents.
function moneyInputCents(value){
let text=String(value||'').trim().replace(/R\$/g,'').replace(/\s/g,'');
if(!text)return null;
if(text.includes(','))text=text.replace(/\./g,'').replace(',','.');
const number=Number(text);
if(!Number.isFinite(number)||number<0)return null;
return Math.round(number*100);
}
// A price that already started is refused by the server (409).
const cancelScheduledPrice=id=>api('/site/prices/'+id+'/cancel',{});
function siteProductRow(product){
const tr=node('tr');
const name=node('td');name.append(node('b',product.title));
const price=node('td',money(product.unit_cents)+SITE_UNIT_LABEL[product.unit],'nowrap');
if(product.fallback)price.append(node('span',' · padrão','muted'));
const state=node('td');
const label=node('label',undefined,'siteSwitch');
const input=node('input');input.type='checkbox';input.checked=product.enabled;
const word=node('span',product.enabled?'Ligado':'Desligado');
input.onchange=async()=>{
input.disabled=true;
try{
await api('/site/products/'+product.id,{enabled:input.checked});
word.textContent=input.checked?'Ligado':'Desligado';
say(product.title+(input.checked?' ligado.':' desligado.'));
await loadSiteAdmin();
}catch(error){input.checked=!input.checked;say(error.message,true);}
finally{input.disabled=false;}
};
label.append(input,word);
state.append(label);
tr.append(name,state,price);
return tr;
}
function sitePriceBlock(product){
const block=node('div',undefined,'sitePriceBlock');
const heading=node('h3',product.title);
heading.append(node('span',' · '+product.unit,'muted'));
// Novo preço: reais with a comma; empty "A partir de" means now.
const form=node('div',undefined,'sitePriceForm');
const priceLabel=node('label');priceLabel.append(node('span','Novo preço'));
const price=node('input');price.type='text';price.inputMode='decimal';price.className='siteMoney';
price.placeholder=(product.unit_cents/100).toFixed(2).replace('.',',');
price.setAttribute('aria-label','Novo preço de '+product.title);
priceLabel.append(price);
const startsLabel=node('label');startsLabel.append(node('span','A partir de'));
const starts=node('input');starts.type='datetime-local';
starts.setAttribute('aria-label','Quando o novo preço de '+product.title+' começa');
startsLabel.append(starts);
const save=button('Salvar',async()=>{
const cents=moneyInputCents(price.value);
if(cents===null)throw new Error('Informe o preço em reais, como 19,90.');
const whenDate=starts.value?new Date(starts.value):null;
if(whenDate&&Number.isNaN(whenDate.getTime()))throw new Error('Data inválida.');
await api('/site/products/'+product.id+'/prices',
{unit_cents:cents,starts_at:whenDate?whenDate.toISOString():null});
say(whenDate?'Preço salvo para '+when(whenDate)+'.':'Preço salvo. Vale a partir de agora.');
await loadSiteAdmin();
},'btn pri');
form.append(priceLabel,startsLabel,save);
const scheduled=node('div',undefined,'siteScheduled');
if(product.scheduled.length){
for(const row of product.scheduled){
const line=node('div',undefined,'siteScheduledRow');
line.append(node('span',money(row.unit_cents)+SITE_UNIT_LABEL[product.unit]+' a partir de '+when(row.starts_at)));
line.append(button('Cancelar',async()=>{
await cancelScheduledPrice(row.id);
say('Preço agendado cancelado.');
await loadSiteAdmin();
},'btn ghost'));
scheduled.append(line);
}
}else scheduled.append(node('span','Nenhum preço agendado.','muted'));
const table=node('table',undefined,'table');
const head=node('thead');const headRow=node('tr');
for(const title of ['Valor','A partir de','Quem','Quando'])headRow.append(node('th',title));
head.append(headRow);
const body=node('tbody');
for(const row of product.history){
const tr=node('tr');
tr.append(node('td',money(row.unit_cents),'nowrap'),node('td',when(row.starts_at),'nowrap'),
node('td',row.created_by),node('td',when(row.created_at),'nowrap'));
body.append(tr);
}
if(!product.history.length){
const tr=node('tr');const td=node('td','Nenhum preço registrado: vale o preço padrão.','muted');
td.colSpan=4;tr.append(td);body.append(tr);
}
table.append(head,body);
const history=node('div',undefined,'siteHistory');
history.append(node('h4','Histórico'),table);
block.append(heading,form,scheduled,history);
return block;
}
async function loadSiteAdmin(){
if(!may('manage'))return;
const data=await api('/site/products');
$('site-products').replaceChildren(...data.products.map(siteProductRow));
$('site-prices').replaceChildren(...data.products.map(sitePriceBlock));
}

View File

@@ -639,6 +639,25 @@ label.fopt{cursor:pointer;user-select:none}
.siteVideoField input,.siteVideoField select{max-width:240px;min-height:38px;color:var(--tx);background:var(--sf);border:1px solid var(--ln2);border-radius:8px;padding:6px}
.siteVideoToggle{display:flex;align-items:center;gap:7px;min-height:38px;font-size:13px}
.siteVideoError{width:100%;margin:0;color:var(--bad);font-size:12px}
/* Site (front 8): what the Site sells, its prices and their history. */
#tab-site .siteSwitch{display:flex;align-items:center;gap:8px;font-size:13px;font-weight:550;cursor:pointer}
#tab-site .siteSwitch input{width:16px;height:16px;margin:0;accent-color:var(--acc)}
#tab-site .sitePriceBlock{display:flex;flex-direction:column;gap:12px;padding:16px 18px}
#tab-site .sitePriceBlock+.sitePriceBlock{border-top:1px solid var(--ln)}
#tab-site .sitePriceBlock h3{margin:0;font-size:14px;font-weight:650}
#tab-site .sitePriceBlock h3 .muted{font-size:12.5px;font-weight:500}
#tab-site .sitePriceForm{display:flex;align-items:end;gap:12px;flex-wrap:wrap}
#tab-site .sitePriceForm label{display:flex;flex-direction:column;gap:6px;font-size:12px;color:var(--tx2)}
#tab-site .sitePriceForm input{height:38px;padding:0 10px;border-radius:8px;border:1px solid var(--ln2);background:var(--sf);color:var(--tx);font-size:14px;font-family:inherit}
#tab-site .sitePriceForm input:focus{border-color:var(--acc);box-shadow:0 0 0 3px color-mix(in srgb,var(--acc) 18%,transparent);outline:none}
#tab-site .siteMoney{width:140px}
#tab-site .siteScheduled{display:flex;flex-direction:column;gap:8px;font-size:13.5px}
#tab-site .siteScheduledRow{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
#tab-site .siteScheduledRow .btn{height:30px;padding:0 10px;font-size:12.5px}
#tab-site .siteHistory{display:flex;flex-direction:column;gap:6px}
#tab-site .siteHistory h4{margin:0;font-size:12.5px;font-weight:600;color:var(--tx3)}
#tab-site .siteHistory .table{font-size:13px}
#tab-site .siteHistory .table th,#tab-site .siteHistory .table td{padding:8px 12px}
.page>*{flex-shrink:0}
.pagetools{display:flex;align-items:center;gap:12px;flex-wrap:wrap}
.panel{background:var(--sf);border:1px solid var(--ln);border-radius:12px}

View File

@@ -40,6 +40,7 @@
<button class="nav" type="button" data-tab="quotes" aria-selected="false"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M5 2.75h7l3 3v11.5H5z M12 2.75v3h3 M7.5 9.5h5 M7.5 12.5h5 M7.5 15h3"></path></svg><span>Cotações</span><span class="pip" id="badge-quotes"></span></button>
<button class="nav" type="button" data-tab="payments" aria-selected="false"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 5h14.5v10H2.75z M2.75 8.25h14.5 M5.5 12.25h3"></path></svg><span>Pagamentos</span><span class="pip" id="badge-payments"></span></button>
<button class="nav" type="button" data-tab="stats" aria-selected="false"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M3 16.75h14 M4.75 14V9.5 M8.5 14V4.5 M12.25 14V7.5 M16 14v-3.5"></path></svg><span>Números</span></button>
<button class="nav" type="button" data-tab="site" aria-selected="false" hidden><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M2.75 10h14.5 M10 2.75c2 2 3 4.5 3 7.25s-1 5.25-3 7.25 M10 2.75c-2 2-3 4.5-3 7.25s1 5.25 3 7.25"></path></svg><span>Site</span></button>
<button class="nav" type="button" data-tab="integrations" aria-selected="false"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M8.5 6.5H6a3.25 3.25 0 0 0 0 6.5h2.5 M11.5 6.5H14a3.25 3.25 0 0 1 0 6.5h-2.5 M7 9.75h6"></path></svg><span>Integrações</span><span class="pip" id="badge-integrations" title="A pasta da fila precisa de atenção"></span></button>
<button class="nav" type="button" data-tab="users" aria-selected="false" hidden><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M6.75 6.25a3.25 3.25 0 1 0 6.5 0a3.25 3.25 0 1 0 -6.5 0 M3.75 17c.6-3.2 3.1-5 6.25-5s5.65 1.8 6.25 5"></path></svg><span>Usuários</span></button>
<button class="nav phone" id="more-nav" type="button" aria-haspopup="menu"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M4.1 10a.9.9 0 1 0 1.8 0a.9.9 0 1 0 -1.8 0 M9.1 10a.9.9 0 1 0 1.8 0a.9.9 0 1 0 -1.8 0 M14.1 10a.9.9 0 1 0 1.8 0a.9.9 0 1 0 -1.8 0"></path></svg><span>Mais</span><span class="pip" id="badge-more"></span></button>
@@ -151,6 +152,18 @@
<section class="panel clip"><div class="phead"><h2>Velocidade do site e do Prumo</h2><span class="hint tip-l" tabindex="0" data-tip="Média e p95 do que o cliente sente, por pedido pago no período: abrir a página, subir o arquivo (segundos por MB), a conferência do Prumo, a montagem das avulsas, a geração do arquivo final por 10 m e o tempo do evento de pagamento até o card. Referências: página < 3 s; conferência < 30 s; geração < 2 min por 10 m; card em até 1 min."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div>
<table class="table"><thead><tr><th scope="col">Etapa</th><th scope="col" class="r">Média</th><th scope="col" class="r">p95</th><th scope="col" class="r">Amostras</th></tr></thead><tbody id="stats-speed"></tbody></table></section>
</section>
<section id="tab-site" class="page" hidden>
<section class="panel clip">
<div class="phead"><h2>Produtos</h2></div>
<p class="phint">O que o Site mostra e vende agora. Um produto desligado some do Site e o servidor recusa novos pedidos com ele.</p>
<div class="scrollx"><table class="table"><thead><tr><th scope="col">Produto</th><th scope="col">Situação</th><th scope="col">Preço atual</th></tr></thead><tbody id="site-products"></tbody></table></div>
</section>
<section class="panel clip">
<div class="phead"><h2>Preços</h2></div>
<p class="phint">Cada preço vale a partir da data escolhida. Um preço que já começou não muda mais: o histórico fica abaixo. Só um preço agendado pode ser cancelado.</p>
<div id="site-prices"></div>
</section>
</section>
<section id="tab-users" class="page" hidden>
<section class="panel clip">
<div class="phead"><h2>Pessoas</h2><span class="n" id="users-count"></span>
@@ -188,4 +201,4 @@
<div class="scrim" id="scrim"></div>
<aside class="drawer" id="panel" aria-label="Pedido"></aside>
</div>
<script src="/upload.js"></script><script src="/kanban-viewer.js"></script><script src="/kanban.js"></script></body></html>
<script src="/upload.js"></script><script src="/kanban-viewer.js"></script><script src="/kanban.js"></script><script src="/kanban-site.js"></script></body></html>

View File

@@ -59,7 +59,8 @@ const mayAct=order=>ME?.role!=='operador'||order.state==='tra'||isMine(order);
// Vendedor and Financeiro consult Cotações and Números without acting there.
const consults=()=>['vendedor','financeiro'].includes(ME?.role);
const TAB_NEEDS={quotes:o=>may('manage')||consults(),payments:()=>may('payments'),
stats:()=>may('manage')||consults(),integrations:()=>may('manage')||may('print'),users:()=>may('users')};
stats:()=>may('manage')||consults(),site:()=>may('manage'),
integrations:()=>may('manage')||may('print'),users:()=>may('users')};
function applyRole(){
for(const b of document.querySelectorAll('[data-tab]')){const need=TAB_NEEDS[b.dataset.tab];b.hidden=!!need&&!need();}
if(TAB_NEEDS[tab]&&!TAB_NEEDS[tab]())showTab('board');
@@ -654,14 +655,14 @@ async function load(quiet=false){
}
}
// The page's name in the top bar; Produção also says what is open.
const PAGE_TITLES={board:'Produção',quotes:'Cotações',payments:'Pagamentos',stats:'Números',integrations:'Integrações',users:'Usuários'};
const PAGE_TITLES={board:'Produção',quotes:'Cotações',payments:'Pagamentos',stats:'Números',site:'Site',integrations:'Integrações',users:'Usuários'};
function showTab(name){
tab=name;$('tab-quotes').classList.remove('reviewing');
for(const b of document.querySelectorAll('[data-tab]'))b.setAttribute('aria-selected',String(b.dataset.tab===name));
$('page-title').textContent=PAGE_TITLES[name];$('board-summary').hidden=name!=='board';$('filter-open').hidden=name!=='board';
$('more-nav').classList.toggle('on',['integrations','users'].includes(name));
for(const id of ['board','quotes','payments','stats','integrations','users'])$('tab-'+id).hidden=name!==id;
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:eventsIfAllowed,users:loadUsers};
for(const id of ['board','quotes','payments','stats','site','integrations','users'])$('tab-'+id).hidden=name!==id;
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,site:loadSiteAdmin,integrations:eventsIfAllowed,users:loadUsers};
if(board&&lists[name])lists[name]().catch(e=>say(e.message,true));
}
function render(){
@@ -674,7 +675,7 @@ function render(){
tinyHeader();renderBoard();renderIntegrations();
$('badge-more').textContent=$('badge-integrations').textContent;
// Lists live on their own pages of the API; refresh the one being looked at.
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:eventsIfAllowed,users:loadUsers};
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,site:loadSiteAdmin,integrations:eventsIfAllowed,users:loadUsers};
if(lists[tab])lists[tab]().catch(e=>say(e.message,true));
if(openOrder){const order=board.orders.find(o=>o.id===openOrder);if(order)renderPanel(order);else closePanel();}
}

View File

@@ -54,9 +54,12 @@ function pintaTipoEnvio(){
$('tipoAvulsaPreco').textContent=rs(PRECO[avulsa])+' /m';
$('larguraFolhaPronta').textContent=String(MODOS[folha].larg).replace('.',',');
const atual = ehFolha() ? 'folha' : 'avulsa';
// A product switched off in the Kanban cannot be chosen (front 8).
const ligado=m=>!(window.dtfProducts&&window.dtfProducts[m]&&!window.dtfProducts[m].enabled);
el.querySelectorAll('.cam').forEach(b=>{
const alvo=b.dataset.tipo==='folha'?folha:avulsa;
b.classList.toggle('on', b.dataset.tipo===atual);
b.disabled=folhas.length>0 || artes.length>0; // já tem arquivo: a escolha está feita
b.disabled=!ligado(alvo) || folhas.length>0 || artes.length>0; // já tem arquivo: a escolha está feita
});
}
function avisoTipo(txt){