Files
dtf-system/web/kanban-montador.js
Cauê Faleiros 6ec0ea31a6
All checks were successful
Build and deploy / Validate source (push) Successful in 14s
Build and deploy / Integration suite on a real stack (push) Successful in 8m42s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m10s
feat: billed every 10 cm with 8 mm in the customer's favour, and the Site shows the whole sum (Marcus, 2026-11-27)
Marcus: a length that passes a 10 cm step by up to 8 mm is billed at that
step; by more, at the next. One rule for every product, on the server
(pricing.billed_length), the Site (arredonda10) and the Montador's estimate;
the print file accepts the 8 mm past the billed length instead of sending
the sheet to hand preparation.

The Site showed four numbers that did not add up (0,88 m, 4,42 m, 4,45 m,
4,50 m), and the team read 4,40 m. The copies line now gives the whole
sum ("5 × 88,4 cm + 4 espaços de 8 mm = 445,2 cm"), and the buy box says
why the billed metres are what they are, as a benefit ("os 4 mm a mais
ficam por nossa conta"). The buy box's parts note said 20 m; parts are
10 m since 18/11.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:04:10 -03:00

963 lines
48 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* 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. */
// Dropstar's codes carry dots (NX.226, NX.1003); not as the first character.
const MONTAR_CODE=/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,39}$/;
// 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;
// Phosphor gear, for the Ajustes button in the page header.
const MONTAR_GEAR='M128 80a48 48 0 1 0 48 48a48.05 48.05 0 0 0-48-48m0 80a32 32 0 1 1 32-32a32 32 0 0 1-32 32m109.94-52.79a8 8 0 0 0-3.89-5.4l-29.83-17l-.12-33.62a8 8 0 0 0-2.83-6.08a111.9 111.9 0 0 0-36.72-20.67a8 8 0 0 0-6.46.59L128 41.85L97.88 25a8 8 0 0 0-6.47-.6a112.1 112.1 0 0 0-36.68 20.75a8 8 0 0 0-2.83 6.07l-.15 33.65l-29.83 17a8 8 0 0 0-3.89 5.4a106.5 106.5 0 0 0 0 41.56a8 8 0 0 0 3.89 5.4l29.83 17l.12 33.62a8 8 0 0 0 2.83 6.08a111.9 111.9 0 0 0 36.72 20.67a8 8 0 0 0 6.46-.59L128 214.15L158.12 231a7.9 7.9 0 0 0 3.9 1a8.1 8.1 0 0 0 2.57-.42a112.1 112.1 0 0 0 36.68-20.73a8 8 0 0 0 2.83-6.07l.15-33.65l29.83-17a8 8 0 0 0 3.89-5.4a106.5 106.5 0 0 0-.03-41.52m-15 34.91l-28.57 16.25a8 8 0 0 0-3 3c-.58 1-1.19 2.06-1.81 3.06a7.94 7.94 0 0 0-1.22 4.21l-.15 32.25a95.9 95.9 0 0 1-25.37 14.3L134 199.13a8 8 0 0 0-3.91-1h-3.83a8.1 8.1 0 0 0-4.1 1l-28.84 16.1A96 96 0 0 1 67.88 201l-.11-32.2a8 8 0 0 0-1.22-4.22c-.62-1-1.23-2-1.8-3.06a8.1 8.1 0 0 0-3-3.06l-28.6-16.29a90.5 90.5 0 0 1 0-28.26l28.52-16.28a8 8 0 0 0 3-3c.58-1 1.19-2.06 1.81-3.06a7.94 7.94 0 0 0 1.22-4.21l.15-32.25a95.9 95.9 0 0 1 25.37-14.3L122 56.87a8 8 0 0 0 4.1 1h3.64a8.1 8.1 0 0 0 4.1-1l28.84-16.1A96 96 0 0 1 188.12 55l.11 32.2a8 8 0 0 0 1.22 4.22c.62 1 1.23 2 1.8 3.06a8.1 8.1 0 0 0 3 3.06l28.6 16.29a90.5 90.5 0 0 1 .05 28.29Z';
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.
// The kinds of each profile, summed (app/api/stamps.py MONTADOR_KINDS).
const montarKindNames=()=>['interno','venda'].filter(kind=>myRoles().some(r=>
r==='expedicao'?kind==='interno':r==='vendedor'?kind==='venda':['superadmin','admin','gestao'].includes(r)));
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();
}
const montarInitials=name=>String(name||'').trim().split(/\s+/).slice(0,2).map(word=>word[0]).join('').toUpperCase()||'·';
function montarPaintCustomer(){
const interno=MONTAR.kind==='interno';
const ready=interno?montarInternalReady():montarCustomerFilled();
$('montar-customer-title').textContent=interno?'Cliente interno':'Cliente do Tiny';
$('montar-customer-search').hidden=interno||ready;
$('montar-customer-card').hidden=!ready;
$('montar-interno-note').hidden=!interno;
$('montar-customer-fields').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);
}
if(ready){
const name=interno?montarInternalField('name'):$('montar-name').value.trim();
$('montar-customer-avatar').textContent=montarInitials(name);
$('montar-customer-name').textContent=name||'Cliente';
$('montar-customer-note').textContent=interno?'Cliente interno':'Contato do Tiny';
$('montar-customer-change').hidden=interno;
}
}
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;copyIndex<source.copies;copyIndex++)
cargas.push({a:{sourceIndex,giro:0,esp:false},img:source.line.img,copyIndex,
w:source.line.widthCm,h:source.line.heightCm,travado:false});
});
return encaixar(cargas,MONTAR_FILM_CM).altura/100;
});
const catalog=MONTAR.catalog?.avulsa;
if(!catalog)throw new Error('Preço de tabela indisponível agora.');
// Every 10 cm, 8 mm in the customer's favour (app/core/pricing.py billed_length).
const billed=heights.map(metres=>Math.max(1,Math.ceil(+((metres-0.008)*10).toFixed(6))/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: the main column asks for it
// and the side panel stays, as the canvas' no-folder screen.
function montarPaintFolder(){
const ok=montarFolderReady();
$('montar-nofolder-panel').hidden=ok;
$('montar-setup').hidden=!ok;
$('montar-sheet').hidden=!ok;
const chip=$('montar-folder-chip');
if(chip){
chip.classList.toggle('warn',!ok);
chip.querySelector('span').textContent=ok?'Pasta: '+FOLDER.handle.name:'Sem pasta neste computador';
}
const ajustes=$('montar-ajustes-open');
if(ajustes)ajustes.hidden=!may('manage');
if(!ok){montarDropPreview();$('montar-preview').replaceChildren();}
}
async function montarChooseFolder(){
await chooseFolder();
montarPaintFolder();
if(!montarFolderReady())return;
montarPaintLines();
if($('montar-code').value.trim())montarQueuePreview();else montarPaintHint();
montarPaintActions();
}
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.');
return true;
}
return false;
}
// The file's own size is a dot and the letter before .png (Marcus,
// 2026-11-16): NX.226.C.png is NX.226 in C. The size asked for first, then the
// code without a size, then another size of it, scaled: the closest larger
// one, so it shrinks, else the largest. Only PNG.
function montarNames(code,size){
const others=MONTAR.sizes.filter(other=>other.letter!==size.letter)
.sort((a,b)=>Number(a.width_cm)-Number(b.width_cm));
const up=others.filter(other=>Number(other.width_cm)>=Number(size.width_cm));
const down=others.filter(other=>Number(other.width_cm)<Number(size.width_cm)).reverse();
return [code+'.'+size.letter+'.png',code+'.png',...[...up,...down].map(other=>code+'.'+other.letter+'.png')];
}
async function montarRead(code,size){
const dir=await FOLDER.handle.getDirectoryHandle('Estampas',{create:true});
for(const name of montarNames(code,size)){
let handle;
try{handle=await dir.getFileHandle(name);}
catch(e){if(['NotFoundError','TypeError'].includes(e.name))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;
const block=$('montar-brand-block');
if(block){block.hidden=true;$('montar-brand-slot').replaceChildren();}
}
function montarFoundMetres(found){
const qty=Math.max(1,Math.round(Number($('montar-qty').value)||1));
const perRow=Math.max(1,Math.floor((MONTAR_FILM_CM-MONTAR_GAP_CM)/(found.widthCm+MONTAR_GAP_CM)));
const rows=Math.ceil(qty/perRow);
return (MONTAR_GAP_CM+rows*(montarHeight(found)+MONTAR_GAP_CM))/100;
}
function montarPaintPreview(found,stamp){
montarDropPreview();
MONTAR.preview=found;
const qty=Math.max(1,Math.round(Number($('montar-qty').value)||1));
const dpi=montarDpi(found);
const words=node('div',undefined,'montar-foundinfo');
words.append(node('b',found.code+' encontrada'),
node('span',qty+' × '+cm(found.widthCm)+' cm de largura · cerca de '+metres(montarFoundMetres(found))+' de filme'));
if(found.name!==found.code+'.'+found.letter+'.png')words.append(node('span','Feita a partir de '+found.name+'.'));
if(dpi<MONTAR_DPI_REFUSE)words.append(node('span','Só '+Math.floor(dpi)+' DPI em '+$('montar-size').value+': pequena demais para imprimir.','montar-missing'));
else if(dpi<MONTAR_DPI_WARN)words.append(node('span',Math.floor(dpi)+' DPI: abaixo de '+MONTAR_DPI_WARN+' DPI.','montar-dpiwarn'));
const img=node('img',undefined,'montar-foundthumb');img.src=found.url;img.alt='Estampa '+found.code;
const wrap=node('div',undefined,'montar-found');wrap.append(img,words);
$('montar-preview').replaceChildren(wrap);
$('montar-brand-title').textContent='Marca da estampa '+found.code;
$('montar-brand-slot').replaceChildren(montarBrandRow(found.code,stamp));
$('montar-brand-block').hidden=false;
}
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 count=MONTAR.lines.length;
const pieces=MONTAR.lines.reduce((total,line)=>total+line.qty,0);
const done=MONTAR.layout&&!MONTAR.layoutPending;
const film=count?(done?MONTAR.layout.altura/100:montarEstimate()):0;
$('montar-count').textContent=count?plural(count,'estampa','estampas')+', '+plural(pieces,'peça','peças'):'';
$('montar-sum-stamps').textContent=String(count);
$('montar-sum-pieces').textContent=String(pieces);
$('montar-sum-film').textContent=count?(done?metres(film):metres(film)+' …'):'—';
$('montar-film-length').textContent=count?metres(film):'—';
$('montar-film-hint').textContent='em filme de 57 cm, já encaixada. Atualiza a cada mudança na lista.'+
(count&&!done?' Calculando a montagem…':'');
$('montar-clear').disabled=!count;
$('montar-warning').hidden=!(count>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();
montarDrawPreview(MONTAR.layout);
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 film column, white film and the
// outline; the set of stamps and their length sit beside it.
function montarDrawPreview(layout){
const box=$('montar-layout'),film=$('montar-film'),canvas=$('montar-canvas'),wait=$('montar-film-wait');
if(!MONTAR.lines.length){box.hidden=true;return;}
box.hidden=false;
canvas.hidden=!layout;wait.hidden=!!layout;
if(!layout)return;
const width=film.clientWidth;
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;copyIndex<source.copies;copyIndex++)
cargas.push({a:{sourceIndex,giro:0,esp:false},img:source.line.img,copyIndex,
w:source.line.widthCm,h:source.line.heightCm,travado:false});
});
const enc=encaixar(cargas,MONTAR_FILM_CM);
const height=+enc.altura.toFixed(4);
const grades=sources.map(source=>montarGrade(source.line.dpi));
const warning=sources.some(source=>source.line.dpi<MONTAR_DPI_WARN);
return {mode:'avulsa',metres:+(height/100).toFixed(4),
grade:Math.round(grades.reduce((sum,n)=>sum+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.');
name=montarInternalField('name');
}else{
customer=montarCustomer();
if(!montarCustomerFilled())return say('Preencha os dados do cliente.');
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.');
}
if(kind==='venda'&&montarDelivery()==='ship'){
destination=montarDestination();
if(!destination)return say('Preencha o endereço de entrega.');
if(!MONTAR.freight)return say('Cote o frete e escolha uma opção.');
if(MONTAR.freight.postal_code!==montarCep())return say('Cote o frete de novo para este CEP.');
deliveryFreight={service:MONTAR.freight.service,postal_code:montarCep()};
}
if(!MONTAR.lines.length)return say('Monte a folha primeiro.');
if(!MONTAR.layout||MONTAR.layoutPending)return say('A montagem ainda está sendo calculada.');
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<lines.length;index++){
const line=lines[index];
say('Enviando estampas '+(index+1)+' de '+lines.length+'…');
const id=await dtfUpload(line.file,{api,startPath:'/montador/uploads',
scope:'montador:'+line.code+'-'+line.letter,progress:say});
uploads.set(line.id,id);
}
say('Criando o pedido…');
if(!MONTAR.requestKey)MONTAR.requestKey=crypto.randomUUID();
const body={request_key:MONTAR.requestKey,kind,items:montarItems(lines,uploads)};
if(kind==='venda'){
body.customer=customer;
if(withOrder)body.with_order=withOrder;
if(deliveryFreight)body.freight=deliveryFreight;
if(destination)body.destination=destination;
}
const order=await api('/montador/orders',body);
MONTAR.requestKey=null;
montarClear();
montarClearCustomer();
montarPaintCustomer();
say('Pedido #'+order.number+' criado em Arte recebida.',false,10000);
load(true).catch(()=>{});
}catch(e){say(e.message,true);}
finally{MONTAR.creating=false;montarPaintActions();}
}
function montarLineMetres(line){
const qty=Math.max(1,Math.round(Number(line.qty)||1));
const perRow=Math.max(1,Math.floor((MONTAR_FILM_CM-MONTAR_GAP_CM)/(line.widthCm+MONTAR_GAP_CM)));
const rows=Math.ceil(qty/perRow);
return (MONTAR_GAP_CM+rows*(line.heightCm+MONTAR_GAP_CM))/100;
}
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('div',undefined,'montar-linemeta');
words.append(node('b',line.code),node('span','tamanho '+line.letter+' · '+cm(line.widthCm)+' cm','sub'));
if(line.dpi<MONTAR_DPI_WARN)words.append(badge(Math.floor(line.dpi)+' DPI','warn','Abaixo de '+MONTAR_DPI_WARN+' DPI.'));
const step=node('div',undefined,'montar-step');
const minus=node('button','−','montar-stepbtn');minus.type='button';minus.setAttribute('aria-label','Menos uma');
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);
const plus=node('button','+','montar-stepbtn');plus.type='button';plus.setAttribute('aria-label','Mais uma');
minus.disabled=line.qty<=1;plus.disabled=line.qty>=9999;
const setQty=value=>{
const next=Math.min(9999,Math.max(1,Math.round(Number(value)||1)));
line.qty=next;qty.value=String(next);montarChanged();
};
minus.onclick=()=>setQty(line.qty-1);
plus.onclick=()=>setQty(line.qty+1);
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();
};
step.append(minus,qty,plus);
row.append(img,words,step,node('span',metres(montarLineMetres(line)),'montar-h'),
iconButton(IC.close,'Remover '+line.code+' '+line.letter,()=>montarRemoveLine(line),'btn sq ghost montar-x'));
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, ponto, hífen ou sublinhado, até 40.');
if(!size)return say('Nenhum tamanho na tabela. Peça à Gestão para cadastrar.');
const qty=Number($('montar-qty').value);
if(!Number.isInteger(qty)||qty<1||qty>9999)return say('A quantidade vai de 1 a 9999.');
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/.');}
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.');
const dpi=montarDpi(found);
if(dpi<MONTAR_DPI_REFUSE)return say('A estampa tem só '+Math.floor(dpi)+' DPI em '+size.letter+': pequena demais.');
const existing=MONTAR.lines.find(line=>line.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;},'btn sq ghost montar-sizex');
row.append(letter,width,node('em','cm'),remove);
return row;
}
function montarPaintSizeEditor(){
const box=$('montar-sizes');
if(!box)return;
if(!may('manage')){box.replaceChildren();return;}
box.replaceChildren(...MONTAR.sizes.map(montarSizeRow));
}
function montarCollectSizes(){
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)){say('Cada tamanho precisa de uma letra de A a ZZ.');return null;}
if(seen.has(letter)){say('A letra '+letter+' aparece mais de uma vez.');return null;}
if(!(width>0&&width<=56)){say('A largura de '+letter+' vai de 0,01 a 56 cm.');return null;}
seen.add(letter);sizes.push({letter,width_cm:Number(width.toFixed(2))});
}
if(!sizes.length){say('A tabela precisa de pelo menos um tamanho.');return null;}
return sizes;
}
async function montarSaveAdjustments(){
const sizes=montarCollectSizes();
if(!sizes)return false;
let customer=null;
if(MONTAR.internalDirty){
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])){
say('Preencha todos os campos do cliente interno.');
return false;
}
}
await api('/stamp-sizes',{sizes});
if(customer)await api('/internal-customer',customer);
MONTAR.dirty=false;MONTAR.internalDirty=false;
say(customer?'Ajustes salvos.':'Tamanhos salvos.');
await Promise.all([montarLoadSizes(true),montarLoadInternal(true)]);
montarQueuePreview();
return true;
}
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')||!$('montar-interno-name'))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');
if(may('manage')&&(repaint||!MONTAR.internalDirty))montarPaintInternalFields();
montarPaintKind();
montarPaintCustomer();
montarPaintActions();
}
// 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;
montarPaintCustomer();
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.lines.length)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;montarPaintCustomer();montarPaintActions();});
$('montar-customer-change').onclick=()=>{
for(const id of MONTAR_CUSTOMER)$(id).value='';
$('montar-customer-q').value='';$('montar-customer-hits').hidden=true;
MONTAR.requestKey=null;montarPaintCustomer();montarPaintActions();$('montar-customer-q').focus();
};
$('montar-nofolder-choose').onclick=async()=>{
$('montar-nofolder-choose').disabled=true;
try{await montarChooseFolder();}catch(e){say(e.message,true);}
finally{$('montar-nofolder-choose').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;
});
// ---- Page header (the canvas' M1/M2): folder chip and Ajustes -------------
const montarHead=node('div',undefined,'montar-head');
const montarFolderChip=node('span',undefined,'mchip');montarFolderChip.id='montar-folder-chip';
montarFolderChip.append(node('i'),node('span'));
const montarAjustes=node('button',undefined,'btn ghost montar-ajustes-open');
montarAjustes.type='button';montarAjustes.id='montar-ajustes-open';montarAjustes.hidden=true;
montarAjustes.append(svgIcon(MONTAR_GEAR,'i m'),node('span','Ajustes'));
montarAjustes.onclick=()=>montarOpenAdjustments();
montarHead.append(montarFolderChip,montarAjustes);
document.querySelector('.top .ptitle').after(montarHead);
const montarShowHead=()=>{montarHead.hidden=$('tab-montar').hidden;};
new MutationObserver(montarShowHead).observe($('tab-montar'),{attributes:true,attributeFilter:['hidden']});
montarShowHead();
// ---- Ajustes (the canvas' M3): sizes and the internal customer -------------
// Built with the shared formDialog when the header button is pressed, so no
// dialog stays in the page: the browser tests count open .modal elements.
function montarAdjustmentFields(){
const sizes=node('section',undefined,'montar-ajustes-sec');
const sizesTitle=node('h3');sizesTitle.append('Tamanhos ',node('span','· cada letra com a largura da estampa','hint'));
const grid=node('div',undefined,'montar-sizes');grid.id='montar-sizes';
grid.append(...MONTAR.sizes.map(montarSizeRow));
const add=node('button',undefined,'btn ghost montar-size-add');add.type='button';add.id='montar-size-add';
add.append(svgIcon(IC.plus,'i m'),'Adicionar tamanho');
add.onclick=()=>{MONTAR.dirty=true;grid.append(montarSizeRow(null));};
sizes.append(sizesTitle,grid,add);
const internal=node('section',undefined,'montar-ajustes-sec');
const internalTitle=node('h3');
internalTitle.append('Cliente interno ',node('span','· o cliente fixo dos pedidos Internos; com um campo vazio, Interno fica indisponível','hint'));
const fields=node('div',undefined,'montar-customer-fields montar-interno-fields');
const makeField=(id,label,attrs,value)=>{
const line=node('label',undefined,'fld');line.append(node('span',label));
const input=node('input');input.id=id;Object.assign(input,attrs);input.autocomplete='off';input.value=value||'';
input.addEventListener('input',()=>{MONTAR.internalDirty=true;});
line.append(input);return line;
};
fields.append(
makeField('montar-interno-name','Nome',{maxLength:80,placeholder:'Nexstar · Marketplace'},montarInternalField('name')),
makeField('montar-interno-doc','CPF ou CNPJ',{inputMode:'numeric',maxLength:18,placeholder:'CPF ou CNPJ'},montarInternalField('cnpj')),
makeField('montar-interno-zap','WhatsApp',{inputMode:'numeric',maxLength:15,placeholder:'(16) 99999-9999'},montarInternalField('zap')),
makeField('montar-interno-mail','E-mail',{type:'email',maxLength:254,placeholder:'voce@empresa.com.br'},montarInternalField('mail')));
internal.append(internalTitle,fields);
return [sizes,internal];
}
function montarOpenAdjustments(){
if(!may('manage')||$('montar-sizes'))return;
MONTAR.dirty=false;MONTAR.internalDirty=false;
formDialog('Ajustes do Montar',{
text:'Valem para todas as folhas. Mudam pouco, por isso ficam aqui e não na tela.',
fields:montarAdjustmentFields(),label:'Salvar ajustes',width:720,className:'montar-ajustes-dlg',
onsave:async()=>montarSaveAdjustments()
});
}
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();