diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 3e44a16..8a971a3 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -86,7 +86,7 @@ jobs: # the generator's geometry. The provider suites use a fake transport: they # prove the documented contract, not the integration. - name: Print-file geometry and provider adapters - run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_large_files tests.test_grade_check tests.test_schema -v + run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document -v - name: Runtime and retention regressions run: | diff --git a/app/api/customer.py b/app/api/customer.py index 469bb5f..b389245 100644 --- a/app/api/customer.py +++ b/app/api/customer.py @@ -226,7 +226,7 @@ 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 CNPJ is the account's and + """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) diff --git a/app/cnpj.py b/app/cnpj.py index b72d3d9..01bc279 100644 --- a/app/cnpj.py +++ b/app/cnpj.py @@ -87,6 +87,8 @@ def company(cnpj, connect=None, transport=None): if connect is None: from .core.db import connect cnpj = digits(cnpj) + if len(cnpj) != 14: # a CPF: a person, not in the company registry + return None with connect() as c: known = names(c, [cnpj]).get(cnpj) if known: diff --git a/app/core/models.py b/app/core/models.py index dca229e..5b562d9 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -7,22 +7,33 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_valida class StrictModel(BaseModel): model_config = ConfigDict(extra='forbid', allow_inf_nan=False) +def check_digit(base, weights): + rem = sum(int(n) * w for n, w in zip(base, weights)) % 11 + return 0 if rem < 2 else 11 - rem + +def cpf_ok(digits): + return (len(digits) == 11 and len(set(digits)) > 1 + and check_digit(digits[:9], range(10, 1, -1)) == int(digits[9]) + and check_digit(digits[:10], range(11, 1, -1)) == int(digits[10])) + +def cnpj_ok(digits): + return (len(digits) == 14 and len(set(digits)) > 1 + 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])) + 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) @field_validator('cnpj') @classmethod - def cnpj_valid(cls, value): + def document_valid(cls, value): digits = re.sub(r'\D', '', value) - if len(digits) != 14 or len(set(digits)) == 1 or not digits.isascii(): - raise ValueError('Invalid CNPJ') - def check(base, weights): - rem = sum(int(n) * w for n,w in zip(base, weights)) % 11 - return 0 if rem < 2 else 11-rem - if check(digits[:12], [5,4,3,2,9,8,7,6,5,4,3,2]) != int(digits[12]) or check(digits[:13], [6,5,4,3,2,9,8,7,6,5,4,3,2]) != int(digits[13]): - raise ValueError('Invalid CNPJ') + if not digits.isascii() or not (cpf_ok(digits) or cnpj_ok(digits)): + raise ValueError('Invalid CPF or CNPJ') return digits @field_validator('zap') diff --git a/app/mail.py b/app/mail.py index 2b24728..ff353ee 100644 --- a/app/mail.py +++ b/app/mail.py @@ -76,10 +76,12 @@ def money(cents): def summary(order): """The lines an alert shows about a cart or an order: who, what, delivery.""" customer = order.get('customer') or {} - cnpj = ''.join(ch for ch in str(customer.get('cnpj', '')) if ch.isdigit()) - if len(cnpj) == 14: - cnpj = f'{cnpj[:2]}.{cnpj[2:5]}.{cnpj[5:8]}/{cnpj[8:12]}-{cnpj[12:]}' - lines = [f"Cliente: {cnpj} · {customer.get('mail', '')}"] + document = ''.join(ch for ch in str(customer.get('cnpj', '')) if ch.isdigit()) + if len(document) == 14: + 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', '')}"] 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/mercadopago.py b/app/mercadopago.py index ef2be3d..8f1db00 100644 --- a/app/mercadopago.py +++ b/app/mercadopago.py @@ -77,7 +77,8 @@ class MercadoPagoPayment: 'description': f'DTF - cotação {quote_id[:8]}', 'external_reference': quote_id, 'payer': {'email': customer['mail'], - 'identification': {'type': 'CNPJ', 'number': customer['cnpj']}}} + 'identification': {'type': 'CPF' if len(customer['cnpj']) == 11 else 'CNPJ', + 'number': customer['cnpj']}}} if self.notification_url: body['notification_url'] = self.notification_url expires_at = None diff --git a/app/tiny.py b/app/tiny.py index 818a954..2ec0286 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -360,12 +360,13 @@ 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.""" + 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).""" customer = order['customer'] destination = order.get('destination') company = company or {} contact = {'nome': company.get('legal') or (destination or {}).get('recipient') or customer['mail'], - 'tipoPessoa': 'J', 'cpfCnpj': customer['cnpj'], 'email': 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'): contact['fantasia'] = company['trade'] @@ -560,7 +561,7 @@ class TinyOrders: if ''.join(ch for ch in str(entry.get('cpfCnpj') or '') if ch.isdigit()) == cnpj: return entry['id'] company = None - if self.names: + if self.names and len(cnpj) == 14: try: company = self.names(cnpj) except Exception: # a name is a nicety; the order must still go diff --git a/app/tiny_probe.py b/app/tiny_probe.py index 70bd93f..37b29e4 100644 --- a/app/tiny_probe.py +++ b/app/tiny_probe.py @@ -144,7 +144,7 @@ def main(argv=None, orders=None, out=print): methods.add_argument('termo', nargs='?', default='') commands.add_parser('conferir') order = commands.add_parser('pedido') - order.add_argument('--cnpj', required=True) + order.add_argument('--cnpj', '--cpf', dest='cnpj', required=True, help='CNPJ ou CPF do cliente') order.add_argument('--email', required=True) order.add_argument('--celular', required=True) order.add_argument('--modo', choices=sorted(tiny.PRODUCT_SETTINGS), default='file') @@ -166,8 +166,8 @@ def main(argv=None, orders=None, out=print): if args.command == 'conferir': return 0 if conferir(orders, out) else 1 cnpj = ''.join(ch for ch in args.cnpj if ch.isdigit()) - if len(cnpj) != 14: - out('Informe um CNPJ com 14 dígitos.') + if len(cnpj) not in (11, 14): + out('Informe um CPF (11 dígitos) ou um CNPJ (14 dígitos).') return 2 try: metres = Decimal(args.metros.replace(',', '.')) diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index d5f7c88..2f88f89 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -149,6 +149,11 @@ The current site contains four product modes, quality-based price tiers, artwork-ready discounts, separate assembly charges for loose artwork, a one-metre minimum, and ten-centimetre billing rounding. +Customers buy with a CPF (a person) or a CNPJ (a company), check digits +validated on both sides. The value keeps the `cnpj` key in orders, quotes and +accounts; Tiny gets a CPF contact as `tipoPessoa` F, Mercado Pago the matching +identification type, and only CNPJs are looked up in the company registry. + The browser may display the calculation, but production payment creation must recalculate and validate all price, quantity, freight, and discount values on the server. Client-provided totals are never authoritative. @@ -322,7 +327,7 @@ as references and are not imported or started by Compose. stronger scrypt password hashing with legacy-hash upgrade, revocable HttpOnly sessions, owned order history/status, secure active file downloads, and correction uploads. Registration/login can claim only the - current guest session's records, never orders found by email or CNPJ. Email + current guest session's records, never orders found by email or CPF/CNPJ. Email verification and password recovery are not implemented. - Unfinished carts (including File blobs) recover from IndexedDB for 24 hours in the same browser, scoped to the guest/account identity. Recovered items can be diff --git a/tests/browser_test.mjs b/tests/browser_test.mjs index 98d521f..681e02f 100644 --- a/tests/browser_test.mjs +++ b/tests/browser_test.mjs @@ -107,7 +107,14 @@ try{ // 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.equal(await site.eval('document.getElementById("bPagar").disabled'),true); + // 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'); + await site.fill('#fCnpj','52998224724'); + assert.equal(await site.eval(`$('fCnpj').value`),'529.982.247-24'); + assert.equal(await site.eval('docOk(cliente.cnpj)'),false); + await site.fill('#fCnpj','52998224725'); + assert.equal(await site.eval(`$('fCnpj').value+' '+$('fCnpj').classList.contains('bom')`),'529.982.247-25 true'); await site.fill('#fZap','11999999999'); await site.fill('#fMail','local-browser@example.test'); assert.equal(await site.eval('pedido[0].localFiles[0].name'),'local-test.cdr'); diff --git a/tests/smoke_test.py b/tests/smoke_test.py index 8e1d818..125127c 100644 --- a/tests/smoke_test.py +++ b/tests/smoke_test.py @@ -166,6 +166,9 @@ def run(): client.call('/quotes',{**draft,'items':[outside]},expected=422) client.call('/quotes',{**draft,'items':[{**items[0],'metres':'1.00'}]},expected=422) client.call('/quotes',{**draft,'customer':{**draft['customer'],'cnpj':'11111111111111'}},expected=422) + # A person buys with a CPF: its check digits count as a CNPJ's do. + client.call('/quotes',{**draft,'customer':{**draft['customer'],'cnpj':'529.982.247-24'}},expected=422) + client.call('/quotes',{**draft,'request_key':str(uuid4()),'customer':{**draft['customer'],'cnpj':'529.982.247-25'}}) quote=client.call('/quotes',draft) assert quote['status']=='pending_review' assert client.call('/quotes/'+quote['id'])['review_reason']=='Pedido acima de 50 m' diff --git a/tests/test_cnpj.py b/tests/test_cnpj.py index 77fea21..d6b62d9 100644 --- a/tests/test_cnpj.py +++ b/tests/test_cnpj.py @@ -23,6 +23,11 @@ class CnpjTests(unittest.TestCase): with self.assertRaises(httpx.HTTPError): cnpj.fetch('11222333000181', transport(503)) + def test_a_cpf_is_never_looked_up(self): + def refuse(): + raise AssertionError('a CPF reached the database') + self.assertIsNone(cnpj.company('529.982.247-25', connect=refuse, transport=transport(500))) + def test_new_tiny_contacts_are_named_after_the_company(self): from app.tiny import contact_payload order = {'customer': {'cnpj': '11222333000181', 'mail': 'loja@example.test', 'zap': '16999999999'}, diff --git a/tests/test_correios.py b/tests/test_correios.py index 4c9ab0f..2d0f0b5 100644 --- a/tests/test_correios.py +++ b/tests/test_correios.py @@ -56,6 +56,8 @@ class FakeCorreios: def quotes(fake, **kwargs): + # A fixed day before the fake token's expiry, so the test never ages. + kwargs.setdefault('clock', lambda: datetime(2026, 10, 15, 12, tzinfo=timezone.utc)) return CorreiosQuotes(user='8825364223', access_code='codigo-1', card='0076691373', transport=httpx.MockTransport(fake), **kwargs) diff --git a/tests/test_customer_document.py b/tests/test_customer_document.py new file mode 100644 index 0000000..923c796 --- /dev/null +++ b/tests/test_customer_document.py @@ -0,0 +1,28 @@ +"""The customer's document: a CPF (a person) or a CNPJ (a company), with its +check digits. Runs where pydantic is installed.""" +import unittest + +from pydantic import ValidationError + +from app.core.models import Customer + + +def customer(document): + return Customer(cnpj=document, zap='16999999999', mail='loja@example.test') + + +class CustomerDocumentTest(unittest.TestCase): + def test_a_cpf_or_a_cnpj_is_kept_as_digits(self): + self.assertEqual(customer('529.982.247-25').cnpj, '52998224725') + self.assertEqual(customer('11.222.333/0001-81').cnpj, '11222333000181') + self.assertEqual(customer('55786635000158').cnpj, '55786635000158') + + def test_wrong_check_digits_repeated_digits_and_other_lengths_are_refused(self): + for document in ('529.982.247-24', '111.111.111-11', '11.222.333/0001-82', '00000000000000', + '5299822472', '529982247250', '١١٢٢٢٣٣٣٠٠٠١٨١'): + with self.subTest(document=document), self.assertRaises(ValidationError): + customer(document) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_mercadopago.py b/tests/test_mercadopago.py index 9e92c33..8638627 100644 --- a/tests/test_mercadopago.py +++ b/tests/test_mercadopago.py @@ -133,6 +133,10 @@ class MercadoPagoTests(unittest.TestCase): self.assertEqual((body['payment_method_id'], body['transaction_amount']), ('pix', 123.45)) self.assertEqual(body['external_reference'], '11111111-2222-3333-4444-555555555555') self.assertEqual(body['notification_url'], 'https://dtf.example/api/payments/webhook') + self.assertEqual(body['payer']['identification'], {'type': 'CNPJ', 'number': '11222333000181'}) + self.mp.create('22222222-2222-3333-4444-555555555555', 1000, {'mail': 'a@example.test', 'cnpj': '52998224725'}) + person = json.loads(self.requests[-1].content) + self.assertEqual(person['payer']['identification'], {'type': 'CPF', 'number': '52998224725'}) self.assertEqual((created['pix_qr_code'], created['status']), ('000201PIX', 'pending')) # The code expires in 30 minutes, in the format Mercado Pago documents. expires = datetime.fromisoformat(body['date_of_expiration']) diff --git a/tests/test_tiny.py b/tests/test_tiny.py index fc8ce4c..d9e5d97 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -137,6 +137,15 @@ class TinyTests(FakeTinyCase): self.assertNotIn(('POST', '/contatos'), self.calls) self.assertEqual(self.orders[0]['idContato'], 321) + def test_a_cpf_customer_is_a_person_and_not_looked_up_in_the_company_registry(self): + looked_up = [] + self.tiny.names = lambda document: looked_up.append(document) + person = {**PAID, 'order': {**PAID['order'], 'customer': {**PAID['order']['customer'], 'cnpj': '52998224725'}}} + self.tiny.deliver('k-cpf', person) + self.assertEqual((self.contacts[0]['tipoPessoa'], self.contacts[0]['cpfCnpj'], self.contacts[0]['nome']), + ('F', '52998224725', 'Loja Teste')) + self.assertEqual(looked_up, []) + def test_production_events_are_not_sent(self): self.assertEqual(self.tiny.deliver('k2', {**PAID, 'event': 'ready'})['status'], 'not-applicable') self.assertEqual(self.calls, []) diff --git a/web/index.html b/web/index.html index bd7b5ee..5ffb3c8 100644 --- a/web/index.html +++ b/web/index.html @@ -1013,8 +1013,8 @@ h2 em{font-style:normal;color:var(--laranja)}
Os pedidos feitos neste navegador passam para a sua conta.