feat: customers buy with a CPF or a CNPJ
All checks were successful
Build and deploy / Validate source (push) Successful in 1m38s
Build and deploy / Integration suite on a real stack (push) Successful in 4m57s
Build and deploy / Secret scan and release gate (push) Successful in 13s
Build and deploy / Publish images (push) Successful in 2m1s

The cart and the account signup take either document, each with its own
mask and check digits. Tiny gets a person (F) for a CPF, Mercado Pago the
matching identification type, and only CNPJs go to the company registry.
The Kanban, the account page and the alerts show which one it is.

Also pins the Correios test's clock: its fake token expired today, so the
suite failed from Oct 16 on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-16 13:33:50 -03:00
parent 37246917b9
commit b83e60ef0c
23 changed files with 138 additions and 46 deletions

View File

@@ -86,7 +86,7 @@ jobs:
# the generator's geometry. The provider suites use a fake transport: they # the generator's geometry. The provider suites use a fake transport: they
# prove the documented contract, not the integration. # prove the documented contract, not the integration.
- name: Print-file geometry and provider adapters - 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 - name: Runtime and retention regressions
run: | run: |

View File

@@ -226,7 +226,7 @@ def account_row(c, identity, lock=False):
@router.post('/api/account/profile') @router.post('/api/account/profile')
def update_profile(body: ProfileUpdate, identity=Depends(owner)): 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.""" does not change; the e-mail is the login and changes on its own route."""
with db.connect() as c: with db.connect() as c:
row = account_row(c, identity, lock=True) row = account_row(c, identity, lock=True)

View File

@@ -87,6 +87,8 @@ def company(cnpj, connect=None, transport=None):
if connect is None: if connect is None:
from .core.db import connect from .core.db import connect
cnpj = digits(cnpj) cnpj = digits(cnpj)
if len(cnpj) != 14: # a CPF: a person, not in the company registry
return None
with connect() as c: with connect() as c:
known = names(c, [cnpj]).get(cnpj) known = names(c, [cnpj]).get(cnpj)
if known: if known:

View File

@@ -7,22 +7,33 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_valida
class StrictModel(BaseModel): class StrictModel(BaseModel):
model_config = ConfigDict(extra='forbid', allow_inf_nan=False) 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): 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 cnpj: str
zap: str zap: str
mail: str = Field(max_length=254) mail: str = Field(max_length=254)
@field_validator('cnpj') @field_validator('cnpj')
@classmethod @classmethod
def cnpj_valid(cls, value): def document_valid(cls, value):
digits = re.sub(r'\D', '', value) digits = re.sub(r'\D', '', value)
if len(digits) != 14 or len(set(digits)) == 1 or not digits.isascii(): if not digits.isascii() or not (cpf_ok(digits) or cnpj_ok(digits)):
raise ValueError('Invalid CNPJ') raise ValueError('Invalid CPF or 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')
return digits return digits
@field_validator('zap') @field_validator('zap')

View File

@@ -76,10 +76,12 @@ def money(cents):
def summary(order): def summary(order):
"""The lines an alert shows about a cart or an order: who, what, delivery.""" """The lines an alert shows about a cart or an order: who, what, delivery."""
customer = order.get('customer') or {} customer = order.get('customer') or {}
cnpj = ''.join(ch for ch in str(customer.get('cnpj', '')) if ch.isdigit()) document = ''.join(ch for ch in str(customer.get('cnpj', '')) if ch.isdigit())
if len(cnpj) == 14: if len(document) == 14:
cnpj = f'{cnpj[:2]}.{cnpj[2:5]}.{cnpj[5:8]}/{cnpj[8:12]}-{cnpj[12:]}' document = f'{document[:2]}.{document[2:5]}.{document[5:8]}/{document[8:12]}-{document[12:]}'
lines = [f"Cliente: {cnpj} · {customer.get('mail', '')}"] 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', []): for item in order.get('items', []):
metres = item.get('billed_metres') or item.get('metres') metres = item.get('billed_metres') or item.get('metres')
lines.append(f"{PRODUCTS.get(item.get('mode'), item.get('mode'))} · {str(metres).replace('.', ',')} m") lines.append(f"{PRODUCTS.get(item.get('mode'), item.get('mode'))} · {str(metres).replace('.', ',')} m")

View File

@@ -77,7 +77,8 @@ class MercadoPagoPayment:
'description': f'DTF - cotação {quote_id[:8]}', 'description': f'DTF - cotação {quote_id[:8]}',
'external_reference': quote_id, 'external_reference': quote_id,
'payer': {'email': customer['mail'], '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: if self.notification_url:
body['notification_url'] = self.notification_url body['notification_url'] = self.notification_url
expires_at = None expires_at = None

View File

@@ -360,12 +360,13 @@ def money(cents):
def contact_payload(order, company=None): def contact_payload(order, company=None):
"""A new contact, named after the company's razão social when the """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'] customer = order['customer']
destination = order.get('destination') destination = order.get('destination')
company = company or {} company = company or {}
contact = {'nome': company.get('legal') or (destination or {}).get('recipient') or customer['mail'], 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'} 'celular': customer['zap'], 'situacao': 'A'}
if company.get('trade'): if company.get('trade'):
contact['fantasia'] = company['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: if ''.join(ch for ch in str(entry.get('cpfCnpj') or '') if ch.isdigit()) == cnpj:
return entry['id'] return entry['id']
company = None company = None
if self.names: if self.names and len(cnpj) == 14:
try: try:
company = self.names(cnpj) company = self.names(cnpj)
except Exception: # a name is a nicety; the order must still go except Exception: # a name is a nicety; the order must still go

View File

@@ -144,7 +144,7 @@ def main(argv=None, orders=None, out=print):
methods.add_argument('termo', nargs='?', default='') methods.add_argument('termo', nargs='?', default='')
commands.add_parser('conferir') commands.add_parser('conferir')
order = commands.add_parser('pedido') 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('--email', required=True)
order.add_argument('--celular', required=True) order.add_argument('--celular', required=True)
order.add_argument('--modo', choices=sorted(tiny.PRODUCT_SETTINGS), default='file') 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': if args.command == 'conferir':
return 0 if conferir(orders, out) else 1 return 0 if conferir(orders, out) else 1
cnpj = ''.join(ch for ch in args.cnpj if ch.isdigit()) cnpj = ''.join(ch for ch in args.cnpj if ch.isdigit())
if len(cnpj) != 14: if len(cnpj) not in (11, 14):
out('Informe um CNPJ com 14 dígitos.') out('Informe um CPF (11 dígitos) ou um CNPJ (14 dígitos).')
return 2 return 2
try: try:
metres = Decimal(args.metros.replace(',', '.')) metres = Decimal(args.metros.replace(',', '.'))

View File

@@ -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 artwork-ready discounts, separate assembly charges for loose artwork, a
one-metre minimum, and ten-centimetre billing rounding. 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 The browser may display the calculation, but production payment creation must
recalculate and validate all price, quantity, freight, and discount values on recalculate and validate all price, quantity, freight, and discount values on
the server. Client-provided totals are never authoritative. 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 stronger scrypt password hashing with legacy-hash upgrade, revocable HttpOnly
sessions, owned order history/status, secure active sessions, owned order history/status, secure active
file downloads, and correction uploads. Registration/login can claim only the 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. verification and password recovery are not implemented.
- Unfinished carts (including File blobs) recover from IndexedDB for 24 hours in - 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 the same browser, scoped to the guest/account identity. Recovered items can be

View File

@@ -107,7 +107,14 @@ try{
// The items come back after a reload; the customer's details do not. // 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(`['fCnpj','fZap','fMail'].map(id=>$(id).value)`),['','','']);
assert.equal(await site.eval('document.getElementById("bPagar").disabled'),true); 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'); 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('#fZap','11999999999');
await site.fill('#fMail','local-browser@example.test'); await site.fill('#fMail','local-browser@example.test');
assert.equal(await site.eval('pedido[0].localFiles[0].name'),'local-test.cdr'); assert.equal(await site.eval('pedido[0].localFiles[0].name'),'local-test.cdr');

View File

@@ -166,6 +166,9 @@ def run():
client.call('/quotes',{**draft,'items':[outside]},expected=422) client.call('/quotes',{**draft,'items':[outside]},expected=422)
client.call('/quotes',{**draft,'items':[{**items[0],'metres':'1.00'}]},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) 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) quote=client.call('/quotes',draft)
assert quote['status']=='pending_review' assert quote['status']=='pending_review'
assert client.call('/quotes/'+quote['id'])['review_reason']=='Pedido acima de 50 m' assert client.call('/quotes/'+quote['id'])['review_reason']=='Pedido acima de 50 m'

View File

@@ -23,6 +23,11 @@ class CnpjTests(unittest.TestCase):
with self.assertRaises(httpx.HTTPError): with self.assertRaises(httpx.HTTPError):
cnpj.fetch('11222333000181', transport(503)) 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): def test_new_tiny_contacts_are_named_after_the_company(self):
from app.tiny import contact_payload from app.tiny import contact_payload
order = {'customer': {'cnpj': '11222333000181', 'mail': 'loja@example.test', 'zap': '16999999999'}, order = {'customer': {'cnpj': '11222333000181', 'mail': 'loja@example.test', 'zap': '16999999999'},

View File

@@ -56,6 +56,8 @@ class FakeCorreios:
def quotes(fake, **kwargs): 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', return CorreiosQuotes(user='8825364223', access_code='codigo-1', card='0076691373',
transport=httpx.MockTransport(fake), **kwargs) transport=httpx.MockTransport(fake), **kwargs)

View File

@@ -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()

View File

@@ -133,6 +133,10 @@ class MercadoPagoTests(unittest.TestCase):
self.assertEqual((body['payment_method_id'], body['transaction_amount']), ('pix', 123.45)) 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['external_reference'], '11111111-2222-3333-4444-555555555555')
self.assertEqual(body['notification_url'], 'https://dtf.example/api/payments/webhook') 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')) self.assertEqual((created['pix_qr_code'], created['status']), ('000201PIX', 'pending'))
# The code expires in 30 minutes, in the format Mercado Pago documents. # The code expires in 30 minutes, in the format Mercado Pago documents.
expires = datetime.fromisoformat(body['date_of_expiration']) expires = datetime.fromisoformat(body['date_of_expiration'])

View File

@@ -137,6 +137,15 @@ class TinyTests(FakeTinyCase):
self.assertNotIn(('POST', '/contatos'), self.calls) self.assertNotIn(('POST', '/contatos'), self.calls)
self.assertEqual(self.orders[0]['idContato'], 321) 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): def test_production_events_are_not_sent(self):
self.assertEqual(self.tiny.deliver('k2', {**PAID, 'event': 'ready'})['status'], 'not-applicable') self.assertEqual(self.tiny.deliver('k2', {**PAID, 'event': 'ready'})['status'], 'not-applicable')
self.assertEqual(self.calls, []) self.assertEqual(self.calls, [])

View File

@@ -1013,8 +1013,8 @@ h2 em{font-style:normal;color:var(--laranja)}
<div class="cxE"> <div class="cxE">
<h4>Seus dados</h4> <h4>Seus dados</h4>
<div class="campos"> <div class="campos">
<div class="cp"><label>CNPJ <span class="obr" aria-hidden="true">*</span></label> <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="00.000.000/0000-00"> <input id="fCnpj" aria-required="true" autocomplete="off" inputmode="numeric" maxlength="18" placeholder="CPF ou CNPJ">
<span class="err" id="eCnpj"></span></div> <span class="err" id="eCnpj"></span></div>
<div class="cp"><label>WhatsApp <span class="obr" aria-hidden="true">*</span></label> <div class="cp"><label>WhatsApp <span class="obr" aria-hidden="true">*</span></label>
<input id="fZap" aria-required="true" autocomplete="off" inputmode="numeric" maxlength="15" placeholder="(16) 99999-9999"> <input id="fZap" aria-required="true" autocomplete="off" inputmode="numeric" maxlength="15" placeholder="(16) 99999-9999">

View File

@@ -27,7 +27,7 @@
<div class="searchbox"> <div class="searchbox">
<label class="search"> <label class="search">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="11" cy="11" r="7"></circle><path d="M20 20l-3.5-3.5"></path></svg> <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="11" cy="11" r="7"></circle><path d="M20 20l-3.5-3.5"></path></svg>
<input id="search" type="search" placeholder="Buscar em pedidos e cotações: cliente, CNPJ, nº" aria-label="Buscar em pedidos e cotações" autocomplete="off" role="combobox" aria-expanded="false" aria-controls="search-results"> <input id="search" type="search" placeholder="Buscar em pedidos e cotações: cliente, CPF/CNPJ, nº" aria-label="Buscar em pedidos e cotações" autocomplete="off" role="combobox" aria-expanded="false" aria-controls="search-results">
<kbd>/</kbd> <kbd>/</kbd>
</label> </label>
<div id="search-results" class="results" role="listbox" aria-label="Resultados da busca" hidden></div> <div id="search-results" class="results" role="listbox" aria-label="Resultados da busca" hidden></div>
@@ -63,7 +63,7 @@
<div class="chips" id="quote-filters"></div> <div class="chips" id="quote-filters"></div>
<label class="qsearch"> <label class="qsearch">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="11" cy="11" r="7"></circle><path d="M20 20l-3.5-3.5"></path></svg> <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="11" cy="11" r="7"></circle><path d="M20 20l-3.5-3.5"></path></svg>
<input id="quote-q" type="search" placeholder="Filtrar por e-mail, CNPJ ou WhatsApp" aria-label="Filtrar cotações por cliente" autocomplete="off"> <input id="quote-q" type="search" placeholder="Filtrar por e-mail, CPF/CNPJ ou WhatsApp" aria-label="Filtrar cotações por cliente" autocomplete="off">
</label> </label>
<div class="chips small" id="quote-chips"></div> <div class="chips small" id="quote-chips"></div>
<div id="quote-list"></div> <div id="quote-list"></div>

View File

@@ -122,7 +122,9 @@ function place(dest,prefix=''){
} }
const cm=v=>Number(v).toLocaleString('pt-BR',{maximumFractionDigits:1}); const cm=v=>Number(v).toLocaleString('pt-BR',{maximumFractionDigits:1});
const plural=(n,one,many)=>n+' '+(n===1?one:many); const plural=(n,one,many)=>n+' '+(n===1?one:many);
function cnpj(value){const d=String(value||'').replace(/\D/g,'');return d.length===14?d.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/,'$1.$2.$3/$4-$5'):String(value||'');} // The customer's CPF or CNPJ, formatted, and which of the two it is.
function cnpj(value){const d=String(value||'').replace(/\D/g,'');return d.length===14?d.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/,'$1.$2.$3/$4-$5'):d.length===11?d.replace(/^(\d{3})(\d{3})(\d{3})(\d{2})$/,'$1.$2.$3-$4'):String(value||'');}
const docKind=value=>String(value||'').replace(/\D/g,'').length===11?'CPF':'CNPJ';
function copyButton(text,label){ function copyButton(text,label){
const b=node('button',undefined,'copy');b.type='button';b.title=label;b.setAttribute('aria-label',label);b.append(icon(ICON_COPY)); const b=node('button',undefined,'copy');b.type='button';b.title=label;b.setAttribute('aria-label',label);b.append(icon(ICON_COPY));
b.onclick=async e=>{e.stopPropagation();try{await navigator.clipboard.writeText(text);say('Copiado.');}catch(_){say('Não foi possível copiar.',true);}}; b.onclick=async e=>{e.stopPropagation();try{await navigator.clipboard.writeText(text);say('Copiado.');}catch(_){say('Não foi possível copiar.',true);}};
@@ -672,7 +674,7 @@ function renderPanel(order){
const s=order.snapshot, dest=s.destination; const s=order.snapshot, dest=s.destination;
const facts=node('section',undefined,'facts'); const facts=node('section',undefined,'facts');
const who=node('div',undefined,'fcard'); const who=node('div',undefined,'fcard');
const doc=node('span',undefined,'line');doc.append('CNPJ '+cnpj(s.customer.cnpj),copyButton(cnpj(s.customer.cnpj),'Copiar CNPJ')); const doc=node('span',undefined,'line');doc.append(docKind(s.customer.cnpj)+' '+cnpj(s.customer.cnpj),copyButton(cnpj(s.customer.cnpj),'Copiar '+docKind(s.customer.cnpj)));
who.append(node('p','Cliente','eyebrow'),buyerBlock(s),doc); who.append(node('p','Cliente','eyebrow'),buyerBlock(s),doc);
const zap=whatsappLink(s.customer.zap); const zap=whatsappLink(s.customer.zap);
if(zap){const a=node('a','Abrir conversa','zapbtn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.title=s.customer.zap;a.prepend(icon(ICON_CHAT));who.append(a);} if(zap){const a=node('a','Abrir conversa','zapbtn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.title=s.customer.zap;a.prepend(icon(ICON_CHAT));who.append(a);}
@@ -1272,7 +1274,7 @@ function review(quote){
const name=node('div',undefined,'qname');name.append(buyerBlock(quote.draft),badge(...status)); const name=node('div',undefined,'qname');name.append(buyerBlock(quote.draft),badge(...status));
const pay=paymentBadge(quote.payment);if(pay)name.append(pay); const pay=paymentBadge(quote.payment);if(pay)name.append(pay);
const sub=node('div',undefined,'qsub');const c=quote.draft.customer; const sub=node('div',undefined,'qsub');const c=quote.draft.customer;
const doc=node('span');doc.append('CNPJ '+cnpj(c.cnpj),copyButton(cnpj(c.cnpj),'Copiar CNPJ'));sub.append(doc); const doc=node('span');doc.append(docKind(c.cnpj)+' '+cnpj(c.cnpj),copyButton(cnpj(c.cnpj),'Copiar '+docKind(c.cnpj)));sub.append(doc);
const zap=whatsappLink(c.zap); const zap=whatsappLink(c.zap);
if(zap){const a=node('a',c.zap,'zapbtn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.prepend(icon(ICON_CHAT));sub.append(a);} if(zap){const a=node('a',c.zap,'zapbtn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.prepend(icon(ICON_CHAT));sub.append(a);}
sub.append(place(quote.draft.destination,'Entrega em '),node('span','#'+quote.id.slice(0,8)+' · '+ago(quote.created_at),'faint')); sub.append(place(quote.draft.destination,'Entrega em '),node('span','#'+quote.id.slice(0,8)+' · '+ago(quote.created_at),'faint'));
@@ -1662,7 +1664,7 @@ async function runSearch(text){
for(const row of rows){const hit=make(row);hit.el.id='hit-'+searchHits.length;searchHits.push(hit);parts.push(hit.el);} for(const row of rows){const hit=make(row);hit.el.id='hit-'+searchHits.length;searchHits.push(hit);parts.push(hit.el);}
} }
if(!searchHits.length)parts.push(node('p','Nada encontrado para “'+text+'”.','rempty')); if(!searchHits.length)parts.push(node('p','Nada encontrado para “'+text+'”.','rempty'));
parts.push(node('div','↑ ↓ para escolher · Enter abre · Esc fecha · busca por e-mail, CNPJ, WhatsApp ou nº do pedido','rhelp')); parts.push(node('div','↑ ↓ para escolher · Enter abre · Esc fecha · busca por e-mail, CPF/CNPJ, WhatsApp ou nº do pedido','rhelp'));
box.replaceChildren(...parts);box.hidden=false;$('search').setAttribute('aria-expanded','true'); box.replaceChildren(...parts);box.hidden=false;$('search').setAttribute('aria-expanded','true');
} }
function hitRow(items,title,sub,meta,badge,color,open){ function hitRow(items,title,sub,meta,badge,color,open){

View File

@@ -59,7 +59,7 @@
<h2>Criar conta</h2> <h2>Criar conta</h2>
<p class="nota2">Os pedidos feitos neste navegador passam para a sua conta.</p> <p class="nota2">Os pedidos feitos neste navegador passam para a sua conta.</p>
<div class="duas"> <div class="duas">
<div><label for="cnpj">CNPJ</label><input id="cnpj" inputmode="numeric" autocomplete="off" required></div> <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> <div><label for="phone">WhatsApp</label><input id="phone" inputmode="numeric" autocomplete="tel" required></div>
</div> </div>
<label for="register-email">E-mail</label> <label for="register-email">E-mail</label>
@@ -141,9 +141,9 @@
<section class="vista" id="vDados" hidden aria-labelledby="tDados"> <section class="vista" id="vDados" hidden aria-labelledby="tDados">
<h1 id="tDados">Dados da conta</h1> <h1 id="tDados">Dados da conta</h1>
<form class="bloco" id="fPerfil"> <form class="bloco" id="fPerfil">
<h2>Empresa e entrega</h2> <h2>Dados e entrega</h2>
<div class="duas"> <div class="duas">
<div><label for="dCnpj">CNPJ</label><input id="dCnpj" readonly aria-readonly="true"></div> <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> <div><label for="dZap">WhatsApp</label><input id="dZap" inputmode="numeric" autocomplete="tel" required></div>
</div> </div>
<div class="duas"> <div class="duas">

View File

@@ -9,7 +9,9 @@ const quando=d=>new Date(d).toLocaleString('pt-BR',{day:'2-digit',month:'2-digit
const dia=d=>new Date(d).toLocaleDateString('pt-BR',{day:'2-digit',month:'2-digit',year:'2-digit'}); const dia=d=>new Date(d).toLocaleDateString('pt-BR',{day:'2-digit',month:'2-digit',year:'2-digit'});
const metros=m=>Number(m).toLocaleString('pt-BR',{minimumFractionDigits:2,maximumFractionDigits:2})+' m'; const metros=m=>Number(m).toLocaleString('pt-BR',{minimumFractionDigits:2,maximumFractionDigits:2})+' m';
const soDigitos=v=>String(v||'').replace(/\D/g,''); const soDigitos=v=>String(v||'').replace(/\D/g,'');
const fmtCnpj=v=>soDigitos(v).replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/,'$1.$2.$3/$4-$5'); // The account's CPF or CNPJ, formatted, and which of the two it is.
const fmtCnpj=v=>{const d=soDigitos(v);return d.length===11?d.replace(/^(\d{3})(\d{3})(\d{3})(\d{2})$/,'$1.$2.$3-$4'):d.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/,'$1.$2.$3/$4-$5');};
const tipoDoc=v=>soDigitos(v).length===11?'CPF':'CNPJ';
const fmtZap=v=>{const d=soDigitos(v);return d.length===11?'('+d.slice(0,2)+') '+d.slice(2,7)+'-'+d.slice(7):d.length===10?'('+d.slice(0,2)+') '+d.slice(2,6)+'-'+d.slice(6):v;}; const fmtZap=v=>{const d=soDigitos(v);return d.length===11?'('+d.slice(0,2)+') '+d.slice(2,7)+'-'+d.slice(7):d.length===10?'('+d.slice(0,2)+') '+d.slice(2,6)+'-'+d.slice(6):v;};
const fmtCep=v=>{const d=soDigitos(v).slice(0,8);return d.length>5?d.slice(0,5)+'-'+d.slice(5):d;}; const fmtCep=v=>{const d=soDigitos(v).slice(0,8);return d.length>5?d.slice(0,5)+'-'+d.slice(5):d;};
// Lucide shapes (ISC licence), the same as on the Site. // Lucide shapes (ISC licence), the same as on the Site.
@@ -264,7 +266,7 @@ async function details(id,container,criado){
// ---- Overview ------------------------------------------------------------ // ---- Overview ------------------------------------------------------------
async function geral(){ async function geral(){
$('account').textContent='CNPJ '+fmtCnpj(conta.cnpj)+' · '+conta.mail; $('account').textContent=tipoDoc(conta.cnpj)+' '+fmtCnpj(conta.cnpj)+' · '+conta.mail;
const data=await api('/customer/orders?page=1&size=1');states=data.states; const data=await api('/customer/orders?page=1&size=1');states=data.states;
const box=$('metricas');box.replaceChildren(); const box=$('metricas');box.replaceChildren();
for(const [key,label] of [['pay','Aguardando pagamento'],['prod','Em produção'],['cor','Correção'],['fin','Finalizados']]){ for(const [key,label] of [['pay','Aguardando pagamento'],['prod','Em produção'],['cor','Correção'],['fin','Finalizados']]){
@@ -283,7 +285,7 @@ async function geral(){
const CAMPOS_END=[['dNome','recipient'],['dRua','street'],['dNum','number'],['dComp','complement'],['dBairro','district'],['dCidade','city'],['dUf','state']]; const CAMPOS_END=[['dNome','recipient'],['dRua','street'],['dNum','number'],['dComp','complement'],['dBairro','district'],['dCidade','city'],['dUf','state']];
function dados(){ function dados(){
$('dCnpj').value=fmtCnpj(conta.cnpj);$('dZap').value=fmtZap(conta.zap);$('dMail').value=conta.mail; $('dCnpjRotulo').textContent=tipoDoc(conta.cnpj);$('dCnpj').value=fmtCnpj(conta.cnpj);$('dZap').value=fmtZap(conta.zap);$('dMail').value=conta.mail;
const end=conta.address||{}; const end=conta.address||{};
$('dCep').value=fmtCep(end.postal_code||''); $('dCep').value=fmtCep(end.postal_code||'');
for(const [id,k] of CAMPOS_END)$(id).value=end[k]||''; for(const [id,k] of CAMPOS_END)$(id).value=end[k]||'';
@@ -386,7 +388,7 @@ 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);}}; $('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; $('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});} 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 CNPJ, o WhatsApp e o e-mail. A senha precisa ter 12 caracteres ou mais.':e.message,true);} 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);}
finally{$('criarConta').disabled=false;}}; finally{$('criarConta').disabled=false;}};
// Signup code: the account is created only once the code e-mailed to the // Signup code: the account is created only once the code e-mailed to the

View File

@@ -97,20 +97,32 @@ let pedido=[]; // itens já fechados · o pagamento
let entrega={tipo:'retira', cep:'', valor:0, cotado:true, end:{}, servico:'', opcoes:[]}; let entrega={tipo:'retira', cep:'', valor:0, cotado:true, end:{}, servico:'', opcoes:[]};
let cliente={cnpj:'', zap:'', mail:''}; let cliente={cnpj:'', zap:'', mail:''};
// CNPJ com os dois dígitos verificadores · máscara sem conta não vale nada // CPF (11 dígitos) ou CNPJ (14), com os dois dígitos verificadores · máscara
function cnpjOk(v){ // sem conta não vale nada. A chave cliente.cnpj guarda qualquer um dos dois.
function docOk(v){
const d=(v||'').replace(/\D/g,''); const d=(v||'').replace(/\D/g,'');
if(d.length!==14 || /^(\d)\1{13}$/.test(d)) return false; if((d.length!==11 && d.length!==14) || /^(\d)\1+$/.test(d)) return false;
const calc=(base,pesos)=>{ const calc=(base,pesos)=>{
const soma=base.split('').reduce((t,n,i)=>t+ +n*pesos[i],0); const soma=base.split('').reduce((t,n,i)=>t+ +n*pesos[i],0);
const r=soma%11; return r<2? 0 : 11-r; const r=soma%11; return r<2? 0 : 11-r;
}; };
if(d.length===11){
const p1=[10,9,8,7,6,5,4,3,2], p2=[11,...p1];
return calc(d.slice(0,9),p1)===+d[9] && calc(d.slice(0,10),p2)===+d[10];
}
const p1=[5,4,3,2,9,8,7,6,5,4,3,2], p2=[6,...p1]; const p1=[5,4,3,2,9,8,7,6,5,4,3,2], p2=[6,...p1];
return calc(d.slice(0,12),p1)===+d[12] && calc(d.slice(0,13),p2)===+d[13]; return calc(d.slice(0,12),p1)===+d[12] && calc(d.slice(0,13),p2)===+d[13];
} }
// 000.000.000-00 até 11 dígitos; passando disso, 00.000.000/0000-00.
function fmtDoc(v){
const d=(v||'').replace(/\D/g,'').slice(0,14);
if(d.length<=11) return d.replace(/^(\d{3})(\d)/,'$1.$2').replace(/^(\d{3})\.(\d{3})(\d)/,'$1.$2.$3')
.replace(/^(\d{3})\.(\d{3})\.(\d{3})(\d)/,'$1.$2.$3-$4');
return d.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{0,2})/,'$1.$2.$3/$4-$5');
}
const zapOk=v=>{ const d=(v||'').replace(/\D/g,''); return d.length===10||d.length===11; }; 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 mailOk=v=>/^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i.test((v||'').trim());
const clienteOk=()=>cnpjOk(cliente.cnpj)&&zapOk(cliente.zap)&&mailOk(cliente.mail); const clienteOk=()=>docOk(cliente.cnpj)&&zapOk(cliente.zap)&&mailOk(cliente.mail);
// Frete cotado pelo CEP não entrega nada sozinho: a transportadora e o Tiny // Frete cotado pelo CEP não entrega nada sozinho: a transportadora e o Tiny
// precisam do endereço completo antes do pagamento. // 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(' '); 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,11 +120,7 @@ function liga(id,fmt,val,chave,erro,msg){
er.textContent = ok? '' : msg; er.textContent = ok? '' : msg;
}); });
} }
liga('fCnpj', v=>{ liga('fCnpj', fmtDoc, docOk, 'cnpj', 'eCnpj', 'CPF ou CNPJ inválido · confira os números');
const d=v.replace(/\D/g,'').slice(0,14);
return d.replace(/^(\d{2})(\d)/,'$1.$2').replace(/^(\d{2})\.(\d{3})(\d)/,'$1.$2.$3')
.replace(/\.(\d{3})(\d)/,'.$1/$2').replace(/(\d{4})(\d)/,'$1-$2');
}, cnpjOk, 'cnpj', 'eCnpj', 'CNPJ inválido · confira os números');
liga('fZap', v=>{ liga('fZap', v=>{
const d=v.replace(/\D/g,'').slice(0,11); const d=v.replace(/\D/g,'').slice(0,11);
return d.length>6 ? '('+d.slice(0,2)+') '+d.slice(2,d.length-4)+'-'+d.slice(-4) return d.length>6 ? '('+d.slice(0,2)+') '+d.slice(2,d.length-4)+'-'+d.slice(-4)