Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Publish images (push) Has been cancelled
Build and deploy / Secret scan and release gate (push) Has been cancelled
Build and deploy / Integration suite on a real stack (push) Has been cancelled
Codes like NX.226 and NX.1003 are allowed in the page, the API and the stamps table (a dot anywhere but first). A file's own size is a dot and its letter before .png (Marcus, 2026-11-16): NX.226.C.png is NX.226 in C, so nobody renames the library. Montar takes the size asked for, else the code without a size, else another size of it scaled (the closest larger one, else the largest) and says which file it was made from; the DPI warning still applies. The <code>-<size>.png form is no longer read. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
162 lines
8.0 KiB
Python
162 lines
8.0 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()
|
|
|
|
# Dropstar's codes carry dots (NX.226); not as the first character.
|
|
CODE = re.compile(r'^[A-Za-z0-9_-][A-Za-z0-9._-]{0,39}$')
|
|
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 (fronts 7a.3 and 7a.4): Interno (the
|
|
fixed internal customer, origin dropflow, never Tiny) or Venda (a Tiny
|
|
customer, origin atendimento, invoiced and sent to Tiny), at the Site's
|
|
table price. A Venda is picked up, travels with a clothing order or ships
|
|
with the Site's freight; approve quotes the freight again."""
|
|
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=body.freight or Freight(service='pickup'),
|
|
destination=body.destination).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
|