feat: the team registers an order paid outside the site, choosing its origin and payment (Dropstar's rule D-35)
Some checks failed
Build and deploy / Integration suite on a real stack (push) Failing after 3m26s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Has been skipped
Build and deploy / Validate source (push) Successful in 6s
Some checks failed
Build and deploy / Integration suite on a real stack (push) Failing after 3m26s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Has been skipped
Build and deploy / Validate source (push) Successful in 6s
On an approved quote in Cotacoes, Administrador, Gestao and Vendedor pick the origin (Site, Dropflow, Atendimento) and how it was paid (Pix, cartao, dinheiro, credito do cliente), neither preselected, with an optional note. The price is the quote's, the Site's table price. The order is marked paid outside, counts in Numeros, and goes to Tiny like a Site order with the payment named in its internal note; a Dropflow order stays out of Tiny, status updates and cancelling included, until its revenue category exists. Auto-refresh waits while a register form on screen is half filled in. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -422,12 +422,40 @@ def test_order(uid: UUID, user=Depends(can('manage'))):
|
||||
raise HTTPException(404 if 'not found' in str(refusal) else 409, str(refusal))
|
||||
receipt = {'provider': payments.TEST_PROVIDER, 'id': f'teste-{uid}', 'status': 'paid',
|
||||
'total_cents': quote['approved']['total_cents'], 'operator': user}
|
||||
order, created = payments.create_order(c, quote, receipt)
|
||||
order, created = payments.create_order(c, quote, receipt, 'site')
|
||||
if created:
|
||||
audit('test_order_created', order=str(order['id']), operator=user)
|
||||
return order
|
||||
|
||||
|
||||
class PaidOutside(StrictModel):
|
||||
# No defaults (D-35): whoever registers the order says where it came from
|
||||
# and how it was paid.
|
||||
origin: Literal['site', 'dropflow', 'atendimento']
|
||||
method: Literal[payments.OUTSIDE_METHODS]
|
||||
note: str = Field(default='', max_length=300)
|
||||
|
||||
|
||||
@router.post('/api/operator/quotes/{uid}/register')
|
||||
def register_order(uid: UUID, body: PaidOutside, user=Depends(can('enter'))):
|
||||
"""The order for an approved quote paid outside the system (Dropstar's
|
||||
rule D-35): the team builds the cart on the Site, as a customer would, and
|
||||
registers it here with its origin and how it was paid. The price is the
|
||||
quote's, the Site's table price."""
|
||||
with db.connect() as c:
|
||||
try:
|
||||
quote = payments.approved_quote(c, uid)
|
||||
except payments.PaymentRefused as refusal:
|
||||
raise HTTPException(404 if 'not found' in str(refusal) else 409, str(refusal))
|
||||
receipt = {'provider': payments.MANUAL_PROVIDER, 'method': body.method, 'note': body.note.strip(),
|
||||
'status': 'paid', 'total_cents': quote['approved']['total_cents'], 'operator': user}
|
||||
order, created = payments.create_order(c, quote, receipt, body.origin)
|
||||
if not created:
|
||||
raise HTTPException(409, f"Esta cotação já virou o pedido #{order['number']}.")
|
||||
audit('manual_order_registered', order=str(order['id']), origin=body.origin, operator=user)
|
||||
return order
|
||||
|
||||
|
||||
@router.post('/api/operator/quotes/{uid}/discard')
|
||||
def discard_quote(uid: UUID, user=Depends(can('manage'))):
|
||||
"""An unpaid quote leaves the Kanban and can no longer be paid. Its files
|
||||
@@ -513,7 +541,7 @@ def cancel_order(uid: UUID, body: Resolution, user=Depends(can('manage'))):
|
||||
(user, body.note, uid)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Pedido não encontrado ou já cancelado.')
|
||||
if not payments.is_test(row):
|
||||
if payments.in_tiny(row):
|
||||
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
|
||||
(f'{uid}:paid:tiny',)).fetchone()
|
||||
enqueue(c, f'{uid}:cancelled:tiny', 'tiny',
|
||||
@@ -664,7 +692,7 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
||||
# Entering the queue (Arte conferida) is Tiny's "Preparando envio";
|
||||
# Finalizado its "Pronto para envio" (Dropstar's flow, 2026-10-23).
|
||||
events = {'tra':'production_started','cor':'correction_needed','fin':'ready'}
|
||||
if body.state in events and not back and not payments.is_test(row):
|
||||
if body.state in events and not back and payments.in_tiny(row):
|
||||
# "Production started" and "ready" reach the customer once per order,
|
||||
# even if a mistaken move is undone and made again. Each correction
|
||||
# is a new request, so it keeps one message per movement.
|
||||
|
||||
@@ -34,5 +34,5 @@ def dev_paid(body: Pay, session_id=Depends(owner)):
|
||||
# The charge happens inside the transaction that persists the order, so a
|
||||
# failure to record it cannot leave a customer charged without an order.
|
||||
receipt = payment.pay(str(body.quote_id), quote['approved']['total_cents'])
|
||||
order, _ = payments.create_order(c, quote, receipt)
|
||||
order, _ = payments.create_order(c, quote, receipt, 'site')
|
||||
return order
|
||||
|
||||
@@ -128,6 +128,8 @@ CAPABILITIES = {
|
||||
'produce': {'superadmin', 'admin', 'gestao', 'designer', 'operador'},
|
||||
'print': {'superadmin', 'admin', 'gestao', 'operador'},
|
||||
'manage': {'superadmin', 'admin', 'gestao'},
|
||||
# Registering an order paid outside the system, from its Site quote (D-35).
|
||||
'enter': {'superadmin', 'admin', 'gestao', 'vendedor'},
|
||||
'users': {'superadmin', 'admin'},
|
||||
'integrations': {'superadmin'},
|
||||
}
|
||||
|
||||
@@ -55,6 +55,20 @@ def is_test(order):
|
||||
return (order.get('payment') or {}).get('provider') == TEST_PROVIDER
|
||||
|
||||
|
||||
# An order paid outside the system (Pix or cash at the counter, a card machine,
|
||||
# the customer's credit) and registered by the team from its Site quote
|
||||
# (Dropstar's rule D-35, 2026-10-26; the user's answers of 2026-10-27).
|
||||
MANUAL_PROVIDER = 'manual'
|
||||
OUTSIDE_METHODS = ('pix', 'card', 'cash', 'credit')
|
||||
|
||||
|
||||
def in_tiny(order):
|
||||
"""Whether the order goes to Tiny: not a test, and not a Dropflow order,
|
||||
held until Dropstar names that channel's revenue category (it must not be
|
||||
DTF SITE, their rules document says)."""
|
||||
return not is_test(order) and order['origin'] != 'dropflow'
|
||||
|
||||
|
||||
# How long a file is kept while nothing has been paid for it. A cart's files
|
||||
# are uploaded before payment, so the price and the security check are done on
|
||||
# the file itself; a cart that is never paid must not keep them for 30 days.
|
||||
@@ -75,8 +89,9 @@ def hold_uploads(c, upload_ids, interval):
|
||||
WHERE id=ANY(%s) AND purged_at IS NULL''', (interval, [str(u) for u in upload_ids]))
|
||||
|
||||
|
||||
def create_order(c, quote, payment):
|
||||
def create_order(c, quote, payment, origin):
|
||||
"""Create the order for a reviewed quote, or return the one already there.
|
||||
`origin` is where it came from (D-21): each way in names its own.
|
||||
|
||||
Returns (order, created). The caller decides what to do about a duplicate;
|
||||
the important part is that asking twice cannot produce two orders, because
|
||||
@@ -93,8 +108,8 @@ def create_order(c, quote, payment):
|
||||
|
||||
order = c.execute(
|
||||
'''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
|
||||
VALUES(%s,%s,%s,%s,%s,'site') RETURNING *''',
|
||||
(uuid4(), quote['id'], quote['owner'], Jsonb(approved), Jsonb(payment))).fetchone()
|
||||
VALUES(%s,%s,%s,%s,%s,%s) RETURNING *''',
|
||||
(uuid4(), quote['id'], quote['owner'], Jsonb(approved), Jsonb(payment), origin)).fetchone()
|
||||
# Paid: the files are kept for the order's retention, counted from upload.
|
||||
c.execute('''UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at, created_at+%s::interval)
|
||||
WHERE id=ANY(%s) AND purged_at IS NULL''', (ORDER_RETENTION, quote_uploads(approved)))
|
||||
@@ -108,13 +123,18 @@ def create_order(c, quote, payment):
|
||||
if is_test(order):
|
||||
return order, True
|
||||
mail.order_paid(c, order, PUBLIC_ORIGIN)
|
||||
if not in_tiny(order):
|
||||
return order, True
|
||||
# How it was paid, for the order's payment in Tiny.
|
||||
paid = c.execute('''SELECT method FROM dtf_local.payment_intents WHERE quote_id=%s AND status='approved'
|
||||
ORDER BY created_at DESC LIMIT 1''', (quote['id'],)).fetchone()
|
||||
if payment.get('provider') == MANUAL_PROVIDER:
|
||||
paid = {'method': payment['method'], 'outside': True}
|
||||
else:
|
||||
paid = c.execute('''SELECT method FROM dtf_local.payment_intents WHERE quote_id=%s AND status='approved'
|
||||
ORDER BY created_at DESC LIMIT 1''', (quote['id'],)).fetchone()
|
||||
enqueue(c, f"{order['id']}:paid:tiny", 'tiny',
|
||||
{'order_id': str(order['id']), 'number': order['number'],
|
||||
'event': 'payment_approved', 'order': approved,
|
||||
'payment': {'method': paid['method']} if paid else {}})
|
||||
'event': 'payment_approved', 'order': approved, 'origin': origin,
|
||||
'payment': dict(paid) if paid else {}})
|
||||
return order, True
|
||||
|
||||
|
||||
@@ -171,7 +191,7 @@ def apply(c, event):
|
||||
expected_cents=expected, paid_cents=event.amount_cents)
|
||||
return f'refused: paid {event.amount_cents} but quote total is {expected}'
|
||||
|
||||
order, created = create_order(c, quote, {'provider': event.raw.get('provider', 'webhook'), **event.raw})
|
||||
order, created = create_order(c, quote, {'provider': event.raw.get('provider', 'webhook'), **event.raw}, 'site')
|
||||
return f"order {order['number']}" + ('' if created else ' (already existed)')
|
||||
|
||||
|
||||
|
||||
14
app/tiny.py
14
app/tiny.py
@@ -92,6 +92,18 @@ SITUACOES = {0: 'Aberta', 3: 'Aprovada', 4: 'Preparando envio', 1: 'Faturada', 7
|
||||
# react to these situações. Off until go-live: while n8n still sends the
|
||||
# designer message for DTFIMP products on "Aprovado", setting it would reach
|
||||
# Site customers.
|
||||
# Where the order came from (D-21) and, when the team registered it, how it was
|
||||
# paid outside the system (D-35), for whoever reads the order in Tiny.
|
||||
ORIGIN_NOTES = {'site': 'Site DTF', 'atendimento': 'Atendimento DTF', 'dropflow': 'Dropflow DTF'}
|
||||
OUTSIDE_NOTES = {'pix': 'Pix', 'card': 'cartão', 'cash': 'dinheiro', 'credit': 'crédito do cliente'}
|
||||
|
||||
|
||||
def internal_note(payload):
|
||||
paid = payload.get('payment') or {}
|
||||
how = f"pago fora do site ({OUTSIDE_NOTES.get(paid.get('method'), paid.get('method'))})" if paid.get('outside') else 'pago'
|
||||
return f"{ORIGIN_NOTES.get(payload.get('origin') or 'site')} · {how} · {payload['order_id']}"
|
||||
|
||||
|
||||
STATUS_UPDATES_SETTING = 'TINY_STATUS_UPDATES'
|
||||
# The client's custom "retirar pessoalmente" forma de envio (v2 code X), which
|
||||
# the pickup notice is keyed on. Found in Tiny by name; this setting, an id,
|
||||
@@ -482,7 +494,7 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
|
||||
'itens': items,
|
||||
'valorFrete': money(freight['total_cents']),
|
||||
'observacoes': f"Pedido DTF #{payload['number']}" + (' · retirada em Franca' if pickup else ''),
|
||||
'observacoesInternas': f"Site DTF · pago · {payload['order_id']}"}
|
||||
'observacoesInternas': internal_note(payload)}
|
||||
carrier = shipping(service) if shipping else None
|
||||
if carrier:
|
||||
pedido['transportador'] = {'fretePorConta': FREIGHT_PAID_BY, **carrier}
|
||||
|
||||
Reference in New Issue
Block a user