Files
dtf-system/app/api/stamps.py
Cauê Faleiros b5a51137fb feat: montador Interno and Venda, Tiny customers, brand per stamp (front 7a.3, Marcus 10/11)
Interno: the Expedição assembles the marketplace's own sales on the fixed
internal customer Gestão fills in once; no Tiny order, no paid e-mail,
marked interno, it stays in house. Venda: a Vendedor or Gestão picks the
customer from the Tiny base and the order goes to Tiny like an approved
quote, faturado (Boleto from TINY_RECEIPT_BOLETO when set), pickup or
'junto com o pedido de roupa nº X'. Números counts both at table price,
apart from cash (and the average ticket over cash orders only). Each stamp
can carry a brand and a public flag for the future catalogue.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 11:01:44 -03:00

160 lines
7.8 KiB
Python

"""The montador's stamp sizes, its brand per stamp, the internal customer and
the Interno and Venda orders a sheet becomes (Fase 2, fronts 7a to 7a.3)."""
import hashlib
import json
import re
from uuid import uuid4
from fastapi import APIRouter, Depends, HTTPException, Request
from psycopg.types.json import Jsonb
from .. import payments, quote_review
from ..core import db
from ..core.auth import audit, can
from ..core.models import (Customer, Freight, MontadorOrder, QuoteRequest, StampBrand,
StampSizeTable, UploadStart)
from ..runtime import operator_identity
from .uploads import begin_upload
router = APIRouter()
CODE = re.compile(r'^[A-Za-z0-9_-]{1,40}$')
INTERNAL_MISSING = 'Peça à Gestão para completar o cliente interno.'
# Who chooses which kind of order in the montador (Marcus, 2026-11-10): the
# Expedição only Interno, the Vendedor only Venda; Gestão and the
# administrators both.
MONTADOR_KINDS = {'expedicao': {'interno'}, 'vendedor': {'venda'},
'superadmin': {'interno', 'venda'}, 'admin': {'interno', 'venda'},
'gestao': {'interno', 'venda'}}
@router.get('/api/operator/stamp-sizes')
def stamp_sizes(user=Depends(can('assemble'))):
with db.connect() as c:
rows = c.execute('SELECT letter,width_cm FROM dtf_local.stamp_sizes ORDER BY width_cm, letter').fetchall()
return {'sizes': rows}
@router.post('/api/operator/stamp-sizes')
def save_stamp_sizes(body: StampSizeTable, user=Depends(can('manage'))):
with db.connect() as c:
c.execute('DELETE FROM dtf_local.stamp_sizes')
c.cursor().executemany('INSERT INTO dtf_local.stamp_sizes(letter,width_cm,updated_by) VALUES(%s,%s,%s)',
[(row.letter, row.width_cm, user) for row in body.sizes])
audit('stamp_sizes_changed', operator=user, sizes=len(body.sizes))
return {'ok': True}
@router.get('/api/operator/internal-customer')
def read_internal_customer(user=Depends(can('assemble'))):
"""The customer every Interno order belongs to; empty fields mean Gestão
still has to complete it."""
with db.connect() as c:
row = c.execute('SELECT name,cnpj,zap,mail FROM dtf_local.internal_customer').fetchone()
return row or {'name': '', 'cnpj': '', 'zap': '', 'mail': ''}
@router.post('/api/operator/internal-customer')
def save_internal_customer(body: Customer, user=Depends(can('manage'))):
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.internal_customer(id,name,cnpj,zap,mail,updated_by,updated_at)
VALUES(1,%s,%s,%s,%s,%s,now()) ON CONFLICT(id) DO UPDATE SET name=EXCLUDED.name,
cnpj=EXCLUDED.cnpj, zap=EXCLUDED.zap, mail=EXCLUDED.mail,
updated_by=EXCLUDED.updated_by, updated_at=now()''',
(body.name, body.cnpj, body.zap, body.mail, user))
audit('internal_customer_changed', operator=user)
return {'ok': True}
def internal_customer(c):
"""The fixed Interno customer, ready to use, or the reason Gestão must
complete it first."""
row = c.execute('SELECT name,cnpj,zap,mail FROM dtf_local.internal_customer').fetchone()
if not row or not all(str(row[key] or '').strip() for key in ('name', 'cnpj', 'zap', 'mail')):
raise HTTPException(409, INTERNAL_MISSING)
try:
return Customer(**row)
except ValueError:
raise HTTPException(409, INTERNAL_MISSING) from None
@router.get('/api/operator/stamps/{code}')
def read_stamp(code: str, user=Depends(can('assemble'))):
"""The brand recorded for a stamp code; nothing else uses it yet."""
if not CODE.fullmatch(code):
raise HTTPException(422, 'Código inválido.')
with db.connect() as c:
row = c.execute('SELECT code,brand,public FROM dtf_local.stamps WHERE code=%s', (code,)).fetchone()
return row or {'code': code, 'brand': '', 'public': False}
@router.post('/api/operator/stamps/{code}')
def save_stamp(code: str, body: StampBrand, user=Depends(can('manage'))):
if not CODE.fullmatch(code):
raise HTTPException(422, 'Código inválido.')
brand = body.brand.strip()
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.stamps(code,brand,public,updated_by,updated_at)
VALUES(%s,%s,%s,%s,now()) ON CONFLICT(code) DO UPDATE SET brand=EXCLUDED.brand,
public=EXCLUDED.public, updated_by=EXCLUDED.updated_by, updated_at=now()''',
(code, brand, body.public, user))
audit('stamp_brand_saved', code=code, operator=user, public=body.public)
return {'ok': True}
@router.post('/api/operator/montador/uploads')
def montador_upload(body: UploadStart, user=Depends(can('assemble'))):
if not body.name.lower().endswith('.png'):
raise HTTPException(422, 'A estampa precisa ser um PNG.')
return begin_upload(body, session_id=operator_identity(user))
@router.post('/api/operator/montador/orders')
def montador_order(body: MontadorOrder, request: Request, user=Depends(can('assemble'))):
"""The card a montador sheet becomes (front 7a.3): Interno (the fixed
internal customer, origin dropflow, never Tiny) or Venda (a Tiny customer,
origin atendimento, invoiced and sent to Tiny). Pickup in both, at the
Site's table price; the order records whether it travels with a clothing
order."""
role = request.state.operator['role']
if body.kind not in MONTADOR_KINDS.get(role, set()):
raise HTTPException(403, 'Seu perfil não permite este tipo de pedido.')
with db.connect() as c:
if body.kind == 'interno':
customer = internal_customer(c)
origin, method = 'dropflow', payments.INTERNAL_METHOD
else:
customer = body.customer
origin, method = 'atendimento', payments.INVOICED_METHOD
draft = QuoteRequest(request_key=body.request_key, customer=customer, items=body.items,
freight=Freight(service='pickup')).model_dump(mode='json', exclude={'request_key'})
draft['montador'] = True
draft['kind'] = body.kind
if body.with_order:
draft['with_order'] = body.with_order
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
owner = operator_identity(user)
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft)
VALUES(%s,%s,%s,%s,%s) ON CONFLICT(owner,request_key) DO NOTHING''',
(uuid4(), owner, body.request_key, digest, Jsonb(draft)))
quote = c.execute('SELECT * FROM dtf_local.quotes WHERE owner=%s AND request_key=%s FOR UPDATE',
(owner, body.request_key)).fetchone()
if quote['request_hash'] != digest:
raise HTTPException(409, 'A montagem mudou durante o envio. Tente de novo.')
if not quote['approved']:
approved = quote_review.approve(c, quote, body.items, user)
# The order's kind and the clothing order it travels with, on the
# card and in Tiny's internal note.
approved = {**approved, 'kind': body.kind,
**({'with_order': body.with_order} if body.with_order else {})}
c.execute('UPDATE dtf_local.quotes SET approved=%s WHERE id=%s',
(Jsonb(approved), quote['id']))
quote = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s', (quote['id'],)).fetchone()
receipt = {'provider': payments.MANUAL_PROVIDER, 'method': method, 'note': '',
'status': 'paid', 'total_cents': quote['approved']['total_cents'], 'operator': user}
order, created = payments.create_order(c, quote, receipt, origin)
if not created:
raise HTTPException(409, f"Esta montagem já virou o pedido #{order['number']}.")
audit('montador_order_created', order=str(order['id']), origin=origin, kind=body.kind, operator=user)
return order