feat: a refused payment says what happened and what to do, in plain Portuguese
All checks were successful
Build and deploy / Validate source (push) Successful in 1m22s
Build and deploy / Integration suite on a real stack (push) Successful in 4m10s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m11s
All checks were successful
Build and deploy / Validate source (push) Successful in 1m22s
Build and deploy / Integration suite on a real stack (push) Successful in 4m10s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m11s
A refused card showed Mercado Pago's code ("Pagamento recusado pelo Mercado
Pago (cc_rejected_insufficient_amount)"), a request it refused showed its
cause list, and some errors were in English ("Quote is already paid",
"Payment provider unavailable; try again"). Each now becomes one sentence:
"O cartão não tem limite suficiente para este valor. Use outro cartão ou
pague com PIX." The codes still go to the log and, on the Kanban's "Cartão
recusado" badge, beside the same sentence. A form check the customer cannot
read is replaced by a general one, and every error a customer or operator
can meet in the quote, upload, account and artwork routes is in Portuguese.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -38,12 +38,12 @@ def register(body: Register, request: Request, response: Response):
|
||||
try:
|
||||
with db.connect() as c:
|
||||
if previous and c.execute('SELECT id FROM dtf_local.accounts WHERE id=%s', (previous['owner'],)).fetchone():
|
||||
raise HTTPException(409, 'Sign out before registering another account')
|
||||
raise HTTPException(409, 'Saia da conta atual antes de criar outra.')
|
||||
c.execute('INSERT INTO dtf_local.accounts(id,email,password_hash,profile) VALUES(%s,%s,%s,%s)', (identity,email,encoded,Jsonb(profile)))
|
||||
if previous: transfer_guest(c, previous, identity)
|
||||
new_session(c, response, identity)
|
||||
except UniqueViolation:
|
||||
raise HTTPException(409, 'An account already exists; sign in')
|
||||
raise HTTPException(409, 'Já existe uma conta com este e-mail. Entre com a sua senha.')
|
||||
audit('account_registered', account=str(identity))
|
||||
return {'customer': profile}
|
||||
|
||||
@@ -223,7 +223,7 @@ def customer_download(oid: UUID, fid: UUID, identity=Depends(owner)):
|
||||
with db.connect() as c:
|
||||
owned_order(c,oid,identity)
|
||||
row = c.execute('SELECT u.* FROM dtf_local.order_files f JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.id=%s AND f.order_id=%s AND f.active', (fid,oid)).fetchone()
|
||||
if not row: raise HTTPException(404, 'Active file not found')
|
||||
if row['expires_at'] <= datetime.now(timezone.utc): raise HTTPException(410, 'File expired')
|
||||
if not row: raise HTTPException(404, 'Arquivo não encontrado.')
|
||||
if row['expires_at'] <= datetime.now(timezone.utc): raise HTTPException(410, 'Este arquivo não está mais disponível: os arquivos ficam guardados por 30 dias.')
|
||||
require_clean(row)
|
||||
return {'url':storage.download(row['object_key'],row['name']), 'name':row['name']}
|
||||
|
||||
@@ -11,7 +11,7 @@ import httpx
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from .. import payments
|
||||
from .. import payment_messages as messages, payments
|
||||
from ..core import db
|
||||
from ..core.auth import audit, client_ip, owner, rate_limit
|
||||
from ..core.models import PaymentIntent
|
||||
@@ -101,9 +101,9 @@ def intent(body: PaymentIntent, session_id=Depends(owner)):
|
||||
try:
|
||||
quote = payments.approved_quote(c, body.quote_id, session_id)
|
||||
except payments.PaymentRefused as refusal:
|
||||
raise HTTPException(404 if 'not found' in str(refusal) else 409, str(refusal))
|
||||
raise HTTPException(404 if 'not found' in str(refusal) else 409, messages.quote_refusal(refusal))
|
||||
if c.execute('SELECT 1 FROM dtf_local.orders WHERE quote_id=%s', (body.quote_id,)).fetchone():
|
||||
raise HTTPException(409, 'Quote is already paid')
|
||||
raise HTTPException(409, 'Este pedido já foi pago.')
|
||||
# Never charge for files that are gone: an unpaid cart's files are
|
||||
# removed after a while. A payment under way keeps them a day longer,
|
||||
# time enough for the provider's notice to become the order.
|
||||
@@ -124,7 +124,8 @@ def intent(body: PaymentIntent, session_id=Depends(owner)):
|
||||
AND NOT (jsonb_typeof(response->'challenge')='object'
|
||||
AND created_at < now() - make_interval(mins => %s))))''',
|
||||
(body.quote_id, CHALLENGE_MINUTES)).fetchone():
|
||||
raise HTTPException(409, 'A payment for this quote is already approved or in review')
|
||||
raise HTTPException(409, 'Já existe um pagamento aprovado ou em análise para este pedido. '
|
||||
'Aguarde a confirmação nesta página.')
|
||||
method = body.method.model_dump()
|
||||
if body.method.type == 'pix':
|
||||
# One open PIX per quote: the same code until it expires, and a new
|
||||
@@ -144,8 +145,8 @@ def intent(body: PaymentIntent, session_id=Depends(owner)):
|
||||
try:
|
||||
created = payment.create(str(body.quote_id), quote['approved']['total_cents'],
|
||||
quote['approved']['customer'], method)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc))
|
||||
except ValueError:
|
||||
raise HTTPException(422, 'Esta forma de pagamento não é aceita. Pague com cartão de crédito ou PIX.')
|
||||
except httpx.HTTPStatusError as exc:
|
||||
# Mercado Pago's own reason (status, message and cause codes) goes to
|
||||
# the log; it never contains card data, only what was refused.
|
||||
@@ -153,11 +154,18 @@ def intent(body: PaymentIntent, session_id=Depends(owner)):
|
||||
audit('payment_intent_refused', quote=str(body.quote_id), method=body.method.type,
|
||||
status=exc.response.status_code, reason=reason)
|
||||
if exc.response.status_code < 500:
|
||||
raise HTTPException(422, f'O Mercado Pago recusou o pagamento: {reason}')
|
||||
raise HTTPException(502, 'Payment provider unavailable; try again')
|
||||
try:
|
||||
data = exc.response.json()
|
||||
except ValueError:
|
||||
data = {}
|
||||
raise HTTPException(422, messages.refusal(data))
|
||||
raise HTTPException(502, messages.UNAVAILABLE)
|
||||
except Exception as exc:
|
||||
audit('payment_intent_failed', quote=str(body.quote_id), error=type(exc).__name__)
|
||||
raise HTTPException(502, 'Payment provider unavailable; try again')
|
||||
raise HTTPException(502, messages.UNAVAILABLE)
|
||||
if created.get('status') == 'rejected':
|
||||
# What to tell the customer; the code stays in status_detail for the team.
|
||||
created['message'] = messages.rejection(created.get('status_detail'))
|
||||
c.execute('''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,method,
|
||||
status,amount_cents,response) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
ON CONFLICT(provider,provider_payment_id) DO NOTHING''',
|
||||
|
||||
@@ -23,7 +23,7 @@ router = APIRouter()
|
||||
def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
||||
for item in body.items:
|
||||
if abs(item.metres*100-item.production.height_cm) > Decimal('0.02'):
|
||||
raise HTTPException(422, 'Quoted metres do not match the submitted layout height')
|
||||
raise HTTPException(422, 'A metragem não confere com a montagem enviada. Monte o pedido de novo.')
|
||||
require_delivery_available(body.freight.service)
|
||||
draft = body.model_dump(mode='json', exclude={'request_key'})
|
||||
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
|
||||
@@ -42,7 +42,7 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
||||
for uid in item.uploads:
|
||||
row = upload_row(c, uid, session_id)
|
||||
if not row['complete']:
|
||||
raise HTTPException(409, 'Complete every upload before requesting a quote')
|
||||
raise HTTPException(409, 'Espere o envio de todos os arquivos terminar antes de continuar.')
|
||||
require_clean(row)
|
||||
rows[str(uid)] = row
|
||||
# The grade sets the price and came from the browser: before a cart is
|
||||
@@ -54,7 +54,7 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
||||
(uid, session_id, body.request_key, digest, Jsonb(draft), note))
|
||||
row = c.execute('SELECT * FROM dtf_local.quotes WHERE owner=%s AND request_key=%s FOR UPDATE', (session_id, body.request_key)).fetchone()
|
||||
if row['request_hash'] != digest:
|
||||
raise HTTPException(409, 'Request key already used for a different cart')
|
||||
raise HTTPException(409, 'O carrinho mudou durante o envio. Tente de novo.')
|
||||
if row['id'] == uid and reason is None:
|
||||
quote_review.approve(c, row, body.items, quote_review.AUTO)
|
||||
return {'id': row['id'], 'status': 'approved'}
|
||||
@@ -68,7 +68,7 @@ def get_quote(uid: UUID, session_id=Depends(owner)):
|
||||
with db.connect() as c:
|
||||
row = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s AND owner=%s', (uid,session_id)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Quote not found')
|
||||
raise HTTPException(404, 'Pedido não encontrado.')
|
||||
view = quote_view(c, row)
|
||||
# The payment page asks every few seconds while it waits for the order. An
|
||||
# approved card with no order yet is checked with the provider now, rather
|
||||
|
||||
@@ -23,7 +23,7 @@ router = APIRouter()
|
||||
@router.post('/api/uploads')
|
||||
def begin_upload(body: UploadStart, session_id=Depends(owner)):
|
||||
if body.size > upload_limit_bytes():
|
||||
raise HTTPException(413, 'File exceeds the malware scan limit; select a smaller file')
|
||||
raise HTTPException(413, 'O arquivo passa do tamanho máximo aceito. Escolha um arquivo menor.')
|
||||
uid = uuid4()
|
||||
key = f'originals/{uid}'
|
||||
rate_limit('upload-start', str(session_id), 60, 900)
|
||||
@@ -60,7 +60,7 @@ def part_url(uid: UUID, part: int, session_id=Depends(owner)):
|
||||
with db.connect() as c:
|
||||
row = upload_row(c, uid, session_id)
|
||||
if row['complete'] or not 1 <= part <= math.ceil(row['size'] / PART_BYTES):
|
||||
raise HTTPException(409, 'Invalid part or completed upload')
|
||||
raise HTTPException(409, 'O envio deste arquivo já terminou ou foi interrompido. Escolha o arquivo de novo.')
|
||||
# The reservation lease is an hour; a multi-GB upload on a slow line
|
||||
# takes longer, so each part it asks for keeps it alive.
|
||||
c.execute("UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at,now()+interval '1 hour') WHERE id=%s", (uid,))
|
||||
@@ -84,11 +84,11 @@ def complete_upload(uid: UUID, session_id=Depends(owner)):
|
||||
expected = math.ceil(row['size'] / PART_BYTES)
|
||||
if [p['PartNumber'] for p in parts] != list(range(1, expected+1)) or any(
|
||||
p['Size'] != min(PART_BYTES, row['size'] - i*PART_BYTES) for i,p in enumerate(parts)):
|
||||
raise HTTPException(409, 'Parts are missing or their sizes do not match')
|
||||
raise HTTPException(409, 'O envio do arquivo não chegou inteiro. Escolha o arquivo de novo.')
|
||||
storage.complete(row['object_key'], row['multipart_id'], parts)
|
||||
existing_size = storage.size(row['object_key'])
|
||||
if existing_size != row['size']:
|
||||
raise HTTPException(409, 'Stored size differs from declared size')
|
||||
raise HTTPException(409, 'O envio do arquivo não chegou inteiro. Escolha o arquivo de novo.')
|
||||
# Held while the cart is unpaid: an abandoned cart's files go after
|
||||
# UNPAID_HOLD; a paid order keeps them for its 30 days (app/payments.py).
|
||||
c.execute('UPDATE dtf_local.uploads SET complete=true,expires_at=now()+%s::interval WHERE id=%s',
|
||||
@@ -134,7 +134,7 @@ def cancel_upload(uid: UUID, session_id=Depends(owner)):
|
||||
with db.connect() as c:
|
||||
row=upload_row(c,uid,session_id,lock=True)
|
||||
if row['complete']:
|
||||
raise HTTPException(409, 'Completed upload cannot be cancelled')
|
||||
raise HTTPException(409, 'Este arquivo já foi enviado e não pode ser cancelado.')
|
||||
storage.discard(row['object_key'],row['multipart_id'],False)
|
||||
c.execute('UPDATE dtf_local.uploads SET purged_at=now() WHERE id=%s',(uid,))
|
||||
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s',(uid,))
|
||||
|
||||
Reference in New Issue
Block a user