feat: the cart and the account ask for the customer's name
All checks were successful
Build and deploy / Validate source (push) Successful in 10s
Build and deploy / Integration suite on a real stack (push) Successful in 4m49s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m15s

The Site asked only for CPF/CNPJ, WhatsApp and e-mail, so a person's Tiny
contact was named after the recipient or the e-mail, and the WhatsApp notices
the client's n8n sends from Tiny greeted "Olá, fulano@gmail.com". The cart's
"Seus dados" and the signup now ask for a name, the account page can change
it, and it names a CPF customer's Tiny contact (a CNPJ keeps the registry's
razão social), the Kanban card and the team's alerts. Orders placed before
have none, as the server still accepts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-16 18:38:09 -03:00
parent 7eb7d90f8b
commit 1f2358c8b5
13 changed files with 78 additions and 20 deletions

View File

@@ -256,12 +256,14 @@ def account_row(c, identity, lock=False):
@router.post('/api/account/profile')
def update_profile(body: ProfileUpdate, identity=Depends(owner)):
"""WhatsApp and the saved delivery address. The CPF or CNPJ is the account's and
"""Name, WhatsApp and the saved delivery address. The CPF or CNPJ is the account's and
does not change; the e-mail is the login and changes on its own route."""
with db.connect() as c:
row = account_row(c, identity, lock=True)
profile = {**row['profile'], 'zap': body.zap,
'address': body.address.model_dump() if body.address else None}
if body.name is not None:
profile['name'] = body.name
c.execute('UPDATE dtf_local.accounts SET profile=%s WHERE id=%s', (Jsonb(profile), identity))
audit('account_profile_updated', account=str(identity))
return {'customer': profile}

View File

@@ -21,12 +21,27 @@ def cnpj_ok(digits):
and check_digit(digits[:12], [5,4,3,2,9,8,7,6,5,4,3,2]) == int(digits[12])
and check_digit(digits[:13], [6,5,4,3,2,9,8,7,6,5,4,3,2]) == int(digits[13]))
def person_name(value):
"""A name as typed, with its spaces tidied; at least two letters when given."""
name = ' '.join(str(value or '').split())
if name and sum(ch.isalpha() for ch in name) < 2:
raise ValueError('Invalid name')
return name
class Customer(StrictModel):
# The customer's CPF or CNPJ, digits only. The key keeps the name it had
# when only companies bought, as stored orders, quotes and accounts use it.
cnpj: str
zap: str
mail: str = Field(max_length=254)
# Who to greet: the Tiny contact and the WhatsApp notices use it. Empty in
# orders placed before the Site asked for it.
name: str = Field(default='', max_length=80)
@field_validator('name')
@classmethod
def name_valid(cls, value):
return person_name(value)
@field_validator('cnpj')
@classmethod
@@ -243,9 +258,15 @@ class Register(StrictModel):
password: str = Field(min_length=12, max_length=128)
class ProfileUpdate(StrictModel):
"""What a customer may change about their account; the CNPJ is not among it."""
"""What a customer may change about their account; the CPF/CNPJ is not among it."""
zap: str
address: Destination | None = None
name: str | None = Field(default=None, max_length=80)
@field_validator('name')
@classmethod
def name_valid(cls, value):
return None if value is None else person_name(value)
@field_validator('zap')
@classmethod

View File

@@ -81,7 +81,8 @@ def summary(order):
document = f'{document[:2]}.{document[2:5]}.{document[5:8]}/{document[8:12]}-{document[12:]}'
elif len(document) == 11:
document = f'{document[:3]}.{document[3:6]}.{document[6:9]}-{document[9:]}'
lines = [f"Cliente: {document} · {customer.get('mail', '')}"]
who = ' · '.join(part for part in (customer.get('name'), document, customer.get('mail', '')) if part)
lines = [f"Cliente: {who}"]
for item in order.get('items', []):
metres = item.get('billed_metres') or item.get('metres')
lines.append(f"{PRODUCTS.get(item.get('mode'), item.get('mode'))} · {str(metres).replace('.', ',')} m")

View File

@@ -360,12 +360,14 @@ def money(cents):
def contact_payload(order, company=None):
"""A new contact, named after the company's razão social when the
registry gave it (app/cnpj.py), else the recipient or the e-mail. A CPF
(11 digits) is a person (F), a CNPJ a company (J)."""
registry gave it (app/cnpj.py), else the customer's name, else the
recipient or the e-mail. A CPF (11 digits) is a person (F), a CNPJ a
company (J)."""
customer = order['customer']
destination = order.get('destination')
company = company or {}
contact = {'nome': company.get('legal') or (destination or {}).get('recipient') or customer['mail'],
contact = {'nome': (company.get('legal') or customer.get('name') or (destination or {}).get('recipient')
or customer['mail']),
'tipoPessoa': 'F' if len(customer['cnpj']) == 11 else 'J', 'cpfCnpj': customer['cnpj'], 'email': customer['mail'],
'celular': customer['zap'], 'situacao': 'A'}
if company.get('trade'):

View File

@@ -82,6 +82,7 @@ try{
const total=Math.round(itemCents)/100;
await waitFor(()=>site.eval(`Math.abs(itemAtual.total-${total})<0.005`),'manual-file price');
assert.equal(await site.eval(`$('carrLin').textContent.includes('Arquivo aberto na mão')`),extraCents>0);
await site.fill('#fNome','Cliente Teste');
await site.fill('#fCnpj','11222333000181');
await site.fill('#fZap','11999999999');
await site.fill('#fMail','local-browser@example.test');
@@ -105,8 +106,14 @@ try{
await site.click('#desfazerBtn');
assert.equal(await site.eval(`pedido.length===1 && Math.abs(pedido[0].total-${total})<0.005 && $("desfazer").hidden`),true);
// The items come back after a reload; the customer's details do not.
assert.deepEqual(await site.eval(`['fCnpj','fZap','fMail'].map(id=>$(id).value)`),['','','']);
assert.deepEqual(await site.eval(`['fNome','fCnpj','fZap','fMail'].map(id=>$(id).value)`),['','','','']);
assert.equal(await site.eval('document.getElementById("bPagar").disabled'),true);
// A name is required: without it, no payment.
await site.fill('#fNome','A');
await site.fill('#fCnpj','52998224725');await site.fill('#fZap','11999999999');await site.fill('#fMail','local-browser@example.test');
assert.equal(await site.eval('clienteOk()'),false);
await site.fill('#fNome',' Maria da Silva');
assert.equal(await site.eval('cliente.name'),'Maria da Silva');
// A CPF or a CNPJ, each in its own mask; this order is a person's.
await site.fill('#fCnpj','11222333000181');
assert.equal(await site.eval(`$('fCnpj').value`),'11.222.333/0001-81');
@@ -172,6 +179,8 @@ try{
await kanban.click('#refresh');
await waitFor(()=>kanban.eval(`board.orders.some(o=>o.quote_id===${JSON.stringify(qid)})`),'paid card');
const oid=await kanban.eval(`board.orders.find(o=>o.quote_id===${JSON.stringify(qid)}).id`);
// The customer's name is on the order, and the Kanban card is titled with it.
assert.equal(await kanban.eval(`board.orders.find(o=>o.id===${JSON.stringify(oid)}).snapshot.customer.name`),'Maria da Silva');
assert.deepEqual(await kanban.eval(`(()=>{const spec=board.orders.find(o=>o.id===${JSON.stringify(oid)}).snapshot.items[0].production;const source=spec.sources[0];return {kind:source.kind,copies:source.copies,length:Number(source.length_cm),height:Number(spec.height_cm),placed:spec.placements.length}})()`),
{kind:'sheet',copies:1,length:101,height:101,placed:1});
// The print queue's folder, switched on in Integrações. The native picker
@@ -260,7 +269,7 @@ try{
await waitFor(()=>portal.eval('document.querySelector("#order-'+oid+' .detalhe")?.hidden===false'),'order from the link opened');
await portal.click('#navEntrar');
await waitFor(()=>portal.eval('location.pathname==="/conta/entrar" && !document.getElementById("auth").hidden'),'sign-in page');
await portal.fill('#cnpj','11222333000181');await portal.fill('#phone','11999999999');
await portal.fill('#register-name','Cliente Portal');await portal.fill('#cnpj','11222333000181');await portal.fill('#phone','11999999999');
await portal.fill('#register-email','browser-'+Date.now()+'@example.test');
await portal.fill('#register-password','local-browser-password-123');
await portal.eval('document.getElementById("register").requestSubmit()');

View File

@@ -24,5 +24,15 @@ class CustomerDocumentTest(unittest.TestCase):
customer(document)
class CustomerNameTest(unittest.TestCase):
def test_a_name_is_tidied_and_may_be_left_out_by_older_carts(self):
self.assertEqual(Customer(cnpj='52998224725', zap='16999999999', mail='a@example.test',
name=' Maria da Silva ').name, 'Maria da Silva')
self.assertEqual(customer('52998224725').name, '')
for name in ('1', 'A', '-- .'):
with self.subTest(name=name), self.assertRaises(ValidationError):
Customer(cnpj='52998224725', zap='16999999999', mail='a@example.test', name=name)
if __name__ == '__main__':
unittest.main()

View File

@@ -144,6 +144,9 @@ class TinyTests(FakeTinyCase):
self.tiny.deliver('k-cpf', person)
self.assertEqual((self.contacts[0]['tipoPessoa'], self.contacts[0]['cpfCnpj'], self.contacts[0]['nome']),
('F', '52998224725', 'Loja Teste'))
# With the name the Site now asks for, the contact is the person's.
named = {**person['order'], 'customer': {**person['order']['customer'], 'name': 'Maria da Silva'}}
self.assertEqual(contact_payload(named)['nome'], 'Maria da Silva')
self.assertEqual(looked_up, [])
def test_production_events_are_not_sent(self):

View File

@@ -4,7 +4,7 @@
(() => {
// A browser may put back what was typed before the reload without telling
// the page, which then shows values it does not know and cannot pay with.
const CAMPOS=['fCnpj','fZap','fMail','cepIn','eNome','eRua','eNum','eComp','eBairro','eCidade','eUf'];
const CAMPOS=['fNome','fCnpj','fZap','fMail','cepIn','eNome','eRua','eNum','eComp','eBairro','eCidade','eUf'];
for(const id of CAMPOS)if($(id))$(id).value='';
let database,scope,timer,restoring=true;
let signedOut=false;
@@ -45,9 +45,9 @@
const account=await window.dtfApi('/account/me');
const c=account.customer;
if(c && !cliente.mail){
cliente={cnpj:c.cnpj,zap:c.zap,mail:c.mail};
cliente={name:c.name||'',cnpj:c.cnpj,zap:c.zap,mail:c.mail};
// The fields' own input handlers format them, as if typed.
for(const [id,key] of [['fCnpj','cnpj'],['fZap','zap'],['fMail','mail']]){$(id).value=cliente[key];$(id).dispatchEvent(new Event('input'));}
for(const [id,key] of [['fNome','name'],['fCnpj','cnpj'],['fZap','zap'],['fMail','mail']]){$(id).value=cliente[key];$(id).dispatchEvent(new Event('input'));}
const a=c.address;
if(a && !entrega.cep){
entrega.cep=a.postal_code;

View File

@@ -1013,6 +1013,9 @@ h2 em{font-style:normal;color:var(--laranja)}
<div class="cxE">
<h4>Seus dados</h4>
<div class="campos">
<div class="cp larga"><label for="fNome">Nome <span class="obr" aria-hidden="true">*</span></label>
<input id="fNome" aria-required="true" autocomplete="name" maxlength="80" placeholder="Como devemos te chamar">
<span class="err" id="eNomeCli"></span></div>
<div class="cp"><label for="fCnpj">CPF ou CNPJ <span class="obr" aria-hidden="true">*</span></label>
<input id="fCnpj" aria-required="true" autocomplete="off" inputmode="numeric" maxlength="18" placeholder="CPF ou CNPJ">
<span class="err" id="eCnpj"></span></div>

View File

@@ -57,7 +57,9 @@
</form>
<form class="bloco" id="register">
<h2>Criar conta</h2>
<p class="nota2">Os pedidos feitos neste navegador passam para a sua conta.</p>
<p class="nota2">Seus pedidos feitos com o mesmo CPF/CNPJ e e-mail aparecem na conta.</p>
<label for="register-name">Nome</label>
<input id="register-name" autocomplete="name" maxlength="80" required>
<div class="duas">
<div><label for="cnpj">CPF ou CNPJ</label><input id="cnpj" inputmode="numeric" autocomplete="off" maxlength="18" required></div>
<div><label for="phone">WhatsApp</label><input id="phone" inputmode="numeric" autocomplete="tel" required></div>
@@ -142,6 +144,8 @@
<h1 id="tDados">Dados da conta</h1>
<form class="bloco" id="fPerfil">
<h2>Dados e entrega</h2>
<label for="dNomeCli">Nome</label>
<input id="dNomeCli" autocomplete="name" maxlength="80" required>
<div class="duas">
<div><label for="dCnpj" id="dCnpjRotulo">CPF ou CNPJ</label><input id="dCnpj" readonly aria-readonly="true"></div>
<div><label for="dZap">WhatsApp</label><input id="dZap" inputmode="numeric" autocomplete="tel" required></div>

View File

@@ -266,7 +266,7 @@ async function details(id,container,criado){
// ---- Overview ------------------------------------------------------------
async function geral(){
$('account').textContent=tipoDoc(conta.cnpj)+' '+fmtCnpj(conta.cnpj)+' · '+conta.mail;
$('account').textContent=(conta.name?conta.name+' · ':'')+tipoDoc(conta.cnpj)+' '+fmtCnpj(conta.cnpj)+' · '+conta.mail;
const data=await api('/customer/orders?page=1&size=1');states=data.states;
const box=$('metricas');box.replaceChildren();
for(const [key,label] of [['pay','Aguardando pagamento'],['prod','Em produção'],['cor','Correção'],['fin','Finalizados']]){
@@ -285,7 +285,7 @@ async function geral(){
const CAMPOS_END=[['dNome','recipient'],['dRua','street'],['dNum','number'],['dComp','complement'],['dBairro','district'],['dCidade','city'],['dUf','state']];
function dados(){
$('dCnpjRotulo').textContent=tipoDoc(conta.cnpj);$('dCnpj').value=fmtCnpj(conta.cnpj);$('dZap').value=fmtZap(conta.zap);$('dMail').value=conta.mail;
$('dNomeCli').value=conta.name||'';$('dCnpjRotulo').textContent=tipoDoc(conta.cnpj);$('dCnpj').value=fmtCnpj(conta.cnpj);$('dZap').value=fmtZap(conta.zap);$('dMail').value=conta.mail;
const end=conta.address||{};
$('dCep').value=fmtCep(end.postal_code||'');
for(const [id,k] of CAMPOS_END)$(id).value=end[k]||'';
@@ -308,9 +308,9 @@ $('fPerfil').onsubmit=async event=>{
const algum=cep||Object.values(campos).some(Boolean);
const address=algum?{...campos,state:campos.state.toUpperCase(),postal_code:cep}:null;
try{
const r=await api('/account/profile',{zap:$('dZap').value,address});
const r=await api('/account/profile',{name:$('dNomeCli').value,zap:$('dZap').value,address});
conta=r.customer;aviso('Dados salvos.');
}catch(e){aviso(e.status===422?(algum?'Confira o WhatsApp e o endereço: todos os campos, menos o complemento, são necessários.':'Confira o WhatsApp.'):e.message,true);}
}catch(e){aviso(e.status===422?(algum?'Confira o nome, o WhatsApp e o endereço: todos os campos, menos o complemento, são necessários.':'Confira o nome e o WhatsApp.'):e.message,true);}
};
// A new e-mail is confirmed with the code sent to it before the account changes.
let troca=null, trocaTimer=null;
@@ -387,8 +387,8 @@ async function authenticate(path,body,destino){
}
$('login').onsubmit=async event=>{event.preventDefault();try{await authenticate('/account/login',{email:$('email').value,password:$('password').value});}catch(e){aviso(e.message,true);}};
$('register').onsubmit=async event=>{event.preventDefault();$('criarConta').disabled=true;
try{await authenticate('/account/register',{customer:{cnpj:$('cnpj').value,zap:$('phone').value,mail:$('register-email').value},password:$('register-password').value});}
catch(e){aviso(e.status===422?'Confira o CPF ou CNPJ, o WhatsApp e o e-mail. A senha precisa ter 12 caracteres ou mais.':e.message,true);}
try{await authenticate('/account/register',{customer:{name:$('register-name').value,cnpj:$('cnpj').value,zap:$('phone').value,mail:$('register-email').value},password:$('register-password').value});}
catch(e){aviso(e.status===422?'Confira o nome, o CPF ou CNPJ, o WhatsApp e o e-mail. A senha precisa ter 12 caracteres ou mais.':e.message,true);}
finally{$('criarConta').disabled=false;}};
// Signup code: the account is created only once the code e-mailed to the

View File

@@ -95,7 +95,7 @@ let pedido=[]; // itens já fechados · o pagamento
// 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:{}, servico:'', opcoes:[]};
let cliente={cnpj:'', zap:'', mail:''};
let cliente={name:'', cnpj:'', zap:'', mail:''};
// CPF (11 dígitos) ou CNPJ (14), com os dois dígitos verificadores · máscara
// sem conta não vale nada. A chave cliente.cnpj guarda qualquer um dos dois.
@@ -122,7 +122,9 @@ function fmtDoc(v){
}
const zapOk=v=>{ const d=(v||'').replace(/\D/g,''); return d.length===10||d.length===11; };
const mailOk=v=>/^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i.test((v||'').trim());
const clienteOk=()=>docOk(cliente.cnpj)&&zapOk(cliente.zap)&&mailOk(cliente.mail);
// Nome: duas letras bastam (o cliente pode ser só "Ana").
const nomeOk=v=>((v||'').match(/\p{L}/gu)||[]).length>=2;
const clienteOk=()=>nomeOk(cliente.name)&&docOk(cliente.cnpj)&&zapOk(cliente.zap)&&mailOk(cliente.mail);
// Frete cotado pelo CEP não entrega nada sozinho: a transportadora e o Tiny
// precisam do endereço completo antes do pagamento.
const 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(' ');

View File

@@ -120,6 +120,7 @@ function liga(id,fmt,val,chave,erro,msg){
er.textContent = ok? '' : msg;
});
}
liga('fNome', v=>v.replace(/\s+/g,' ').replace(/^ /,''), nomeOk, 'name', 'eNomeCli', 'Informe seu nome');
liga('fCnpj', fmtDoc, docOk, 'cnpj', 'eCnpj', 'CPF ou CNPJ inválido · confira os números');
liga('fZap', v=>{
const d=v.replace(/\D/g,'').slice(0,11);