/* 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. The packing is the Site's own engine (web/packing.js). Montar creates the card: Interno for the Expedição, Venda for a customer picked from Tiny (front 7a.3). Uses the globals of kanban.js and packing.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, layout:null,layoutTimer:null,layoutToken:0,layoutPending:false,creating:false,requestKey:null, kind:null,internal:null,internalDirty:false,brands:new Map(),contactToken:0,contactTimer:null, freights:null,freight:null,catalog:null}; 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; // ---- Interno or Venda ------------------------------------------------------ // Marcus's answers of 2026-11-10 (front 7a.3): the Expedição only makes // Interno orders, the Vendedor only Venda, and Gestão and the administrators // both. An Interno order uses the fixed internal customer; a Venda one is // picked from Tiny. const montarKindNames=()=>ME?.role==='expedicao'?['interno']:ME?.role==='vendedor'?['venda']:['interno','venda']; const montarInternalField=key=>String(MONTAR.internal?.[key]||''); const montarInternalReady=()=>!!MONTAR.internal&&['name','cnpj','zap','mail'].every(key=>montarInternalField(key).trim()); function montarPaintKind(){ const kinds=montarKindNames(); if(!MONTAR.kind||!kinds.includes(MONTAR.kind))MONTAR.kind=kinds.length===1?kinds[0]:'venda'; if(MONTAR.kind==='interno'&&!montarInternalReady()&&kinds.length>1){ MONTAR.kind='venda'; for(const id of ['montar-name','montar-doc','montar-zap','montar-mail'])$(id).value=''; } const box=$('montar-kind'); $('montar-kind-hint').textContent=kinds.length===1 ?(MONTAR.kind==='interno'?'Interno, para a Expedição.':'Venda, para o Vendedor.') :'Interno para a Expedição; Venda para um cliente do Tiny.'; box.hidden=kinds.length<2; box.replaceChildren(...kinds.map(kind=>{ const b=node('button',kind==='interno'?'Interno':'Venda',kind===MONTAR.kind?'on':'');b.type='button'; b.setAttribute('aria-pressed',String(kind===MONTAR.kind)); b.disabled=kind==='interno'&&!montarInternalReady(); b.title=b.disabled?'Peça à Gestão para completar o cliente interno.':''; b.onclick=()=>montarSetKind(kind); return b; })); $('montar-interno-missing').hidden=montarInternalReady(); } function montarSetKind(kind){ if(MONTAR.kind===kind)return; MONTAR.kind=kind; montarClearCustomer(); montarPaintKind();montarPaintCustomer();montarPaintActions(); } function montarPaintCustomer(){ const interno=MONTAR.kind==='interno'; $('montar-customer-title').textContent=interno?'Cliente interno':'Cliente'; $('montar-customer-search').hidden=interno; $('montar-interno-note').hidden=!interno; $('montar-delivery').hidden=interno; for(const [id,key] of [['montar-name','name'],['montar-doc','cnpj'],['montar-zap','zap'],['montar-mail','mail']]){ $(id).disabled=interno; if(interno)$(id).value=montarInternalField(key); } } const montarDelivery=()=>document.querySelector('input[name="montar-delivery"]:checked')?.value||'pickup'; function montarPaintDelivery(){ const delivery=montarDelivery(),withOrder=delivery==='with_order',ship=delivery==='ship'; $('montar-with-order').disabled=!withOrder; if(!withOrder)$('montar-with-order').value=''; $('montar-shipping').hidden=!ship; if(ship&&!$('montar-ship-recipient').value.trim()) $('montar-ship-recipient').value=$('montar-name').value.trim(); montarPaintFreights(); } function montarWithOrder(){ if(MONTAR.kind!=='venda'||montarDelivery()!=='with_order')return null; const value=Math.round(Number($('montar-with-order').value)); return Number.isInteger(value)&&value>=1&&value<=999999?value:null; } // ---- Envio (front 7a.4): the Site's own freight --------------------------- // The Site's public routes for the CEP and the carrier quotes (app/api/health.py); // the Kanban's api() helper only reaches /api/operator. // The Site's UFS list (web/site-config.js), copied for the address select. const MONTAR_UFS='AC AL AP AM BA CE DF ES GO MA MT MS MG PA PB PR PE PI RJ RN RS RO RR SC SP SE TO'.split(' '); const montarCep=()=>$('montar-ship-cep').value.replace(/\D/g,'').slice(0,8); function montarDestination(){ const destination={recipient:$('montar-ship-recipient').value.trim(), street:$('montar-ship-street').value.trim(),number:$('montar-ship-number').value.trim(), complement:$('montar-ship-complement').value.trim(), district:$('montar-ship-district').value.trim(),city:$('montar-ship-city').value.trim(), state:$('montar-ship-state').value.trim().toUpperCase(),postal_code:montarCep()}; const ok=destination.postal_code.length===8&&destination.recipient.length>=2&& destination.street.length>=2&&destination.number.length>=1&& destination.district.length>=2&&destination.city.length>=2&&MONTAR_UFS.includes(destination.state); return ok?destination:null; } const montarShipReady=()=>montarDelivery()==='ship'&&!!montarDestination()&& !!MONTAR.freight&&MONTAR.freight.postal_code===montarCep(); function montarResetFreight(){ MONTAR.freights=null;MONTAR.freight=null; $('montar-freights').replaceChildren();$('montar-freights').hidden=true; $('montar-freight-msg').textContent=''; } async function montarPublic(path,options={}){ const response=await fetch('/api'+path,options); const data=await response.json().catch(()=>({})); if(!response.ok)throw new Error(typeof data.detail==='string'?data.detail:'Não foi possível agora ('+response.status+').'); return data; } async function montarCepLookup(){ const msg=$('montar-ship-msg'),cep=montarCep(); if(cep.length!==8){msg.textContent='Informe um CEP com oito dígitos.';return;} msg.textContent='Buscando o endereço…'; try{ const address=await montarPublic('/cep/'+cep); $('montar-ship-street').value=address.street||''; $('montar-ship-district').value=address.district||''; $('montar-ship-city').value=address.city||''; if(MONTAR_UFS.includes(address.state))$('montar-ship-state').value=address.state; if(!$('montar-ship-recipient').value.trim())$('montar-ship-recipient').value=$('montar-name').value.trim(); msg.textContent='';MONTAR.requestKey=null;montarPaintActions(); }catch(e){msg.textContent=e.message;} } // The item's packed metres and the table value of the items, as the server // will price them: the band price of the loose-art mode on the billed metres. function montarQuoteFigures(lines){ const heights=montarGroups(lines).map(group=>{ const cargas=[]; group.sources.forEach((source,sourceIndex)=>{ for(let copyIndex=0;copyIndexMath.max(1,Math.ceil(metres*10)/10)); const total=+billed.reduce((sum,metres)=>sum+metres,0).toFixed(2); let unit=catalog.unit_cents,best=null; for(const band of catalog.bands||[]){ const from=Number(band.from_metres); if(total>=from&&(best===null||from>=best)){best=from;unit=band.unit_cents;} } return {metres:+heights.reduce((sum,metres)=>sum+metres,0).toFixed(4), cents:billed.reduce((sum,metres)=>sum+Math.floor(Number((metres*unit).toFixed(6))),0)}; } async function montarCatalog(){ if(MONTAR.catalog)return MONTAR.catalog; const session=await montarPublic('/session'); MONTAR.catalog=session.products||null; return MONTAR.catalog; } async function montarFreightQuote(){ const msg=$('montar-freight-msg'),cep=montarCep(); if(cep.length!==8){msg.textContent='Informe o CEP de entrega primeiro.';return;} if(!MONTAR.lines.length||!MONTAR.layout||MONTAR.layoutPending){ msg.textContent='Monte a folha antes de cotar o frete.';return; } msg.textContent='Cotando o frete…'; const token=MONTAR.layoutToken; try{ await montarCatalog(); if(token!==MONTAR.layoutToken||montarCep()!==cep)return; const figures=montarQuoteFigures([...MONTAR.lines]); const result=await montarPublic('/freight/options',{method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({postal_code:cep,metres:figures.metres,declared_cents:figures.cents})}); if(token!==MONTAR.layoutToken||montarCep()!==cep)return; MONTAR.freights=result.options||[]; MONTAR.freight=MONTAR.freights.length?{...MONTAR.freights[0],postal_code:cep}:null; MONTAR.requestKey=null; msg.textContent='';montarPaintFreights();montarPaintActions(); }catch(e){ if(token!==MONTAR.layoutToken||montarCep()!==cep)return; MONTAR.freights=null;MONTAR.freight=null; $('montar-freights').replaceChildren();$('montar-freights').hidden=true; msg.textContent=e.message;montarPaintActions(); } } function montarPaintFreights(){ const box=$('montar-freights'),options=MONTAR.freights||[]; box.hidden=!options.length; box.replaceChildren(...options.map(option=>{ const label=node('label',undefined,'montar-freight'); const radio=node('input');radio.type='radio';radio.name='montar-freight';radio.value=option.service; radio.checked=!!MONTAR.freight&&option.service===MONTAR.freight.service; radio.onchange=()=>{ MONTAR.freight={...option,postal_code:montarCep()};MONTAR.requestKey=null;montarPaintActions(); }; const meta=node('span',undefined,'montar-freight-meta'); meta.append(node('b',option.description||option.service), node('span',option.days?'até '+option.days+' dias úteis':'','sub'), node('em',money(option.total_cents))); label.append(radio,meta); return label; })); } // The brand of a stamp, recorded for the future catalogue (Marcus, 10/11): // only Gestão edits it; everyone who assembles reads it. async function montarStampBrand(code){ if(MONTAR.brands.has(code))return MONTAR.brands.get(code); const stamp=await api('/stamps/'+encodeURIComponent(code)); MONTAR.brands.set(code,stamp); return stamp; } function montarBrandRow(code,stamp){ const current=stamp||{brand:'',public:false}; const row=node('div',undefined,'montar-brand'); row.append(node('span','Marca','lbl')); if(!may('manage')){ row.append(node('b',current.brand||'—'),node('span',current.public?'Pública':'Não pública','lbl')); return row; } const brand=node('input',undefined,'montar-brandinput'); brand.value=current.brand||'';brand.maxLength=120;brand.autocomplete='off';brand.spellcheck=false; brand.setAttribute('aria-label','Marca da estampa '+code); const pub=node('label',undefined,'montar-public'); const check=node('input');check.type='checkbox';check.checked=!!current.public; pub.append(check,'Pública'); const save=node('button','Salvar marca','btn');save.type='button'; save.onclick=async()=>{ save.disabled=true; try{ await api('/stamps/'+encodeURIComponent(code),{brand:brand.value.trim(),public:check.checked}); MONTAR.brands.set(code,{code,brand:brand.value.trim(),public:check.checked}); say('Marca salva.'); }catch(e){say(e.message,true);}finally{save.disabled=false;} }; row.append(brand,pub,save); return row; } // 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,stamp){ 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 body=node('div',undefined,'montar-stampbody'); body.append(words,montarBrandRow(found.code,stamp)); const wrap=node('div',undefined,'montar-stamp');wrap.append(img,body); $('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){ let stamp=null; try{stamp=await montarStampBrand(code);}catch(e){stamp={code,brand:'',public:false};} if(token!==MONTAR.token){URL.revokeObjectURL(found.url);return;} montarPaintPreview(found,stamp); }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(){ const done=MONTAR.layout&&!MONTAR.layoutPending; $('montar-total').textContent=done ? 'Montagem: '+metres(MONTAR.layout.altura/100) : 'Estimativa: '+metres(montarEstimate())+(MONTAR.layoutPending?' · montando…':''); $('montar-count').textContent=MONTAR.lines.length?plural(MONTAR.lines.length,'estampa','estampas'):''; $('montar-clear').disabled=!MONTAR.lines.length; $('montar-warning').hidden=!(MONTAR.lines.length>20||MONTAR.lines.some(line=>line.qty>200)); montarPaintActions(); } // The line's image, loaded once and kept for the packing and the preview. function montarStampImage(url){ const img=new Image(); const loading=new Promise(ok=>{img.onload=()=>ok(img);img.onerror=()=>ok(null);}); img.src=url; return {img,loading}; } // Every list change shows the estimate at once and schedules the real packing, // 300 ms later; a run that finishes after a newer change is thrown away. function montarChanged(){ MONTAR.layoutToken+=1; MONTAR.layout=null; MONTAR.layoutPending=true; MONTAR.requestKey=null; montarResetFreight(); montarPaintLines(); if(!MONTAR.lines.length)montarDrawPreview(null); clearTimeout(MONTAR.layoutTimer); MONTAR.layoutTimer=setTimeout(()=>montarLayout(MONTAR.layoutToken).catch(e=>say(e.message,true)),300); } async function montarLayout(token){ if(token!==MONTAR.layoutToken)return; const lines=[...MONTAR.lines]; if(!lines.length){MONTAR.layout=null;MONTAR.layoutPending=false;montarPaintTotals();montarDrawPreview(null);return;} const images=await Promise.all(lines.map(line=>line.loading)); if(token!==MONTAR.layoutToken)return; if(images.some(image=>!image)){ MONTAR.layoutPending=false;montarPaintTotals(); say('A estampa não pôde ser lida.',true);return; } const cargas=lines.flatMap((line,sourceIndex)=>Array.from({length:line.qty},(_,copyIndex)=>({ a:{sourceIndex,giro:0,esp:false},img:line.img,copyIndex,w:line.widthCm,h:line.heightCm,travado:false}))); let enc; try{enc=encaixar(cargas,MONTAR_FILM_CM);} catch(e){ if(token!==MONTAR.layoutToken)return; MONTAR.layoutPending=false;montarPaintTotals();say(e.message,true);return; } if(token!==MONTAR.layoutToken)return; MONTAR.layout={token,altura:enc.altura,pos:enc.pos}; MONTAR.layoutPending=false; montarPaintTotals(); montarDrawPreview(MONTAR.layout); } // The sheet's preview: 57 cm across the panel, white film and the outline. function montarDrawPreview(layout){ const box=$('montar-layout'),canvas=$('montar-canvas'); if(!layout){box.hidden=true;return;} box.hidden=false; const width=box.clientWidth-24; // the box's padding if(width<60)return; const px=width/MONTAR_FILM_CM; const height=Math.max(20,layout.altura*px); const dpr=Math.min(2,window.devicePixelRatio||1); canvas.width=Math.round(width*dpr);canvas.height=Math.round(height*dpr); canvas.style.width=width+'px';canvas.style.height=height+'px'; const ctx=canvas.getContext('2d'); ctx.setTransform(dpr,0,0,dpr,0,0); ctx.fillStyle='#fff';ctx.fillRect(0,0,width,height); ctx.strokeStyle='#B4BAC5';ctx.lineWidth=1; ctx.strokeRect(.5,.5,width-1,height-1); for(const p of layout.pos){ const c=p.ref; const giro=(p.rot===90?90:0)+(c.a&&c.a.giro?90:0); ctx.save(); ctx.translate((p.x+p.w/2)*px,(p.y+p.h/2)*px); ctx.rotate(giro*Math.PI/180); if(c.a&&c.a.esp)ctx.scale(-1,1); const dw=((giro%180===90)?p.h:p.w)*px, dh=((giro%180===90)?p.w:p.h)*px; if(c.img)ctx.drawImage(c.img,-dw/2,-dh/2,dw,dh); else{ctx.fillStyle='#E7E7E3';ctx.fillRect(-dw/2,-dh/2,dw,dh);} ctx.restore(); } } // ---- Criar o pedido ------------------------------------------------------- // The typed customer, as the Site's own Customer model validates it. const MONTAR_CUSTOMER=['montar-name','montar-doc','montar-zap','montar-mail']; function montarCustomer(){ return {name:$('montar-name').value.trim(),cnpj:$('montar-doc').value.trim(), zap:$('montar-zap').value.trim(),mail:$('montar-mail').value.trim()}; } const montarCustomerFilled=()=>MONTAR_CUSTOMER.every(id=>$(id).value.trim()); function montarClearCustomer(){ for(const id of MONTAR_CUSTOMER)$(id).value=''; $('montar-customer-q').value=''; $('montar-customer-hits').hidden=true; for(const id of ['montar-ship-cep','montar-ship-recipient','montar-ship-street','montar-ship-number', 'montar-ship-complement','montar-ship-district','montar-ship-city','montar-ship-state']) $(id).value=''; $('montar-ship-msg').textContent=''; montarResetFreight(); document.querySelector('input[name="montar-delivery"][value="pickup"]').checked=true; montarPaintDelivery(); MONTAR.requestKey=null; } // Montar is the real thing now: a sheet, its layout and the customer, which // Interno reads from the database and Venda from Tiny. function montarPaintActions(){ const build=$('montar-build'); const customerReady=MONTAR.kind==='interno'?montarInternalReady():montarCustomerFilled(); const deliveryReady=MONTAR.kind!=='venda'||montarDelivery()!=='ship'||montarShipReady(); const ready=!!(MONTAR.lines.length&&MONTAR.layout&&!MONTAR.layoutPending&& customerReady&&deliveryReady&&!MONTAR.creating); build.disabled=!ready; build.title=ready?'':(!MONTAR.lines.length?'Monte a folha primeiro.' :(MONTAR.layoutPending||!MONTAR.layout)?'Aguarde a montagem da folha.' :MONTAR.kind==='interno'?'Peça à Gestão para completar o cliente interno.' :!customerReady?'Preencha os dados do cliente.' :!deliveryReady?(!montarDestination()?'Preencha o endereço de entrega.':'Cote o frete e escolha uma opção.') :''); } // The Site's grade for loose art (web/site-quality.js): each stamp's DPI over // the ideal 200, from 6 to 100; the item's is the average of its stamps'. const montarGrade=dpi=>Math.max(6,Math.min(100,Math.round(dpi/200*100))); function montarItem(sources){ const cargas=[]; sources.forEach((source,sourceIndex)=>{ for(let copyIndex=0;copyIndexmontarGrade(source.line.dpi)); const warning=sources.some(source=>source.line.dpisum+n,0)/grades.length), uploads:sources.map(source=>source.uploadId), production:{version:3,film_width_cm:MONTAR_FILM_CM,height_cm:height, sources:sources.map(source=>({upload_id:source.uploadId,kind:'artwork', width_cm:source.line.widthCm,length_cm:+source.line.heightCm.toFixed(4), copies:source.copies,rotation_degrees:0,mirrored:false,measurement:'file'})), placements:placementsDe(enc.pos)}, quality_status:warning?'warning':'ok',quality_acknowledged:warning,residue_accepted:0}; } // 20 sources and 4000 copies per item; a stamp above 200 copies becomes // several sources of the same upload, 200 each; items in list order. function montarGroups(lines){ const pool=[]; for(const line of lines) for(let left=line.qty;left>0;left-=200) pool.push({line,copies:Math.min(200,left)}); const groups=[];let current=null; for(const source of pool){ if(!current||current.sources.length>=20||current.copies+source.copies>4000){ current={sources:[],copies:0};groups.push(current); } current.sources.push(source);current.copies+=source.copies; } return groups; } function montarItems(lines,uploads){ return montarGroups(lines).map(group=>montarItem(group.sources.map(source=> ({...source,uploadId:uploads.get(source.line.id)})))); } async function montarCreate(){ if(MONTAR.creating)return; const kind=MONTAR.kind||'venda'; let customer=null,name=''; if(kind==='interno'){ if(!montarInternalReady())return say('Peça à Gestão para completar o cliente interno.',true); name=montarInternalField('name'); }else{ customer=montarCustomer(); if(!montarCustomerFilled())return say('Preencha os dados do cliente.',true); name=customer.name; } let withOrder=null,deliveryFreight=null,destination=null; if(kind==='venda'&&montarDelivery()==='with_order'){ withOrder=montarWithOrder(); if(!withOrder)return say('Informe o número do pedido de roupa.',true); } if(kind==='venda'&&montarDelivery()==='ship'){ destination=montarDestination(); if(!destination)return say('Preencha o endereço de entrega.',true); if(!MONTAR.freight)return say('Cote o frete e escolha uma opção.',true); if(MONTAR.freight.postal_code!==montarCep())return say('Cote o frete de novo para este CEP.',true); deliveryFreight={service:MONTAR.freight.service,postal_code:montarCep()}; } if(!MONTAR.lines.length)return say('Monte a folha primeiro.',true); if(!MONTAR.layout||MONTAR.layoutPending)return say('A montagem ainda está sendo calculada.',true); const lines=[...MONTAR.lines]; if(!await ask('Criar pedido','Criar o pedido com '+plural(lines.reduce((t,line)=>t+line.qty,0),'estampa','estampas')+ ', '+metres(MONTAR.layout.altura/100)+', para '+name+'?','Criar pedido'))return; MONTAR.creating=true;montarPaintActions(); try{ const uploads=new Map(); for(let index=0;index{}); }catch(e){say(e.message,true);} finally{MONTAR.creating=false;montarPaintActions();} } 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);montarChanged(); }; 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); montarChanged(); } function montarClear(){ for(const line of MONTAR.lines)URL.revokeObjectURL(line.url); MONTAR.lines=[]; montarChanged(); } 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);} let stamp=null; try{stamp=await montarStampBrand(code);}catch(e){stamp={code,brand:'',public:false};} montarPaintPreview(found,stamp); 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);montarChanged();return;} const url=URL.createObjectURL(found.file),picture=montarStampImage(url); MONTAR.lines.push({id:++MONTAR.seq,code,letter:size.letter,widthCm:found.widthCm,qty, heightCm:montarHeight(found),dpi,url,img:picture.img,loading:picture.loading,file:found.file}); montarChanged(); } 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(); } // The fixed internal customer, completed by Gestão in the panel next to the // size table. Copied into the form only while it is not being edited. function montarPaintInternalFields(){ if(!may('manage'))return; $('montar-interno-name').value=montarInternalField('name'); $('montar-interno-doc').value=montarInternalField('cnpj'); $('montar-interno-zap').value=montarInternalField('zap'); $('montar-interno-mail').value=montarInternalField('mail'); } async function montarLoadInternal(repaint){ MONTAR.internal=await api('/internal-customer'); const panel=$('montar-interno-panel'); panel.hidden=!may('manage'); if(may('manage')&&(repaint||!MONTAR.internalDirty))montarPaintInternalFields(); montarPaintKind(); montarPaintCustomer(); montarPaintActions(); } async function montarSaveInternal(){ const customer={name:$('montar-interno-name').value.trim(),cnpj:$('montar-interno-doc').value.trim(), zap:$('montar-interno-zap').value.trim(),mail:$('montar-interno-mail').value.trim()}; if(!['name','cnpj','zap','mail'].every(key=>customer[key]))return say('Preencha todos os campos do cliente interno.',true); await api('/internal-customer',customer); MONTAR.internalDirty=false; say('Cliente interno salvo.'); await montarLoadInternal(true); } // The Venda customer comes from Tiny's contacts, by name or CPF/CNPJ. async function montarSearchContacts(){ const token=++MONTAR.contactToken,q=$('montar-customer-q').value.trim(),hits=$('montar-customer-hits'); if(q.length<2){hits.hidden=true;hits.replaceChildren();return;} let contacts; try{contacts=await api('/tiny/contacts?q='+encodeURIComponent(q));} catch(e){ if(token!==MONTAR.contactToken)return; hits.replaceChildren(node('p',e.message,'montar-hint'));hits.hidden=false;return; } if(token!==MONTAR.contactToken)return; if(!contacts.length){hits.replaceChildren(node('p','Nenhum contato no Tiny.','montar-hint'));hits.hidden=false;return;} hits.replaceChildren(...contacts.map(contact=>{ const hit=node('button',undefined,'montar-hit');hit.type='button';hit.setAttribute('role','option'); hit.append(node('b',contact.name||contact.document||'Contato'), node('span',[contact.document,contact.email,contact.phone].filter(Boolean).join(' · '),'sub')); hit.onclick=()=>montarPickContact(contact); return hit; })); hits.hidden=false; } function montarQueueContacts(){ clearTimeout(MONTAR.contactTimer); MONTAR.contactTimer=setTimeout(()=>montarSearchContacts().catch(e=>say(e.message,true)),300); } function montarPickContact(contact){ const previous=$('montar-name').value.trim(); $('montar-name').value=contact.name||''; $('montar-doc').value=contact.document||''; $('montar-zap').value=contact.phone||''; $('montar-mail').value=contact.email||''; $('montar-customer-q').value=contact.name||contact.document||''; $('montar-customer-hits').hidden=true; const recipient=$('montar-ship-recipient').value.trim(); if(montarDelivery()==='ship'&&(!recipient||recipient===previous)) $('montar-ship-recipient').value=contact.name||''; MONTAR.requestKey=null; montarPaintActions(); const missing=MONTAR_CUSTOMER.find(id=>!$(id).value.trim()); if(missing)$(missing).focus(); } async function loadMontador(){ montarPaintFolder(); // Paint the chosen kind and customer before the fetch answers: an Expedição // never sees an editable customer field, not even for a moment. montarPaintKind();montarPaintCustomer(); try{await Promise.all([montarLoadSizes(false),montarLoadInternal(false)]);} catch(e){say(e.message,true);return;} if(montarFolderReady()){ if($('montar-code').value.trim()){if(!MONTAR.preview)montarQueuePreview();} else montarPaintHint(); } montarPaintLines(); if(MONTAR.layout)montarDrawPreview(MONTAR.layout); } // 2b splits an order that passes these limits into more than one sheet; from // now on it only warns, it does not block. const montarWarning=node('p','O pedido será dividido em mais de uma folha.','montar-warn'); montarWarning.id='montar-warning';montarWarning.hidden=true; $('montar-sheet').insertBefore(montarWarning,$('montar-lines')); let montarResize=null; addEventListener('resize',()=>{ clearTimeout(montarResize); montarResize=setTimeout(()=>{if(MONTAR.layout)montarDrawPreview(MONTAR.layout);},200); }); $('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').onclick=()=>montarCreate(); for(const id of MONTAR_CUSTOMER)$(id).addEventListener('input',()=>{MONTAR.requestKey=null;montarPaintActions();}); $('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;} }; for(const id of ['montar-interno-name','montar-interno-doc','montar-interno-zap','montar-interno-mail']) $(id).addEventListener('input',()=>{MONTAR.internalDirty=true;}); $('montar-interno-save').onclick=async()=>{ $('montar-interno-save').disabled=true; try{await montarSaveInternal();}catch(e){say(e.message,true);}finally{$('montar-interno-save').disabled=false;} }; $('montar-customer-q').addEventListener('input',montarQueueContacts); $('montar-customer-q').addEventListener('focus',()=>{if($('montar-customer-hits').children.length)$('montar-customer-hits').hidden=false;}); $('montar-with-order').addEventListener('focus',()=>{ document.querySelector('input[name="montar-delivery"][value="with_order"]').checked=true; montarPaintDelivery(); }); $('montar-with-order').addEventListener('input',()=>{MONTAR.requestKey=null;}); for(const radio of document.querySelectorAll('input[name="montar-delivery"]')) radio.addEventListener('change',()=>{MONTAR.requestKey=null;montarPaintDelivery();montarPaintActions();}); $('montar-ship-cep').addEventListener('input',()=>{ const digits=$('montar-ship-cep').value.replace(/\D/g,'').slice(0,8); $('montar-ship-cep').value=digits.length>5?digits.slice(0,5)+'-'+digits.slice(5):digits; MONTAR.requestKey=null;montarResetFreight();montarPaintActions(); }); $('montar-cep-find').onclick=async()=>{ $('montar-cep-find').disabled=true; try{await montarCepLookup();}catch(e){say(e.message,true);} finally{$('montar-cep-find').disabled=false;} }; $('montar-freight-quote').onclick=async()=>{ $('montar-freight-quote').disabled=true; try{await montarFreightQuote();}catch(e){say(e.message,true);} finally{$('montar-freight-quote').disabled=false;} }; for(const id of ['montar-ship-recipient','montar-ship-street','montar-ship-number', 'montar-ship-complement','montar-ship-district','montar-ship-city']) $(id).addEventListener('input',()=>{MONTAR.requestKey=null;montarPaintActions();}); $('montar-ship-state').addEventListener('change',()=>{MONTAR.requestKey=null;montarPaintActions();}); document.addEventListener('click',event=>{ if(!event.target.closest('.montar-customer-search'))$('montar-customer-hits').hidden=true; }); const montarUfPlaceholder=node('option','UF');montarUfPlaceholder.value=''; $('montar-ship-state').append(montarUfPlaceholder,...MONTAR_UFS.map(uf=>{ const option=node('option',uf);option.value=uf;return option; })); montarPaintDelivery();