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
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:
@@ -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)
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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')
|
||||
|
||||
10
app/mail.py
10
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")
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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(',', '.'))
|
||||
|
||||
Reference in New Issue
Block a user