/* Kanban DTF: "Montar folha" (Fase 2, front 7). The stamps are the PNG files in Estampas/ inside the folder chosen in Integrações; the sizes are the table Gestão edits. Slice 1: the list and the estimate; Montar is slice 2. Uses the globals of kanban.js, loaded first. */ const MONTAR_CODE=/^[A-Za-z0-9_-]{1,40}$/; // The Site's ruler (web/site-config.js): the same numbers, copied there too. const MONTAR_DPI_REFUSE=96, MONTAR_DPI_WARN=200; const MONTAR_FILM_CM=57, MONTAR_GAP_CM=0.5; const MONTAR={sizes:[],lines:[],seq:0,preview:null,timer:null,dirty:false,token:0}; const montarFolderReady=()=>!!FOLDER.handle&&!!FOLDER.granted; const montarDpi=found=>found.width/(found.widthCm/2.54); const montarHeight=found=>found.widthCm*(found.height/found.width); const montarSelected=()=>MONTAR.sizes.find(size=>size.letter===$('montar-size').value)||null; // Without the folder there is no Estampas/ to read: only the size table works. function montarPaintFolder(){ const ok=montarFolderReady(); $('montar-nofolder').hidden=ok; $('montar-setup').querySelector('.montar-add').hidden=!ok; $('montar-preview').hidden=!ok; $('montar-sheet').hidden=!ok; $('montar-folder').textContent=ok?'Pasta “'+FOLDER.handle.name+'” · Estampas/':''; if(!ok){montarDropPreview();$('montar-preview').replaceChildren();} } function montarFolderError(error){ if(error&&['NotAllowedError','SecurityError'].includes(error.name)){ say('Para ler as estampas, escolha a pasta dos pedidos em Integrações neste computador.',true); return true; } return false; } // -.png wins over .png; only PNG. async function montarRead(code,size){ const dir=await FOLDER.handle.getDirectoryHandle('Estampas',{create:true}); for(const name of [code+'-'+size.letter+'.png',code+'.png']){ let handle; try{handle=await dir.getFileHandle(name);} catch(e){if(e.name==='NotFoundError')continue;throw e;} const file=await handle.getFile(),url=URL.createObjectURL(file); try{const dim=await montarPicture(url);return {code,letter:size.letter,widthCm:Number(size.width_cm),file,name,url,width:dim.width,height:dim.height};} catch(e){URL.revokeObjectURL(url);throw e;} } return null; } function montarPicture(url){ return new Promise((ok,fail)=>{ const img=new Image(); img.onload=()=>ok({width:img.naturalWidth,height:img.naturalHeight}); img.onerror=()=>fail(new Error('A estampa não pôde ser lida.')); img.src=url; }); } function montarDropPreview(){ if(MONTAR.preview)URL.revokeObjectURL(MONTAR.preview.url); MONTAR.preview=null; } function montarPaintPreview(found){ montarDropPreview(); MONTAR.preview=found; const words=node('span',undefined,'montar-stampinfo'); words.append(node('b',found.code), node('span',cm(found.widthCm)+' cm de largura · '+cm(montarHeight(found))+' cm de altura · '+Math.floor(montarDpi(found))+' DPI')); const img=node('img');img.src=found.url;img.alt='Estampa '+found.code; const wrap=node('div',undefined,'montar-stamp');wrap.append(img,words); $('montar-preview').replaceChildren(wrap); } function montarPaintNotFound(){ montarDropPreview(); $('montar-preview').replaceChildren(node('p','Código não existe em Estampas/.','montar-missing')); } function montarPaintHint(){ montarDropPreview(); $('montar-preview').replaceChildren(node('p','Digite o código e escolha o tamanho para ver a estampa.','montar-hint')); } async function montarPreview(){ const token=++MONTAR.token; const code=$('montar-code').value.trim(),size=montarSelected(); if(!montarFolderReady())return; if(!code){montarPaintHint();return;} if(!MONTAR_CODE.test(code)||!size){montarDropPreview();$('montar-preview').replaceChildren();return;} let found; try{found=await montarRead(code,size);} catch(e){if(token===MONTAR.token&&!montarFolderError(e))say(e.message,true);return;} if(token!==MONTAR.token){if(found)URL.revokeObjectURL(found.url);return;} if(found)montarPaintPreview(found);else montarPaintNotFound(); } function montarQueuePreview(){ clearTimeout(MONTAR.timer); MONTAR.timer=setTimeout(()=>montarPreview().catch(e=>say(e.message,true)),250); } function montarEstimate(){ if(!MONTAR.lines.length)return 0; let total=0; for(const line of MONTAR.lines){ const perRow=Math.max(1,Math.floor((MONTAR_FILM_CM-MONTAR_GAP_CM)/(line.widthCm+MONTAR_GAP_CM))); const rows=Math.ceil(line.qty/perRow); total+=rows*(line.heightCm+MONTAR_GAP_CM); } return (MONTAR_GAP_CM+total)/100; } function montarPaintTotals(){ $('montar-total').textContent='Estimativa: '+metres(montarEstimate()); $('montar-count').textContent=MONTAR.lines.length?plural(MONTAR.lines.length,'estampa','estampas'):''; $('montar-clear').disabled=!MONTAR.lines.length; } function montarLine(line){ const row=node('div',undefined,'montar-line'); const img=node('img',undefined,'montar-thumb');img.src=line.url;img.alt=''; const words=node('span',undefined,'montar-linemeta'); words.append(node('b',line.code),node('span',line.letter+' · '+cm(line.widthCm)+' cm')); const qty=node('input',undefined,'montar-qty');qty.type='number';qty.min='1';qty.max='9999';qty.step='1'; qty.value=String(line.qty);qty.setAttribute('aria-label','Quantidade de '+line.code+' '+line.letter); qty.onchange=()=>{ const value=Math.round(Number(qty.value)); if(!Number.isInteger(value)||value<1||value>9999){qty.value=String(line.qty);return;} line.qty=value;qty.value=String(value);montarPaintTotals(); }; const dpi=node('span',undefined,'montar-dpi'); if(line.dpimontarRemoveLine(line))); return row; } function montarPaintLines(){ const box=$('montar-lines'); box.replaceChildren(...(MONTAR.lines.length?MONTAR.lines.map(montarLine) :[emptyState(IC.box,'Nenhuma estampa na folha','Digite o código, escolha o tamanho e Adicionar.')])); montarPaintTotals(); } function montarRemoveLine(line){ URL.revokeObjectURL(line.url); MONTAR.lines=MONTAR.lines.filter(other=>other!==line); montarPaintLines(); } function montarClear(){ for(const line of MONTAR.lines)URL.revokeObjectURL(line.url); MONTAR.lines=[]; montarPaintLines(); } async function montarAdd(){ const code=$('montar-code').value.trim(),size=montarSelected(); if(!MONTAR_CODE.test(code))return say('Código inválido: use letras, números, hífen ou sublinhado, até 40.',true); if(!size)return say('Nenhum tamanho na tabela. Peça à Gestão para cadastrar.',true); const qty=Number($('montar-qty').value); if(!Number.isInteger(qty)||qty<1||qty>9999)return say('A quantidade vai de 1 a 9999.',true); if(!montarFolderReady())return; let found; try{found=await montarRead(code,size);} catch(e){if(!montarFolderError(e))say(e.message,true);return;} if(!found){montarPaintNotFound();return say('Código não existe em Estampas/.',true);} montarPaintPreview(found); if(found.widthCm>56)return say('A estampa tem '+cm(found.widthCm)+' cm de largura: o máximo é 56 cm.',true); const dpi=montarDpi(found); if(dpiline.code===code&&line.letter===size.letter); if(existing){existing.qty=Math.min(9999,existing.qty+qty);montarPaintLines();return;} MONTAR.lines.push({id:++MONTAR.seq,code,letter:size.letter,widthCm:found.widthCm,qty, heightCm:montarHeight(found),dpi,url:URL.createObjectURL(found.file),file:found.file}); montarPaintLines(); } function montarPaintSelect(){ const select=$('montar-size'),current=select.value; select.replaceChildren(...MONTAR.sizes.map(size=>{ const option=node('option',size.letter+' · '+cm(size.width_cm)+' cm');option.value=size.letter;return option; })); select.disabled=!MONTAR.sizes.length; select.value=MONTAR.sizes.some(size=>size.letter===current)?current:(MONTAR.sizes[0]?.letter||''); } // A row of the table: the letter and its width in centimetres. function montarSizeRow(size){ const row=node('div',undefined,'montar-size-row'); const letter=node('input',undefined,'montar-letter');letter.value=size?.letter||'';letter.maxLength=2; letter.autocomplete='off';letter.setAttribute('aria-label','Letra do tamanho'); letter.oninput=()=>{letter.value=letter.value.toUpperCase().replace(/[^A-Z]/g,'');MONTAR.dirty=true;}; const width=node('input',undefined,'montar-width');width.type='number';width.min='0.01';width.max='56';width.step='0.01'; width.value=size?Number(size.width_cm):'';width.setAttribute('aria-label','Largura em centímetros'); width.oninput=()=>{MONTAR.dirty=true;}; const remove=iconButton(IC.close,'Remover tamanho',()=>{row.remove();MONTAR.dirty=true;}); row.append(letter,width,remove); return row; } function montarPaintSizeEditor(){ const panel=$('montar-sizes-panel'); if(!may('manage')){panel.hidden=true;return;} panel.hidden=false; const head=node('div',undefined,'montar-size-head'); head.append(node('span','Letra'),node('span','Largura (cm)'),node('span')); $('montar-sizes').replaceChildren(head,...MONTAR.sizes.map(montarSizeRow)); } async function montarSaveSizes(){ const rows=[...$('montar-sizes').querySelectorAll('.montar-size-row')]; const sizes=[],seen=new Set(); for(const row of rows){ const letter=row.querySelector('.montar-letter').value.trim().toUpperCase(); const width=Number(row.querySelector('.montar-width').value); if(!/^[A-Z]{1,2}$/.test(letter))return say('Cada tamanho precisa de uma letra de A a ZZ.',true); if(seen.has(letter))return say('A letra '+letter+' aparece mais de uma vez.',true); if(!(width>0&&width<=56))return say('A largura de '+letter+' vai de 0,01 a 56 cm.',true); seen.add(letter);sizes.push({letter,width_cm:Number(width.toFixed(2))}); } if(!sizes.length)return say('A tabela precisa de pelo menos um tamanho.',true); await api('/stamp-sizes',{sizes}); MONTAR.dirty=false; say('Tamanhos salvos.'); await montarLoadSizes(true); montarQueuePreview(); } async function montarLoadSizes(repaint){ MONTAR.sizes=(await api('/stamp-sizes')).sizes||[]; montarPaintSelect(); if(repaint||!MONTAR.dirty)montarPaintSizeEditor(); } async function loadMontador(){ montarPaintFolder(); try{await montarLoadSizes(false);} catch(e){say(e.message,true);return;} if(montarFolderReady()){ if($('montar-code').value.trim()){if(!MONTAR.preview)montarQueuePreview();} else montarPaintHint(); } montarPaintLines(); } $('montar-code').addEventListener('input',montarQueuePreview); $('montar-size').addEventListener('change',()=>montarPreview().catch(e=>say(e.message,true))); $('montar-qty').addEventListener('keydown',event=>{ if(event.key==='Enter'){event.preventDefault();$('montar-add').click();} }); $('montar-add').onclick=async()=>{ $('montar-add').disabled=true; try{await montarAdd();}catch(e){say(e.message,true);}finally{$('montar-add').disabled=false;} }; $('montar-clear').onclick=()=>montarClear(); $('montar-build').title='Em breve'; $('montar-size-add').onclick=()=>{MONTAR.dirty=true;$('montar-sizes').append(montarSizeRow(null));}; $('montar-size-save').onclick=async()=>{ $('montar-size-save').disabled=true; try{await montarSaveSizes();}catch(e){say(e.message,true);}finally{$('montar-size-save').disabled=false;} };