Files
dtf-system/app/correios.py
Cauê Faleiros 90e3126075
All checks were successful
Build and deploy / Validate source (push) Successful in 1m48s
Build and deploy / Integration suite on a real stack (push) Successful in 4m25s
Build and deploy / Secret scan and release gate (push) Successful in 15s
Build and deploy / Publish images (push) Successful in 1m54s
feat: the cart offers Correios PAC and SEDEX next to Jadlog
Dropstar sent its Correios contract. The cart now asks every carrier at once
for the CEP and lists each option with its delivery time, cheapest first and
chosen by default: Jadlog .PACKAGE, Correios PAC and Correios SEDEX, plus
pickup. A carrier that does not answer is left out instead of blocking the
others, and the server quotes the customer's choice again at approval. The
order summary, the Kanban and Minha conta name the carrier chosen.

app/correios.py follows the CWS manuals: a token from the posting card (kept
until shortly before it expires, renewed once if refused), the contract's own
prices by its DR, and the delivery time. Each box is one object priced by its
sides; Correios work out the cubic weight. All carriers price the same
package, now in app/package.py. Only CORREIOS_CODIGO_ACESSO goes in the
stack; the user, card and contract are its defaults. python -m
app.correios_probe checks the contract and its service codes on the account.

Tested: tests/test_correios (token, contract parameters, prices in Brazilian
format, boxes, a code override, a failing carrier), the full suite in a
CI-style stack, and the cart in Brave on desktop and phone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 13:47:53 -03:00

185 lines
8.3 KiB
Python

"""Correios freight quotes (CWS API: Token, Preço and Prazo), PAC and SEDEX.
Written from the Correios manuals (API Preço, API Prazo) and exercised against
a fake HTTP transport until app.correios_probe has run on Dropstar's contract.
A quote is read-only: it creates no shipment and costs nothing.
The token comes from the posting card (cartão de postagem) with the CWS user
and its access code, lasts about a day and is reused until shortly before it
expires. It also says the contract and its regional office (DR), which price
the contract's own rates. Each box of the order (app/package.py) is one
object: Correios price the larger of its real and cubic weight themselves,
from the box's sides, so only the real weight is sent.
"""
import base64
import os
import threading
from datetime import datetime, timedelta, timezone
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal, InvalidOperation
import httpx
from .package import Package
API = 'https://api.correios.com.br'
ORIGIN = '14402310'
# The contract's service codes ("contrato agência"); a setting overrides each.
SERVICES = {'pac': ('CORREIOS_COD_PAC', '03298', 'Correios PAC'),
'sedex': ('CORREIOS_COD_SEDEX', '03220', 'Correios SEDEX')}
PACKAGE = '2'
MAX_KG = Decimal(30)
BRASILIA = timezone(timedelta(hours=-3))
class CorreiosError(Exception):
pass
def digits(value):
return ''.join(ch for ch in str(value or '') if ch.isdigit())
def required_settings():
return ('CORREIOS_USUARIO', 'CORREIOS_CODIGO_ACESSO', 'CORREIOS_CARTAO')
def configured():
return bool(os.environ.get('CORREIOS_CODIGO_ACESSO', '').strip())
def problem(response):
"""The Correios' own words for a refusal: txErro, or the gateway's msgs."""
try:
data = response.json()
except ValueError:
return f'HTTP {response.status_code}'
if isinstance(data, list):
data = data[0] if data else {}
if isinstance(data, dict):
if data.get('txErro'):
return data['txErro']
if data.get('msgs'):
return '; '.join(map(str, data['msgs']))
return f'HTTP {response.status_code}'
def cents(text):
"""'11,64' (or 11.64) in centavos."""
try:
value = Decimal(str(text).replace('.', '').replace(',', '.')) if ',' in str(text) else Decimal(str(text))
except InvalidOperation:
raise CorreiosError(f'preço ilegível: {text!r}') from None
return int((value * 100).quantize(Decimal('1'), ROUND_HALF_UP))
class CorreiosQuotes:
def __init__(self, user=None, access_code=None, card=None, origin=None, transport=None, clock=None):
self.user = (user or os.environ.get('CORREIOS_USUARIO', '')).strip()
self.access_code = (access_code or os.environ.get('CORREIOS_CODIGO_ACESSO', '')).strip()
self.card = digits(card or os.environ.get('CORREIOS_CARTAO'))
self.origin = digits(origin or os.environ.get('CORREIOS_ORIGEM_CEP') or ORIGIN)
if not (self.user and self.access_code and self.card):
raise RuntimeError('Correios needs ' + ', '.join(required_settings()))
self.http = httpx.Client(base_url=API, timeout=15, transport=transport)
self.clock = clock or (lambda: datetime.now(timezone.utc))
self.lock = threading.Lock()
self.token = None
self.expires = None
self.contract = None
self.dr = None
def authenticate(self):
basic = base64.b64encode(f'{self.user}:{self.access_code}'.encode()).decode()
response = self.http.post('/token/v1/autentica/cartaopostagem', json={'numero': self.card},
headers={'Authorization': f'Basic {basic}'})
if response.status_code >= 400:
raise CorreiosError(f'token recusado: {problem(response)}')
data = response.json()
card = data.get('cartaoPostagem') or {}
self.token = data['token']
self.contract = card.get('contrato') or os.environ.get('CORREIOS_CONTRATO') or None
self.dr = card.get('dr') or os.environ.get('CORREIOS_DR') or None
try:
# "2026-10-16T10:00:00", Brasília time unless it says otherwise.
expires = datetime.fromisoformat(data['expiraEm'])
self.expires = expires if expires.tzinfo else expires.replace(tzinfo=BRASILIA)
except (KeyError, TypeError, ValueError):
self.expires = self.clock() + timedelta(hours=23)
def bearer(self, fresh=False):
with self.lock:
if fresh or not self.token or self.clock() >= self.expires - timedelta(minutes=10):
self.authenticate()
return self.token
def get(self, path, params):
"""A GET with the token, renewed once if the Correios refuse it."""
for fresh in (False, True):
response = self.http.get(path, params=params, headers={'Authorization': f'Bearer {self.bearer(fresh)}',
'Accept': 'application/json'})
if response.status_code != 401:
break
if response.status_code >= 400:
raise CorreiosError(problem(response))
return response.json()
def price(self, code, postal_code, grams, sides):
"""The contract's price in centavos for one package."""
length, width, height = (int(side.to_integral_value(ROUND_CEILING)) for side in sides)
params = {'cepOrigem': self.origin, 'cepDestino': postal_code, 'psObjeto': str(grams),
'tpObjeto': PACKAGE, 'comprimento': str(length), 'largura': str(width), 'altura': str(height)}
self.bearer()
if self.contract and self.dr:
params.update(nuContrato=str(self.contract), nuDR=str(self.dr))
data = self.get(f'/preco/v1/nacional/{code}', params)
if data.get('txErro'):
raise CorreiosError(data['txErro'])
if data.get('pcFinal') in (None, ''):
raise CorreiosError('sem preço na resposta')
return cents(data['pcFinal'])
def days(self, code, postal_code):
"""Delivery time in working days from posting, or None."""
data = self.get(f'/prazo/v1/nacional/{code}', {'cepOrigem': self.origin, 'cepDestino': postal_code})
if data.get('txErro'):
raise CorreiosError(data['txErro'])
return data.get('prazoEntrega')
class CorreiosFreight(Package):
"""The Site's PAC and SEDEX options for the order's package."""
name = 'correios'
def __init__(self, quotes=None):
super().__init__()
if not self.box_cm:
raise RuntimeError('Correios price by the box: set JADLOG_CAIXA_CM')
self.quotes = quotes or CorreiosQuotes()
self.codes = {service: (os.environ.get(setting) or code).strip()
for service, (setting, code, _) in SERVICES.items()}
self.services = {service: label for service, (_, _, label) in SERVICES.items()}
def quote(self, service, postal_code, metres=None, declared_cents=0):
if service == 'pickup':
return {'provider': self.name, 'service': 'pickup', 'total_cents': 0, 'postal_code': ''}
if service not in self.codes or len(postal_code) != 8 or not postal_code.isascii() or not postal_code.isdigit():
raise ValueError('Select pickup or Correios delivery with an eight-digit CEP')
if metres is None or Decimal(str(metres)) <= 0:
raise ValueError('The order length is required to quote freight')
weights = self.box_weights_kg(metres)
if max(weights) > MAX_KG:
raise ValueError('Uma caixa passa de 30 kg, o limite dos Correios.')
code = self.codes[service]
try:
# Boxes of the same weight cost the same: one price per weight.
prices = {weight: self.quotes.price(code, postal_code, int(weight * 1000), self.box_cm)
for weight in set(weights)}
days = self.quotes.days(code, postal_code)
except (CorreiosError, httpx.HTTPError) as error:
raise ValueError(f'Não foi possível cotar o {self.services[service]} agora: {error}') from None
return {'provider': self.name, 'service': service, 'postal_code': postal_code,
'total_cents': sum(prices[weight] for weight in weights),
'real_kg': str(sum(weights)), 'boxes': len(weights),
'days': None if days is None else int(days) + self.production_days,
'description': self.services[service]}