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>
This commit is contained in:
Cauê Faleiros
2026-11-09 15:27:04 -03:00
parent 8993eb25db
commit 2c80de0c0a
11 changed files with 312 additions and 15 deletions

View File

@@ -1,13 +1,19 @@
"""The montador's stamp sizes: Expedição reads them and Gestão edits them.
"""The montador: stamp sizes, and the invoiced order a sheet becomes.
Run against the local stack: python -m tests.stamps_test
"""
import secrets
import time
from pathlib import Path
from urllib.request import Request, urlopen
from uuid import UUID, uuid4
from app.core import db
from app.runtime import operator_identity
from tests.smoke_test import Client
PASSWORD = 'senha-de-teste-123'
PNG = (Path(__file__).resolve().parent / 'fixtures' / 'final-300.png').read_bytes()
def signed_in(email, password=PASSWORD):
@@ -17,6 +23,38 @@ def signed_in(email, password=PASSWORD):
return client
def upload_stamp(client, name='LOCAL-ESTAMP.png'):
start = client.call('/operator/montador/uploads', {'name': name, 'size': len(PNG)})
uid = start['id']
url = client.call(f'/operator/uploads/{uid}/parts/1', {})['url']
with urlopen(Request(url, data=PNG, method='PUT'), timeout=30) as response:
assert response.status == 200
client.call(f'/operator/uploads/{uid}/complete', {})
deadline = time.monotonic() + 150
while client.call(f'/operator/uploads/{uid}')['scan_state'] != 'clean':
assert time.monotonic() < deadline, 'stamp scan did not finish'
time.sleep(0.5)
return uid
def montador_item(uid, mode='avulsa'):
"""One source, 3 copies in a row: a valid Item for the montador route."""
sheet = mode == 'file'
height = 1.75 if sheet else 1.25
return {
'mode': mode, 'metres': height / 100, 'grade': 100, 'uploads': [uid],
'production': {
'version': 3, 'film_width_cm': 57, 'height_cm': height,
'sources': [{'upload_id': uid, 'kind': 'sheet' if sheet else 'artwork',
'width_cm': 0.5, 'length_cm': 0.25, 'copies': 3,
'rotation_degrees': 0, 'mirrored': False, 'measurement': 'file'}],
'placements': [{'source_index': 0, 'copy_index': copy,
'x_cm': 0 if sheet else 0.5 + copy * 0.5, 'y_cm': 0.5 + copy * 0.5,
'width_cm': 0.5, 'length_cm': 0.25,
'rotation_degrees': 0, 'mirrored': False} for copy in range(3)]},
'quality_status': 'ok', 'quality_acknowledged': False, 'residue_accepted': 0}
def run():
tag = secrets.token_hex(3)
su = Client()
@@ -26,6 +64,10 @@ def run():
original = c.execute('SELECT letter,width_cm FROM dtf_local.stamp_sizes ORDER BY width_cm, letter').fetchall()
emails = {role: f'{role}-{tag}@example.test' for role in ('expedicao', 'designer', 'gestao')}
table = [(row['letter'], float(row['width_cm'])) for row in original]
customer = {'name': 'Cliente Montador', 'cnpj': '11222333000181', 'zap': '16999999999',
'mail': f'montador-{tag}@example.test'}
identity = operator_identity(emails['expedicao'])
made_orders, made_quotes = [], []
try:
for role, email in emails.items():
su.call('/operator/users', {'name': role.title(), 'email': email, 'role': role,
@@ -59,9 +101,46 @@ def run():
expected=403)
read = manager.call('/operator/stamp-sizes')['sizes']
assert [(row['letter'], float(row['width_cm'])) for row in read] == [('A', 20), ('B', 24.5), ('D', 30)], read
print('PASS: Expedição reads the montador size table; Gestão replaces it; invalid rows are refused')
# The montador's order: the stamp upload, then the invoiced card in rec.
stamp = upload_stamp(shipping)
request_key = uuid4()
body = {'request_key': str(request_key), 'customer': customer,
'items': [montador_item(stamp)]}
order = shipping.call('/operator/montador/orders', body)
made_orders.append(UUID(order['id']))
made_quotes.append(UUID(order['quote_id']))
assert order['state'] == 'rec' and order['origin'] == 'dropflow', order
payment = order['payment']
assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'faturado', 'paid'), payment
assert payment['total_cents'] == order['snapshot']['total_cents'], payment
with db.connect() as c:
assert c.execute('SELECT 1 FROM dtf_local.print_files WHERE order_id=%s',
(UUID(order['id']),)).fetchone()
assert not c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s',
(f"{order['id']}:paid:tiny",)).fetchone()
# The same montagem cannot become a second order.
refused = shipping.call('/operator/montador/orders', body, expected=409)
assert refused['detail'] == f"Esta montagem já virou o pedido #{order['number']}.", refused
# A designer does not use the montador, and only loose art becomes one.
designer.call('/operator/montador/uploads', {'name': 'ESTAMPA.png', 'size': 1}, expected=403)
designer.call('/operator/montador/orders', body, expected=403)
shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'customer': customer,
'items': [montador_item(stamp, 'file')]}, expected=422)
print('PASS: Expedição reads the sizes, uploads a stamp and gets the invoiced montador card; '
'Gestão edits the table; invalid rows, profiles and modes are refused')
finally:
with db.connect() as c:
for oid in made_orders:
c.execute('DELETE FROM dtf_local.print_files WHERE order_id=%s', (oid,))
c.execute('DELETE FROM dtf_local.order_files WHERE order_id=%s', (oid,))
c.execute('DELETE FROM dtf_local.movements WHERE order_id=%s', (oid,))
c.execute('DELETE FROM dtf_local.contact_waits WHERE order_id=%s', (oid,))
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (oid,))
if made_quotes:
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', (made_quotes,))
c.execute('DELETE FROM dtf_local.mail_queue WHERE to_addr=%s', (customer['mail'],))
c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (identity,))
c.execute('DELETE FROM dtf_local.stamp_sizes')
c.cursor().executemany('INSERT INTO dtf_local.stamp_sizes(letter,width_cm) VALUES(%s,%s)', table)
c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',))

View File

@@ -1,6 +1,9 @@
"""Who moves which card on the Kanban: Dropstar's flow of 2026-10-23."""
import unittest
from unittest import mock
from app import payments
from app.core import auth
from app.core.auth import CAPABILITIES, ROLES, may_move, may_reorder
from app.runtime import BACK, STATES, TRANSITIONS
@@ -60,5 +63,29 @@ class MovesTest(unittest.TestCase):
self.assertTrue(all(may_reorder('gestao', s) for s in STATES))
class CanAnyTest(unittest.TestCase):
def test_a_profile_with_any_of_the_capabilities_gets_through(self):
# The montador's stamp uploads: deliver or assemble (Fase 2, front 7).
for role, allowed in (('operador', True), ('expedicao', True), ('vendedor', True),
('designer', True), ('financeiro', False)):
with mock.patch.object(auth, 'signed_in',
return_value={'role': role, 'email': role + '@example.test'}):
route = auth.can_any('deliver', 'assemble')
if allowed:
self.assertEqual(route(None), role + '@example.test')
else:
with self.assertRaises(auth.HTTPException):
route(None)
class InvoicedOrderTest(unittest.TestCase):
def test_an_invoiced_montador_order_is_held_out_of_tiny(self):
self.assertEqual(payments.INVOICED_METHOD, 'faturado')
# It is not one of the Cotações "registrar" methods.
self.assertNotIn(payments.INVOICED_METHOD, payments.OUTSIDE_METHODS)
self.assertFalse(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'faturado'}}))
self.assertTrue(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'pix'}}))
if __name__ == '__main__':
unittest.main()