Files
dtf-system/tests/stamps_test.py
Cauê Faleiros aaa6090642
All checks were successful
Build and deploy / Validate source (push) Successful in 10s
Build and deploy / Integration suite on a real stack (push) Successful in 7m38s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m19s
feat: places per machine, drops on Imprimindo go to your machine, a Venda carries its seller to Tiny (DTF-WEB-V)
Marcus, 2026-11-17:
- Each machine has its own places (machines.places, 1 to 6, three to
  start): orders at once in Imprimindo and files at once in its hot
  folder. Admin sets it in the machine dialog; Admin and Gestão in the
  machine sheet's Dados da máquina. A third order shows as "Na vez".
- Whoever is signed in on a machine drops a card anywhere in Imprimindo
  and it goes to that machine; without one, the lane under the pointer.
- Each Kanban user may name their Tiny seller (Usuários, read from
  Tiny's own list); a montador Venda reaches Tiny with the seller of who
  assembled it. Every other order still sends no seller.
- A folder download that never reached storage (a network drop) waits
  for the next pass as a warning and is reported only if it keeps
  failing (Sentry DTF-WEB-V).

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

273 lines
17 KiB
Python

"""The montador: stamp sizes, brand per stamp, and the Interno and Venda
orders a sheet becomes (fronts 7a to 7a.3).
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()
INTERNAL_MISSING = 'Peça à Gestão para completar o cliente interno.'
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 * 1.0, 'y_cm': 0.5 + copy * 0.5 if sheet else 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 price_table(stats):
return {row['method']: row for row in stats['price_table']}
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()
internal = c.execute('SELECT name,cnpj,zap,mail FROM dtf_local.internal_customer').fetchone()
# The seed state: only the name, so Interno must be refused until
# Gestão completes the other fields.
c.execute("UPDATE dtf_local.internal_customer SET name='Nexstar · Marketplace',"
"cnpj='',zap='',mail=''")
emails = {role: f'{role}-{tag}@example.test' for role in ('expedicao', 'vendedor', 'designer', 'gestao')}
table = [(row['letter'], float(row['width_cm'])) for row in original]
internal_customer = {'name': 'Nexstar · Marketplace', 'cnpj': '11222333000181',
'zap': '1633334444', 'mail': f'interno-{tag}@example.test'}
venda_customer = {'name': 'Maria Souza', 'cnpj': '12345678909',
'zap': '16988887777', 'mail': f'venda-{tag}@example.test'}
envio_customer = {'name': 'Maria Souza', 'cnpj': '12345678909',
'zap': '16988887777', 'mail': f'envio-{tag}@example.test'}
identities = [operator_identity(emails['expedicao']), operator_identity(emails['vendedor'])]
made_orders, made_quotes = [], []
# A code of its own, so a brand someone saved in Estampas/ is never touched.
# With a dot, as Dropstar's own codes (NX.226).
stamp_code = 'T.' + tag
try:
# The seller is a Tiny seller too (Marcus, 2026-11-17): the fake Tiny
# lists two, and a Venda this user assembles carries the one chosen.
sellers = su.call('/operator/tiny/sellers', operator=True)
assert sellers == [{'id': 2001, 'name': 'Lais'}, {'id': 2002, 'name': 'Marcus'}], sellers
for role, email in emails.items():
su.call('/operator/users', {'name': role.title(), 'email': email, 'role': role, 'password': PASSWORD,
**({'tiny_seller': sellers[0]} if role == 'vendedor' else {})},
operator=True)
listed = {u['email']: u for u in su.call('/operator/users', operator=True)['users']}
assert listed[emails['vendedor']]['tiny_seller'] == sellers[0], listed[emails['vendedor']]
assert listed[emails['gestao']]['tiny_seller'] is None, listed[emails['gestao']]
# The new profile creates through the users API and reads the table.
shipping = signed_in(emails['expedicao'])
seller = signed_in(emails['vendedor'])
manager = signed_in(emails['gestao'])
designer = signed_in(emails['designer'])
me = shipping.call('/operator/me')
assert me['role'] == 'expedicao' and me['can'] == ['assemble', 'label', '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.call('/operator/stamp-sizes', expected=403)
# Gestão replaces the whole table in one go and reads it back, by width.
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 brand per stamp: read by whoever assembles, saved by Gestão.
default = shipping.call('/operator/stamps/' + stamp_code)
assert default == {'code': stamp_code, 'brand': '', 'public': False}, default
manager.call('/operator/stamps/' + stamp_code, {'brand': 'Dropstar', 'public': True})
saved = shipping.call('/operator/stamps/' + stamp_code)
assert saved == {'code': stamp_code, 'brand': 'Dropstar', 'public': True}, saved
designer.call('/operator/stamps/' + stamp_code, {'brand': 'X', 'public': False}, expected=403)
shipping.call('/operator/stamps/' + stamp_code, {'brand': 'X', 'public': False}, expected=403)
# The fake Tiny answers the Venda customer search with two contacts.
contacts = shipping.call('/operator/tiny/contacts?q=Nexstar')
assert len(contacts) == 2, contacts
assert set(contacts[0]) == {'id', 'name', 'document', 'email', 'phone'}, contacts[0]
assert contacts[0]['document'] == '11.222.333/0001-81', contacts[0]
# Interno is refused while Gestão has not completed the customer.
stamp = upload_stamp(shipping)
interno = {'kind': 'interno', 'items': [montador_item(stamp)]}
refused = shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), **interno},
expected=409)
assert refused['detail'] == INTERNAL_MISSING, refused
manager.call('/operator/internal-customer', internal_customer)
completed = shipping.call('/operator/internal-customer')
assert (completed['name'], completed['cnpj'], completed['zap'], completed['mail']) == (
'Nexstar · Marketplace', '11222333000181', '1633334444', internal_customer['mail']), completed
before_stats = manager.call('/operator/stats?days=30')
before = price_table(before_stats)
# Interno: the fixed customer, origin dropflow, no Tiny, no paid e-mail.
order_interno = shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), **interno})
made_orders.append(UUID(order_interno['id']))
made_quotes.append(UUID(order_interno['quote_id']))
assert order_interno['state'] == 'rec' and order_interno['origin'] == 'dropflow', order_interno
assert order_interno['snapshot']['kind'] == 'interno', order_interno['snapshot'].get('kind')
assert order_interno['snapshot']['customer']['cnpj'] == '11222333000181', order_interno['snapshot']
payment = order_interno['payment']
assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'interno', 'paid'), payment
with db.connect() as c:
assert c.execute('SELECT 1 FROM dtf_local.print_files WHERE order_id=%s',
(UUID(order_interno['id']),)).fetchone()
assert not c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s',
(f"{order_interno['id']}:paid:tiny",)).fetchone()
assert not c.execute('SELECT 1 FROM dtf_local.mail_queue WHERE to_addr=%s',
(internal_customer['mail'],)).fetchone()
# Venda: a Tiny customer, origin atendimento, invoiced and sent to Tiny.
venda_stamp = upload_stamp(seller)
venda = {'kind': 'venda', 'customer': venda_customer, 'with_order': 4321,
'items': [montador_item(venda_stamp)]}
venda_body = {'request_key': str(uuid4()), **venda}
order_venda = seller.call('/operator/montador/orders', venda_body)
made_orders.append(UUID(order_venda['id']))
made_quotes.append(UUID(order_venda['quote_id']))
assert order_venda['state'] == 'rec' and order_venda['origin'] == 'atendimento', order_venda
assert order_venda['snapshot']['with_order'] == 4321, order_venda['snapshot'].get('with_order')
assert order_venda['snapshot']['seller'] == {'id': 2001, 'name': 'Lais'}, order_venda['snapshot'].get('seller')
assert 'seller' not in order_interno['snapshot'], order_interno['snapshot'].get('seller')
payment = order_venda['payment']
assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'faturado', 'paid'), payment
with db.connect() as c:
assert c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s AND provider=%s',
(f"{order_venda['id']}:paid:tiny", 'tiny')).fetchone()
assert not c.execute('SELECT 1 FROM dtf_local.mail_queue WHERE to_addr=%s',
(venda_customer['mail'],)).fetchone()
# Números: both are counted apart from the money received.
after_stats = manager.call('/operator/stats?days=30')
after = price_table(after_stats)
for method, order in (('interno', order_interno), ('faturado', order_venda)):
assert after[method]['orders'] == before[method]['orders'] + 1, (method, before[method], after[method])
assert after[method]['cents'] == before[method]['cents'] + order['snapshot']['total_cents'], (method, before[method], after[method])
assert after[method]['metres'] > before[method]['metres'], (method, before[method], after[method])
assert after_stats['cents'] == before_stats['cents'], (before_stats['cents'], after_stats['cents'])
# The same montagem cannot become a second order.
refused = seller.call('/operator/montador/orders', venda_body, expected=409)
assert refused['detail'] == f"Esta montagem já virou o pedido #{order_venda['number']}.", refused
# Each profile makes only its own kind, and only loose art becomes one.
seller.call('/operator/montador/orders', {'request_key': str(uuid4()), **interno}, expected=403)
shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), **venda}, expected=403)
designer.call('/operator/montador/uploads', {'name': 'ESTAMPA.png', 'size': 1}, expected=403)
designer.call('/operator/montador/orders', {'request_key': str(uuid4()), **venda}, expected=403)
shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'kind': 'interno',
'items': [montador_item(stamp, 'file')]}, expected=422)
# Venda with Envio: the Site's freight, re-quoted by the server.
destination = {'recipient': 'Maria Souza', 'street': 'Rua das Flores', 'number': '100',
'complement': 'Sala 2', 'district': 'Centro', 'city': 'Franca',
'state': 'SP', 'postal_code': '14400000'}
envio_stamp = upload_stamp(seller)
envio = {'kind': 'venda', 'customer': envio_customer, 'items': [montador_item(envio_stamp)],
'freight': {'service': 'mock-standard', 'postal_code': '14400000'},
'destination': destination}
order_envio = seller.call('/operator/montador/orders', {'request_key': str(uuid4()), **envio})
made_orders.append(UUID(order_envio['id']))
made_quotes.append(UUID(order_envio['quote_id']))
snapshot = order_envio['snapshot']
assert snapshot['destination'] == destination, snapshot.get('destination')
assert snapshot['freight']['service'] == 'mock-standard', snapshot.get('freight')
assert snapshot['freight']['total_cents'] > 0, snapshot.get('freight')
assert snapshot['total_cents'] == (sum(item['total_cents'] for item in snapshot['items']) +
snapshot['freight']['total_cents']), snapshot['total_cents']
with db.connect() as c:
assert c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s AND provider=%s',
(f"{order_envio['id']}:paid:tiny", 'tiny')).fetchone()
# Envio needs the full address; an Interno order never ships.
sem_destino = {key: value for key, value in envio.items() if key != 'destination'}
seller.call('/operator/montador/orders', {'request_key': str(uuid4()), **sem_destino}, expected=422)
shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'kind': 'interno',
'items': [montador_item(stamp)],
'destination': destination}, expected=422)
print('PASS: Expedição makes Interno and Vendedor makes Venda; the internal customer, the Tiny '
'contacts, the stamp brand and the table price in Números work; a Venda with Envio carries '
'the destination and the quoted freight; invalid profiles, modes and deliveries are refused')
finally:
with db.connect() as c:
if made_orders:
c.execute("DELETE FROM dtf_local.outbox WHERE payload->>'order_id' = ANY(%s::text[])",
([str(oid) for oid in made_orders],))
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 IN (%s,%s,%s)',
(internal_customer['mail'], venda_customer['mail'], envio_customer['mail']))
for identity in identities:
c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (identity,))
c.execute('DELETE FROM dtf_local.stamps WHERE code=%s', (stamp_code,))
c.execute('UPDATE dtf_local.internal_customer SET name=%s,cnpj=%s,zap=%s,mail=%s',
(internal['name'], internal['cnpj'], internal['zap'], internal['mail']))
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()