/* 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',{}); // "5" or "5,5": a band's start in metres, as the table reads it. function bandMetres(value){return String(Number(value)).replace('.',',');} function bandsText(bands){ return (bands||[]).map(band=>' · '+bandMetres(band.from_metres)+' m: '+money(band.unit_cents)).join(''); } 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); // Faixas progressivas (front 8.2): a nova tabela começa vazia; as faixas // viajam com este preço. O tratamento é um valor por pedido, sem faixas. const bandRows=node('div',undefined,'siteBandRows'); const addBand=node('button','Adicionar faixa','btn ghost');addBand.type='button'; const paintAdd=()=>{addBand.disabled=bandRows.children.length>=5;}; const bandRow=()=>{ const row=node('div',undefined,'siteBandRow'); const fromLabel=node('label');fromLabel.append(node('span','A partir de (m)')); const from=node('input');from.type='text';from.inputMode='decimal';from.className='siteBandFrom'; from.setAttribute('aria-label','Metragem da faixa de '+product.title); fromLabel.append(from); const priceLabel=node('label');priceLabel.append(node('span','R$ por metro')); const bandPrice=node('input');bandPrice.type='text';bandPrice.inputMode='decimal';bandPrice.className='siteBandPrice'; bandPrice.setAttribute('aria-label','Preço da faixa de '+product.title); priceLabel.append(bandPrice); const remove=button('Remover',()=>{row.remove();paintAdd();},'btn ghost'); row.append(fromLabel,priceLabel,remove); return row; }; addBand.onclick=()=>{if(bandRows.children.length>=5)return;bandRows.append(bandRow());paintAdd();}; const bands=node('div',undefined,'siteBands'); const bandsHead=node('div',undefined,'siteBandsHead'); bandsHead.append(node('span','Faixas'),addBand); bands.append(bandsHead,bandRows); const formBands=()=>[...bandRows.children].map(row=>{ const from=Number(row.querySelector('.siteBandFrom').value.replace(',','.')); const unit=moneyInputCents(row.querySelector('.siteBandPrice').value); if(!Number.isFinite(from)||from<=0||unit===null||unit<=0) throw new Error('Confira as faixas: metragem e preço maiores que zero.'); return {from_metres:String(from),unit_cents:unit}; }); 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, bands:product.id==='tratamento'?[]:formBands()}); 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); if(product.id!=='tratamento')form.append(bands); 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]+bandsText(row.bands)+ ' 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)+bandsText(row.bands),'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)); await loadSiteVideos(); } async function loadSiteVideos(){ const host=$('site-videos-list'),panel=$('site-videos-panel'); panel.hidden=!may('manage'); if(panel.hidden)return; const data=await api('/site-videos'); host.replaceChildren(...data.videos.map(video=>{ const row=node('div',undefined,'siteVideoRow'); const heading=node('div',undefined,'siteVideoHeading'); heading.append(node('b',video.title),node('span',video.enabled?'Publicado':'Rascunho','pill'+(video.enabled?' ok':''))); const videoInput=node('input');videoInput.type='file';videoInput.accept='.mp4,.webm,video/mp4,video/webm'; const captionsInput=node('input');captionsInput.type='file';captionsInput.accept='.vtt,text/vtt'; const videoLabel=node('label',undefined,'siteVideoField'); videoLabel.append(node('span','Vídeo · '+(video.video_name||'nenhum arquivo')),videoInput); const captionsLabel=node('label',undefined,'siteVideoField'); captionsLabel.append(node('span','Legenda (opcional) · '+(video.captions_name||'nenhuma legenda')),captionsInput); const product=node('select');product.setAttribute('aria-label','Produto do vídeo '+video.title); for(const [value,title] of [['','Só na categoria DTF'],['file','Arquivo por metro'], ['avulsa','Artes avulsas'],['uvfile','Arquivo por metro UV'],['uv','Artes avulsas UV']]){ const option=node('option',title);option.value=value;product.append(option); } product.value=video.product||''; const productLabel=node('label',undefined,'siteVideoField');productLabel.append(node('span','Vídeo flutuante'),product); const enabled=node('input');enabled.type='checkbox';enabled.checked=video.enabled; const publish=node('label',undefined,'siteVideoToggle');publish.append(enabled,node('span','Publicado no Site')); const errorMessage=node('p',undefined,'siteVideoError');errorMessage.setAttribute('role','alert'); const save=button('Salvar vídeo',async()=>{ save.disabled=true; errorMessage.textContent=''; try{ let uploadId=video.upload_id,captionsId=video.captions_id; if(videoInput.files[0])uploadId=await dtfUpload(videoInput.files[0],{api,startPath:'/site-videos/uploads', scope:'site-video:'+video.id+':video',progress:text=>say(text)}); if(captionsInput.files[0])captionsId=await dtfUpload(captionsInput.files[0],{api,startPath:'/site-videos/uploads', scope:'site-video:'+video.id+':captions',progress:text=>say(text)}); await api('/site-videos/'+video.id,{upload_id:uploadId,captions_id:captionsId, product:product.value||null,enabled:enabled.checked}); say('Vídeo salvo. O Site mostrará a nova versão na próxima abertura.'); await loadSiteVideos(); }catch(error){errorMessage.textContent=error.message;save.disabled=false;} },'btn'); const fields=node('div',undefined,'siteVideoFields'); fields.append(videoLabel,captionsLabel,productLabel,publish,save,errorMessage); row.append(heading,fields);return row; })); }