diff --git a/tests/browser_test.mjs b/tests/browser_test.mjs index a3ad2f2..8d4c99b 100644 --- a/tests/browser_test.mjs +++ b/tests/browser_test.mjs @@ -171,9 +171,15 @@ try{ assert.equal(await kanban.eval('sessionStorage.getItem("dtf-operator")'),null); assert.equal(await kanban.eval('document.getElementById("password").value'),''); await kanban.click('[data-tab="site"]'); + await waitFor(()=>kanban.eval('!!document.querySelector("[data-site-tab=\\"videos\\"]")'),'Site tabs in Gestão'); + await kanban.click('[data-site-tab="videos"]'); await waitFor(()=>kanban.eval('document.querySelectorAll("#site-videos-list .siteVideoRow").length===6'), 'six video slots in Gestão'); - assert.equal(await kanban.eval('document.querySelectorAll("#site-videos-list input[type=file]").length'),12); + assert.equal(await kanban.eval('document.querySelectorAll("#site-videos-list input[type=file]").length'),0); + await kanban.click('#site-videos-list .siteVideoRow .btn'); + await waitFor(()=>kanban.eval('document.querySelectorAll(".modal input[type=file]").length===2'),'video edit dialog'); + await kanban.eval('document.querySelector(".modal .dlghead .btn.sq")?.click()'); + await waitFor(()=>kanban.eval('!document.querySelector(".modal")'),'video dialog closed'); await mkdir('output/local',{recursive:true}); await kanban.eval('document.getElementById("site-videos-panel").scrollIntoView()'); await kanban.screenshot('output/local/kanban-videos.png'); diff --git a/web/kanban-numbers.js b/web/kanban-numbers.js index 994919c..293aacf 100644 --- a/web/kanban-numbers.js +++ b/web/kanban-numbers.js @@ -33,53 +33,95 @@ function statsPeriod(){ wrap.replaceChildren(open); } // The calendar: presets on the left, a month where a click starts the -// period and the next one ends it. -function calendar(){ - const pop=node('div',undefined,'pop calpop');pop.setAttribute('role','dialog');pop.setAttribute('aria-label','Escolher o período'); +// period and the next one ends it. `single`, `future` and `time` add the +// Site's price picker (one future day and a time); without options this is +// exactly the Números range picker. +function calendar(options={}){ + const single=!!options.single, future=!!options.future, withTime=!!options.time; + const onApply=options.onApply||null, onCancel=options.onCancel||null; + const pop=node('div',undefined,'pop calpop'+(single?' single':'')); + pop.setAttribute('role','dialog');pop.setAttribute('aria-label',single?'Escolher a data':'Escolher o período'); pop.onclick=e=>e.stopPropagation(); const today=todayIso(); - let pick=statsRange?{...statsRange}:null, month=new Date((statsRange?.end||today)+'T12:00:00');month.setDate(1); + const initial=options.value||null; + let pick=single + ?(initial?.date?{start:initial.date,end:initial.date}:null) + :statsRange?{...statsRange}:null; + let month=new Date(((single?pick?.start:pick?.end)||today)+'T12:00:00');month.setDate(1); const presets=node('div',undefined,'presets'),grid=node('div',undefined,'dgrid'),title=node('b'); const label=node('span','','lbl'); + const time=node('input');time.type='time';time.className='inp';time.value=initial?.time||'08:00'; const apply=node('button','Aplicar','btn pri');apply.type='button'; - const cancel=node('button','Cancelar','btn ghost right');cancel.type='button';cancel.onclick=()=>pop.remove(); - apply.onclick=()=>{if(!pick?.end)return;statsRange=pick;pop.remove();loadStats().catch(e=>say(e.message,true));}; - const back=n=>{const d=new Date(today+'T12:00:00');d.setDate(d.getDate()-n);return isoDay(d);}; - const first=new Date(today+'T12:00:00');first.setDate(1); - const prevEnd=new Date(first);prevEnd.setDate(0);const prevStart=new Date(prevEnd);prevStart.setDate(1); - for(const [text,range] of [['Hoje',[today,today]],['Últimos 7 dias',[back(6),today]],['Últimos 30 dias',[back(29),today]], - ['Este mês',[isoDay(first),today]],['Mês passado',[isoDay(prevStart),isoDay(prevEnd)]],['Últimos 90 dias',[back(89),today]]]){ - const b=node('button',text,'preset');b.type='button';b.dataset.range=range.join('|'); - b.onclick=()=>{pick={start:range[0],end:range[1]};month=new Date(range[1]+'T12:00:00');month.setDate(1);paint();};presets.append(b); + const cancel=node('button','Cancelar','btn ghost right');cancel.type='button'; + cancel.onclick=()=>{onCancel?.();pop.remove();}; + apply.onclick=()=>{ + if(single){ + if(!pick?.start)return; + if(onApply)onApply({date:pick.start,time:withTime?time.value||'08:00':null}); + pop.remove();return; + } + if(!pick?.end)return; + if(onApply){onApply({start:pick.start,end:pick.end});pop.remove();return;} + statsRange=pick;pop.remove();loadStats().catch(e=>say(e.message,true)); + }; + if(!single){ + const back=n=>{const d=new Date(today+'T12:00:00');d.setDate(d.getDate()-n);return isoDay(d);}; + const first=new Date(today+'T12:00:00');first.setDate(1); + const prevEnd=new Date(first);prevEnd.setDate(0);const prevStart=new Date(prevEnd);prevStart.setDate(1); + for(const [text,range] of [['Hoje',[today,today]],['Últimos 7 dias',[back(6),today]],['Últimos 30 dias',[back(29),today]], + ['Este mês',[isoDay(first),today]],['Mês passado',[isoDay(prevStart),isoDay(prevEnd)]],['Últimos 90 dias',[back(89),today]]]){ + const b=node('button',text,'preset');b.type='button';b.dataset.range=range.join('|'); + b.onclick=()=>{pick={start:range[0],end:range[1]};month=new Date(range[1]+'T12:00:00');month.setDate(1);paint();};presets.append(b); + } } const prev=iconButton(IC.left,'Mês anterior',()=>{month.setMonth(month.getMonth()-1);paint();},'btn sq ghost'); const next=iconButton(IC.right,'Próximo mês',()=>{month.setMonth(month.getMonth()+1);paint();},'btn sq ghost'); const head=node('div',undefined,'mhd');head.append(title,prev,next); function paint(){ title.textContent=month.toLocaleDateString('pt-BR',{month:'long',year:'numeric'}).replace(/^./,c=>c.toUpperCase()); - next.disabled=isoDay(month)>=today.slice(0,8)+'01'; + next.disabled=future?false:isoDay(month)>=today.slice(0,8)+'01'; for(const b of presets.children){const [a,z]=b.dataset.range.split('|');b.classList.toggle('on',!!pick&&pick.start===a&&pick.end===z);} const days=[...['D','S','T','Q','Q','S','S'].map(w=>node('span',w,'dow'))]; const start=new Date(month);start.setDate(1-start.getDay()); for(let i=0;i<42;i++){ const d=new Date(start);d.setDate(start.getDate()+i);const iso=isoDay(d); if(i>=35&&d.getMonth()!==month.getMonth())break; - const end=pick?.end||pick?.start; - const cls=['day'];if(d.getMonth()!==month.getMonth())cls.push('mute');if(iso>today)cls.push('future');if(iso===today)cls.push('today'); - if(pick&&iso===pick.start)cls.push('s');if(pick&&iso===end)cls.push('e');if(pick&&iso>pick.start&&iso=today:iso<=today; + const cls=['day'];if(d.getMonth()!==month.getMonth())cls.push('mute');if(!allowed)cls.push('future');if(iso===today)cls.push('today'); + if(single){ + if(pick&&iso===pick.start)cls.push('s'); + }else{ + const end=pick?.end||pick?.start; + if(pick&&iso===pick.start)cls.push('s');if(pick&&iso===end)cls.push('e');if(pick&&iso>pick.start&&isotoday; - b.onclick=()=>{if(!pick||pick.end)pick={start:iso,end:null};else if(iso{ + if(single)pick={start:iso,end:iso}; + else if(!pick||pick.end)pick={start:iso,end:null}; + else if(isopaint(); const monthBox=node('div',undefined,'month');monthBox.append(head,grid); - const body=node('div',undefined,'cal');body.append(presets,monthBox); + const body=node('div',undefined,'cal'+(single?' single':'')); + if(single)body.append(monthBox);else body.append(presets,monthBox); + const timeBox=node('div',undefined,'time'); + if(withTime)timeBox.append(node('span','Horário'),time); const foot=node('div',undefined,'popfoot');foot.append(label,cancel,apply); - pop.append(body,foot);paint(); + pop.append(body,...(withTime?[timeBox]:[]),foot);paint(); document.addEventListener('click',()=>pop.remove(),{once:true}); return pop; } diff --git a/web/kanban-site.js b/web/kanban-site.js index f271f36..13320f3 100644 --- a/web/kanban-site.js +++ b/web/kanban-site.js @@ -3,7 +3,21 @@ 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',arte:' por arte'}; +const SITE_TAB_KEY='dtf-site-tab'; +const SITE_TICKET='M232,104a8,8,0,0,0,8-8V64a16,16,0,0,0-16-16H32A16,16,0,0,0,16,64V96a8,8,0,0,0,8,8,24,24,0,0,1,0,48,8,8,0,0,0-8,8v32a16,16,0,0,0,16,16H224a16,16,0,0,0,16-16V160a8,8,0,0,0-8-8,24,24,0,0,1,0-48ZM32,167.2a40,40,0,0,0,0-78.4V64H88V192H32Zm192,0V192H104V64H224V88.8a40,40,0,0,0,0,78.4Z'; +const SITE_TABS=[ + {id:'products',label:'Produtos e preços',note:'Um produto desligado some do Site e não aceita pedidos novos.'}, + {id:'coupons',label:'Cupons',note:'Um cupom por pedido.'}, + {id:'grade',label:'Nota da arte',note:'A regra do Ajuste Fino precisa ser menor ou igual à do aviso.'}, + {id:'videos',label:'Vídeos',note:'MP4 ou WebM até 500 MB; legenda VTT opcional. Só aparece no Site depois de publicado.'}, +]; +const SITE_VIDEO_PRODUCTS=[['','Só na categoria DTF'],['file','Arquivo por metro'], + ['avulsa','Artes avulsas'],['uvfile','Arquivo por metro UV'],['uv','Artes avulsas UV']]; +let siteTab=(()=>{ + try{const saved=localStorage.getItem(SITE_TAB_KEY);return SITE_TABS.some(t=>t.id===saved)?saved:'products';} + catch(_){return 'products';} +})(); +let siteProducts=[],siteCoupons=[],siteVideos=[],siteRules={}; // Reais with a comma, as the Site shows them: "19,90" is 1990 cents. function moneyInputCents(value){ @@ -24,234 +38,359 @@ function bandsText(bands,unit='metro'){ return (bands||[]).map(band=>' · '+bandMetres(band.from_metres)+' '+ (unit==='arte'?(Number(band.from_metres)===1?'arte':'artes'):'m')+': '+money(band.unit_cents)).join(''); } +function siteQty(value,unit){ + const n=Number(value); + if(unit==='arte')return bandMetres(n)+(n===1?' arte':' artes'); + return bandMetres(n)+' m'; +} +function siteTomorrow(){ + const d=new Date(todayIso()+'T12:00:00');d.setDate(d.getDate()+1);return isoDay(d); +} +function siteDateText(value){ + if(!value)return 'Escolher data'; + const d=new Date(value.date+'T'+(value.time||'08:00')+':00'); + if(Number.isNaN(d.getTime()))return 'Escolher data'; + const day=d.toLocaleDateString('pt-BR',{day:'2-digit',month:'short',year:'numeric'}) + .replace(/\./g,'').replace(/ de /g,' '); + return day+', '+(value.time||'08:00'); +} +// ---- Tabs ----------------------------------------------------------------- +function saveSiteTab(id){ + try{localStorage.setItem(SITE_TAB_KEY,id);}catch(_){} +} +function paintSiteTabs(){ + const host=$('site-tabs');if(!host)return; + host.replaceChildren(...SITE_TABS.map(tab=>{ + const b=node('button');b.type='button';b.dataset.siteTab=tab.id; + b.setAttribute('role','tab');b.setAttribute('aria-selected',String(siteTab===tab.id)); + if(siteTab===tab.id)b.classList.add('on'); + b.append(node('span',tab.label)); + if(tab.id==='coupons')b.append(node('span',String(siteCoupons.length),'n')); + if(tab.id==='videos')b.append(node('span',String(siteVideos.length),'n')); + b.onclick=()=>openSiteTab(tab.id); + return b; + })); + const current=SITE_TABS.find(tab=>tab.id===siteTab)||SITE_TABS[0]; + $('site-note').textContent=current.note; + for(const tab of SITE_TABS){ + const pane=$('site-pane-'+tab.id); + if(pane)pane.hidden=tab.id!==siteTab; + } +} +function openSiteTab(id){ + if(!SITE_TABS.some(tab=>tab.id===id))return; + siteTab=id;saveSiteTab(id);paintSiteTabs(); +} + +// ---- Produtos e preços (S1) ----------------------------------------------- +function renderSiteProducts(){ + const host=$('site-products');if(!host)return; + host.replaceChildren(...siteProducts.map(siteProductRow)); + const enabled=siteProducts.filter(product=>product.enabled).length; + $('site-sub').textContent=enabled+' de '+siteProducts.length+' produtos à venda'; +} +function siteBandTag(band,unit){return siteQty(band.from_metres,unit)+': '+money(band.unit_cents);} 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; + const tr=node('tr',undefined,product.enabled?'':'off'); + const name=node('td'); + name.append(node('span',product.title,'pname'),node('span',product.unit,'unit')); + const sale=node('td');sale.dataset.label='À venda'; + const sw=node('button',undefined,'sw'+(product.enabled?' on':'')); + sw.type='button';sw.setAttribute('role','switch');sw.setAttribute('aria-checked',String(product.enabled)); + sw.append(node('span',undefined,'t'),product.enabled?'Ligado':'Desligado'); + sw.onclick=async()=>{ + sw.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 api('/site/products/'+product.id,{enabled:!product.enabled}); + say(product.title+(product.enabled?' desligado.':' ligado.')); await loadSiteAdmin(); - }catch(error){input.checked=!input.checked;say(error.message,true);} - finally{input.disabled=false;} + }catch(error){say(error.message,true);sw.disabled=false;} }; - label.append(input,word); - state.append(label); - tr.append(name,state,price); + sale.append(sw); + const price=node('td',undefined,'r');price.dataset.label='Preço atual'; + price.append(node('span',money(product.unit_cents),'money')); + if(product.fallback)price.append(node('span',' · padrão','muted')); + const bands=node('td');bands.dataset.label='Faixas'; + if(product.id==='redesenho')bands.append(node('span','preço único','muted')); + else if((product.bands||[]).length){ + for(const band of product.bands)bands.append(node('span',siteBandTag(band,product.unit),'tag')); + }else bands.append(node('span','—','muted')); + const next=node('td');next.dataset.label='Próxima mudança'; + if(product.scheduled.length){ + for(const row of product.scheduled){ + const line=node('div',undefined,'siteNext'); + line.append(node('b',money(row.unit_cents)),node('span',when(row.starts_at),'muted')); + next.append(line); + } + }else next.append(node('span','nenhuma','muted')); + const action=node('td',undefined,'r siteAction'); + action.append(button('Mudar preço',()=>priceDialog(product),'btn sm')); + tr.append(name,sale,price,bands,next,action); return tr; } -function sitePriceBlock(product){ - const block=node('div',undefined,'sitePriceBlock'); - const heading=node('h3',product.title); - heading.append(node('span',' · '+product.unit,'muted')); +// A live line of what the customer will see: the base price up to the first +// band, then each band's range, and the last one open-ended. +function siteBandPreview(base,rows,unit){ + if(base===null)return 'Informe o preço acima para ver o que o cliente vê.'; + const valid=rows.filter(row=>Number.isFinite(row.from)&&row.from>0&&row.cents!==null&&row.cents>0) + .sort((a,b)=>a.from-b.from); + if(!valid.length)return '1 '+(unit==='arte'?'arte':'m')+' ou mais por '+money(base)+'.'; + const parts=[]; + let start=1,price=base; + for(const row of valid){ + if(row.from>start){ + const end=unit==='arte'?row.from-1:Number.isInteger(row.from)?row.from-1:Number((row.from-0.1).toFixed(1)); + if(end>=start)parts.push(bandMetres(start)+' a '+siteQty(end,unit)+' por '+money(price)); + } + start=row.from;price=row.cents; + } + parts.push('a partir de '+siteQty(start,unit)+', '+money(price)); + return parts.join(' · '); +} - // 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. Ajuste Fino conta as faixas em artes, os produtos em - // metros. O Redesenho tem um preço único por arte, nunca faixas (front 1b). +function priceDialog(product){ + const unit=product.unit==='arte'?'arte':'metro'; + const current=product.unit_cents; const permiteFaixas=product.id!=='redesenho'; - const bandUnit=product.unit==='arte'?'artes':'m'; - 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 ('+bandUnit+')')); - const from=node('input');from.type='text';from.inputMode='decimal';from.className='siteBandFrom'; - from.setAttribute('aria-label','Início da faixa em '+bandUnit+' de '+product.title); - fromLabel.append(from); - const priceLabel=node('label');priceLabel.append(node('span','R$ por '+(product.unit==='arte'?'arte':'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: início e preço maiores que zero.'); - return {from_metres:String(from),unit_cents:unit}; - }); - const save=button('Salvar',async()=>{ - // Empty keeps the current price (the grey hint), so a band alone can be added. - const cents=price.value.trim()?moneyInputCents(price.value):product.unit_cents>0?product.unit_cents:null; - 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:permiteFaixas?formBands():[]}); - say(whenDate?'Preço salvo para '+when(whenDate)+'.':'Preço salvo. Vale a partir de agora.'); - await loadSiteAdmin(); - },'btn pri'); - // Salvar after the bands: it saves the price and its bands together. - form.append(priceLabel,startsLabel,...(permiteFaixas?[bands]:[]),save); + let mode='now',chosen=null,m=null; + const bandRows=[]; - 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,product.unit)+ - ' a partir de '+when(row.starts_at))); + const now=node('div',undefined,'sitePriceNow'); + now.append(node('b',current>0?money(current):'Sem preço'),node('span','por '+unit+' · preço em vigor')); + + const priceInput=node('input');priceInput.type='text';priceInput.inputMode='decimal';priceInput.className='siteInp'; + priceInput.placeholder=current>0?(current/100).toFixed(2).replace('.',','):'0,00'; + const priceBox=node('span',undefined,'inp siteInpBox');priceBox.append(node('span','R$','pre'),priceInput); + const priceField=node('div',undefined,'fld'); + priceField.append(node('span','Novo preço por '+unit),priceBox, + node('small',current>0?'Vazio: mantém '+money(current)+'.':'Informe o preço em reais.')); + + const modeSeg=node('div',undefined,'seg');modeSeg.setAttribute('role','radiogroup'); + modeSeg.setAttribute('aria-label','Quando começa'); + const nowBtn=node('button','Agora');nowBtn.type='button';nowBtn.setAttribute('role','radio'); + const laterBtn=node('button','Agendar');laterBtn.type='button';laterBtn.setAttribute('role','radio'); + modeSeg.append(nowBtn,laterBtn); + const dateText=node('span','Escolher data'); + const dateButton=node('button',undefined,'inp');dateButton.type='button'; + dateButton.setAttribute('aria-haspopup','dialog');dateButton.setAttribute('aria-expanded','false'); + dateButton.append(svgIcon(IC.calendar,'i m'),dateText); + const dateWrap=node('div',undefined,'calwrap');dateWrap.append(dateButton); + const startRow=node('div',undefined,'siteStartRow');startRow.append(modeSeg,dateWrap); + const startField=node('div',undefined,'fld');startField.append(node('span','Começa'),startRow); + + const paintDate=()=>{dateText.textContent=siteDateText(chosen);}; + const setSaveLabel=()=>{ + const save=m?.box.querySelector('.dfoot .btn.pri'); + if(save)save.textContent=mode==='schedule'?'Agendar preço':'Salvar preço'; + }; + const setMode=next=>{ + mode=next; + nowBtn.classList.toggle('on',next==='now');nowBtn.setAttribute('aria-checked',String(next==='now')); + laterBtn.classList.toggle('on',next==='schedule');laterBtn.setAttribute('aria-checked',String(next==='schedule')); + dateWrap.hidden=next!=='schedule'; + if(next==='schedule'&&!chosen)chosen={date:siteTomorrow(),time:'08:00'}; + paintDate();setSaveLabel(); + }; + nowBtn.onclick=()=>setMode('now'); + laterBtn.onclick=()=>setMode('schedule'); + dateButton.onclick=event=>{ + event.stopPropagation(); + const open=dateWrap.querySelector('.pop'); + if(open){open.remove();dateButton.setAttribute('aria-expanded','false');return;} + dateButton.setAttribute('aria-expanded','true'); + dateWrap.append(calendar({single:true,future:true,time:true,value:chosen,onApply:value=>{ + chosen=value;paintDate();dateButton.setAttribute('aria-expanded','false'); + }})); + }; + + const bandsSection=node('div',undefined,'siteDlgSection'); + const bandsTitle=node('h3');bandsTitle.append('Faixas por quantidade',node('span',' · opcional','siteSoft')); + bandsSection.append(bandsTitle); + let preview=null,addBand=null,baseValue=null; + const paintBase=()=>{ + const typed=priceInput.value.trim(); + const cents=typed?moneyInputCents(typed):current>0?current:null; + if(baseValue)baseValue.textContent=cents===null?'—':money(cents); + }; + const paintPreview=()=>{ + if(!preview)return; + const typed=priceInput.value.trim(); + const base=typed?moneyInputCents(typed):current>0?current:null; + const rows=bandRows.map(row=>({from:Number(row.from.value.replace(',','.')), + cents:moneyInputCents(row.price.value)})); + const line=siteBandPreview(base,rows,unit); + preview.replaceChildren(node('span','O cliente vê: '),node('b',line)); + }; + const paintAdd=()=>{if(addBand)addBand.disabled=bandRows.length>=5;}; + const bandRow=()=>{ + const row=node('tr'); + const fromCell=node('td'); + const fromBox=node('span',undefined,'inp siteInpBox'); + const from=node('input');from.type='text';from.inputMode='decimal';from.className='siteInp';from.placeholder='10'; + fromBox.append(from,node('span',unit==='arte'?'artes':'m','pre siteSuffix')); + fromCell.append(fromBox); + const priceCell=node('td'); + const priceInput2=node('input');priceInput2.type='text';priceInput2.inputMode='decimal';priceInput2.className='siteInp'; + priceInput2.placeholder='0,00'; + const priceBox2=node('span',undefined,'inp siteInpBox');priceBox2.append(node('span','R$','pre'),priceInput2); + priceCell.append(priceBox2); + const action=node('td'); + const entry={row,from,price:priceInput2}; + action.append(button('Tirar',()=>{ + row.remove();bandRows.splice(bandRows.indexOf(entry),1);paintAdd();paintPreview(); + },'btn ghost sm')); + row.append(fromCell,priceCell,action); + from.oninput=paintPreview;priceInput2.oninput=paintPreview; + return entry; + }; + if(permiteFaixas){ + const bandsBox=node('div',undefined,'siteBands'); + const table=node('table'); + const thead=node('thead'),headRow=node('tr'); + headRow.append(node('th','A partir de'),node('th','R$ por '+unit),node('th','')); + thead.append(headRow); + const tbody=node('tbody'); + const baseRow=node('tr',undefined,'base'); + const baseFrom=node('td',siteQty(1,unit)); + const basePrice=node('td'); + baseValue=node('b'); + basePrice.append(baseValue,node('span',' · o preço acima','siteSoft')); + baseRow.append(baseFrom,basePrice,node('td')); + tbody.append(baseRow); + const addRow=node('tr',undefined,'add'); + const addCell=node('td');addCell.colSpan=3; + addBand=button('Adicionar faixa',()=>{ + if(bandRows.length>=5)return; + const entry=bandRow();bandRows.push(entry); + tbody.insertBefore(entry.row,addRow);paintAdd();paintPreview(); + },'btn ghost sm'); + addBand.prepend(svgIcon(IC.plus,'i m')); + addCell.append(addBand);addRow.append(addCell);tbody.append(addRow); + table.append(thead,tbody);bandsBox.append(table); + preview=node('p',undefined,'siteSee'); + bandsSection.append(bandsBox,preview); + }else bandsSection.append(node('p','Preço único por arte, sem faixas.','siteSoft')); + + const history=node('div',undefined,'siteDlgSection'); + const paintHistory=()=>{ + history.replaceChildren(node('h3','Histórico')); + const scheduledIds=new Set(product.scheduled.map(row=>row.id)); + const past=product.history.filter(row=>!scheduledIds.has(row.id)) + .sort((a,b)=>new Date(b.starts_at)-new Date(a.starts_at)); + if(!product.scheduled.length&&!past.length){ + history.append(node('p','Nenhuma mudança ainda. Preço agendado aparece aqui e pode ser cancelado até começar.','siteSoft')); + return; + } + for(const row of product.scheduled)history.append(historyRow(row,true)); + for(const row of past)history.append(historyRow(row,false)); + }; + const historyRow=(row,scheduled)=>{ + const line=node('div',undefined,'siteHistRow'); + const main=node('div',undefined,'siteHistMain'); + main.append(node('b',money(row.unit_cents)),node('span',when(row.starts_at)), + node('span',(row.bands||[]).length?bandsText(row.bands,unit):'sem faixas','siteSoft'), + ...(row.created_by?[node('span',row.created_by,'siteSoft')]:[])); + line.append(main); + if(scheduled){ 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,product.unit),'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; -} - -// ── Nota da arte (front 8.5) ──────────────────────────────────────────────── -function ensureGradePanel(){ - let panel=$('site-grade-panel'); - if(panel)return panel; - panel=node('section',undefined,'panel clip');panel.id='site-grade-panel'; - const head=node('div',undefined,'phead');head.append(node('h2','Nota da arte')); - panel.append(head,node('p','A menor nota dos itens do pedido decide. Sem regra, a nota não muda nada.','phint')); - const body=node('div',undefined,'siteGradeBody');body.id='site-grade-body';panel.append(body); - const coupons=$('site-coupons-panel'); - if(coupons)coupons.before(panel); - else{ - const videos=$('site-videos-panel'); - if(videos)videos.before(panel);else $('tab-site').append(panel); - } - return panel; -} - -function gradeRuleRow(label, value){ - const row=node('div',undefined,'siteGradeRow'); - const on=node('input');on.type='checkbox';on.checked=value!=null; - const word=node('span',on.checked?'Ligado':'Desligado'); - const toggle=node('label',undefined,'siteSwitch');toggle.append(on,word); - const num=node('input');num.type='number';num.min='1';num.max='100';num.step='1'; - num.className='siteGradeNumber';num.value=value!=null?String(value):'';num.disabled=!on.checked; - on.onchange=()=>{ - word.textContent=on.checked?'Ligado':'Desligado'; - num.disabled=!on.checked; - if(on.checked)num.focus(); + product.scheduled=product.scheduled.filter(item=>item.id!==row.id); + product.history=product.history.filter(item=>item.id!==row.id); + paintHistory();await loadSiteAdmin(); + },'btn ghost sm')); + }else line.append(node('span','já começou','siteSoft')); + return line; }; - const fieldLabel=node('label',undefined,'siteGradeField'); - fieldLabel.append(node('span',label),num); - row.append(toggle,fieldLabel); - return {row,on,num}; + const formBands=()=>bandRows.map(row=>{ + const from=Number(row.from.value.replace(',','.')); + const cents=moneyInputCents(row.price.value); + if(!Number.isFinite(from)||from<=0||cents===null||cents<=0) + throw new Error('Confira as faixas: início e preço maiores que zero.'); + return {from_metres:String(from),unit_cents:cents}; + }); + + m=formDialog(product.title,{width:640,className:'siteDialog', + text:(product.enabled?'Ligado':'Desligado')+' · por '+unit, + fields:[now,priceField,startField,bandsSection,history],label:'Salvar preço', + onsave:async()=>{ + const typed=priceInput.value.trim(); + const cents=typed?moneyInputCents(typed):current>0?current:null; + if(cents===null)throw new Error('Informe o preço em reais, como 19,90.'); + let starts_at=null; + if(mode==='schedule'){ + if(!chosen)throw new Error('Escolha a data e o horário em que o preço começa.'); + const date=new Date(chosen.date+'T'+(chosen.time||'08:00')+':00'); + if(Number.isNaN(date.getTime()))throw new Error('Data inválida.'); + starts_at=date.toISOString(); + } + await api('/site/products/'+product.id+'/prices',{unit_cents:cents,starts_at, + bands:permiteFaixas?formBands():[]}); + say(starts_at?'Preço salvo para '+when(starts_at)+'.':'Preço salvo. Vale a partir de agora.'); + await loadSiteAdmin(); + }}); + priceInput.oninput=()=>{paintBase();paintPreview();}; + setMode('now');paintBase();paintPreview();paintHistory();paintAdd(); } -async function loadGradeRules(){ - if(!may('manage'))return; - ensureGradePanel(); - const data=await api('/site/grade-rules'); - const aviso=gradeRuleRow('Avisar o designer abaixo de',data.aviso); - const tratamento=gradeRuleRow('Exigir o Ajuste Fino abaixo de',data.tratamento); - const save=button('Salvar',async()=>{ - const avisoValue=aviso.on.checked?Number(aviso.num.value):null; - const tratamentoValue=tratamento.on.checked?Number(tratamento.num.value):null; - for(const value of [avisoValue,tratamentoValue]) - if(value!==null&&(!Number.isInteger(value)||value<1||value>100)) - throw new Error('A nota vai de 1 a 100.'); - if(avisoValue!==null&&tratamentoValue!==null&&tratamentoValue>avisoValue) - throw new Error('A regra do Ajuste Fino precisa ser menor ou igual à do aviso.'); - await api('/site/grade-rules',{aviso:avisoValue,tratamento:tratamentoValue}); - say('Regras da nota da arte salvas.'); - await loadGradeRules(); - },'btn pri'); - const children=[aviso.row,tratamento.row]; - if(!data.treatment_offered) - children.push(node('p','Ative e dê preço ao Ajuste Fino para esta regra valer.','siteGradeWarn')); - const foot=node('div',undefined,'siteGradeSave');foot.append(save);children.push(foot); - $('site-grade-body').replaceChildren(...children); -} - -// ── Cupons (front 8.3) ────────────────────────────────────────────────────── -// A "ficha" of the date in the browser's timezone, for datetime-local inputs. +// ---- Cupons (S3) ---------------------------------------------------------- function couponDate(iso){ const d=new Date(iso),p=n=>String(n).padStart(2,'0'); return d.getFullYear()+'-'+p(d.getMonth()+1)+'-'+p(d.getDate())+'T'+p(d.getHours())+':'+p(d.getMinutes()); } - -function ensureCouponsPanel(){ - let panel=$('site-coupons-panel'); - if(panel)return panel; - panel=node('section',undefined,'panel clip');panel.id='site-coupons-panel'; - const head=node('div',undefined,'phead'); - head.append(node('h2','Cupons'),button('Novo cupom',()=>couponDialog(null),'btn right')); - panel.append(head,node('p','Cupons de desconto do checkout: validade, mínimo de metros, limite de usos e produto. Um cupom por pedido.','phint')); - const list=node('div',undefined,'siteCouponList');list.id='site-coupons';panel.append(list); - const videos=$('site-videos-panel'); - if(videos)videos.before(panel); else $('tab-site').append(panel); - return panel; +function couponStatus(coupon){ + if(coupon.paused)return ['Pausado','warn']; + if(coupon.valid_until&&new Date(coupon.valid_until)<=new Date())return ['Expirado','']; + return ['Ativo','ok']; +} +function renderSiteCoupons(){ + const host=$('site-coupons');if(!host)return; + if(!siteCoupons.length){ + const panel=node('section',undefined,'panel clip'); + const box=emptyState(SITE_TICKET,'Nenhum cupom ainda', + 'Cupom dá desconto no checkout, com validade, mínimo de metros e limite de usos. Um por pedido.'); + box.append(button('Novo cupom',()=>couponDialog(null),'btn pri')); + panel.append(box);host.replaceChildren(panel); + return; + } + const tools=node('div',undefined,'siteTools'); + tools.append(node('span',siteCoupons.length+(siteCoupons.length===1?' cupom':' cupons'),'siteSoft'), + button('Novo cupom',()=>couponDialog(null),'btn pri')); + const table=node('table',undefined,'dtable site-table'); + const head=node('thead'),headRow=node('tr'); + for(const title of ['Código','Desconto','Produto','Validade','Usos','Situação','Ações']){ + const th=node('th',title);if(title==='Ações')th.className='r';headRow.append(th); + } + head.append(headRow); + const body=node('tbody');body.replaceChildren(...siteCoupons.map(couponRow)); + table.append(head,body); + const panel=node('section',undefined,'panel clip');panel.append(table); + host.replaceChildren(tools,panel); } - function couponRow(coupon){ - const expired=coupon.valid_until && new Date(coupon.valid_until)<=new Date(); - const status=coupon.paused?['Pausado','warn']:expired?['Expirado','']:['Ativo','ok']; - const row=node('div',undefined,'siteCouponRow'); - const top=node('div',undefined,'siteCouponTop'); - top.append(node('b',coupon.code),badge(status[0],status[1]), - node('span',coupon.kind==='percent'?coupon.value+'%':money(coupon.value)+'/m','siteCouponOffer')); - const meta=node('div',undefined,'siteCouponMeta'); - meta.append(node('span','Validade: de '+when(coupon.valid_from)+ - (coupon.valid_until?' até '+when(coupon.valid_until):' sem fim')), - node('span','Produto: '+(coupon.product?SHORT[coupon.product]:'todos')), - node('span','Usos: '+coupon.uses+(coupon.max_uses?' de '+coupon.max_uses:''))); - const actions=node('div',undefined,'siteCouponActions'); + const tr=node('tr'); + const code=node('td');code.append(node('b',coupon.code,'code')); + if(coupon.note)code.append(node('span',coupon.note,'sub')); + const offer=node('td');offer.dataset.label='Desconto'; + offer.append(node('b',coupon.kind==='percent'?coupon.value+'%':money(coupon.value)+'/m')); + const product=node('td',coupon.product?SHORT[coupon.product]:'Todos');product.dataset.label='Produto'; + const valid=node('td');valid.dataset.label='Validade'; + valid.append(node('span',when(coupon.valid_from)+(coupon.valid_until?' a '+when(coupon.valid_until):' sem fim'))); + const uses=node('td');uses.dataset.label='Usos'; + uses.append(node('span',coupon.uses+(coupon.max_uses?' de '+coupon.max_uses:'')), + ...(coupon.max_uses_per_customer?[node('span',coupon.max_uses_per_customer+' por cliente','sub')]:[])); + const [status,tone]=couponStatus(coupon); + const situation=node('td');situation.dataset.label='Situação'; + situation.append(node('span',status,'tag'+(tone?' '+tone:''))); + const actions=node('td',undefined,'r siteAction'); actions.append(button(coupon.paused?'Retomar':'Pausar',async()=>{ await api('/site/coupons/'+coupon.id,{paused:!coupon.paused}); say('Cupom '+coupon.code+(coupon.paused?' retomado.':' pausado.')); await loadSiteCoupons(); - },'btn'), - button('Editar',()=>couponDialog(coupon),'btn ghost'), + },'btn sm'), + button('Editar',()=>couponDialog(coupon),'btn sm ghost'), button('Apagar',async()=>{ if(!(await ask('Apagar cupom', 'O cupom '+coupon.code+' deixa de valer. Os pedidos que já o usaram continuam no histórico.', @@ -259,25 +398,27 @@ function couponRow(coupon){ await api('/site/coupons/'+coupon.id+'/delete',{}); say('Cupom '+coupon.code+' apagado.'); await loadSiteCoupons(); - },'btn quiet')); - row.append(top,meta,actions); - if(coupon.note)row.append(node('p',coupon.note,'siteCouponNote')); - return row; + },'btn sm quiet')); + tr.append(code,offer,product,valid,uses,situation,actions); + return tr; } - function couponDialog(coupon){ const editing=!!coupon; const code=node('input');code.maxLength=30;code.value=coupon?coupon.code:'';code.placeholder='Ex.: REINA-2026'; if(editing)code.disabled=true; - const kind=node('select'); - for(const [value,label] of [['percent','Porcentagem (%)'],['per_metre','Por metro (R$)']]){ - const option=node('option',label);option.value=value;kind.append(option); - } - kind.value=coupon?coupon.kind:'percent'; - const pct=node('input');pct.type='number';pct.min='1';pct.max='90';pct.step='1'; + let kind=coupon?coupon.kind:'percent'; + const kindSeg=node('div',undefined,'seg full');kindSeg.setAttribute('role','radiogroup'); + kindSeg.setAttribute('aria-label','Tipo de desconto'); + const pctBtn=node('button','Porcentagem');pctBtn.type='button';pctBtn.setAttribute('role','radio'); + const metreBtn=node('button','Por metro');metreBtn.type='button';metreBtn.setAttribute('role','radio'); + kindSeg.append(pctBtn,metreBtn); + const pct=node('input');pct.type='number';pct.min='1';pct.max='90';pct.step='1';pct.className='siteInp'; pct.value=coupon&&coupon.kind==='percent'?String(coupon.value):''; - const price=node('input');price.type='text';price.inputMode='decimal';price.placeholder='2,00'; + const pctBox=node('span',undefined,'inp siteInpBox');pctBox.append(pct,node('span','%','pre siteSuffix')); + const price=node('input');price.type='text';price.inputMode='decimal';price.className='siteInp'; + price.placeholder='2,00'; if(coupon&&coupon.kind==='per_metre')price.value=(coupon.value/100).toFixed(2).replace('.',','); + const priceBox=node('span',undefined,'inp siteInpBox');priceBox.append(node('span','R$','pre'),price); const from=node('input');from.type='datetime-local';from.value=coupon?couponDate(coupon.valid_from):''; const until=node('input');until.type='datetime-local'; until.value=coupon&&coupon.valid_until?couponDate(coupon.valid_until):''; @@ -293,27 +434,37 @@ function couponDialog(coupon){ } product.value=coupon?coupon.product||'':''; const note=node('textarea');note.maxLength=1000;note.value=coupon?coupon.note:''; - const pctField=field('Desconto (%)',pct,'De 1 a 90.'); - const priceField=field('Desconto por metro (R$)',price,'Valor em reais por metro, como 2,00.'); - const paint=()=>{pctField.hidden=kind.value!=='percent';priceField.hidden=kind.value!=='per_metre';}; - kind.onchange=paint;paint(); - const fields=[ - field('Código',code,editing?'O código não muda depois de criado.':'De 3 a 30 letras, números ou hífens.'), - field('Tipo de desconto',kind), - pctField,priceField, - field('Válido a partir de',from,'Vazio: agora.'), - field('Válido até',until,'Vazio: sem fim.'), - field('Mínimo de metros',min,'Vazio: sem mínimo. Conta só os metros dos itens do produto.'), + const descHint=node('small'); + const descField=node('div',undefined,'fld'); + descField.append(node('span','Desconto'),pctBox,priceBox,descHint); + const paint=()=>{ + pctBtn.classList.toggle('on',kind==='percent');pctBtn.setAttribute('aria-checked',String(kind==='percent')); + metreBtn.classList.toggle('on',kind==='per_metre');metreBtn.setAttribute('aria-checked',String(kind==='per_metre')); + pctBox.hidden=kind!=='percent';priceBox.hidden=kind!=='per_metre'; + descHint.textContent=kind==='percent'?'De 1 a 90.':'Valor em reais por metro, como 2,00.'; + }; + pctBtn.onclick=()=>{kind='percent';paint();}; + metreBtn.onclick=()=>{kind='per_metre';paint();}; + paint(); + const kindField=node('div',undefined,'fld');kindField.append(node('span','Tipo de desconto'),kindSeg); + const row1=node('div',undefined,'g2'); + row1.append(field('Código',code,editing?'O código não muda depois de criado.':'De 3 a 30 letras, números ou hífens.'), + field('Produto',product,'Todos os produtos, ou só um.')); + const row2=node('div',undefined,'g2');row2.append(kindField,descField); + const row3=node('div',undefined,'g2'); + row3.append(field('Válido a partir de',from,'Vazio: agora.'),field('Válido até',until,'Vazio: sem fim.')); + const row4=node('div',undefined,'g3'); + row4.append(field('Mínimo de metros',min,'Vazio: sem mínimo. Conta só os metros dos itens do produto.'), field('Limite de usos',max,'Vazio: sem limite.'), - field('Limite por cliente',per,'Vazio: sem limite.'), - field('Produto',product,'Todos os produtos, ou só um.'), - field('Observação',note,'Aparece só no Kanban.'), - ]; - formDialog(editing?'Editar cupom':'Novo cupom',{width:640,fields,label:'Salvar cupom',onsave:async()=>{ + field('Limite por cliente',per,'Vazio: sem limite.')); + formDialog(editing?'Editar cupom':'Novo cupom',{width:640,className:'siteDialog', + text:'Desconto no checkout. Um cupom por pedido.',fields:[row1,row2,row3,row4, + field('Observação',note,'Aparece só no Kanban.')], + label:editing?'Salvar cupom':'Criar cupom',onsave:async()=>{ const rawMin=min.value.trim().replace(',','.'); const payload={ - kind:kind.value, - value:kind.value==='percent'?Number(pct.value):moneyInputCents(price.value), + kind, + value:kind==='percent'?Number(pct.value):moneyInputCents(price.value), valid_from:from.value?new Date(from.value).toISOString():null, valid_until:until.value?new Date(until.value).toISOString():null, min_metres:rawMin||null, @@ -322,9 +473,9 @@ function couponDialog(coupon){ product:product.value||null, note:note.value.trim(), }; - if(kind.value==='percent'&&(!Number.isInteger(payload.value)||payload.value<1||payload.value>90)) + if(kind==='percent'&&(!Number.isInteger(payload.value)||payload.value<1||payload.value>90)) throw new Error('A porcentagem precisa ser de 1 a 90.'); - if(kind.value==='per_metre'&&(payload.value===null||payload.value<=0)) + if(kind==='per_metre'&&(payload.value===null||payload.value<=0)) throw new Error('Informe o desconto por metro em reais, como 2,00.'); if(rawMin&&!/^\d+([.,]\d)?$/.test(rawMin)) throw new Error('O mínimo de metros usa no máximo uma casa decimal.'); @@ -348,67 +499,136 @@ function couponDialog(coupon){ }}); } -async function loadSiteCoupons(){ - if(!may('manage'))return; - ensureCouponsPanel(); - const data=await api('/site/coupons'); - const host=$('site-coupons'); - host.replaceChildren(...(data.coupons.length?data.coupons.map(couponRow) - :[node('p','Nenhum cupom criado ainda.','empty')])); +// ---- Nota da arte (S4) ---------------------------------------------------- +function renderSiteGrade(){ + const host=$('site-grade-body');if(!host)return; + const table=node('div',undefined,'siteGradeTable'); + const head=node('div',undefined,'siteGradeHead'); + head.append(node('span','Regra'),node('span','Nota abaixo de'),node('span','Situação')); + table.append(head); + const ruleRow=(label,value,soft=false)=>{ + let on=value!=null; + const row=node('div',undefined,'siteGradeRow'); + row.append(node('span',label,'siteGradeName'+(soft?' siteSoft':''))); + const num=node('input');num.type='number';num.min='1';num.max='100';num.step='1'; + num.className='siteGradeNumber';num.placeholder='—';num.value=value!=null?String(value):'';num.disabled=!on; + const numBox=node('span',undefined,'inp siteInpBox');numBox.append(num); + row.append(numBox); + const sw=node('button',undefined,'sw'+(on?' on':'')); + sw.type='button';sw.setAttribute('role','switch');sw.setAttribute('aria-checked',String(on)); + const word=node('span',on?'Ligada':'Desligada'); + sw.append(node('span',undefined,'t'),word); + const setOn=next=>{ + on=next;sw.classList.toggle('on',next);sw.setAttribute('aria-checked',String(next)); + word.textContent=next?'Ligada':'Desligada';num.disabled=!next; + }; + sw.onclick=()=>setOn(!on); + row.append(sw); + return {row,value:()=>on?Number(num.value):null}; + }; + const aviso=ruleRow('Avisar o designer',siteRules.aviso); + const treatment=ruleRow('Exigir o Ajuste Fino',siteRules.tratamento,true); + table.append(aviso.row,treatment.row); + const warning=!siteRules.treatment_offered + ?node('p','Ative e dê preço ao Ajuste Fino para esta regra valer.','siteGradeWarn') + :null; + const foot=node('div',undefined,'siteGradeSave'); + foot.append(button('Salvar regras',async()=>{ + const avisoValue=aviso.value(),treatmentValue=treatment.value(); + for(const value of [avisoValue,treatmentValue]) + if(value!==null&&(!Number.isInteger(value)||value<1||value>100)) + throw new Error('A nota vai de 1 a 100.'); + if(avisoValue!==null&&treatmentValue!==null&&treatmentValue>avisoValue) + throw new Error('A regra do Ajuste Fino precisa ser menor ou igual à do aviso.'); + await api('/site/grade-rules',{aviso:avisoValue,tratamento:treatmentValue}); + say('Regras da nota da arte salvas.'); + siteRules=await api('/site/grade-rules');renderSiteGrade(); + },'btn pri')); + host.replaceChildren(table,...(warning?[warning]:[]),foot); } +// ---- Vídeos (S5, S6) ------------------------------------------------------ +function videoProductLabel(product){ + return (SITE_VIDEO_PRODUCTS.find(([value])=>value===(product||''))||SITE_VIDEO_PRODUCTS[0])[1]; +} +function renderSiteVideos(){ + const host=$('site-videos-list');if(!host)return; + host.replaceChildren(...siteVideos.map(siteVideoRow)); +} +function siteVideoRow(video){ + const tr=node('tr',undefined,'siteVideoRow'); + const title=node('td');title.append(node('span',video.title,'pname')); + const file=node('td');file.dataset.label='Arquivo'; + file.append(video.video_name?node('span',video.video_name,'siteFileName'):node('span','sem vídeo','muted')); + const captions=node('td');captions.dataset.label='Legenda'; + captions.append(video.captions_name?node('span',video.captions_name,'siteFileName'):node('span','sem legenda','muted')); + const where=node('td',videoProductLabel(video.product));where.dataset.label='Onde aparece'; + const situation=node('td');situation.dataset.label='Situação'; + situation.append(node('span',video.enabled?'Publicado':'Rascunho','tag'+(video.enabled?' ok':''))); + const action=node('td',undefined,'r siteAction'); + action.append(button('Editar',()=>videoDialog(video),'btn sm')); + tr.append(title,file,captions,where,situation,action); + return tr; +} +function videoDialog(video){ + let published=!!video.enabled; + const videoInput=node('input');videoInput.type='file';videoInput.accept='.mp4,.webm,video/mp4,video/webm'; + const videoField=node('div',undefined,'fld'); + videoField.append(node('span','Vídeo'), + dropField(videoInput,{title:'Escolher arquivo',hint:'MP4 ou WebM até 500 MB.'}), + node('small',video.video_name||'Nenhum arquivo enviado.')); + const captionsInput=node('input');captionsInput.type='file';captionsInput.accept='.vtt,text/vtt'; + const captionsField=node('div',undefined,'fld'); + captionsField.append(node('span',video.captions_name?'Legenda':'Legenda · opcional'), + dropField(captionsInput,{title:'Escolher legenda',hint:'Arquivo VTT.'}), + node('small',video.captions_name||'Nenhuma legenda enviada.')); + const product=node('select'); + for(const [value,label] of SITE_VIDEO_PRODUCTS){ + const option=node('option',label);option.value=value;product.append(option); + } + product.value=video.product||''; + const sw=node('button',undefined,'sw'+(published?' on':'')); + sw.type='button';sw.setAttribute('role','switch');sw.setAttribute('aria-checked',String(published)); + sw.append(node('span',undefined,'t'),'Publicar no Site'); + sw.onclick=()=>{published=!published;sw.classList.toggle('on',published);sw.setAttribute('aria-checked',String(published));}; + const situation=node('div',undefined,'fld');situation.append(node('span','Situação'),sw); + const row=node('div',undefined,'g2'); + row.append(field('Onde aparece',product,'Ou flutuando na página de um produto.'),situation); + formDialog(video.title,{width:640,className:'siteDialog', + text:video.enabled?'Publicado no Site':'Rascunho · ainda não aparece no Site', + fields:[videoField,captionsField,row],label:'Salvar vídeo',onsave:async()=>{ + 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:published}); + say('Vídeo salvo. O Site mostrará a nova versão na próxima abertura.'); + await loadSiteVideos(); + }}); +} + +// ---- Loading -------------------------------------------------------------- +async function loadSiteCoupons(){ + const data=await api('/site/coupons'); + siteCoupons=data.coupons;renderSiteCoupons();paintSiteTabs(); +} +async function loadSiteVideos(){ + const data=await api('/site-videos'); + siteVideos=data.videos;renderSiteVideos();paintSiteTabs(); +} 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 loadSiteCoupons(); - await loadGradeRules(); - 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; - })); + const products=await api('/site/products'); + siteProducts=products.products;renderSiteProducts(); + const rest=await Promise.allSettled([api('/site/coupons'),api('/site/grade-rules'),api('/site-videos')]); + const [coupons,grade,videos]=rest; + if(coupons.status==='fulfilled')siteCoupons=coupons.value.coupons; + else say(coupons.reason.message,true); + if(grade.status==='fulfilled')siteRules=grade.value; + else say(grade.reason.message,true); + if(videos.status==='fulfilled')siteVideos=videos.value.videos; + else say(videos.reason.message,true); + renderSiteCoupons();renderSiteGrade();renderSiteVideos();paintSiteTabs(); } diff --git a/web/kanban.css b/web/kanban.css index b9d6ee3..a26c2f1 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -637,56 +637,90 @@ label.fopt{cursor:pointer;user-select:none} /* Pages (redesign, steps 5 to 7): Pagamentos, Números, Integrações and Usuários, made of panels with a head and a table or a list. */ .page:not([hidden]){padding:24px 28px 40px;display:flex;flex-direction:column;gap:20px;animation:fadeUp .35s cubic-bezier(.2,.8,.2,1) both} -.siteVideoList{display:flex;flex-direction:column;padding:0 18px 18px} -.siteVideoRow{display:flex;flex-direction:column;gap:12px;padding:18px 0;border-top:1px solid var(--ln)} -.siteVideoHeading{display:flex;align-items:center;gap:12px;flex-wrap:wrap} -.siteVideoHeading b{font-size:14px} -.siteVideoFields{display:flex;align-items:end;gap:12px;flex-wrap:wrap} -.siteVideoField{display:flex;flex-direction:column;gap:6px;min-width:175px;font-size:12px;color:var(--tx2)} -.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 .siteBands{display:flex;flex-direction:column;gap:8px;flex:1 0 100%} -#tab-site .siteBandsHead{display:flex;align-items:center;gap:10px;flex-wrap:wrap} -#tab-site .siteBandsHead>span{font-size:12px;color:var(--tx2)} -#tab-site .siteBandRows{display:flex;flex-direction:column;gap:8px} -#tab-site .siteBandRow{display:flex;align-items:end;gap:10px;flex-wrap:wrap} -#tab-site .siteBandFrom{width:100px} -#tab-site .siteBandPrice{width:120px} -#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 .siteCouponList{display:flex;flex-direction:column;padding:0 18px 18px} -#tab-site .siteCouponRow{display:flex;flex-direction:column;gap:8px;padding:16px 0;border-top:1px solid var(--ln)} -#tab-site .siteCouponTop{display:flex;align-items:center;gap:10px;flex-wrap:wrap} -#tab-site .siteCouponTop b{font-size:14px} -#tab-site .siteCouponOffer{font-size:13.5px;font-weight:650;color:var(--tx2)} -#tab-site .siteCouponMeta{display:flex;gap:16px;flex-wrap:wrap;font-size:12.5px;color:var(--tx3)} -#tab-site .siteCouponActions{display:flex;gap:8px;flex-wrap:wrap} -#tab-site .siteCouponActions .btn{height:32px;padding:0 10px;font-size:12.5px} -#tab-site .siteCouponNote{margin:0;font-size:13px;color:var(--tx2)} -#tab-site .siteGradeBody{display:flex;flex-direction:column;gap:14px;padding:16px 18px} -#tab-site .siteGradeRow{display:flex;align-items:center;gap:16px;flex-wrap:wrap} -#tab-site .siteGradeField{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--tx2)} -#tab-site .siteGradeNumber{width:80px;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 .siteGradeWarn{margin:0;font-size:12.5px;font-weight:600;color:var(--warn)} -#tab-site .siteGradeSave{display:flex;gap:8px} -#tab-site .siteHistory .table{font-size:13px} -#tab-site .siteHistory .table th,#tab-site .siteHistory .table td{padding:8px 12px} +/* Site (Phase B): the segmented tabs, the product/coupon/video tables and the + price, coupon and video dialogs. */ +#tab-site .site-sub{font-size:13.5px;color:var(--tx2)} +#tab-site .site-bar{display:flex;align-items:center;gap:12px;flex-wrap:wrap} +#tab-site .site-note{margin-left:auto;font-size:13px;color:var(--tx3)} +#tab-site .site-pane{display:flex;flex-direction:column;gap:20px} +#tab-site .site-pane[hidden]{display:none} +#tab-site .site-table .pname{font-weight:600;font-size:14.5px} +#tab-site .site-table .unit{font-size:12.5px;color:var(--tx3);margin-left:8px} +#tab-site .site-table tr.off .pname,#tab-site .site-table tr.off .money{color:var(--tx3)} +#tab-site .site-table .money{font-size:14.5px;font-weight:600} +#tab-site .site-table .tag{margin-right:4px} +#tab-site .site-table .siteFileName{font-size:13px} +#tab-site .siteAction{width:1%;white-space:nowrap} +#tab-site .siteNext{display:flex;align-items:baseline;gap:8px;font-size:13px} +#tab-site .siteTools{display:flex;align-items:center;gap:12px} +#tab-site .siteTools .btn{margin-left:auto} +#tab-site .tag.ok{background:color-mix(in srgb,var(--mine) 14%,transparent);color:var(--mine)} +#tab-site .tag.warn{background:color-mix(in srgb,var(--warn) 14%,transparent);color:var(--warn)} +#tab-site #site-grade-panel{max-width:880px;width:100%} +#tab-site .siteGradeTable{display:flex;flex-direction:column;padding:0 18px} +#tab-site .siteGradeHead,#tab-site .siteGradeRow{display:grid;grid-template-columns:minmax(0,1fr) 120px 140px;align-items:center;gap:16px;padding:12px 0;border-bottom:1px solid var(--ln)} +#tab-site .siteGradeHead{padding:10px 0;font-size:12.5px;color:var(--tx3);font-weight:500} +#tab-site .siteGradeName{font-size:14.5px} +#tab-site .siteGradeRow .inp{height:38px;justify-content:center} +#tab-site .siteGradeNumber{border:0;background:transparent;width:100%;text-align:center;height:auto;padding:0} +#tab-site .siteGradeWarn{margin:0;padding:0 18px 12px;font-size:12.5px;font-weight:600;color:var(--warn)} +#tab-site .siteGradeSave{display:flex;justify-content:flex-end;padding:14px 18px} +/* The same pieces live inside the Site dialogs, which open over the page. */ +.siteSoft{color:var(--tx3);font-size:13px;font-weight:500} +.siteInpBox{display:flex;align-items:center;gap:8px} +.inp .siteInp{border:0;background:transparent;height:auto;padding:0;min-width:0;flex:1;font:inherit;font-weight:600;color:inherit;outline:none;width:100%;box-shadow:none} +.inp .siteInp:focus{border:0;box-shadow:none} +.siteSuffix{margin-left:auto} +.sitePriceNow{display:flex;align-items:baseline;gap:10px} +.sitePriceNow b{font-size:28px;font-weight:650;letter-spacing:-.01em} +.sitePriceNow span{font-size:13px;color:var(--tx3)} +.siteStartRow{display:flex;align-items:center;gap:8px;flex-wrap:wrap} +.siteStartRow .calwrap{flex:1;min-width:200px} +.siteStartRow .inp{width:100%;text-align:left;display:flex;align-items:center;gap:8px} +.modal.siteDialog:has(.calpop) .dfoot{visibility:hidden} +.siteDlgSection{display:flex;flex-direction:column;gap:10px} +.siteDlgSection h3{margin:0;font-size:14px;font-weight:650} +.siteBands{border:1px solid var(--ln);border-radius:10px;overflow:hidden} +.siteBands table{width:100%;border-collapse:collapse} +.siteBands th{text-align:left;font-size:12.5px;font-weight:500;color:var(--tx3);padding:9px 14px;border-bottom:1px solid var(--ln)} +.siteBands td{padding:8px 14px;border-bottom:1px solid var(--ln);font-size:14px} +.siteBands .base td{color:var(--tx2);height:48px} +.siteBands .inp{height:36px;width:150px} +.siteBands .add td{border-bottom:0;padding:6px 8px} +.siteSee{margin:0;font-size:13px;color:var(--tx2)} +.siteSee b{color:var(--tx);font-weight:600} +.siteHistRow{display:flex;align-items:center;gap:12px;padding:8px 0;border-bottom:1px solid var(--ln);font-size:13px} +.siteHistRow:last-child{border-bottom:0} +.siteHistMain{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap;flex:1;min-width:0} +.siteHistMain b{font-weight:600} +.seg.full{width:100%} +.seg.full button{flex:1;justify-content:center} +@media (max-width:700px){ + #tab-site .site-note{margin-left:0;flex-basis:100%} + #tab-site .site-bar .seg{width:100%;overflow-x:auto;scrollbar-width:none} + #tab-site .site-bar .seg button{min-height:44px;flex:none} + #tab-site .site-table thead{display:none} + #tab-site .site-table tbody{display:block} + #tab-site .site-table tr{display:block;padding:12px 14px;border-bottom:1px solid var(--ln)} + #tab-site .site-table td{display:flex;justify-content:flex-end;align-items:baseline;gap:6px;height:auto;padding:6px 0;border:0;white-space:normal;text-align:right} + #tab-site .site-table td::before{content:attr(data-label);color:var(--tx3);font-size:12.5px;font-weight:500;text-align:left;flex:none;margin-right:auto;padding-right:6px} + #tab-site .site-table td:first-child::before{display:none} + #tab-site .site-table td:first-child,#tab-site .site-table td.siteAction{justify-content:flex-start;text-align:left} + #tab-site .siteAction{justify-content:flex-end} + #tab-site .siteAction::before{display:none} + #tab-site .siteTools{flex-wrap:wrap} + #tab-site .siteTools .btn{margin-left:0} + #tab-site .siteGradeHead{display:none} + #tab-site .siteGradeRow{grid-template-columns:1fr;gap:8px;padding:14px 0} + #tab-site .siteGradeRow .inp{justify-content:flex-start} + #tab-site .siteGradeNumber{text-align:left} + .modal.siteDialog{left:0;right:0;top:0;bottom:0;width:auto!important;max-width:none;max-height:none;height:100%;transform:none;border-radius:0;padding:18px 16px;animation:none} + .modal.siteDialog .g2,.modal.siteDialog .g3{grid-template-columns:1fr} + .modal.siteDialog .sw{min-height:44px} + .siteStartRow{flex-direction:column;align-items:stretch} + .siteStartRow .calwrap{min-width:0} + .siteBands .inp{width:100%} +} .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} @@ -746,6 +780,9 @@ select.inp{appearance:none;-webkit-appearance:none;padding-right:32px;background .calwrap{position:relative} .calpop{left:0;top:calc(100% + 8px)} .cal{display:grid;grid-template-columns:170px 300px} +.cal.single{grid-template-columns:1fr} +.calpop .time{display:flex;align-items:center;gap:10px;padding:10px 14px;border-top:1px solid var(--ln);font-size:13px;color:var(--tx2)} +.calpop .time .inp{height:36px;width:110px} .presets{display:flex;flex-direction:column;gap:2px;padding:10px;border-right:1px solid var(--ln)} .preset{height:34px;padding:0 10px;border:0;border-radius:8px;background:transparent;color:var(--tx2);font-size:13px;font-weight:550;text-align:left} .preset:hover{background:var(--sf2);color:var(--tx)} diff --git a/web/kanban.html b/web/kanban.html index c1674e9..5308ad6 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -249,21 +249,31 @@
EtapaMédiap95Amostras