Files
dtf-system/tests/stamps_test.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

151 lines
8.2 KiB
Python

"""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):
client = Client()
client.call('/session')
client.call('/operator/login', {'email': 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()
su.call('/session')
assert su.call('/operator/me', operator=True)['role'] == 'superadmin'
with db.connect() as c:
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,
'password': PASSWORD}, operator=True)
# The new profile creates through the users API and reads the table.
shipping = signed_in(emails['expedicao'])
me = shipping.call('/operator/me')
assert me['role'] == 'expedicao' and me['can'] == ['assemble', 'view'], me
read = shipping.call('/operator/stamp-sizes')['sizes']
assert [(row['letter'], float(row['width_cm'])) for row in read] == table, read
# The designer does not assemble: no reading the table.
designer = signed_in(emails['designer'])
designer.call('/operator/stamp-sizes', expected=403)
# Gestão replaces the whole table in one go and reads it back, by width.
manager = signed_in(emails['gestao'])
manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'D', 'width_cm': 30},
{'letter': 'A', 'width_cm': 20},
{'letter': 'B', 'width_cm': 24.5}]})
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
# A repeated letter and a width out of range are refused.
manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 20},
{'letter': 'A', 'width_cm': 24}]},
expected=422)
manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 0}]},
expected=422)
manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 57}]},
expected=422)
# Expedição only reads them; saving stays with Gestão.
shipping.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 20}]},
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
# 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',))
if __name__ == '__main__':
run()