Files
dtf-system/app/api/stamps.py
Cauê Faleiros 2c80de0c0a feat: Montar creates the invoiced order card (front 7a.2b)
The montador sends each stamp to storage, splits the list into items of
at most 20 sources and 4000 copies, packs each one with the Site's engine
and creates the order in Arte recebida: typed customer, pickup, the Site's
table price, payment 'faturado', origin dropflow for Expedição and
atendimento otherwise. Until Dropstar decides, these orders do not go to
Tiny and the customer gets no paid e-mail. Vendedor and Expedição may now
upload through the operator upload routes (can_any).

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

71 lines
3.5 KiB
Python

"""The montador's stamp sizes and its invoiced orders (Fase 2, front 7)."""
import hashlib
import json
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 Freight, MontadorOrder, QuoteRequest, StampSizeTable, UploadStart
from ..runtime import operator_identity
from .uploads import begin_upload
router = APIRouter()
@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.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.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 order a montador sheet becomes, already invoiced (front 7a.2b):
typed customer, pickup, the Site's table price, and held out of Tiny until
Dropstar decides how it is invoiced there."""
origin = 'dropflow' if request.state.operator['role'] == 'expedicao' else 'atendimento'
draft = QuoteRequest(request_key=body.request_key, customer=body.customer, items=body.items,
freight=Freight(service='pickup')).model_dump(mode='json', exclude={'request_key'})
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
owner = operator_identity(user)
with db.connect() as c:
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']:
quote_review.approve(c, quote, body.items, user)
quote = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s', (quote['id'],)).fetchone()
receipt = {'provider': payments.MANUAL_PROVIDER, 'method': payments.INVOICED_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, operator=user)
return order