Compare commits
3 Commits
95be624cca
...
90e3126075
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
90e3126075 | ||
|
|
69997f4598 | ||
|
|
7383e44ff4 |
@@ -86,7 +86,7 @@ jobs:
|
|||||||
# the generator's geometry. The provider suites use a fake transport: they
|
# the generator's geometry. The provider suites use a fake transport: they
|
||||||
# prove the documented contract, not the integration.
|
# prove the documented contract, not the integration.
|
||||||
- name: Print-file geometry and provider adapters
|
- name: Print-file geometry and provider adapters
|
||||||
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_quote_review tests.test_large_files tests.test_grade_check -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
|
- name: Runtime and retention regressions
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -27,6 +27,13 @@ def require_runtime():
|
|||||||
raise RuntimeError(f'{name} is required for the Jadlog adapter')
|
raise RuntimeError(f'{name} is required for the Jadlog adapter')
|
||||||
elif freight != 'fake':
|
elif freight != 'fake':
|
||||||
raise RuntimeError('FREIGHT must use the fake or jadlog adapter')
|
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')
|
tiny = os.environ.get('TINY_ADAPTER')
|
||||||
if tiny == 'tiny':
|
if tiny == 'tiny':
|
||||||
from .tiny import required_settings
|
from .tiny import required_settings
|
||||||
@@ -169,6 +176,7 @@ class FreightAdapter(Protocol):
|
|||||||
|
|
||||||
class FakeFreight:
|
class FakeFreight:
|
||||||
name = 'fake'
|
name = 'fake'
|
||||||
|
services = {'mock-standard': 'Entrega simulada'}
|
||||||
|
|
||||||
def quote(self, service: str, postal_code: str, metres=None, declared_cents: int = 0) -> dict:
|
def quote(self, service: str, postal_code: str, metres=None, declared_cents: int = 0) -> dict:
|
||||||
if service == 'pickup':
|
if service == 'pickup':
|
||||||
@@ -179,7 +187,7 @@ class FakeFreight:
|
|||||||
if cents < 0:
|
if cents < 0:
|
||||||
raise ValueError('Invalid mock freight configuration')
|
raise ValueError('Invalid mock freight configuration')
|
||||||
return {'provider': 'fake', 'service': service, 'postal_code': postal_code,
|
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):
|
class EventAdapter(Protocol):
|
||||||
def deliver(self, event_key: str, payload: dict) -> dict: ...
|
def deliver(self, event_key: str, payload: dict) -> dict: ...
|
||||||
|
|||||||
@@ -14,8 +14,8 @@ from ..core import db
|
|||||||
from ..artwork import submit_files
|
from ..artwork import submit_files
|
||||||
from ..core.auth import (DUMMY_PASSWORD_HASH, audit, client_ip, new_session, owner, login_failed, password_hash,
|
from ..core.auth import (DUMMY_PASSWORD_HASH, audit, client_ip, new_session, owner, login_failed, password_hash,
|
||||||
password_matches, rate_limit, session_row, throttle, transfer_guest)
|
password_matches, rate_limit, session_row, throttle, transfer_guest)
|
||||||
from ..core.models import (ArtworkSubmission, EmailChange, ForgotPassword, Login, PasswordChange, PasswordReset,
|
from ..core.models import (ArtworkSubmission, EmailChange, EmailCode, EmailResend, ForgotPassword, Login,
|
||||||
ProfileUpdate, Register, SignupCode, SignupResend)
|
PasswordChange, PasswordReset, ProfileUpdate, Register, SignupCode, SignupResend)
|
||||||
from .. import mail
|
from .. import mail
|
||||||
from ..runtime import ENVIRONMENT, PUBLIC_ORIGIN, STATES, file_rows, order_code, owned_order, storage
|
from ..runtime import ENVIRONMENT, PUBLIC_ORIGIN, STATES, file_rows, order_code, owned_order, storage
|
||||||
from ..scanning import require_clean
|
from ..scanning import require_clean
|
||||||
@@ -47,11 +47,45 @@ def signup_code(c, signup_id, email, exists):
|
|||||||
'Esqueceu a senha? Na mesma página, clique em “Esqueci minha senha”.\n\n'
|
'Esqueceu a senha? Na mesma página, clique em “Esqueci minha senha”.\n\n'
|
||||||
'Se não foi você, ignore este e-mail: nada muda na sua conta.')
|
'Se não foi você, ignore este e-mail: nada muda na sua conta.')
|
||||||
return None
|
return None
|
||||||
|
return send_code(c, signup_id, email, 'criar a conta no DTF Dropstar')
|
||||||
|
|
||||||
|
|
||||||
|
def send_code(c, key, email, purpose):
|
||||||
|
"""A fresh 6-digit code by e-mail for `purpose`; returns its hash."""
|
||||||
code = f'{secrets.randbelow(10 ** 6):06d}'
|
code = f'{secrets.randbelow(10 ** 6):06d}'
|
||||||
mail.queue(c, 'code', email, f'{code} é o seu código · DTF Dropstar',
|
mail.queue(c, 'code', email, f'{code} é o seu código · DTF Dropstar',
|
||||||
f'Olá!\n\nO seu código para criar a conta no DTF Dropstar é:\n\n{code}\n\n'
|
f'Olá!\n\nO seu código para {purpose} é:\n\n{code}\n\n'
|
||||||
f'Ele vale por {mail.CODE_MINUTES} minutos. Se não foi você, ignore este e-mail.')
|
f'Ele vale por {mail.CODE_MINUTES} minutos. Se não foi você, ignore este e-mail.')
|
||||||
return code_digest(signup_id, code)
|
return code_digest(key, code)
|
||||||
|
|
||||||
|
|
||||||
|
def checked_code(c, table, key, code, request, extra=''):
|
||||||
|
"""The pending row a code confirms, locked, or the refusal to raise. A wrong
|
||||||
|
code counts against the row; the caller raises after its block commits."""
|
||||||
|
row = c.execute(f'SELECT * FROM dtf_local.{table} WHERE id=%s AND done_at IS NULL {extra} FOR UPDATE',
|
||||||
|
key).fetchone()
|
||||||
|
if not row or row['expires_at'] <= datetime.now(timezone.utc):
|
||||||
|
return None, HTTPException(410, 'Este código venceu. Clique em “Reenviar código”.')
|
||||||
|
if row['attempts'] >= CODE_ATTEMPTS:
|
||||||
|
return None, HTTPException(429, 'Muitas tentativas com este código. Clique em “Reenviar código”.')
|
||||||
|
if row['code_hash'] and secrets.compare_digest(row['code_hash'], code_digest(row['id'], code)):
|
||||||
|
c.execute(f'UPDATE dtf_local.{table} SET done_at=now() WHERE id=%s', (row['id'],))
|
||||||
|
return row, None
|
||||||
|
c.execute(f'UPDATE dtf_local.{table} SET attempts=attempts+1 WHERE id=%s', (row['id'],))
|
||||||
|
left = CODE_ATTEMPTS - row['attempts'] - 1
|
||||||
|
audit('code_wrong', kind=table, ip=client_ip(request))
|
||||||
|
return None, HTTPException(400, 'Código incorreto. ' + (f'Restam {left} tentativas.' if left > 1 else
|
||||||
|
'Resta 1 tentativa.' if left == 1 else 'Clique em “Reenviar código”.'))
|
||||||
|
|
||||||
|
|
||||||
|
def resend_wait(row):
|
||||||
|
"""Why another code cannot go yet, or None."""
|
||||||
|
wait = RESEND_SECONDS - (datetime.now(timezone.utc) - row['sent_at']).total_seconds()
|
||||||
|
if wait > 0:
|
||||||
|
return HTTPException(429, f'Aguarde {int(wait) + 1} s para pedir outro código.')
|
||||||
|
if row['sends'] >= CODE_SENDS:
|
||||||
|
return HTTPException(429, 'Limite de códigos atingido. Comece de novo em alguns minutos.')
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def code_digest(signup_id, code):
|
def code_digest(signup_id, code):
|
||||||
@@ -101,27 +135,12 @@ def create_account(profile, password, previous, response):
|
|||||||
|
|
||||||
@router.post('/api/account/register/verify')
|
@router.post('/api/account/register/verify')
|
||||||
def register_verify(body: SignupCode, request: Request, response: Response):
|
def register_verify(body: SignupCode, request: Request, response: Response):
|
||||||
rate_limit('signup-verify', client_ip(request), 30)
|
rate_limit('code-verify', client_ip(request), 30)
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
signup = c.execute('SELECT * FROM dtf_local.account_signups WHERE id=%s AND done_at IS NULL FOR UPDATE',
|
signup, refusal = checked_code(c, 'account_signups', (body.signup,), body.code, request)
|
||||||
(body.signup,)).fetchone()
|
# Raised outside the block, so a wrong attempt is counted, not rolled back.
|
||||||
if not signup or signup['expires_at'] <= datetime.now(timezone.utc):
|
if refusal:
|
||||||
raise HTTPException(410, 'Este código venceu. Clique em “Reenviar código”.')
|
raise refusal
|
||||||
if signup['attempts'] >= CODE_ATTEMPTS:
|
|
||||||
raise HTTPException(429, 'Muitas tentativas com este código. Clique em “Reenviar código”.')
|
|
||||||
right = signup['code_hash'] and secrets.compare_digest(signup['code_hash'], code_digest(signup['id'], body.code))
|
|
||||||
if not right:
|
|
||||||
c.execute('UPDATE dtf_local.account_signups SET attempts=attempts+1 WHERE id=%s', (signup['id'],))
|
|
||||||
left = CODE_ATTEMPTS - signup['attempts'] - 1
|
|
||||||
audit('account_signup_code_wrong', ip=client_ip(request))
|
|
||||||
# Committed with the attempt: the connection's block ends cleanly.
|
|
||||||
wrong = HTTPException(400, 'Código incorreto. ' + (f'Restam {left} tentativas.' if left > 1 else
|
|
||||||
'Resta 1 tentativa.' if left == 1 else 'Clique em “Reenviar código”.'))
|
|
||||||
else:
|
|
||||||
wrong = None
|
|
||||||
c.execute('UPDATE dtf_local.account_signups SET done_at=now() WHERE id=%s', (signup['id'],))
|
|
||||||
if wrong:
|
|
||||||
raise wrong
|
|
||||||
return create_account(profile=signup['profile'], password=signup['password_hash'],
|
return create_account(profile=signup['profile'], password=signup['password_hash'],
|
||||||
previous=current(request), response=response)
|
previous=current(request), response=response)
|
||||||
|
|
||||||
@@ -143,17 +162,14 @@ def register_dev_code(signup: UUID):
|
|||||||
|
|
||||||
@router.post('/api/account/register/resend')
|
@router.post('/api/account/register/resend')
|
||||||
def register_resend(body: SignupResend, request: Request):
|
def register_resend(body: SignupResend, request: Request):
|
||||||
rate_limit('signup-verify', client_ip(request), 30)
|
rate_limit('code-verify', client_ip(request), 30)
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
signup = c.execute('SELECT * FROM dtf_local.account_signups WHERE id=%s AND done_at IS NULL FOR UPDATE',
|
signup = c.execute('SELECT * FROM dtf_local.account_signups WHERE id=%s AND done_at IS NULL FOR UPDATE',
|
||||||
(body.signup,)).fetchone()
|
(body.signup,)).fetchone()
|
||||||
if not signup:
|
if not signup:
|
||||||
raise HTTPException(410, 'Este cadastro venceu. Preencha os dados de novo.')
|
raise HTTPException(410, 'Este cadastro venceu. Preencha os dados de novo.')
|
||||||
wait = RESEND_SECONDS - (datetime.now(timezone.utc) - signup['sent_at']).total_seconds()
|
if refusal := resend_wait(signup):
|
||||||
if wait > 0:
|
raise refusal
|
||||||
raise HTTPException(429, f'Aguarde {int(wait) + 1} s para pedir outro código.')
|
|
||||||
if signup['sends'] >= CODE_SENDS:
|
|
||||||
raise HTTPException(429, 'Limite de códigos atingido. Preencha os dados de novo em alguns minutos.')
|
|
||||||
exists = c.execute('SELECT 1 FROM dtf_local.accounts WHERE email=%s', (signup['email'],)).fetchone()
|
exists = c.execute('SELECT 1 FROM dtf_local.accounts WHERE email=%s', (signup['email'],)).fetchone()
|
||||||
digest = signup_code(c, signup['id'], signup['email'], exists)
|
digest = signup_code(c, signup['id'], signup['email'], exists)
|
||||||
c.execute('''UPDATE dtf_local.account_signups SET code_hash=%s, attempts=0, sends=sends+1, sent_at=now(),
|
c.execute('''UPDATE dtf_local.account_signups SET code_hash=%s, attempts=0, sends=sends+1, sent_at=now(),
|
||||||
@@ -228,15 +244,66 @@ def change_email(body: EmailChange, request: Request, identity=Depends(owner)):
|
|||||||
if not password_matches(body.password, row['password_hash']):
|
if not password_matches(body.password, row['password_hash']):
|
||||||
login_failed(row['email'])
|
login_failed(row['email'])
|
||||||
raise HTTPException(401, 'Senha incorreta.')
|
raise HTTPException(401, 'Senha incorreta.')
|
||||||
profile = {**row['profile'], 'mail': body.email}
|
if body.email == row['email']:
|
||||||
|
raise HTTPException(422, 'Este já é o e-mail da sua conta.')
|
||||||
|
if not mail.configured():
|
||||||
|
return apply_email(identity, row, body.email)
|
||||||
|
# With e-mail on, the change waits for the code sent to the new address.
|
||||||
|
rate_limit('email-change', str(identity), CODE_SENDS, 3600)
|
||||||
|
change = uuid4()
|
||||||
|
with db.connect() as c:
|
||||||
|
if c.execute('SELECT 1 FROM dtf_local.accounts WHERE email=%s', (body.email,)).fetchone():
|
||||||
|
raise HTTPException(409, 'Este e-mail já é de outra conta.')
|
||||||
|
digest = send_code(c, change, body.email, 'trocar o e-mail da sua conta no DTF Dropstar')
|
||||||
|
c.execute('''INSERT INTO dtf_local.email_changes(id,account_id,new_email,code_hash,expires_at)
|
||||||
|
VALUES(%s,%s,%s,%s,now() + %s * interval '1 minute')''', (change, identity, body.email, digest, mail.CODE_MINUTES))
|
||||||
|
audit('account_email_change_started', account=str(identity))
|
||||||
|
return {'verify': str(change), 'email': body.email, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
|
||||||
|
|
||||||
|
|
||||||
|
def apply_email(identity, row, email):
|
||||||
|
"""Switch the account to the new e-mail and tell the old address."""
|
||||||
|
profile = {**row['profile'], 'mail': email}
|
||||||
try:
|
try:
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
c.execute('UPDATE dtf_local.accounts SET email=%s, profile=%s WHERE id=%s', (body.email, Jsonb(profile), identity))
|
c.execute('UPDATE dtf_local.accounts SET email=%s, profile=%s WHERE id=%s', (email, Jsonb(profile), identity))
|
||||||
|
mail.queue(c, 'notice', row['email'], 'O e-mail da sua conta foi trocado · DTF Dropstar',
|
||||||
|
f'Olá!\n\nO e-mail da sua conta no DTF Dropstar foi trocado para {email}. '
|
||||||
|
'A partir de agora, entre com ele.\n\n'
|
||||||
|
'Se não foi você, fale com a Dropstar pelo WhatsApp 16 99428-0056.')
|
||||||
except UniqueViolation:
|
except UniqueViolation:
|
||||||
raise HTTPException(409, 'Este e-mail já é de outra conta.')
|
raise HTTPException(409, 'Este e-mail já é de outra conta.')
|
||||||
audit('account_email_changed', account=str(identity))
|
audit('account_email_changed', account=str(identity))
|
||||||
return {'customer': profile}
|
return {'customer': profile}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/account/email/verify')
|
||||||
|
def change_email_verify(body: EmailCode, request: Request, identity=Depends(owner)):
|
||||||
|
rate_limit('code-verify', client_ip(request), 30)
|
||||||
|
with db.connect() as c:
|
||||||
|
change, refusal = checked_code(c, 'email_changes', (body.change, identity), body.code, request,
|
||||||
|
extra='AND account_id=%s')
|
||||||
|
row = account_row(c, identity) if change else None
|
||||||
|
if refusal:
|
||||||
|
raise refusal
|
||||||
|
return apply_email(identity, row, change['new_email'])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/account/email/resend')
|
||||||
|
def change_email_resend(body: EmailResend, request: Request, identity=Depends(owner)):
|
||||||
|
rate_limit('code-verify', client_ip(request), 30)
|
||||||
|
with db.connect() as c:
|
||||||
|
change = c.execute('''SELECT * FROM dtf_local.email_changes WHERE id=%s AND account_id=%s AND done_at IS NULL
|
||||||
|
FOR UPDATE''', (body.change, identity)).fetchone()
|
||||||
|
if not change:
|
||||||
|
raise HTTPException(410, 'Esta troca venceu. Comece de novo.')
|
||||||
|
if refusal := resend_wait(change):
|
||||||
|
raise refusal
|
||||||
|
digest = send_code(c, change['id'], change['new_email'], 'trocar o e-mail da sua conta no DTF Dropstar')
|
||||||
|
c.execute('''UPDATE dtf_local.email_changes SET code_hash=%s, attempts=0, sends=sends+1, sent_at=now(),
|
||||||
|
expires_at=now() + %s * interval '1 minute' WHERE id=%s''', (digest, mail.CODE_MINUTES, change['id']))
|
||||||
|
return {'ok': True, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
|
||||||
|
|
||||||
@router.post('/api/account/password')
|
@router.post('/api/account/password')
|
||||||
def change_password(body: PasswordChange, request: Request, identity=Depends(owner)):
|
def change_password(body: PasswordChange, request: Request, identity=Depends(owner)):
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ from .. import mail
|
|||||||
from ..core.auth import client_ip, owner, new_session, rate_limit
|
from ..core.auth import client_ip, owner, new_session, rate_limit
|
||||||
from ..core.limits import upload_limit_bytes
|
from ..core.limits import upload_limit_bytes
|
||||||
from ..core.pricing import manual_extra_cents
|
from ..core.pricing import manual_extra_cents
|
||||||
from ..core.models import FreightEstimate
|
from ..core.models import FreightAsk, FreightEstimate
|
||||||
from ..runtime import (ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, freight, payment,
|
from ..runtime import (ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, delivery_services, freight, payment,
|
||||||
require_delivery_available, storage)
|
require_delivery_available, storage)
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
@@ -45,8 +45,8 @@ def session(request: Request, response: Response):
|
|||||||
'manual_extra_cents': manual_extra_cents(),
|
'manual_extra_cents': manual_extra_cents(),
|
||||||
# Public by design: Mercado Pago's card form needs it in the browser.
|
# 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 '',
|
'payment_public_key': os.environ.get('MP_PUBLIC_KEY', '') if payment.name == 'mercadopago' else '',
|
||||||
# The delivery service the cart quotes, or none: pickup only.
|
# The delivery options the cart quotes, or none: pickup only.
|
||||||
'freight_service': 'jadlog' if freight.name == 'jadlog' else 'mock-standard' if ENVIRONMENT == 'local' else None}
|
'freight_services': delivery_services()}
|
||||||
|
|
||||||
@router.post('/api/freight')
|
@router.post('/api/freight')
|
||||||
def quote_freight(body: FreightEstimate):
|
def quote_freight(body: FreightEstimate):
|
||||||
@@ -56,6 +56,19 @@ def quote_freight(body: FreightEstimate):
|
|||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(422, str(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 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.
|
# the browser, which keeps the Site's CSP to its own origin.
|
||||||
VIACEP = 'https://viacep.com.br/ws/{}/json/'
|
VIACEP = 'https://viacep.com.br/ws/{}/json/'
|
||||||
|
|||||||
@@ -68,15 +68,12 @@ def operator_logout(request: Request, response: Response):
|
|||||||
|
|
||||||
def freight_status():
|
def freight_status():
|
||||||
"""What delivery the Site offers, and the package rule it prices with."""
|
"""What delivery the Site offers, and the package rule it prices with."""
|
||||||
if freight.name != 'jadlog':
|
real = [carrier for carrier in freight.carriers if carrier.name != 'fake']
|
||||||
return {'provider': freight.name}
|
status = {'carriers': [carrier.name for carrier in real], 'services': freight.services if real else {}}
|
||||||
cubed = freight.cubed_kg()
|
if real:
|
||||||
return {'provider': 'jadlog', 'base_kg': str(freight.base_kg), 'per_metre_kg': str(freight.per_metre_kg),
|
# One package for every carrier (app/package.py).
|
||||||
'production_days': freight.production_days,
|
status.update(real[0].status())
|
||||||
'box_cm': [str(side) for side in freight.box_cm] if freight.box_cm else None,
|
return status
|
||||||
'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}
|
|
||||||
|
|
||||||
|
|
||||||
def backup_status(c):
|
def backup_status(c):
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ class Customer(StrictModel):
|
|||||||
return value.strip()
|
return value.strip()
|
||||||
|
|
||||||
class Freight(StrictModel):
|
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)
|
postal_code: str = Field(default='', max_length=8)
|
||||||
|
|
||||||
class FreightEstimate(Freight):
|
class FreightEstimate(Freight):
|
||||||
@@ -50,6 +50,12 @@ class FreightEstimate(Freight):
|
|||||||
metres: Decimal | None = Field(default=None, gt=0, le=12000)
|
metres: Decimal | None = Field(default=None, gt=0, le=12000)
|
||||||
declared_cents: int = Field(default=0, ge=0, le=100_000_000, strict=True)
|
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',
|
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']
|
'PR','PE','PI','RJ','RN','RS','RO','RR','SC','SP','SE','TO']
|
||||||
|
|
||||||
@@ -261,6 +267,13 @@ class SignupCode(StrictModel):
|
|||||||
class SignupResend(StrictModel):
|
class SignupResend(StrictModel):
|
||||||
signup: UUID
|
signup: UUID
|
||||||
|
|
||||||
|
class EmailCode(StrictModel):
|
||||||
|
change: UUID
|
||||||
|
code: str = Field(pattern=r'^[0-9]{6}$')
|
||||||
|
|
||||||
|
class EmailResend(StrictModel):
|
||||||
|
change: UUID
|
||||||
|
|
||||||
class ForgotPassword(StrictModel):
|
class ForgotPassword(StrictModel):
|
||||||
email: str = Field(min_length=3, max_length=254)
|
email: str = Field(min_length=3, max_length=254)
|
||||||
|
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ SECRET_FILE_SETTINGS = (
|
|||||||
'TINY_TOKEN',
|
'TINY_TOKEN',
|
||||||
'WHATSAPP_TOKEN',
|
'WHATSAPP_TOKEN',
|
||||||
'SMTP_PASSWORD',
|
'SMTP_PASSWORD',
|
||||||
|
'CORREIOS_CODIGO_ACESSO',
|
||||||
)
|
)
|
||||||
|
|
||||||
SUFFIX = '_FILE'
|
SUFFIX = '_FILE'
|
||||||
|
|||||||
184
app/correios.py
Normal file
184
app/correios.py
Normal 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
70
app/correios_probe.py
Normal 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
46
app/freight.py
Normal 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}
|
||||||
@@ -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),
|
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
|
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
|
real and the cubed weight, both from the order's package (app/package.py).
|
||||||
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.
|
|
||||||
"""
|
"""
|
||||||
import math
|
|
||||||
import os
|
import os
|
||||||
import re
|
|
||||||
from decimal import ROUND_HALF_UP, Decimal
|
from decimal import ROUND_HALF_UP, Decimal
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
|
from .package import WEIGHT_SETTINGS, Package
|
||||||
|
|
||||||
QUOTE_URL = 'https://www.jadlog.com.br/embarcador/api/frete/valor'
|
QUOTE_URL = 'https://www.jadlog.com.br/embarcador/api/frete/valor'
|
||||||
PACKAGE = 3
|
PACKAGE = 3
|
||||||
ORIGIN = '14402310'
|
ORIGIN = '14402310'
|
||||||
SERVICE = 'jadlog'
|
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):
|
class JadlogError(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -99,53 +80,14 @@ def required_settings():
|
|||||||
return ('JADLOG_TOKEN', 'JADLOG_CNPJ') + WEIGHT_SETTINGS
|
return ('JADLOG_TOKEN', 'JADLOG_CNPJ') + WEIGHT_SETTINGS
|
||||||
|
|
||||||
|
|
||||||
class JadlogFreight:
|
class JadlogFreight(Package):
|
||||||
"""The Site's delivery option: Jadlog's price for the order's package."""
|
"""The Site's Jadlog option: Jadlog's price for the order's package."""
|
||||||
name = 'jadlog'
|
name = 'jadlog'
|
||||||
|
services = {SERVICE: 'Jadlog .PACKAGE'}
|
||||||
|
|
||||||
def __init__(self, quotes=None):
|
def __init__(self, quotes=None):
|
||||||
|
super().__init__()
|
||||||
self.quotes = quotes or JadlogQuotes()
|
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):
|
def quote(self, service, postal_code, metres=None, declared_cents=0):
|
||||||
if service == 'pickup':
|
if service == 'pickup':
|
||||||
@@ -164,4 +106,4 @@ class JadlogFreight:
|
|||||||
'total_cents': result['total_cents'], 'weight_kg': str(weight), 'real_kg': str(real),
|
'total_cents': result['total_cents'], 'weight_kg': str(weight), 'real_kg': str(real),
|
||||||
'boxes': self.boxes(metres),
|
'boxes': self.boxes(metres),
|
||||||
'days': None if days is None else int(days) + self.production_days,
|
'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
91
app/package.py
Normal 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}
|
||||||
@@ -13,6 +13,7 @@ from fastapi import HTTPException
|
|||||||
from psycopg.types.json import Jsonb
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
from .adapters import FakeFreight, FakePayment, LocalS3Storage, require_runtime
|
from .adapters import FakeFreight, FakePayment, LocalS3Storage, require_runtime
|
||||||
|
from .freight import FreightOptions
|
||||||
from .core.secrets import load as load_secret_files
|
from .core.secrets import load as load_secret_files
|
||||||
|
|
||||||
# Secret files must resolve before any configuration below is read.
|
# Secret files must resolve before any configuration below is read.
|
||||||
@@ -25,11 +26,15 @@ if os.environ.get('PAYMENT_ADAPTER') == 'mercadopago':
|
|||||||
payment = MercadoPagoPayment()
|
payment = MercadoPagoPayment()
|
||||||
else:
|
else:
|
||||||
payment = FakePayment()
|
payment = FakePayment()
|
||||||
|
# Every carrier configured; the simulated one only where there is none.
|
||||||
|
_carriers = []
|
||||||
if os.environ.get('FREIGHT_ADAPTER') == 'jadlog':
|
if os.environ.get('FREIGHT_ADAPTER') == 'jadlog':
|
||||||
from .jadlog import JadlogFreight
|
from .jadlog import JadlogFreight
|
||||||
freight = JadlogFreight()
|
_carriers.append(JadlogFreight())
|
||||||
else:
|
from . import correios as _correios
|
||||||
freight = FakeFreight()
|
if _correios.configured():
|
||||||
|
_carriers.append(_correios.CorreiosFreight())
|
||||||
|
freight = FreightOptions(_carriers or [FakeFreight()])
|
||||||
ENVIRONMENT = os.environ.get('APP_ENV', 'local')
|
ENVIRONMENT = os.environ.get('APP_ENV', 'local')
|
||||||
PUBLIC_ORIGIN = os.environ.get('PUBLIC_ORIGIN', 'http://localhost')
|
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]
|
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'}
|
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):
|
def require_delivery_available(service):
|
||||||
"""Outside the local stack, a simulated freight price must never reach a
|
"""Outside the local stack, a simulated freight price must never reach a
|
||||||
customer: until a real freight provider exists, only pickup is offered."""
|
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.')
|
raise HTTPException(503, 'A entrega ainda não está disponível. Escolha a retirada em Franca.')
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -283,11 +283,6 @@ ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_since timestamptz;
|
|||||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_by text;
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_by text;
|
||||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_note text;
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_note text;
|
||||||
|
|
||||||
-- E-mail kinds: a password-recovery link, a signup code, the notice that an
|
|
||||||
-- account already exists, the team's alerts and a test.
|
|
||||||
ALTER TABLE dtf_local.mail_queue DROP CONSTRAINT IF EXISTS mail_queue_kind_check;
|
|
||||||
ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check
|
|
||||||
CHECK(kind IN ('reset','code','account','alert','test'));
|
|
||||||
-- A signup waiting for its e-mail code. The account is created only when the
|
-- A signup waiting for its e-mail code. The account is created only when the
|
||||||
-- code is entered; the password is already hashed and the code only hashed.
|
-- code is entered; the password is already hashed and the code only hashed.
|
||||||
CREATE TABLE IF NOT EXISTS dtf_local.account_signups (
|
CREATE TABLE IF NOT EXISTS dtf_local.account_signups (
|
||||||
@@ -297,3 +292,19 @@ CREATE TABLE IF NOT EXISTS dtf_local.account_signups (
|
|||||||
done_at timestamptz
|
done_at timestamptz
|
||||||
);
|
);
|
||||||
CREATE INDEX IF NOT EXISTS account_signups_created ON dtf_local.account_signups(created_at);
|
CREATE INDEX IF NOT EXISTS account_signups_created ON dtf_local.account_signups(created_at);
|
||||||
|
|
||||||
|
-- A customer changing the account's e-mail: the change waits for the code sent
|
||||||
|
-- to the new address, as a signup does, and the old address is told.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.email_changes (
|
||||||
|
id uuid PRIMARY KEY, account_id uuid NOT NULL REFERENCES dtf_local.accounts(id) ON DELETE CASCADE,
|
||||||
|
new_email text NOT NULL, code_hash text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
sent_at timestamptz NOT NULL DEFAULT now(), expires_at timestamptz NOT NULL,
|
||||||
|
sends int NOT NULL DEFAULT 1, attempts int NOT NULL DEFAULT 0, done_at timestamptz
|
||||||
|
);
|
||||||
|
-- E-mail kinds: a password-recovery link, a code, the notice that an account
|
||||||
|
-- already exists, the notice of a changed e-mail, the team's alerts and a test.
|
||||||
|
-- Defined once, here: the schema runs on every start, and an earlier, narrower
|
||||||
|
-- copy would refuse the rows of the kinds added after it.
|
||||||
|
ALTER TABLE dtf_local.mail_queue DROP CONSTRAINT IF EXISTS mail_queue_kind_check;
|
||||||
|
ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check
|
||||||
|
CHECK(kind IN ('reset','code','account','notice','alert','test'));
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ def cleanup():
|
|||||||
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (row['id'],))
|
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (row['id'],))
|
||||||
c.execute('DELETE FROM dtf_local.sessions WHERE expires_at<=now()')
|
c.execute('DELETE FROM dtf_local.sessions WHERE expires_at<=now()')
|
||||||
c.execute("DELETE FROM dtf_local.account_signups WHERE created_at<now()-interval '1 day'")
|
c.execute("DELETE FROM dtf_local.account_signups WHERE created_at<now()-interval '1 day'")
|
||||||
|
c.execute("DELETE FROM dtf_local.email_changes WHERE created_at<now()-interval '1 day'")
|
||||||
c.execute("DELETE FROM dtf_local.password_resets WHERE expires_at<now()-interval '1 day'")
|
c.execute("DELETE FROM dtf_local.password_resets WHERE expires_at<now()-interval '1 day'")
|
||||||
c.execute('DELETE FROM dtf_local.operator_sessions WHERE expires_at<=now()')
|
c.execute('DELETE FROM dtf_local.operator_sessions WHERE expires_at<=now()')
|
||||||
c.execute("DELETE FROM dtf_local.login_attempts WHERE started_at<now()-interval '1 day'")
|
c.execute("DELETE FROM dtf_local.login_attempts WHERE started_at<now()-interval '1 day'")
|
||||||
|
|||||||
@@ -47,6 +47,13 @@ x-app: &app
|
|||||||
JADLOG_CUBAGEM_KG_M3: ${JADLOG_CUBAGEM_KG_M3:-}
|
JADLOG_CUBAGEM_KG_M3: ${JADLOG_CUBAGEM_KG_M3:-}
|
||||||
JADLOG_METROS_POR_CAIXA: ${JADLOG_METROS_POR_CAIXA:-}
|
JADLOG_METROS_POR_CAIXA: ${JADLOG_METROS_POR_CAIXA:-}
|
||||||
FREIGHT_PRODUCTION_DAYS: ${FREIGHT_PRODUCTION_DAYS:-0}
|
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.
|
# Carts the Site priced are approved at checkout; larger ones wait for review.
|
||||||
QUOTE_AUTO_APPROVE: ${QUOTE_AUTO_APPROVE:-true}
|
QUOTE_AUTO_APPROVE: ${QUOTE_AUTO_APPROVE:-true}
|
||||||
QUOTE_AUTO_MAX_METRES: ${QUOTE_AUTO_MAX_METRES:-50}
|
QUOTE_AUTO_MAX_METRES: ${QUOTE_AUTO_MAX_METRES:-50}
|
||||||
|
|||||||
@@ -55,6 +55,17 @@ x-app-environment: &app-environment
|
|||||||
JADLOG_METROS_POR_CAIXA: ${JADLOG_METROS_POR_CAIXA:-}
|
JADLOG_METROS_POR_CAIXA: ${JADLOG_METROS_POR_CAIXA:-}
|
||||||
# Working days of production added to Jadlog's delivery time.
|
# Working days of production added to Jadlog's delivery time.
|
||||||
FREIGHT_PRODUCTION_DAYS: ${FREIGHT_PRODUCTION_DAYS:-0}
|
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;
|
# 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
|
# 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).
|
# compute, wait for an operator on the Kanban (app/quote_review.py).
|
||||||
|
|||||||
@@ -169,6 +169,17 @@ It defaults to 0; the amount is the client's to set. The Site reads it from
|
|||||||
|
|
||||||
## Freight
|
## 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
|
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
|
functional. The localhost bridge now supports pickup and backend fake freight
|
||||||
quotes; there is still no real carrier quotation or production checkout.
|
quotes; there is still no real carrier quotation or production checkout.
|
||||||
@@ -230,7 +241,9 @@ Signup (2026-10-14): with e-mail on, an account is created only after the
|
|||||||
a new code after 60 s, at most 5). The password is hashed at the first step
|
a new code after 60 s, at most 5). The password is hashed at the first step
|
||||||
and the code stored only as a hash. The answer is the same for an address that
|
and the code stored only as a hash. The answer is the same for an address that
|
||||||
already has an account: it gets a "você já tem conta" notice instead of a code.
|
already has an account: it gets a "você já tem conta" notice instead of a code.
|
||||||
Production sends through the client's Locaweb SMTP (set in the stack).
|
Changing the account's e-mail works the same way: the code goes to the new
|
||||||
|
address, the e-mail changes only once it is entered, and the old address is
|
||||||
|
told. Production sends through the client's Locaweb SMTP (set in the stack).
|
||||||
|
|
||||||
### WhatsApp
|
### WhatsApp
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
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.
|
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
|
## Current blocker
|
||||||
|
|
||||||
This is the final deployment shape, but it is not authorized for production
|
This is the final deployment shape, but it is not authorized for production
|
||||||
|
|||||||
@@ -190,6 +190,40 @@ def signup(tag):
|
|||||||
late.call('/account/register/verify', {'signup': expiring['verify'], 'code': code}, expected=410)
|
late.call('/account/register/verify', {'signup': expiring['verify'], 'code': code}, expected=410)
|
||||||
|
|
||||||
|
|
||||||
|
def email_change(tag):
|
||||||
|
"""A new e-mail is the account's only once the code sent to it is entered,
|
||||||
|
and the old address is told."""
|
||||||
|
old, new, taken = (f'{n}-{tag}@example.test' for n in ('antigo', 'trocado', 'ocupado'))
|
||||||
|
owner = Client()
|
||||||
|
owner.call('/session')
|
||||||
|
register(owner, {'cnpj': CNPJ, 'zap': '16999990000', 'mail': old}, PASSWORD)
|
||||||
|
register(Client(), {'cnpj': CNPJ, 'zap': '16999990000', 'mail': taken}, PASSWORD)
|
||||||
|
owner.call('/account/email', {'email': new, 'password': 'senha-errada-123'}, expected=401)
|
||||||
|
owner.call('/account/email', {'email': old, 'password': PASSWORD}, expected=422)
|
||||||
|
owner.call('/account/email', {'email': taken, 'password': PASSWORD}, expected=409)
|
||||||
|
started = owner.call('/account/email', {'email': new.upper(), 'password': PASSWORD})
|
||||||
|
assert started['email'] == new and started['verify'], started
|
||||||
|
assert owner.call('/account/me')['customer']['mail'] == old
|
||||||
|
with db.connect() as c:
|
||||||
|
code = code_of(c, new)
|
||||||
|
wrong = '000000' if code != '000000' else '111111'
|
||||||
|
assert 'Restam 4' in owner.call('/account/email/verify', {'change': started['verify'], 'code': wrong}, expected=400)['detail']
|
||||||
|
# Another signed-in customer cannot complete someone else's change.
|
||||||
|
stranger = Client()
|
||||||
|
stranger.call('/session')
|
||||||
|
register(stranger, {'cnpj': CNPJ, 'zap': '16999990000', 'mail': f'outro-{tag}@example.test'}, PASSWORD)
|
||||||
|
stranger.call('/account/email/verify', {'change': started['verify'], 'code': code}, expected=410)
|
||||||
|
owner.call('/account/email/resend', {'change': started['verify']}, expected=429)
|
||||||
|
assert owner.call('/account/email/verify', {'change': started['verify'], 'code': code})['customer']['mail'] == new
|
||||||
|
assert owner.call('/account/me')['customer']['mail'] == new
|
||||||
|
owner.call('/account/email/verify', {'change': started['verify'], 'code': code}, expected=410)
|
||||||
|
Client().call('/account/login', {'email': new, 'password': PASSWORD})
|
||||||
|
Client().call('/account/login', {'email': old, 'password': PASSWORD}, expected=401)
|
||||||
|
with db.connect() as c:
|
||||||
|
[notice] = queued(c, old, 'notice')
|
||||||
|
assert new in notice['body'] and 'Se não foi você' in notice['body']
|
||||||
|
|
||||||
|
|
||||||
def smtp_delivery(tag):
|
def smtp_delivery(tag):
|
||||||
"""The worker's SMTP path, against a server of our own."""
|
"""The worker's SMTP path, against a server of our own."""
|
||||||
sink = Sink()
|
sink = Sink()
|
||||||
@@ -285,9 +319,10 @@ def run():
|
|||||||
try:
|
try:
|
||||||
recovery(tag)
|
recovery(tag)
|
||||||
signup(tag)
|
signup(tag)
|
||||||
|
email_change(tag)
|
||||||
smtp_delivery(tag)
|
smtp_delivery(tag)
|
||||||
order, quote = alerts(tag)
|
order, quote = alerts(tag)
|
||||||
print('PASS: password recovery by a one-time link, signup confirmed by an e-mailed code, '
|
print('PASS: password recovery by a one-time link, signup and e-mail changes confirmed by an e-mailed code, '
|
||||||
'SMTP delivery and retry, alerts to who asked for them')
|
'SMTP delivery and retry, alerts to who asked for them')
|
||||||
finally:
|
finally:
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
@@ -301,6 +336,7 @@ def run():
|
|||||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,))
|
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,))
|
||||||
c.execute("DELETE FROM dtf_local.mail_queue WHERE to_addr LIKE %s OR kind='test'", (f'%-{tag}@example.test',))
|
c.execute("DELETE FROM dtf_local.mail_queue WHERE to_addr LIKE %s OR kind='test'", (f'%-{tag}@example.test',))
|
||||||
c.execute('DELETE FROM dtf_local.account_signups WHERE email LIKE %s', (f'%-{tag}@example.test',))
|
c.execute('DELETE FROM dtf_local.account_signups WHERE email LIKE %s', (f'%-{tag}@example.test',))
|
||||||
|
c.execute('DELETE FROM dtf_local.email_changes WHERE new_email LIKE %s', (f'%-{tag}@example.test',))
|
||||||
c.execute('DELETE FROM dtf_local.accounts WHERE email LIKE %s', (f'%-{tag}@example.test',))
|
c.execute('DELETE FROM dtf_local.accounts WHERE email LIKE %s', (f'%-{tag}@example.test',))
|
||||||
c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',))
|
c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',))
|
||||||
c.execute('DELETE FROM dtf_local.login_attempts')
|
c.execute('DELETE FROM dtf_local.login_attempts')
|
||||||
|
|||||||
165
tests/test_correios.py
Normal file
165
tests/test_correios.py
Normal 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()
|
||||||
20
tests/test_schema.py
Normal file
20
tests/test_schema.py
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
"""The schema runs on every start (app/bootstrap.py), so each constraint it
|
||||||
|
re-adds must be defined once: an earlier, narrower copy would refuse rows
|
||||||
|
written under a later one, and the database would never finish starting.
|
||||||
|
Run from the repository root: python3 -m unittest tests.test_schema
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
import unittest
|
||||||
|
from collections import Counter
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
class SchemaTest(unittest.TestCase):
|
||||||
|
def test_each_constraint_is_added_once(self):
|
||||||
|
schema = Path(__file__).resolve().parent.parent.joinpath('app', 'schema.sql').read_text()
|
||||||
|
added = Counter(re.findall(r'ADD CONSTRAINT\s+(\w+)', schema, re.I))
|
||||||
|
self.assertEqual([name for name, count in added.items() if count > 1], [])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -103,7 +103,7 @@
|
|||||||
(MODOS[item.mode]?.tit || item.mode)+' · '+fmtM(Number(item.billed_metres))+' m', rs(item.total_cents/100)));
|
(MODOS[item.mode]?.tit || item.mode)+' · '+fmtM(Number(item.billed_metres))+' m', rs(item.total_cents/100)));
|
||||||
const pickup = approved.freight.service === 'pickup';
|
const pickup = approved.freight.service === 'pickup';
|
||||||
const prazo = approved.freight.days ? ' · até '+approved.freight.days+' dias úteis' : '';
|
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'));
|
approved.freight.total_cents ? rs(approved.freight.total_cents/100) : 'Grátis'));
|
||||||
rows.push(linha('Total', rs(approved.total_cents/100), 'tot'));
|
rows.push(linha('Total', rs(approved.total_cents/100), 'tot'));
|
||||||
resumo.replaceChildren(node('h4','Resumo do pedido'), ...rows);
|
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)};
|
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;
|
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 () => {
|
window.dtfFreight = async () => {
|
||||||
const cep = entrega.cep;
|
const cep = entrega.cep;
|
||||||
const service = (await ready).freight_service;
|
if (!(await ready).freight_services?.length) {
|
||||||
if (!service) {
|
|
||||||
$('cepMsg').textContent = 'A entrega ainda não está disponível. Escolha a retirada em Franca.';
|
$('cepMsg').textContent = 'A entrega ainda não está disponível. Escolha a retirada em Franca.';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -266,15 +267,18 @@
|
|||||||
if (!metres) { $('cepMsg').textContent = 'Adicione um item ao pedido para cotar o frete.'; return; }
|
if (!metres) { $('cepMsg').textContent = 'Adicione um item ao pedido para cotar o frete.'; return; }
|
||||||
$('cepMsg').textContent = 'Cotando o frete…';
|
$('cepMsg').textContent = 'Cotando o frete…';
|
||||||
try {
|
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;
|
if (entrega.cep !== cep || entrega.tipo !== 'frete') return;
|
||||||
entrega.valor = result.total_cents/100;
|
entrega.opcoes = result.options;
|
||||||
entrega.dias = result.days || null;
|
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;
|
entrega.cotado = true;
|
||||||
freightQuoted = JSON.stringify(pacote());
|
freightQuoted = JSON.stringify(pacote());
|
||||||
$('cepMsg').textContent = '';
|
$('cepMsg').textContent = '';
|
||||||
pintaEntrega();
|
pintaFretes(); pintaEntrega();
|
||||||
} catch(error) { $('cepMsg').textContent = error.message; }
|
} catch(error) { entrega.opcoes=[]; pintaFretes(); $('cepMsg').textContent = error.message; }
|
||||||
};
|
};
|
||||||
// A different package is a different freight: quote it again.
|
// A different package is a different freight: quote it again.
|
||||||
window.addEventListener('dtf-cart-changed',()=>{
|
window.addEventListener('dtf-cart-changed',()=>{
|
||||||
@@ -314,7 +318,7 @@
|
|||||||
upload_id:uploads[index],...source}))},
|
upload_id:uploads[index],...source}))},
|
||||||
quality_status:item.qualityStatus,quality_acknowledged:item.qualityAcknowledged});
|
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.');
|
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 content = {customer:{...cliente},items,freight:{service,postal_code:entrega.tipo==='retira'?'':entrega.cep}};
|
||||||
const destination = destinoApi();
|
const destination = destinoApi();
|
||||||
|
|||||||
@@ -1041,7 +1041,7 @@ h2 em{font-style:normal;color:var(--laranja)}
|
|||||||
<span class="mk"></span>
|
<span class="mk"></span>
|
||||||
<div>
|
<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>
|
<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>
|
</div>
|
||||||
<em id="vFrete">—</em>
|
<em id="vFrete">—</em>
|
||||||
</button>
|
</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">
|
<input id="cepIn" aria-required="true" autocomplete="off" inputmode="numeric" maxlength="9" placeholder="00000-000">
|
||||||
</div>
|
</div>
|
||||||
<p id="cepMsg"></p>
|
<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="campos endereco" id="endereco">
|
||||||
<div class="cp larga"><label>Quem recebe <span class="obr" aria-hidden="true">*</span></label>
|
<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>
|
<input id="eNome" aria-required="true" autocomplete="off" maxlength="120" placeholder="Nome ou empresa"></div>
|
||||||
|
|||||||
@@ -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');
|
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,
|
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'));
|
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);
|
facts.append(who,where);
|
||||||
if(order.machine||board.machines?.length)facts.append(machineCard(order));
|
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'));
|
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):[]}));
|
details:mp&&mpCheck?mercadoPagoCheck(mpCheck):[]}));
|
||||||
const fr=board.providers?.freight||{};
|
const fr=board.providers?.freight||{};
|
||||||
const kg=v=>String(v).replace('.',',')+' kg';
|
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',
|
? 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.'
|
summary:fr.box_cm?list(carriers)+' e retirada em Franca · prazo + '+fr.production_days+' dia(s) de produção.'
|
||||||
:'Cubagem não configurada: a Jadlog pode cobrar mais que a cotação.',
|
:'Caixa não configurada: as transportadoras podem cobrar mais que a cotação.',
|
||||||
details:[['Pacote',kg(fr.base_kg)+' + '+kg(fr.per_metre_kg)+' por metro'],
|
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'],
|
...(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']]:[])]:[]),
|
...(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.
|
// Each carrier 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.')]})
|
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.'}));
|
: 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(integration({name:'WhatsApp',state:'Não configurado',tone:'off',summary:'Mensagens registradas, sem envio.'}));
|
||||||
rows.push(mailRow(board.providers?.mail||{}));
|
rows.push(mailRow(board.providers?.mail||{}));
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ button:disabled{opacity:.6;cursor:default}
|
|||||||
.bloco input.codigo{height:60px;font-size:30px;font-weight:700;letter-spacing:.45em;text-align:center;font-variant-numeric:tabular-nums;padding-left:.45em}
|
.bloco input.codigo{height:60px;font-size:30px;font-weight:700;letter-spacing:.45em;text-align:center;font-variant-numeric:tabular-nums;padding-left:.45em}
|
||||||
.codigoAcoes{display:flex;flex-wrap:wrap;gap:4px 22px}
|
.codigoAcoes{display:flex;flex-wrap:wrap;gap:4px 22px}
|
||||||
#fCodigo{max-width:520px}
|
#fCodigo{max-width:520px}
|
||||||
|
#fEmailCodigo input.codigo{max-width:340px}
|
||||||
.nota2 a{color:var(--laranja-escuro)}
|
.nota2 a{color:var(--laranja-escuro)}
|
||||||
.bloco label{margin:10px 0 5px;font-size:14px;font-weight:600;color:var(--texto2)}
|
.bloco label{margin:10px 0 5px;font-size:14px;font-weight:600;color:var(--texto2)}
|
||||||
.bloco label .obs{font-weight:400;color:var(--fraco)}
|
.bloco label .obs{font-weight:400;color:var(--fraco)}
|
||||||
|
|||||||
@@ -166,7 +166,20 @@
|
|||||||
<h2>E-mail</h2>
|
<h2>E-mail</h2>
|
||||||
<label for="dMail">E-mail</label><input id="dMail" type="email" autocomplete="email" required>
|
<label for="dMail">E-mail</label><input id="dMail" type="email" autocomplete="email" required>
|
||||||
<label for="dMailSenha">Senha atual, para confirmar</label><input id="dMailSenha" type="password" autocomplete="current-password" required>
|
<label for="dMailSenha">Senha atual, para confirmar</label><input id="dMailSenha" type="password" autocomplete="current-password" required>
|
||||||
<button class="bSec">Alterar e-mail</button>
|
<button class="bSec" id="dMailOk">Alterar e-mail</button>
|
||||||
|
</form>
|
||||||
|
<!-- Takes the place of the e-mail form until the new address is confirmed. -->
|
||||||
|
<form class="bloco" id="fEmailCodigo" hidden>
|
||||||
|
<h2>Confirme o novo e-mail</h2>
|
||||||
|
<p class="nota2">Enviamos um código de 6 números para <b id="emailNovo"></b>. O e-mail da conta só muda depois que você digitar o código.</p>
|
||||||
|
<label for="emailCodigo">Código</label>
|
||||||
|
<input id="emailCodigo" class="codigo" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required>
|
||||||
|
<button class="bSec" id="emailCodigoOk">Confirmar novo e-mail</button>
|
||||||
|
<div class="codigoAcoes">
|
||||||
|
<button type="button" class="bLink" id="emailReenviar" disabled>Reenviar código</button>
|
||||||
|
<button type="button" class="bLink" id="emailCancelar">Cancelar</button>
|
||||||
|
</div>
|
||||||
|
<p class="nota2">Não chegou? Confira a caixa de spam.</p>
|
||||||
</form>
|
</form>
|
||||||
<form class="bloco" id="fSenha">
|
<form class="bloco" id="fSenha">
|
||||||
<h2>Senha</h2>
|
<h2>Senha</h2>
|
||||||
|
|||||||
@@ -205,7 +205,7 @@ function itensPedido(snapshot){
|
|||||||
}
|
}
|
||||||
function entrega(snapshot){
|
function entrega(snapshot){
|
||||||
const d=snapshot.destination, p=node('p',null,'entregaPed');
|
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;
|
return p;
|
||||||
}
|
}
|
||||||
async function details(id,container,criado){
|
async function details(id,container,criado){
|
||||||
@@ -310,12 +310,51 @@ $('fPerfil').onsubmit=async event=>{
|
|||||||
conta=r.customer;aviso('Dados salvos.');
|
conta=r.customer;aviso('Dados salvos.');
|
||||||
}catch(e){aviso(e.status===422?(algum?'Confira o WhatsApp e o endereço: todos os campos, menos o complemento, são necessários.':'Confira o WhatsApp.'):e.message,true);}
|
}catch(e){aviso(e.status===422?(algum?'Confira o WhatsApp e o endereço: todos os campos, menos o complemento, são necessários.':'Confira o WhatsApp.'):e.message,true);}
|
||||||
};
|
};
|
||||||
|
// A new e-mail is confirmed with the code sent to it before the account changes.
|
||||||
|
let troca=null, trocaTimer=null;
|
||||||
|
function emailTrocado(r){
|
||||||
|
conta=r.customer;$('quem').textContent=conta.mail;$('dMail').value=conta.mail;
|
||||||
|
fechaTroca();aviso('E-mail alterado. Use o novo e-mail para entrar.');
|
||||||
|
}
|
||||||
|
function fechaTroca(){
|
||||||
|
clearInterval(trocaTimer);troca=null;$('fEmailCodigo').hidden=true;$('fEmail').hidden=false;
|
||||||
|
}
|
||||||
|
function trocaContagem(segundos){
|
||||||
|
clearInterval(trocaTimer);
|
||||||
|
const b=$('emailReenviar');let falta=segundos;
|
||||||
|
const pinta=()=>{b.disabled=falta>0;b.textContent=falta>0?'Reenviar código ('+falta+' s)':'Reenviar código';};
|
||||||
|
pinta();trocaTimer=setInterval(()=>{falta--;pinta();if(falta<=0)clearInterval(trocaTimer);},1000);
|
||||||
|
}
|
||||||
$('fEmail').onsubmit=async event=>{
|
$('fEmail').onsubmit=async event=>{
|
||||||
event.preventDefault();
|
event.preventDefault();$('dMailOk').disabled=true;
|
||||||
try{const r=await api('/account/email',{email:$('dMail').value,password:$('dMailSenha').value});
|
try{
|
||||||
conta=r.customer;$('dMailSenha').value='';$('quem').textContent=conta.mail;aviso('E-mail alterado. Use o novo e-mail para entrar.');}
|
const r=await api('/account/email',{email:$('dMail').value,password:$('dMailSenha').value});
|
||||||
catch(e){aviso(e.status===422?'Confira o e-mail.':e.message,true);}
|
$('dMailSenha').value='';
|
||||||
|
if(!r.verify){emailTrocado(r);return;}
|
||||||
|
troca=r.verify;$('emailNovo').textContent=r.email;$('emailCodigo').value='';
|
||||||
|
$('fEmail').hidden=true;$('fEmailCodigo').hidden=false;aviso('');trocaContagem(r.resend_seconds);$('emailCodigo').focus();
|
||||||
|
}catch(e){aviso(e.status===422&&!e.message.startsWith('Este')?'Confira o e-mail.':e.message,true);}
|
||||||
|
finally{$('dMailOk').disabled=false;}
|
||||||
};
|
};
|
||||||
|
$('emailCodigo').addEventListener('input',e=>{
|
||||||
|
e.target.value=e.target.value.replace(/\D/g,'').slice(0,6);
|
||||||
|
if(e.target.value.length===6&&!$('emailCodigoOk').disabled)$('fEmailCodigo').requestSubmit();
|
||||||
|
});
|
||||||
|
$('fEmailCodigo').onsubmit=async event=>{
|
||||||
|
event.preventDefault();$('emailCodigoOk').disabled=true;
|
||||||
|
try{emailTrocado(await api('/account/email/verify',{change:troca,code:$('emailCodigo').value}));}
|
||||||
|
catch(e){
|
||||||
|
aviso(e.status===422?'O código tem 6 números.':e.message,true);$('emailCodigo').select();
|
||||||
|
if(e.status===410||e.status===429){$('emailReenviar').disabled=false;$('emailReenviar').textContent='Reenviar código';clearInterval(trocaTimer);}
|
||||||
|
}finally{$('emailCodigoOk').disabled=false;}
|
||||||
|
};
|
||||||
|
$('emailReenviar').onclick=async()=>{
|
||||||
|
$('emailReenviar').disabled=true;
|
||||||
|
try{const r=await api('/account/email/resend',{change:troca});aviso('Enviamos um código novo para '+$('emailNovo').textContent+'.');
|
||||||
|
trocaContagem(r.resend_seconds);$('emailCodigo').value='';$('emailCodigo').focus();}
|
||||||
|
catch(e){aviso(e.message,true);if(e.status===410)fechaTroca();else $('emailReenviar').disabled=false;}
|
||||||
|
};
|
||||||
|
$('emailCancelar').onclick=()=>{aviso('');$('dMail').value=conta.mail;fechaTroca();};
|
||||||
$('fSenha').onsubmit=async event=>{
|
$('fSenha').onsubmit=async event=>{
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
try{await api('/account/password',{current:$('dAtual').value,new:$('dNova').value});
|
try{await api('/account/password',{current:$('dAtual').value,new:$('dNova').value});
|
||||||
|
|||||||
@@ -63,7 +63,9 @@ function pintaPedido(){
|
|||||||
'<div class="l"><span>'+n+(n===1?' item':' itens')+'</span><b>'+rs(itens+eco)+'</b></div>'+
|
'<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>'+
|
(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>' : '')+
|
'<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>'+
|
? ' · até '+entrega.dias+' dias úteis' : '')+'</span><b>'+
|
||||||
(entrega.tipo==='retira' ? '<span style="color:var(--verde-ml)">Grátis</span>'
|
(entrega.tipo==='retira' ? '<span style="color:var(--verde-ml)">Grátis</span>'
|
||||||
: entrega.cotado ? rs(frete) : 'a cotar')+'</b></div>'+
|
: entrega.cotado ? rs(frete) : 'a cotar')+'</b></div>'+
|
||||||
|
|||||||
@@ -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
|
// 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
|
// 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.
|
// 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:''};
|
let cliente={cnpj:'', zap:'', mail:''};
|
||||||
|
|
||||||
// CNPJ com os dois dígitos verificadores · máscara sem conta não vale nada
|
// CNPJ com os dois dígitos verificadores · máscara sem conta não vale nada
|
||||||
|
|||||||
@@ -73,6 +73,26 @@ $('pVolta').addEventListener('click',()=>{
|
|||||||
$('cPro').addEventListener('click',()=>ir(atual()+1));
|
$('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(){
|
function pintaEntrega(){
|
||||||
document.querySelectorAll('.opE').forEach(b=>
|
document.querySelectorAll('.opE').forEach(b=>
|
||||||
b.classList.toggle('on', b.dataset.ent===entrega.tipo));
|
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);
|
const v=e.target.value.replace(/\D/g,'').slice(0,8);
|
||||||
e.target.value = fmtCep(v);
|
e.target.value = fmtCep(v);
|
||||||
if(v===entrega.cep) return;
|
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(); }
|
if(v.length===8){ buscaEndereco(v); if(window.dtfFreight) window.dtfFreight(); }
|
||||||
});
|
});
|
||||||
for(const [id,chave] of [['eNome','nome'],['eRua','rua'],['eNum','num'],['eComp','comp'],
|
for(const [id,chave] of [['eNome','nome'],['eRua','rua'],['eNum','num'],['eComp','comp'],
|
||||||
|
|||||||
@@ -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
|
so the page's full height is 100/0.88 vh there (site-shell.css keeps the
|
||||||
footer at the bottom). */
|
footer at the bottom). */
|
||||||
@media (min-width:1100px){html{zoom:.88}body{min-height:calc(100vh / .88)}}
|
@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}
|
||||||
|
|||||||
Reference in New Issue
Block a user