diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index beffdb3..3e44a16 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -86,7 +86,7 @@ jobs: # the generator's geometry. The provider suites use a fake transport: they # prove the documented contract, not the integration. - name: Print-file geometry and provider adapters - run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_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: | diff --git a/app/adapters.py b/app/adapters.py index 6128bf2..e8a3305 100644 --- a/app/adapters.py +++ b/app/adapters.py @@ -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: ... diff --git a/app/api/health.py b/app/api/health.py index 7269462..d86acd9 100644 --- a/app/api/health.py +++ b/app/api/health.py @@ -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/' diff --git a/app/api/operator.py b/app/api/operator.py index ea27b93..56701c8 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -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): diff --git a/app/core/models.py b/app/core/models.py index 864c4c1..dca229e 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -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'] diff --git a/app/core/secrets.py b/app/core/secrets.py index e410d7b..982e921 100644 --- a/app/core/secrets.py +++ b/app/core/secrets.py @@ -29,6 +29,7 @@ SECRET_FILE_SETTINGS = ( 'TINY_TOKEN', 'WHATSAPP_TOKEN', 'SMTP_PASSWORD', + 'CORREIOS_CODIGO_ACESSO', ) SUFFIX = '_FILE' diff --git a/app/correios.py b/app/correios.py new file mode 100644 index 0000000..f642a74 --- /dev/null +++ b/app/correios.py @@ -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]} diff --git a/app/correios_probe.py b/app/correios_probe.py new file mode 100644 index 0000000..81dbda4 --- /dev/null +++ b/app/correios_probe.py @@ -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()) diff --git a/app/freight.py b/app/freight.py new file mode 100644 index 0000000..44f3368 --- /dev/null +++ b/app/freight.py @@ -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} diff --git a/app/jadlog.py b/app/jadlog.py index b33142c..23f5daf 100644 --- a/app/jadlog.py +++ b/app/jadlog.py @@ -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]} diff --git a/app/package.py b/app/package.py new file mode 100644 index 0000000..29b8497 --- /dev/null +++ b/app/package.py @@ -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} diff --git a/app/runtime.py b/app/runtime.py index 1e35748..973b240 100644 --- a/app/runtime.py +++ b/app/runtime.py @@ -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.') diff --git a/compose.local.yaml b/compose.local.yaml index decf240..06399cc 100644 --- a/compose.local.yaml +++ b/compose.local.yaml @@ -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} diff --git a/docker-compose.yml b/docker-compose.yml index 77d8e06..2316779 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -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). diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index 5c2ea8b..d5f7c88 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -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. diff --git a/docs/PORTAINER.md b/docs/PORTAINER.md index d8fb19f..3eaf906 100644 --- a/docs/PORTAINER.md +++ b/docs/PORTAINER.md @@ -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 diff --git a/tests/test_correios.py b/tests/test_correios.py new file mode 100644 index 0000000..690b40c --- /dev/null +++ b/tests/test_correios.py @@ -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() diff --git a/web/checkout.js b/web/checkout.js index 057ab36..a06fe75 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -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(); diff --git a/web/index.html b/web/index.html index af8ee2d..37f4090 100644 --- a/web/index.html +++ b/web/index.html @@ -1041,7 +1041,7 @@ h2 em{font-style:normal;color:var(--laranja)}