feat: the cart offers Correios PAC and SEDEX next to Jadlog
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

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>
This commit is contained in:
Cauê Faleiros
2026-10-15 13:47:53 -03:00
parent 69997f4598
commit 90e3126075
25 changed files with 735 additions and 108 deletions

View File

@@ -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_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 -v
- name: Runtime and retention regressions
run: |

View File

@@ -27,6 +27,13 @@ def require_runtime():
raise RuntimeError(f'{name} is required for the Jadlog adapter')
elif freight != 'fake':
raise RuntimeError('FREIGHT must use the fake or jadlog adapter')
# Correios is on when its access code is set; it prices the same package.
if os.environ.get('CORREIOS_CODIGO_ACESSO', '').strip():
from .correios import required_settings as correios_settings
from .package import WEIGHT_SETTINGS
for name in (*correios_settings(), *WEIGHT_SETTINGS, 'JADLOG_CAIXA_CM'):
if not os.environ.get(name):
raise RuntimeError(f'{name} is required for Correios freight')
tiny = os.environ.get('TINY_ADAPTER')
if tiny == 'tiny':
from .tiny import required_settings
@@ -169,6 +176,7 @@ class FreightAdapter(Protocol):
class FakeFreight:
name = 'fake'
services = {'mock-standard': 'Entrega simulada'}
def quote(self, service: str, postal_code: str, metres=None, declared_cents: int = 0) -> dict:
if service == 'pickup':
@@ -179,7 +187,7 @@ class FakeFreight:
if cents < 0:
raise ValueError('Invalid mock freight configuration')
return {'provider': 'fake', 'service': service, 'postal_code': postal_code,
'total_cents': cents, 'description': 'Local simulated freight'}
'total_cents': cents, 'description': 'Entrega simulada'}
class EventAdapter(Protocol):
def deliver(self, event_key: str, payload: dict) -> dict: ...

View File

@@ -10,8 +10,8 @@ from .. import mail
from ..core.auth import client_ip, owner, new_session, rate_limit
from ..core.limits import upload_limit_bytes
from ..core.pricing import manual_extra_cents
from ..core.models import FreightEstimate
from ..runtime import (ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, freight, payment,
from ..core.models import FreightAsk, FreightEstimate
from ..runtime import (ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, delivery_services, freight, payment,
require_delivery_available, storage)
router = APIRouter()
@@ -45,8 +45,8 @@ def session(request: Request, response: Response):
'manual_extra_cents': manual_extra_cents(),
# Public by design: Mercado Pago's card form needs it in the browser.
'payment_public_key': os.environ.get('MP_PUBLIC_KEY', '') if payment.name == 'mercadopago' else '',
# The delivery service the cart quotes, or none: pickup only.
'freight_service': 'jadlog' if freight.name == 'jadlog' else 'mock-standard' if ENVIRONMENT == 'local' else None}
# The delivery options the cart quotes, or none: pickup only.
'freight_services': delivery_services()}
@router.post('/api/freight')
def quote_freight(body: FreightEstimate):
@@ -56,6 +56,19 @@ def quote_freight(body: FreightEstimate):
except ValueError as exc:
raise HTTPException(422, str(exc))
@router.post('/api/freight/options')
def freight_options(body: FreightAsk, request: Request):
"""Every delivery option for the cart, cheapest first. Each asks a carrier,
so a source asking too often is held back."""
rate_limit('freight-options', client_ip(request), 120, 900)
if not delivery_services():
raise HTTPException(503, 'A entrega ainda não está disponível. Escolha a retirada em Franca.')
found = freight.options(body.postal_code, body.metres, body.declared_cents)
if not found['options']:
reasons = '; '.join(item['error'] for item in found['unavailable'])
raise HTTPException(422, 'Não foi possível cotar a entrega para este CEP agora.' + (f' ({reasons})' if reasons else ''))
return found
# The address of a CEP, so the cart fills it in. Looked up here rather than in
# the browser, which keeps the Site's CSP to its own origin.
VIACEP = 'https://viacep.com.br/ws/{}/json/'

View File

@@ -68,15 +68,12 @@ def operator_logout(request: Request, response: Response):
def freight_status():
"""What delivery the Site offers, and the package rule it prices with."""
if freight.name != 'jadlog':
return {'provider': freight.name}
cubed = freight.cubed_kg()
return {'provider': 'jadlog', 'base_kg': str(freight.base_kg), 'per_metre_kg': str(freight.per_metre_kg),
'production_days': freight.production_days,
'box_cm': [str(side) for side in freight.box_cm] if freight.box_cm else None,
'cubage_kg_m3': str(freight.cubage_kg_m3) if freight.cubage_kg_m3 else None,
'cubed_kg': str(cubed) if cubed is not None else None,
'metres_per_box': str(freight.metres_per_box) if freight.metres_per_box else None}
real = [carrier for carrier in freight.carriers if carrier.name != 'fake']
status = {'carriers': [carrier.name for carrier in real], 'services': freight.services if real else {}}
if real:
# One package for every carrier (app/package.py).
status.update(real[0].status())
return status
def backup_status(c):

View File

@@ -41,7 +41,7 @@ class Customer(StrictModel):
return value.strip()
class Freight(StrictModel):
service: Literal['pickup','mock-standard','jadlog'] = 'pickup'
service: Literal['pickup','mock-standard','jadlog','pac','sedex'] = 'pickup'
postal_code: str = Field(default='', max_length=8)
class FreightEstimate(Freight):
@@ -50,6 +50,12 @@ class FreightEstimate(Freight):
metres: Decimal | None = Field(default=None, gt=0, le=12000)
declared_cents: int = Field(default=0, ge=0, le=100_000_000, strict=True)
class FreightAsk(StrictModel):
"""Every delivery option for the cart's package to a CEP."""
postal_code: str = Field(pattern=r'^[0-9]{8}$')
metres: Decimal = Field(gt=0, le=12000)
declared_cents: int = Field(default=0, ge=0, le=100_000_000, strict=True)
UF = Literal['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']

View File

@@ -29,6 +29,7 @@ SECRET_FILE_SETTINGS = (
'TINY_TOKEN',
'WHATSAPP_TOKEN',
'SMTP_PASSWORD',
'CORREIOS_CODIGO_ACESSO',
)
SUFFIX = '_FILE'

184
app/correios.py Normal file
View File

@@ -0,0 +1,184 @@
"""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]}

70
app/correios_probe.py Normal file
View File

@@ -0,0 +1,70 @@
"""Read-only check against Dropstar's real Correios contract, run by hand.
A quote creates no shipment and costs nothing.
python -m app.correios_probe [--cep 01310100 ...] [--peso 0.5 ...]
It answers whether the user, access code and posting card are accepted (and
which contract and DR the token carries), whether the contract prices PAC and
SEDEX with the codes in use, and what they cost and take for one box (the
JADLOG_CAIXA_CM sides) to a few regions. The first failure stops the run: an
account problem would repeat on every line.
In production, from the worker's console (Portainer > Containers > worker >
Console), with CORREIOS_CODIGO_ACESSO in the stack:
python -m app.correios_probe
"""
import argparse
import os
import sys
from decimal import Decimal
from .core.secrets import load as load_secret_files
from .correios import SERVICES, CorreiosError, CorreiosQuotes
from .package import box_cm
DESTINATIONS = {'01310100': 'São Paulo', '20040002': 'Rio de Janeiro', '80010000': 'Curitiba',
'50030230': 'Recife', '69005010': 'Manaus'}
WEIGHTS = ['0.5', '2', '5']
def money(cents):
return f'R$ {cents / 100:.2f}'.replace('.', ',')
def run(quotes, sides, ceps, weights, out):
try:
quotes.bearer()
except CorreiosError as error:
out(f'ERRO no token: {error}')
return 1
out(f'Token ok · cartão {quotes.card} · contrato {quotes.contract or "-"} · DR {quotes.dr or "-"} '
f'· válido até {quotes.expires:%d/%m %H:%M}')
out(f"Origem {quotes.origin} · caixa {' × '.join(str(side) for side in sides)} cm")
for service, (setting, default, label) in SERVICES.items():
code = (os.environ.get(setting) or default).strip()
for cep in ceps:
try:
days = quotes.days(code, cep)
for weight in weights:
cents = quotes.price(code, cep, int(Decimal(weight) * 1000), sides)
out(f"{label} ({code})\t{weight} kg\t{cep}\t{DESTINATIONS.get(cep, '')}\t{money(cents)}\t"
f"{days if days is not None else '?'} dia(s)")
except CorreiosError as error:
out(f'ERRO {label} ({code}) para {cep}: {error}')
return 1
return 0
def main(argv=None):
parser = argparse.ArgumentParser(prog='python -m app.correios_probe')
parser.add_argument('--cep', action='append', help='destination CEP (repeatable)')
parser.add_argument('--peso', action='append', help='weight in kg (repeatable)')
args = parser.parse_args(argv)
load_secret_files()
sides = box_cm(os.environ.get('JADLOG_CAIXA_CM') or '63x15.5x15.5')
return run(CorreiosQuotes(), sides, args.cep or list(DESTINATIONS), args.peso or WEIGHTS, print)
if __name__ == '__main__':
sys.exit(main())

46
app/freight.py Normal file
View File

@@ -0,0 +1,46 @@
"""Every delivery option the Site offers, from every carrier configured.
The cart asks for all options at once and shows them cheapest first; the
customer's choice is quoted again by the server when the cart is approved.
A carrier that does not answer leaves its options out instead of blocking the
others.
"""
from concurrent.futures import ThreadPoolExecutor
class FreightOptions:
name = 'carriers'
def __init__(self, carriers):
self.carriers = carriers
self.by_service = {service: carrier for carrier in carriers for service in carrier.services}
@property
def services(self):
return {service: carrier.services[service] for service, carrier in self.by_service.items()}
def carrier(self, name):
return next((c for c in self.carriers if c.name == name), None)
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': ''}
carrier = self.by_service.get(service)
if not carrier:
raise ValueError('Esta forma de entrega não está disponível. Escolha outra.')
return carrier.quote(service, postal_code, metres, declared_cents)
def options(self, postal_code, metres=None, declared_cents=0):
"""Each service's quote, cheapest first, and why any could not be quoted."""
services = list(self.by_service)
with ThreadPoolExecutor(max_workers=max(1, len(services))) as pool:
futures = {service: pool.submit(self.quote, service, postal_code, metres, declared_cents)
for service in services}
found, missing = [], []
for service, future in futures.items():
try:
found.append(future.result())
except ValueError as error:
missing.append({'service': service, 'description': self.services[service], 'error': str(error)})
found.sort(key=lambda option: (option['total_cents'], option.get('days') or 99))
return {'options': found, 'unavailable': missing}

View File

@@ -7,38 +7,19 @@ unlike Tiny it can be tried on the real account as often as needed.
The client's contract: origin CEP 14402-310, service .PACKAGE (modalidade 3),
home delivery. Jadlog prices by weight in kg and expects the larger of the
real and the cubed weight. The package weight comes from the client (a base
plus a weight per billed metre) and has no default: FREIGHT_ADAPTER=jadlog
refuses to start without it, so a guessed weight never prices a customer's
freight. The cubed weight is the box's volume times the contract's factor
(JADLOG_CAIXA_CM, JADLOG_CUBAGEM_KG_M3); set both or neither, and with neither
only the real weight is sent. A box holds JADLOG_METROS_POR_CAIXA metres of
film; a longer order ships in as many boxes as it needs, each with its own
packaging weight and volume.
real and the cubed weight, both from the order's package (app/package.py).
"""
import math
import os
import re
from decimal import ROUND_HALF_UP, Decimal
import httpx
from .package import WEIGHT_SETTINGS, Package
QUOTE_URL = 'https://www.jadlog.com.br/embarcador/api/frete/valor'
PACKAGE = 3
ORIGIN = '14402310'
SERVICE = 'jadlog'
WEIGHT_SETTINGS = ('JADLOG_PESO_BASE_KG', 'JADLOG_PESO_POR_METRO_KG')
GRAMS = Decimal('0.001')
def box_cm(text):
"""The box's three sides in cm from "56x14x14" ("56 × 14 × 14", "56,5x14x14")."""
sides = [Decimal(side.strip().replace(',', '.')) for side in re.split(r'[x×*]', text.lower())]
if len(sides) != 3 or any(side <= 0 for side in sides):
raise RuntimeError('JADLOG_CAIXA_CM takes three sides in cm, such as 56x14x14')
return sides
class JadlogError(Exception):
pass
@@ -99,53 +80,14 @@ def required_settings():
return ('JADLOG_TOKEN', 'JADLOG_CNPJ') + WEIGHT_SETTINGS
class JadlogFreight:
"""The Site's delivery option: Jadlog's price for the order's package."""
class JadlogFreight(Package):
"""The Site's Jadlog option: Jadlog's price for the order's package."""
name = 'jadlog'
services = {SERVICE: 'Jadlog .PACKAGE'}
def __init__(self, quotes=None):
super().__init__()
self.quotes = quotes or JadlogQuotes()
self.base_kg = Decimal(os.environ['JADLOG_PESO_BASE_KG'])
self.per_metre_kg = Decimal(os.environ['JADLOG_PESO_POR_METRO_KG'])
# Jadlog's time counts from collection; the order is printed first.
self.production_days = int(os.environ.get('FREIGHT_PRODUCTION_DAYS') or 0)
if self.base_kg < 0 or self.per_metre_kg <= 0 or self.production_days < 0:
raise RuntimeError('Jadlog package weight and production days must be positive')
# A box without its factor (or a factor without a box) would price by a guess.
box = (os.environ.get('JADLOG_CAIXA_CM') or '').strip()
factor = (os.environ.get('JADLOG_CUBAGEM_KG_M3') or '').strip()
if bool(box) != bool(factor):
raise RuntimeError('Set JADLOG_CAIXA_CM and JADLOG_CUBAGEM_KG_M3 together, or neither')
self.box_cm = box_cm(box) if box else None
self.cubage_kg_m3 = Decimal(factor.replace(',', '.')) if factor else None
if self.cubage_kg_m3 is not None and self.cubage_kg_m3 <= 0:
raise RuntimeError('JADLOG_CUBAGEM_KG_M3 must be positive')
per_box = (os.environ.get('JADLOG_METROS_POR_CAIXA') or '').strip()
self.metres_per_box = Decimal(per_box.replace(',', '.')) if per_box else None
if self.metres_per_box is not None and self.metres_per_box <= 0:
raise RuntimeError('JADLOG_METROS_POR_CAIXA must be positive')
def boxes(self, metres=None):
"""How many boxes the order fills; one when the capacity is not set."""
if metres is None or self.metres_per_box is None:
return 1
return max(1, math.ceil(Decimal(str(metres)) / self.metres_per_box))
def real_kg(self, metres):
return (self.boxes(metres) * self.base_kg + self.per_metre_kg * Decimal(str(metres))).quantize(GRAMS)
def cubed_kg(self, metres=None):
"""The boxes' volume in m³ times the contract's factor (one box without a
length); None without a box."""
if not self.box_cm:
return None
a, b, c = self.box_cm
return (self.boxes(metres) * a * b * c / Decimal(1_000_000) * self.cubage_kg_m3).quantize(GRAMS)
def weight_kg(self, metres):
"""What Jadlog charges by: the larger of the real and the cubed weight."""
real, cubed = self.real_kg(metres), self.cubed_kg(metres)
return max(real, cubed) if cubed is not None else real
def quote(self, service, postal_code, metres=None, declared_cents=0):
if service == 'pickup':
@@ -164,4 +106,4 @@ class JadlogFreight:
'total_cents': result['total_cents'], 'weight_kg': str(weight), 'real_kg': str(real),
'boxes': self.boxes(metres),
'days': None if days is None else int(days) + self.production_days,
'description': 'Jadlog .PACKAGE'}
'description': self.services[SERVICE]}

91
app/package.py Normal file
View File

@@ -0,0 +1,91 @@
"""The package an order ships in, as every carrier is quoted for it.
The weight comes from the client (a base per box plus a weight per billed
metre of film) and has no default: a carrier refuses to start without it, so
a guessed weight never prices a customer's freight. A box holds
JADLOG_METROS_POR_CAIXA metres; a longer order ships in as many boxes as it
needs, each with its own packaging weight. The box's sides (JADLOG_CAIXA_CM)
are what the Correios price by, and with the contract's factor
(JADLOG_CUBAGEM_KG_M3) what Jadlog's cubed weight is. The settings keep the
Jadlog names they had when Jadlog was the only carrier.
"""
import math
import os
import re
from decimal import Decimal
WEIGHT_SETTINGS = ('JADLOG_PESO_BASE_KG', 'JADLOG_PESO_POR_METRO_KG')
GRAMS = Decimal('0.001')
def box_cm(text):
"""The box's three sides in cm from "56x14x14" ("56 × 14 × 14", "56,5x14x14")."""
sides = [Decimal(side.strip().replace(',', '.')) for side in re.split(r'[x×*]', text.lower())]
if len(sides) != 3 or any(side <= 0 for side in sides):
raise RuntimeError('JADLOG_CAIXA_CM takes three sides in cm, such as 56x14x14')
return sides
class Package:
def __init__(self):
self.base_kg = Decimal(os.environ['JADLOG_PESO_BASE_KG'])
self.per_metre_kg = Decimal(os.environ['JADLOG_PESO_POR_METRO_KG'])
# A carrier's time counts from collection; the order is printed first.
self.production_days = int(os.environ.get('FREIGHT_PRODUCTION_DAYS') or 0)
if self.base_kg < 0 or self.per_metre_kg <= 0 or self.production_days < 0:
raise RuntimeError('Package weight and production days must be positive')
# A box without its factor (or a factor without a box) would price by a guess.
box = (os.environ.get('JADLOG_CAIXA_CM') or '').strip()
factor = (os.environ.get('JADLOG_CUBAGEM_KG_M3') or '').strip()
if bool(box) != bool(factor):
raise RuntimeError('Set JADLOG_CAIXA_CM and JADLOG_CUBAGEM_KG_M3 together, or neither')
self.box_cm = box_cm(box) if box else None
self.cubage_kg_m3 = Decimal(factor.replace(',', '.')) if factor else None
if self.cubage_kg_m3 is not None and self.cubage_kg_m3 <= 0:
raise RuntimeError('JADLOG_CUBAGEM_KG_M3 must be positive')
per_box = (os.environ.get('JADLOG_METROS_POR_CAIXA') or '').strip()
self.metres_per_box = Decimal(per_box.replace(',', '.')) if per_box else None
if self.metres_per_box is not None and self.metres_per_box <= 0:
raise RuntimeError('JADLOG_METROS_POR_CAIXA must be positive')
def boxes(self, metres=None):
"""How many boxes the order fills; one when the capacity is not set."""
if metres is None or self.metres_per_box is None:
return 1
return max(1, math.ceil(Decimal(str(metres)) / self.metres_per_box))
def real_kg(self, metres):
return (self.boxes(metres) * self.base_kg + self.per_metre_kg * Decimal(str(metres))).quantize(GRAMS)
def box_weights_kg(self, metres):
"""Each box's real weight: full boxes first, the rest in the last one."""
metres = Decimal(str(metres))
count = self.boxes(metres)
if count == 1:
return [self.real_kg(metres)]
full = (self.base_kg + self.per_metre_kg * self.metres_per_box).quantize(GRAMS)
rest = metres - self.metres_per_box * (count - 1)
return [full] * (count - 1) + [(self.base_kg + self.per_metre_kg * rest).quantize(GRAMS)]
def cubed_kg(self, metres=None):
"""The boxes' volume in m³ times the contract's factor (one box without a
length); None without a box."""
if not self.box_cm:
return None
a, b, c = self.box_cm
return (self.boxes(metres) * a * b * c / Decimal(1_000_000) * self.cubage_kg_m3).quantize(GRAMS)
def weight_kg(self, metres):
"""What Jadlog charges by: the larger of the real and the cubed weight."""
real, cubed = self.real_kg(metres), self.cubed_kg(metres)
return max(real, cubed) if cubed is not None else real
def status(self):
"""The package rule, as the Kanban's Integrações shows it."""
cubed = self.cubed_kg()
return {'base_kg': str(self.base_kg), 'per_metre_kg': str(self.per_metre_kg),
'production_days': self.production_days,
'box_cm': [str(side) for side in self.box_cm] if self.box_cm else None,
'cubage_kg_m3': str(self.cubage_kg_m3) if self.cubage_kg_m3 else None,
'cubed_kg': str(cubed) if cubed is not None else None,
'metres_per_box': str(self.metres_per_box) if self.metres_per_box else None}

View File

@@ -13,6 +13,7 @@ from fastapi import HTTPException
from psycopg.types.json import Jsonb
from .adapters import FakeFreight, FakePayment, LocalS3Storage, require_runtime
from .freight import FreightOptions
from .core.secrets import load as load_secret_files
# Secret files must resolve before any configuration below is read.
@@ -25,11 +26,15 @@ if os.environ.get('PAYMENT_ADAPTER') == 'mercadopago':
payment = MercadoPagoPayment()
else:
payment = FakePayment()
# Every carrier configured; the simulated one only where there is none.
_carriers = []
if os.environ.get('FREIGHT_ADAPTER') == 'jadlog':
from .jadlog import JadlogFreight
freight = JadlogFreight()
else:
freight = FakeFreight()
_carriers.append(JadlogFreight())
from . import correios as _correios
if _correios.configured():
_carriers.append(_correios.CorreiosFreight())
freight = FreightOptions(_carriers or [FakeFreight()])
ENVIRONMENT = os.environ.get('APP_ENV', 'local')
PUBLIC_ORIGIN = os.environ.get('PUBLIC_ORIGIN', 'http://localhost')
ALLOWED_HOSTS = [host for host in os.environ.get('ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',') if host]
@@ -55,10 +60,23 @@ TRANSITIONS = {'rec': ['tra','cor'], 'tra': ['fil','cor'], 'fil': ['imp','cor'],
BACK = {'tra': 'rec', 'fil': 'tra', 'imp': 'fil', 'fin': 'imp'}
def real_delivery():
"""Whether a real carrier is configured; a simulated price is local only."""
return any(carrier.name != 'fake' for carrier in freight.carriers)
def delivery_services():
"""The delivery options the cart may offer: none outside the local stack
without a real carrier, so a customer sees only pickup."""
if ENVIRONMENT != 'local' and not real_delivery():
return []
return [{'service': service, 'description': label} for service, label in freight.services.items()]
def require_delivery_available(service):
"""Outside the local stack, a simulated freight price must never reach a
customer: until a real freight provider exists, only pickup is offered."""
if service != 'pickup' and ENVIRONMENT != 'local' and getattr(freight, 'name', '') == 'fake':
if service != 'pickup' and ENVIRONMENT != 'local' and not real_delivery():
raise HTTPException(503, 'A entrega ainda não está disponível. Escolha a retirada em Franca.')

View File

@@ -47,6 +47,13 @@ x-app: &app
JADLOG_CUBAGEM_KG_M3: ${JADLOG_CUBAGEM_KG_M3:-}
JADLOG_METROS_POR_CAIXA: ${JADLOG_METROS_POR_CAIXA:-}
FREIGHT_PRODUCTION_DAYS: ${FREIGHT_PRODUCTION_DAYS:-0}
# Correios: off locally unless an access code is set in .env.
CORREIOS_CODIGO_ACESSO: ${CORREIOS_CODIGO_ACESSO:-}
CORREIOS_USUARIO: ${CORREIOS_USUARIO:-}
CORREIOS_CARTAO: ${CORREIOS_CARTAO:-}
CORREIOS_CONTRATO: ${CORREIOS_CONTRATO:-}
CORREIOS_COD_PAC: ${CORREIOS_COD_PAC:-}
CORREIOS_COD_SEDEX: ${CORREIOS_COD_SEDEX:-}
# Carts the Site priced are approved at checkout; larger ones wait for review.
QUOTE_AUTO_APPROVE: ${QUOTE_AUTO_APPROVE:-true}
QUOTE_AUTO_MAX_METRES: ${QUOTE_AUTO_MAX_METRES:-50}

View File

@@ -55,6 +55,17 @@ x-app-environment: &app-environment
JADLOG_METROS_POR_CAIXA: ${JADLOG_METROS_POR_CAIXA:-}
# Working days of production added to Jadlog's delivery time.
FREIGHT_PRODUCTION_DAYS: ${FREIGHT_PRODUCTION_DAYS:-0}
# Correios PAC and SEDEX, on when CORREIOS_CODIGO_ACESSO (the CWS access
# code, a secret: set it in the stack) is set. They price the package above
# (weights and JADLOG_CAIXA_CM). The rest is Dropstar's contract, not secret.
CORREIOS_CODIGO_ACESSO: ${CORREIOS_CODIGO_ACESSO:-}
CORREIOS_USUARIO: ${CORREIOS_USUARIO:-8825364223}
CORREIOS_CARTAO: ${CORREIOS_CARTAO:-0076691373}
CORREIOS_CONTRATO: ${CORREIOS_CONTRATO:-9912551407}
# Only if the contract's codes differ from 03298 (PAC) and 03220 (SEDEX);
# python -m app.correios_probe shows whether they price.
CORREIOS_COD_PAC: ${CORREIOS_COD_PAC:-}
CORREIOS_COD_SEDEX: ${CORREIOS_COD_SEDEX:-}
# A cart the Site priced is approved at checkout and can be paid at once;
# orders above QUOTE_AUTO_MAX_METRES, or with a grade the Site did not
# compute, wait for an operator on the Kanban (app/quote_review.py).

View File

@@ -169,6 +169,17 @@ It defaults to 0; the amount is the client's to set. The Site reads it from
## Freight
**Current (2026-10-15):** the cart quotes every carrier configured at once and
lists the options cheapest first, with the delivery time: Jadlog .PACKAGE
(`app/jadlog.py`) and Correios PAC and SEDEX (`app/correios.py`, Dropstar's
contract 9912551407, card 0076691373), plus pickup in Franca. A carrier that
does not answer is left out; the customer's choice is quoted again by the
server at approval. All carriers price the same package (`app/package.py`: a
base weight per box, a weight per metre, the box's sides, metres per box).
Correios is on when `CORREIOS_CODIGO_ACESSO` is set; `python -m
app.correios_probe` checks the contract's token, codes (03298 PAC, 03220
SEDEX by default), prices and times. The history below is kept as recorded.
The original visual freight flow in `web/index.html` was a stub with only pickup
functional. The localhost bridge now supports pickup and backend fake freight
quotes; there is still no real carrier quotation or production checkout.

View File

@@ -205,6 +205,22 @@ Usuários. Use a sending domain with SPF and DKIM, or the messages land in spam.
opens by hand (CDR, AI, PSD, TIFF); 500 is R$ 5,00 a metro. Change it only on
the client's instruction; the Site shows the new price after the redeploy.
## 8. Correios
PAC and SEDEX appear in the cart once `CORREIOS_CODIGO_ACESSO` (the CWS access
code, a secret) is set in the stack and the stack redeployed. The user, posting
card and contract are Dropstar's and already the stack's defaults. Then, from
the worker's console:
```bash
python -m app.correios_probe
```
It shows the token's contract and DR and prices PAC and SEDEX to a few CEPs.
If a service is refused, the contract uses other codes: set `CORREIOS_COD_PAC`
or `CORREIOS_COD_SEDEX`. Correios price by the box, so `JADLOG_CAIXA_CM` and the
package weights must be set (they already are for Jadlog).
## Current blocker
This is the final deployment shape, but it is not authorized for production

165
tests/test_correios.py Normal file
View File

@@ -0,0 +1,165 @@
"""The Correios client against a fake HTTP transport: token, price, time, boxes.
This proves the manuals' contract only; app.correios_probe must still confirm
it on Dropstar's contract. Runs where httpx is installed.
"""
import base64
import json
import os
import unittest
from datetime import datetime, timezone
from decimal import Decimal
from unittest import mock
import httpx
from app.correios import CorreiosFreight, CorreiosQuotes, cents
from app.freight import FreightOptions
BOX = [Decimal('63'), Decimal('15.5'), Decimal('15.5')]
PACKAGE = {'JADLOG_PESO_BASE_KG': '0.3', 'JADLOG_PESO_POR_METRO_KG': '0.075', 'FREIGHT_PRODUCTION_DAYS': '1',
'JADLOG_CAIXA_CM': '63x15.5x15.5', 'JADLOG_CUBAGEM_KG_M3': '300', 'JADLOG_METROS_POR_CAIXA': '60'}
class FakeCorreios:
"""Answers as the Token, Preço and Prazo manuals describe."""
def __init__(self, prices=None, token_status=201, expires='2026-10-16T10:00:00'):
self.calls = []
self.tokens = 0
self.prices = prices or {'03298': '23,50', '03220': '41,10'}
self.token_status = token_status
self.expires = expires
self.refuse_next = False
def __call__(self, request):
self.calls.append(request)
path = request.url.path
if path == '/token/v1/autentica/cartaopostagem':
self.tokens += 1
if self.token_status != 201:
return httpx.Response(self.token_status, json={'msgs': ['Usuário ou senha inválidos']})
return httpx.Response(201, json={'token': f'tok-{self.tokens}', 'expiraEm': self.expires,
'cartaoPostagem': {'numero': '0076691373', 'contrato': '9912551407',
'dr': 72}})
if self.refuse_next:
self.refuse_next = False
return httpx.Response(401, json={'msgs': ['Token expirado']})
code = path.rsplit('/', 1)[-1]
if path.startswith('/preco/v1/nacional/'):
if request.url.params['cepDestino'] == '00000000':
return httpx.Response(400, json={'txErro': 'ERP-006: CEP de destino inválido.'})
return httpx.Response(200, json={'coProduto': code, 'pcFinal': self.prices[code]})
if path.startswith('/prazo/v1/nacional/'):
return httpx.Response(200, json={'coProduto': code, 'prazoEntrega': 3 if code == '03298' else 1})
return httpx.Response(404)
def quotes(fake, **kwargs):
return CorreiosQuotes(user='8825364223', access_code='codigo-1', card='0076691373',
transport=httpx.MockTransport(fake), **kwargs)
class CorreiosQuotesTest(unittest.TestCase):
def test_token_from_the_posting_card_then_contract_prices(self):
fake = FakeCorreios()
q = quotes(fake)
self.assertEqual(q.price('03298', '01310100', 1500, BOX), 2350)
token, price = fake.calls
self.assertEqual(token.headers['authorization'],
'Basic ' + base64.b64encode(b'8825364223:codigo-1').decode())
self.assertEqual(json.loads(token.content), {'numero': '0076691373'})
params = dict(price.url.params)
self.assertEqual(price.headers['authorization'], 'Bearer tok-1')
# Grams, a package with whole centimetres, and the contract's own rates.
self.assertEqual(params, {'cepOrigem': '14402310', 'cepDestino': '01310100', 'psObjeto': '1500',
'tpObjeto': '2', 'comprimento': '63', 'largura': '16', 'altura': '16',
'nuContrato': '9912551407', 'nuDR': '72'})
def test_the_token_is_reused_until_it_expires_and_renewed_when_refused(self):
now = [datetime(2026, 10, 15, 12, tzinfo=timezone.utc)]
fake = FakeCorreios(expires='2026-10-16T10:00:00')
q = quotes(fake, clock=lambda: now[0])
q.days('03298', '01310100')
q.days('03220', '01310100')
self.assertEqual(fake.tokens, 1)
# Close to its end (10:00 in Brasília is 13:00 UTC), a new one.
fake.expires = '2026-10-17T10:00:00'
now[0] = datetime(2026, 10, 16, 12, 55, tzinfo=timezone.utc)
q.days('03298', '01310100')
self.assertEqual(fake.tokens, 2)
# Refused before its time: renewed once and asked again.
fake.refuse_next = True
self.assertEqual(q.days('03298', '01310100'), 3)
self.assertEqual(fake.tokens, 3)
def test_refusals_say_what_the_correios_said(self):
q = quotes(FakeCorreios(token_status=401))
with self.assertRaisesRegex(Exception, 'Usuário ou senha inválidos'):
q.bearer()
with self.assertRaisesRegex(Exception, 'ERP-006'):
quotes(FakeCorreios()).price('03298', '00000000', 500, BOX)
def test_prices_in_brazilian_format_become_centavos(self):
self.assertEqual([cents('23,50'), cents('1.234,56'), cents('7'), cents(11.64)], [2350, 123456, 700, 1164])
class CorreiosFreightTest(unittest.TestCase):
def freight(self, fake, **env):
with mock.patch.dict(os.environ, {**PACKAGE, **env}):
return CorreiosFreight(quotes(fake))
def test_pac_and_sedex_for_the_package(self):
fake = FakeCorreios()
freight = self.freight(fake)
pac = freight.quote('pac', '01310100', '2.8')
self.assertEqual((pac['total_cents'], pac['days'], pac['description']), (2350, 4, 'Correios PAC'))
sedex = freight.quote('sedex', '01310100', '2.8')
self.assertEqual((sedex['total_cents'], sedex['days']), (4110, 2))
# 0.3 kg of box plus 0.075 kg for each of the 2.8 metres, in grams.
grams = [c.url.params['psObjeto'] for c in fake.calls if c.url.path.startswith('/preco')]
self.assertEqual(grams, ['510', '510'])
def test_a_long_order_is_one_object_per_box(self):
fake = FakeCorreios()
quote = self.freight(fake).quote('pac', '01310100', '130')
# 60 + 60 + 10 metres: two full boxes at one price, the last at its own.
grams = sorted(c.url.params['psObjeto'] for c in fake.calls if c.url.path.startswith('/preco'))
self.assertEqual(grams, ['1050', '4800'])
self.assertEqual((quote['boxes'], quote['total_cents']), (3, 3 * 2350))
def test_a_setting_overrides_a_service_code(self):
fake = FakeCorreios(prices={'03298': '23,50', '03220': '41,10', '04669': '19,90'})
quote = self.freight(fake, CORREIOS_COD_PAC='04669').quote('pac', '01310100', '1')
self.assertEqual(quote['total_cents'], 1990)
def test_no_box_no_correios(self):
with mock.patch.dict(os.environ, {**PACKAGE, 'JADLOG_CAIXA_CM': '', 'JADLOG_CUBAGEM_KG_M3': ''}):
with self.assertRaises(RuntimeError):
CorreiosFreight(quotes(FakeCorreios()))
class FreightOptionsTest(unittest.TestCase):
def test_every_option_cheapest_first_and_a_failing_carrier_left_out(self):
with mock.patch.dict(os.environ, PACKAGE):
correios = CorreiosFreight(quotes(FakeCorreios()))
class Broken:
name = 'jadlog'
services = {'jadlog': 'Jadlog .PACKAGE'}
def quote(self, *args):
raise ValueError('Não foi possível cotar o frete na Jadlog agora: HTTP 500')
options = FreightOptions([Broken(), correios])
found = options.options('01310100', '2.8', 5000)
self.assertEqual([o['service'] for o in found['options']], ['pac', 'sedex'])
self.assertEqual(found['unavailable'][0]['service'], 'jadlog')
self.assertEqual(options.quote('sedex', '01310100', '2.8')['total_cents'], 4110)
self.assertEqual(options.quote('pickup', '')['total_cents'], 0)
with self.assertRaises(ValueError):
options.quote('motoboy', '01310100', '2.8')
if __name__ == '__main__':
unittest.main()

View File

@@ -103,7 +103,7 @@
(MODOS[item.mode]?.tit || item.mode)+' · '+fmtM(Number(item.billed_metres))+' m', rs(item.total_cents/100)));
const pickup = approved.freight.service === 'pickup';
const prazo = approved.freight.days ? ' · até '+approved.freight.days+' dias úteis' : '';
rows.push(linha(pickup ? 'Retirada em Franca' : 'Frete'+prazo,
rows.push(linha(pickup ? 'Retirada em Franca' : (approved.freight.description || 'Frete')+prazo,
approved.freight.total_cents ? rs(approved.freight.total_cents/100) : 'Grátis'));
rows.push(linha('Total', rs(approved.total_cents/100), 'tot'));
resumo.replaceChildren(node('h4','Resumo do pedido'), ...rows);
@@ -255,10 +255,11 @@
return {metres:items.reduce((t,it)=>t+(it.cob||0),0), cents:Math.round(items.reduce((t,it)=>t+(it.total||0),0)*100)};
};
let freightQuoted = null;
// Every carrier's option for the CEP; the customer's choice stays chosen
// when the cart changes, else the cheapest is.
window.dtfFreight = async () => {
const cep = entrega.cep;
const service = (await ready).freight_service;
if (!service) {
if (!(await ready).freight_services?.length) {
$('cepMsg').textContent = 'A entrega ainda não está disponível. Escolha a retirada em Franca.';
return;
}
@@ -266,15 +267,18 @@
if (!metres) { $('cepMsg').textContent = 'Adicione um item ao pedido para cotar o frete.'; return; }
$('cepMsg').textContent = 'Cotando o frete…';
try {
const result = await api('/freight',{service,postal_code:cep,metres:metres.toFixed(2),declared_cents:cents});
const result = await api('/freight/options',{postal_code:cep,metres:metres.toFixed(2),declared_cents:cents});
if (entrega.cep !== cep || entrega.tipo !== 'frete') return;
entrega.valor = result.total_cents/100;
entrega.dias = result.days || null;
entrega.opcoes = result.options;
const chosen = result.options.find(o=>o.service===entrega.servico) || result.options[0];
entrega.servico = chosen.service;
entrega.valor = chosen.total_cents/100;
entrega.dias = chosen.days || null;
entrega.cotado = true;
freightQuoted = JSON.stringify(pacote());
$('cepMsg').textContent = '';
pintaEntrega();
} catch(error) { $('cepMsg').textContent = error.message; }
pintaFretes(); pintaEntrega();
} catch(error) { entrega.opcoes=[]; pintaFretes(); $('cepMsg').textContent = error.message; }
};
// A different package is a different freight: quote it again.
window.addEventListener('dtf-cart-changed',()=>{
@@ -314,7 +318,7 @@
upload_id:uploads[index],...source}))},
quality_status:item.qualityStatus,quality_acknowledged:item.qualityAcknowledged});
}
const service = entrega.tipo==='retira' ? 'pickup' : (await ready).freight_service;
const service = entrega.tipo==='retira' ? 'pickup' : entrega.servico;
if (!service) throw new Error('A entrega ainda não está disponível. Escolha a retirada em Franca.');
const content = {customer:{...cliente},items,freight:{service,postal_code:entrega.tipo==='retira'?'':entrega.cep}};
const destination = destinoApi();

View File

@@ -1041,7 +1041,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<span class="mk"></span>
<div>
<b><svg class="ic" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"/><path d="M15 18H9"/><path d="M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.62l-3.48-4.35A1 1 0 0 0 17.52 8H14"/><circle cx="17" cy="18" r="2"/><circle cx="7" cy="18" r="2"/></svg>Receber em casa</b>
<span>Entrega pela Jadlog em todo o Brasil. Informe o CEP para ver o valor e o prazo.</span>
<span>Jadlog ou Correios (PAC e SEDEX), para todo o Brasil. Informe o CEP para ver as opções.</span>
</div>
<em id="vFrete">—</em>
</button>
@@ -1051,6 +1051,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<input id="cepIn" aria-required="true" autocomplete="off" inputmode="numeric" maxlength="9" placeholder="00000-000">
</div>
<p id="cepMsg"></p>
<div class="fretes" id="fretes" role="radiogroup" aria-label="Opções de entrega" hidden></div>
<div class="campos endereco" id="endereco">
<div class="cp larga"><label>Quem recebe <span class="obr" aria-hidden="true">*</span></label>
<input id="eNome" aria-required="true" autocomplete="off" maxlength="120" placeholder="Nome ou empresa"></div>

View File

@@ -680,7 +680,7 @@ function renderPanel(order){
const placeLine=node('b');placeLine.append(icon(dest?ICON_TRUCK:ICON_PIN),dest?dest.recipient:'Retirada em Franca');
where.append(node('p','Entrega','eyebrow'),placeLine,
node('span',dest?dest.street+', '+dest.number+(dest.complement?' '+dest.complement:'')+' · '+dest.district+' · '+dest.city+'/'+dest.state+' · CEP '+dest.postal_code:'Cliente retira na fábrica'));
if(dest&&s.freight?.total_cents)where.append(node('span','Jadlog · '+money(s.freight.total_cents)+(s.freight.weight_kg?' · '+freightWeight(s.freight):''),'faint'));
if(dest&&s.freight?.total_cents)where.append(node('span',(s.freight.description||'Jadlog')+' · '+money(s.freight.total_cents)+(s.freight.weight_kg?' · '+freightWeight(s.freight):''),'faint'));
facts.append(who,where);
if(order.machine||board.machines?.length)facts.append(machineCard(order));
const items=node('section');items.append(node('p',s.items.length>1?'Itens':'Item','eyebrow'));
@@ -1587,16 +1587,18 @@ function renderIntegrations(){
details:mp&&mpCheck?mercadoPagoCheck(mpCheck):[]}));
const fr=board.providers?.freight||{};
const kg=v=>String(v).replace('.',',')+' kg';
rows.push(fr.provider==='jadlog'
const carriers=Object.values(fr.services||{});
const list=names=>names.length>1?names.slice(0,-1).join(', ')+' e '+names.at(-1):names[0];
rows.push(carriers.length
? integration({name:'Frete',state:fr.box_cm?'Ativo':'Verificar',tone:fr.box_cm?'ok':'warn',
summary:fr.box_cm?'Jadlog e retirada em Franca · prazo da Jadlog + '+fr.production_days+' dia(s) de produção.'
:'Cubagem não configurada: a Jadlog pode cobrar mais que a cotação.',
details:[['Pacote',kg(fr.base_kg)+' + '+kg(fr.per_metre_kg)+' por metro'],
summary:fr.box_cm?list(carriers)+' e retirada em Franca · prazo + '+fr.production_days+' dia(s) de produção.'
:'Caixa não configurada: as transportadoras podem cobrar mais que a cotação.',
details:[['Opções',list(carriers)],['Pacote',kg(fr.base_kg)+' + '+kg(fr.per_metre_kg)+' por metro'],
...(fr.box_cm?[['Caixa',fr.box_cm.map(n=>String(n).replace('.',',')).join(' × ')+' cm'],
['Cubagem',String(fr.cubage_kg_m3).replace('.',',')+' kg/m³ = '+kg(fr.cubed_kg)+' cubados'],
['Cubagem Jadlog',String(fr.cubage_kg_m3).replace('.',',')+' kg/m³ = '+kg(fr.cubed_kg)+' cubados'],
...(fr.metres_per_box?[['Por caixa','Até '+String(fr.metres_per_box).replace('.',',')+' m']]:[])]:[]),
// Jadlog charges the larger of the real and the cubed weight.
node('p',fr.box_cm?'A Jadlog cobra o maior entre o peso real e o cubado.':'Sem a caixa, a cotação usa só o peso real.')]})
// Each carrier charges the larger of the real and the cubed weight.
node('p','No carrinho o cliente vê todas as opções, da mais barata para a mais cara, com o prazo. Cada transportadora cobra o maior entre o peso real e o cubado.')]})
: integration({name:'Frete',state:'Não configurado',tone:'off',summary:'Somente retirada.'}));
rows.push(integration({name:'WhatsApp',state:'Não configurado',tone:'off',summary:'Mensagens registradas, sem envio.'}));
rows.push(mailRow(board.providers?.mail||{}));

View File

@@ -205,7 +205,7 @@ function itensPedido(snapshot){
}
function entrega(snapshot){
const d=snapshot.destination, p=node('p',null,'entregaPed');
p.append(icone(d?'caminhao':'local'),node('span',d?'Entrega pela Jadlog · '+d.street+', '+d.number+' · '+d.city+'/'+d.state:'Retirada em Franca · Av. Major Elias Motta, 1281'));
p.append(icone(d?'caminhao':'local'),node('span',d?'Entrega por '+(snapshot.freight?.description||'Jadlog')+' · '+d.street+', '+d.number+' · '+d.city+'/'+d.state:'Retirada em Franca · Av. Major Elias Motta, 1281'));
return p;
}
async function details(id,container,criado){

View File

@@ -63,7 +63,9 @@ function pintaPedido(){
'<div class="l"><span>'+n+(n===1?' item':' itens')+'</span><b>'+rs(itens+eco)+'</b></div>'+
(eco>0.01? '<div class="l" style="color:var(--verde-ml)"><span>Desconto pela nota</span>'+
'<b style="color:var(--verde-ml)">− '+rs(eco)+'</b></div>' : '')+
'<div class="l"><span>Frete'+(entrega.tipo==='frete' && entrega.cotado && entrega.dias
'<div class="l"><span>'+(entrega.tipo==='frete' && entrega.cotado
? escapeHTML((entrega.opcoes||[]).find(o=>o.service===entrega.servico)?.description||'Frete') : 'Frete')+
(entrega.tipo==='frete' && entrega.cotado && entrega.dias
? ' · até '+entrega.dias+' dias úteis' : '')+'</span><b>'+
(entrega.tipo==='retira' ? '<span style="color:var(--verde-ml)">Grátis</span>'
: entrega.cotado ? rs(frete) : 'a cotar')+'</b></div>'+

View File

@@ -94,7 +94,7 @@ let pedido=[]; // itens já fechados · o pagamento
// A escolha de entrega vale para o pedido inteiro, não por item. No Tiny, retirada
// grava forma_envio X, transportador DropStar e frete por conta do remetente — igual
// ao que a expedição já recebe hoje, sem criar processo novo.
let entrega={tipo:'retira', cep:'', valor:0, cotado:true, end:{}};
let entrega={tipo:'retira', cep:'', valor:0, cotado:true, end:{}, servico:'', opcoes:[]};
let cliente={cnpj:'', zap:'', mail:''};
// CNPJ com os dois dígitos verificadores · máscara sem conta não vale nada

View File

@@ -73,6 +73,26 @@ $('pVolta').addEventListener('click',()=>{
$('cPro').addEventListener('click',()=>ir(atual()+1));
})();
// The delivery options for the CEP, cheapest first: carrier, time and price.
function pintaFretes(){
const box=$('fretes'), opcoes=entrega.opcoes||[];
box.hidden=!opcoes.length;
box.innerHTML=opcoes.map((o,i)=>{
const on=o.service===entrega.servico, id='frete-'+o.service;
return '<label class="opF'+(on?' on':'')+'" for="'+id+'">'+
'<input type="radio" name="frete" id="'+id+'" value="'+escapeHTML(o.service)+'"'+(on?' checked':'')+'>'+
'<span class="opFn"><b>'+escapeHTML(o.description)+'</b>'+
(o.days?'<small>até '+o.days+' dias úteis</small>':'')+'</span>'+
(i===0&&opcoes.length>1?'<i>mais barato</i>':'')+
'<em>'+rs(o.total_cents/100)+'</em></label>';
}).join('');
}
$('fretes').addEventListener('change',e=>{
const o=(entrega.opcoes||[]).find(x=>x.service===e.target.value);
if(!o) return;
entrega.servico=o.service; entrega.valor=o.total_cents/100; entrega.dias=o.days||null; entrega.cotado=true;
pintaFretes(); pintaEntrega();
});
function pintaEntrega(){
document.querySelectorAll('.opE').forEach(b=>
b.classList.toggle('on', b.dataset.ent===entrega.tipo));
@@ -164,7 +184,7 @@ $('cepIn').addEventListener('input',e=>{
const v=e.target.value.replace(/\D/g,'').slice(0,8);
e.target.value = fmtCep(v);
if(v===entrega.cep) return;
entrega.cep=v; entrega.cotado=false; entrega.valor=0; entrega.dias=null; pintaEntrega();
entrega.cep=v; entrega.cotado=false; entrega.valor=0; entrega.dias=null; entrega.opcoes=[]; pintaFretes(); pintaEntrega();
if(v.length===8){ buscaEndereco(v); if(window.dtfFreight) window.dtfFreight(); }
});
for(const [id,chave] of [['eNome','nome'],['eRua','rua'],['eNum','num'],['eComp','comp'],

View File

@@ -498,3 +498,15 @@ html:is([data-rota="pagamento"],[data-rota="pix"]) .pagGrid{display:grid;grid-te
so the page's full height is 100/0.88 vh there (site-shell.css keeps the
footer at the bottom). */
@media (min-width:1100px){html{zoom:.88}body{min-height:calc(100vh / .88)}}
/* Delivery options for the CEP: one row each, the chosen one marked. */
.fretes{display:flex;flex-direction:column;gap:8px;margin:2px 0 14px}
/* Inside .cep, whose own "label" rule would stack each row. */
.cep .opF{display:flex;align-items:center;gap:12px;margin:0;padding:12px 14px;border:1px solid var(--linha);border-radius:10px;background:#fff;color:var(--preto);font-size:15px;cursor:pointer}
.cep .opF.on{border:2px solid var(--laranja);padding:11px 13px;background:var(--aviso-fundo)}
.opF input{accent-color:var(--laranja-escuro);width:18px;height:18px;margin:0}
.opFn{display:flex;flex-direction:column;flex:1;min-width:0}
.opFn b{font-size:15px}
.opFn small{font-size:13.5px;color:var(--texto2)}
.opF i{font-style:normal;font-size:12px;font-weight:700;color:var(--verde-ml);white-space:nowrap}
.opF em{font-style:normal;font-weight:800;white-space:nowrap}