diff --git a/app/api/customer.py b/app/api/customer.py index 42f9202..977f5ea 100644 --- a/app/api/customer.py +++ b/app/api/customer.py @@ -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} diff --git a/app/core/models.py b/app/core/models.py index 5b562d9..5990413 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -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 diff --git a/app/mail.py b/app/mail.py index ff353ee..e2697f4 100644 --- a/app/mail.py +++ b/app/mail.py @@ -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") diff --git a/app/tiny.py b/app/tiny.py index 2ec0286..fd12b3e 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -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'): diff --git a/tests/browser_test.mjs b/tests/browser_test.mjs index f30b379..b89559e 100644 --- a/tests/browser_test.mjs +++ b/tests/browser_test.mjs @@ -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()'); diff --git a/tests/test_customer_document.py b/tests/test_customer_document.py index 923c796..4a25c18 100644 --- a/tests/test_customer_document.py +++ b/tests/test_customer_document.py @@ -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() diff --git a/tests/test_tiny.py b/tests/test_tiny.py index d9e5d97..a42a0b3 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -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): diff --git a/web/cart.js b/web/cart.js index e91172f..a647e40 100644 --- a/web/cart.js +++ b/web/cart.js @@ -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; diff --git a/web/index.html b/web/index.html index b1d95bc..3fdb3a7 100644 --- a/web/index.html +++ b/web/index.html @@ -1013,6 +1013,9 @@ h2 em{font-style:normal;color:var(--laranja)}