feat: montador Interno and Venda, Tiny customers, brand per stamp (front 7a.3, Marcus 10/11)

Interno: the Expedição assembles the marketplace's own sales on the fixed
internal customer Gestão fills in once; no Tiny order, no paid e-mail,
marked interno, it stays in house. Venda: a Vendedor or Gestão picks the
customer from the Tiny base and the order goes to Tiny like an approved
quote, faturado (Boleto from TINY_RECEIPT_BOLETO when set), pickup or
'junto com o pedido de roupa nº X'. Números counts both at table price,
apart from cash (and the average ticket over cash orders only). Each stamp
can carry a brand and a public flag for the future catalogue.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-11 11:01:44 -03:00
parent e6197d6e40
commit b5a51137fb
15 changed files with 710 additions and 97 deletions

View File

@@ -1,20 +1,115 @@
/* 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, which creates the card, is slice 2b. Uses the globals of kanban.js
and packing.js, loaded first. */
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};
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};
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 withOrder=montarDelivery()==='with_order';
$('montar-with-order').disabled=!withOrder;
if(!withOrder)$('montar-with-order').value='';
}
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;
}
// 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();
@@ -59,14 +154,16 @@ function montarDropPreview(){
if(MONTAR.preview)URL.revokeObjectURL(MONTAR.preview.url);
MONTAR.preview=null;
}
function montarPaintPreview(found){
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 wrap=node('div',undefined,'montar-stamp');wrap.append(img,words);
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(){
@@ -88,7 +185,12 @@ async function montarPreview(){
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();
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);
@@ -198,15 +300,24 @@ function montarCustomer(){
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;
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.
// 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 ready=!!(MONTAR.lines.length&&MONTAR.layout&&!MONTAR.layoutPending&&
montarCustomerFilled()&&!MONTAR.creating);
customerReady&&!MONTAR.creating);
build.disabled=!ready;
build.title=ready?'':(MONTAR.lines.length?'Aguarde a montagem e preencha o cliente.':'Monte a folha primeiro.');
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.'
:'Preencha os dados do cliente.');
}
// 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'.
@@ -252,13 +363,23 @@ function montarItems(lines,uploads){
}
async function montarCreate(){
if(MONTAR.creating)return;
const customer=montarCustomer();
if(!montarCustomerFilled())return say('Preencha os dados do cliente.',true);
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;
}
if(kind==='venda'&&montarDelivery()==='with_order'&&!montarWithOrder())
return say('Informe o número do pedido de roupa.',true);
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 '+customer.name+'?','Criar pedido'))return;
', '+metres(MONTAR.layout.altura/100)+', para '+name+'?','Criar pedido'))return;
MONTAR.creating=true;montarPaintActions();
try{
const uploads=new Map();
@@ -271,11 +392,17 @@ async function montarCreate(){
}
say('Criando o pedido…');
if(!MONTAR.requestKey)MONTAR.requestKey=crypto.randomUUID();
const order=await api('/montador/orders',{request_key:MONTAR.requestKey,
customer,items:montarItems(lines,uploads)});
const body={request_key:MONTAR.requestKey,kind,items:montarItems(lines,uploads)};
if(kind==='venda'){
body.customer=customer;
const withOrder=montarWithOrder();
if(withOrder)body.with_order=withOrder;
}
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);}
@@ -328,7 +455,9 @@ async function montarAdd(){
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);
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(dpi<MONTAR_DPI_REFUSE)return say('A estampa tem só '+Math.floor(dpi)+' DPI em '+size.letter+': pequena demais.',true);
@@ -392,9 +521,76 @@ async function montarLoadSizes(repaint){
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){
$('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;
MONTAR.requestKey=null;
montarPaintActions();
const missing=MONTAR_CUSTOMER.find(id=>!$(id).value.trim());
if(missing)$(missing).focus();
}
async function loadMontador(){
montarPaintFolder();
try{await montarLoadSizes(false);}
// 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();}
@@ -433,3 +629,22 @@ $('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();});
document.addEventListener('click',event=>{
if(!event.target.closest('.montar-customer-search'))$('montar-customer-hits').hidden=true;
});
montarPaintDelivery();