feat: the cart offers Correios PAC and SEDEX next to Jadlog
All checks were successful
Build and deploy / Validate source (push) Successful in 1m48s
Build and deploy / Integration suite on a real stack (push) Successful in 4m25s
Build and deploy / Secret scan and release gate (push) Successful in 15s
Build and deploy / Publish images (push) Successful in 1m54s

Dropstar sent its Correios contract. The cart now asks every carrier at once
for the CEP and lists each option with its delivery time, cheapest first and
chosen by default: Jadlog .PACKAGE, Correios PAC and Correios SEDEX, plus
pickup. A carrier that does not answer is left out instead of blocking the
others, and the server quotes the customer's choice again at approval. The
order summary, the Kanban and Minha conta name the carrier chosen.

app/correios.py follows the CWS manuals: a token from the posting card (kept
until shortly before it expires, renewed once if refused), the contract's own
prices by its DR, and the delivery time. Each box is one object priced by its
sides; Correios work out the cubic weight. All carriers price the same
package, now in app/package.py. Only CORREIOS_CODIGO_ACESSO goes in the
stack; the user, card and contract are its defaults. python -m
app.correios_probe checks the contract and its service codes on the account.

Tested: tests/test_correios (token, contract parameters, prices in Brazilian
format, boxes, a code override, a failing carrier), the full suite in a
CI-style stack, and the cart in Brave on desktop and phone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-15 13:47:53 -03:00
parent 69997f4598
commit 90e3126075
25 changed files with 735 additions and 108 deletions

View File

@@ -103,7 +103,7 @@
(MODOS[item.mode]?.tit || item.mode)+' · '+fmtM(Number(item.billed_metres))+' m', rs(item.total_cents/100)));
const pickup = approved.freight.service === 'pickup';
const prazo = approved.freight.days ? ' · até '+approved.freight.days+' dias úteis' : '';
rows.push(linha(pickup ? 'Retirada em Franca' : 'Frete'+prazo,
rows.push(linha(pickup ? 'Retirada em Franca' : (approved.freight.description || 'Frete')+prazo,
approved.freight.total_cents ? rs(approved.freight.total_cents/100) : 'Grátis'));
rows.push(linha('Total', rs(approved.total_cents/100), 'tot'));
resumo.replaceChildren(node('h4','Resumo do pedido'), ...rows);
@@ -255,10 +255,11 @@
return {metres:items.reduce((t,it)=>t+(it.cob||0),0), cents:Math.round(items.reduce((t,it)=>t+(it.total||0),0)*100)};
};
let freightQuoted = null;
// Every carrier's option for the CEP; the customer's choice stays chosen
// when the cart changes, else the cheapest is.
window.dtfFreight = async () => {
const cep = entrega.cep;
const service = (await ready).freight_service;
if (!service) {
if (!(await ready).freight_services?.length) {
$('cepMsg').textContent = 'A entrega ainda não está disponível. Escolha a retirada em Franca.';
return;
}
@@ -266,15 +267,18 @@
if (!metres) { $('cepMsg').textContent = 'Adicione um item ao pedido para cotar o frete.'; return; }
$('cepMsg').textContent = 'Cotando o frete…';
try {
const result = await api('/freight',{service,postal_code:cep,metres:metres.toFixed(2),declared_cents:cents});
const result = await api('/freight/options',{postal_code:cep,metres:metres.toFixed(2),declared_cents:cents});
if (entrega.cep !== cep || entrega.tipo !== 'frete') return;
entrega.valor = result.total_cents/100;
entrega.dias = result.days || null;
entrega.opcoes = result.options;
const chosen = result.options.find(o=>o.service===entrega.servico) || result.options[0];
entrega.servico = chosen.service;
entrega.valor = chosen.total_cents/100;
entrega.dias = chosen.days || null;
entrega.cotado = true;
freightQuoted = JSON.stringify(pacote());
$('cepMsg').textContent = '';
pintaEntrega();
} catch(error) { $('cepMsg').textContent = error.message; }
pintaFretes(); pintaEntrega();
} catch(error) { entrega.opcoes=[]; pintaFretes(); $('cepMsg').textContent = error.message; }
};
// A different package is a different freight: quote it again.
window.addEventListener('dtf-cart-changed',()=>{
@@ -314,7 +318,7 @@
upload_id:uploads[index],...source}))},
quality_status:item.qualityStatus,quality_acknowledged:item.qualityAcknowledged});
}
const service = entrega.tipo==='retira' ? 'pickup' : (await ready).freight_service;
const service = entrega.tipo==='retira' ? 'pickup' : entrega.servico;
if (!service) throw new Error('A entrega ainda não está disponível. Escolha a retirada em Franca.');
const content = {customer:{...cliente},items,freight:{service,postal_code:entrega.tipo==='retira'?'':entrega.cep}};
const destination = destinoApi();

View File

@@ -1041,7 +1041,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<span class="mk"></span>
<div>
<b><svg class="ic" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"/><path d="M15 18H9"/><path d="M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.62l-3.48-4.35A1 1 0 0 0 17.52 8H14"/><circle cx="17" cy="18" r="2"/><circle cx="7" cy="18" r="2"/></svg>Receber em casa</b>
<span>Entrega pela Jadlog em todo o Brasil. Informe o CEP para ver o valor e o prazo.</span>
<span>Jadlog ou Correios (PAC e SEDEX), para todo o Brasil. Informe o CEP para ver as opções.</span>
</div>
<em id="vFrete">—</em>
</button>
@@ -1051,6 +1051,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<input id="cepIn" aria-required="true" autocomplete="off" inputmode="numeric" maxlength="9" placeholder="00000-000">
</div>
<p id="cepMsg"></p>
<div class="fretes" id="fretes" role="radiogroup" aria-label="Opções de entrega" hidden></div>
<div class="campos endereco" id="endereco">
<div class="cp larga"><label>Quem recebe <span class="obr" aria-hidden="true">*</span></label>
<input id="eNome" aria-required="true" autocomplete="off" maxlength="120" placeholder="Nome ou empresa"></div>

View File

@@ -680,7 +680,7 @@ function renderPanel(order){
const placeLine=node('b');placeLine.append(icon(dest?ICON_TRUCK:ICON_PIN),dest?dest.recipient:'Retirada em Franca');
where.append(node('p','Entrega','eyebrow'),placeLine,
node('span',dest?dest.street+', '+dest.number+(dest.complement?' '+dest.complement:'')+' · '+dest.district+' · '+dest.city+'/'+dest.state+' · CEP '+dest.postal_code:'Cliente retira na fábrica'));
if(dest&&s.freight?.total_cents)where.append(node('span','Jadlog · '+money(s.freight.total_cents)+(s.freight.weight_kg?' · '+freightWeight(s.freight):''),'faint'));
if(dest&&s.freight?.total_cents)where.append(node('span',(s.freight.description||'Jadlog')+' · '+money(s.freight.total_cents)+(s.freight.weight_kg?' · '+freightWeight(s.freight):''),'faint'));
facts.append(who,where);
if(order.machine||board.machines?.length)facts.append(machineCard(order));
const items=node('section');items.append(node('p',s.items.length>1?'Itens':'Item','eyebrow'));
@@ -1587,16 +1587,18 @@ function renderIntegrations(){
details:mp&&mpCheck?mercadoPagoCheck(mpCheck):[]}));
const fr=board.providers?.freight||{};
const kg=v=>String(v).replace('.',',')+' kg';
rows.push(fr.provider==='jadlog'
const carriers=Object.values(fr.services||{});
const list=names=>names.length>1?names.slice(0,-1).join(', ')+' e '+names.at(-1):names[0];
rows.push(carriers.length
? integration({name:'Frete',state:fr.box_cm?'Ativo':'Verificar',tone:fr.box_cm?'ok':'warn',
summary:fr.box_cm?'Jadlog e retirada em Franca · prazo da Jadlog + '+fr.production_days+' dia(s) de produção.'
:'Cubagem não configurada: a Jadlog pode cobrar mais que a cotação.',
details:[['Pacote',kg(fr.base_kg)+' + '+kg(fr.per_metre_kg)+' por metro'],
summary:fr.box_cm?list(carriers)+' e retirada em Franca · prazo + '+fr.production_days+' dia(s) de produção.'
:'Caixa não configurada: as transportadoras podem cobrar mais que a cotação.',
details:[['Opções',list(carriers)],['Pacote',kg(fr.base_kg)+' + '+kg(fr.per_metre_kg)+' por metro'],
...(fr.box_cm?[['Caixa',fr.box_cm.map(n=>String(n).replace('.',',')).join(' × ')+' cm'],
['Cubagem',String(fr.cubage_kg_m3).replace('.',',')+' kg/m³ = '+kg(fr.cubed_kg)+' cubados'],
['Cubagem Jadlog',String(fr.cubage_kg_m3).replace('.',',')+' kg/m³ = '+kg(fr.cubed_kg)+' cubados'],
...(fr.metres_per_box?[['Por caixa','Até '+String(fr.metres_per_box).replace('.',',')+' m']]:[])]:[]),
// Jadlog charges the larger of the real and the cubed weight.
node('p',fr.box_cm?'A Jadlog cobra o maior entre o peso real e o cubado.':'Sem a caixa, a cotação usa só o peso real.')]})
// Each carrier charges the larger of the real and the cubed weight.
node('p','No carrinho o cliente vê todas as opções, da mais barata para a mais cara, com o prazo. Cada transportadora cobra o maior entre o peso real e o cubado.')]})
: integration({name:'Frete',state:'Não configurado',tone:'off',summary:'Somente retirada.'}));
rows.push(integration({name:'WhatsApp',state:'Não configurado',tone:'off',summary:'Mensagens registradas, sem envio.'}));
rows.push(mailRow(board.providers?.mail||{}));

View File

@@ -205,7 +205,7 @@ function itensPedido(snapshot){
}
function entrega(snapshot){
const d=snapshot.destination, p=node('p',null,'entregaPed');
p.append(icone(d?'caminhao':'local'),node('span',d?'Entrega pela Jadlog · '+d.street+', '+d.number+' · '+d.city+'/'+d.state:'Retirada em Franca · Av. Major Elias Motta, 1281'));
p.append(icone(d?'caminhao':'local'),node('span',d?'Entrega por '+(snapshot.freight?.description||'Jadlog')+' · '+d.street+', '+d.number+' · '+d.city+'/'+d.state:'Retirada em Franca · Av. Major Elias Motta, 1281'));
return p;
}
async function details(id,container,criado){

View File

@@ -63,7 +63,9 @@ function pintaPedido(){
'<div class="l"><span>'+n+(n===1?' item':' itens')+'</span><b>'+rs(itens+eco)+'</b></div>'+
(eco>0.01? '<div class="l" style="color:var(--verde-ml)"><span>Desconto pela nota</span>'+
'<b style="color:var(--verde-ml)">− '+rs(eco)+'</b></div>' : '')+
'<div class="l"><span>Frete'+(entrega.tipo==='frete' && entrega.cotado && entrega.dias
'<div class="l"><span>'+(entrega.tipo==='frete' && entrega.cotado
? escapeHTML((entrega.opcoes||[]).find(o=>o.service===entrega.servico)?.description||'Frete') : 'Frete')+
(entrega.tipo==='frete' && entrega.cotado && entrega.dias
? ' · até '+entrega.dias+' dias úteis' : '')+'</span><b>'+
(entrega.tipo==='retira' ? '<span style="color:var(--verde-ml)">Grátis</span>'
: entrega.cotado ? rs(frete) : 'a cotar')+'</b></div>'+

View File

@@ -94,7 +94,7 @@ let pedido=[]; // itens já fechados · o pagamento
// A escolha de entrega vale para o pedido inteiro, não por item. No Tiny, retirada
// grava forma_envio X, transportador DropStar e frete por conta do remetente — igual
// ao que a expedição já recebe hoje, sem criar processo novo.
let entrega={tipo:'retira', cep:'', valor:0, cotado:true, end:{}};
let entrega={tipo:'retira', cep:'', valor:0, cotado:true, end:{}, servico:'', opcoes:[]};
let cliente={cnpj:'', zap:'', mail:''};
// CNPJ com os dois dígitos verificadores · máscara sem conta não vale nada

View File

@@ -73,6 +73,26 @@ $('pVolta').addEventListener('click',()=>{
$('cPro').addEventListener('click',()=>ir(atual()+1));
})();
// The delivery options for the CEP, cheapest first: carrier, time and price.
function pintaFretes(){
const box=$('fretes'), opcoes=entrega.opcoes||[];
box.hidden=!opcoes.length;
box.innerHTML=opcoes.map((o,i)=>{
const on=o.service===entrega.servico, id='frete-'+o.service;
return '<label class="opF'+(on?' on':'')+'" for="'+id+'">'+
'<input type="radio" name="frete" id="'+id+'" value="'+escapeHTML(o.service)+'"'+(on?' checked':'')+'>'+
'<span class="opFn"><b>'+escapeHTML(o.description)+'</b>'+
(o.days?'<small>até '+o.days+' dias úteis</small>':'')+'</span>'+
(i===0&&opcoes.length>1?'<i>mais barato</i>':'')+
'<em>'+rs(o.total_cents/100)+'</em></label>';
}).join('');
}
$('fretes').addEventListener('change',e=>{
const o=(entrega.opcoes||[]).find(x=>x.service===e.target.value);
if(!o) return;
entrega.servico=o.service; entrega.valor=o.total_cents/100; entrega.dias=o.days||null; entrega.cotado=true;
pintaFretes(); pintaEntrega();
});
function pintaEntrega(){
document.querySelectorAll('.opE').forEach(b=>
b.classList.toggle('on', b.dataset.ent===entrega.tipo));
@@ -164,7 +184,7 @@ $('cepIn').addEventListener('input',e=>{
const v=e.target.value.replace(/\D/g,'').slice(0,8);
e.target.value = fmtCep(v);
if(v===entrega.cep) return;
entrega.cep=v; entrega.cotado=false; entrega.valor=0; entrega.dias=null; pintaEntrega();
entrega.cep=v; entrega.cotado=false; entrega.valor=0; entrega.dias=null; entrega.opcoes=[]; pintaFretes(); pintaEntrega();
if(v.length===8){ buscaEndereco(v); if(window.dtfFreight) window.dtfFreight(); }
});
for(const [id,chave] of [['eNome','nome'],['eRua','rua'],['eNum','num'],['eComp','comp'],

View File

@@ -498,3 +498,15 @@ html:is([data-rota="pagamento"],[data-rota="pix"]) .pagGrid{display:grid;grid-te
so the page's full height is 100/0.88 vh there (site-shell.css keeps the
footer at the bottom). */
@media (min-width:1100px){html{zoom:.88}body{min-height:calc(100vh / .88)}}
/* Delivery options for the CEP: one row each, the chosen one marked. */
.fretes{display:flex;flex-direction:column;gap:8px;margin:2px 0 14px}
/* Inside .cep, whose own "label" rule would stack each row. */
.cep .opF{display:flex;align-items:center;gap:12px;margin:0;padding:12px 14px;border:1px solid var(--linha);border-radius:10px;background:#fff;color:var(--preto);font-size:15px;cursor:pointer}
.cep .opF.on{border:2px solid var(--laranja);padding:11px 13px;background:var(--aviso-fundo)}
.opF input{accent-color:var(--laranja-escuro);width:18px;height:18px;margin:0}
.opFn{display:flex;flex-direction:column;flex:1;min-width:0}
.opFn b{font-size:15px}
.opFn small{font-size:13.5px;color:var(--texto2)}
.opF i{font-style:normal;font-size:12px;font-weight:700;color:var(--verde-ml);white-space:nowrap}
.opF em{font-style:normal;font-weight:800;white-space:nowrap}