Files
dtf-system/tests/users_test.py
Cauê Faleiros d962865944
All checks were successful
Build and deploy / Validate source (push) Successful in 4s
Build and deploy / Integration suite on a real stack (push) Successful in 3m38s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 59s
feat: the pickup receipt in Recibos/ and "Retirado" on the card (Dropstar's third round, item 14)
A pickup order reaching Finalizado has its receipt due: a PDF for the
80 mm roll with the order number large at the top, the customer and
CPF/CNPJ, each product and its metres, the amount and how it was paid,
the date issued, and the "Retirado em" and "Assinatura" lines
(app/receipt.py). The Kanban's folder saves it in Recibos/, where the
counter's print queue sends it to the Bematech. One computer claims each
receipt on the server before writing it, so it is never printed twice,
and gives it back if it could not save it. Orders sent by carrier have
none.

"Retirado" on a pickup in Finalizado records when and who handed it
over, with an optional photo of the signed receipt (kept 30 days). Anyone
but the seller may mark it (new "deliver" capability); the order panel
also opens the receipt to print it again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:39:17 -03:00

490 lines
34 KiB
Python

"""Kanban profiles, users and machines: who may do what, and who sees which orders.
Run inside the API container: python -m tests.users_test
"""
import secrets
import time
from decimal import Decimal
from urllib.request import Request, urlopen
from uuid import uuid4
from psycopg.types.json import Jsonb
from app import machines as routing
from app import payments, proof
from app.core import db
from tests.smoke_test import BASE, Client, with_host
PASSWORD = 'senha-de-teste-123'
def signed_in(email, password=PASSWORD):
client = Client()
client.call('/session')
client.call('/operator/login', {'email': email, 'password': password})
return client
def order_fixture(c, owner, mode, metres='1', printed=None):
"""A paid order straight in the database, as the payment would leave it:
`metres` billed, `printed` the film the sheet takes, when it differs."""
quote, order = uuid4(), uuid4()
item = {'mode': mode, 'grade': 100, 'billed_metres': metres, 'unit_cents': 1490, 'uploads': []}
if printed is not None:
item['metres'] = printed
content = {'customer': {'mail': 'm@example.test', 'cnpj': '11222333000181', 'zap': '16999999999'},
'items': [item], 'freight': {'service': 'pickup'}, 'total_cents': 1490}
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
VALUES(%s,%s,%s,'users-fixture',%s,%s,now())''', (quote, owner, uuid4(), Jsonb(content), Jsonb(content)))
c.execute("INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) VALUES(%s,%s,%s,%s,%s,'site')",
(order, quote, owner, Jsonb(content), Jsonb({'provider': 'teste', 'id': str(order)})))
return quote, order
def raw(client, path):
"""A response's bytes, for what is not JSON (the receipt's PDF)."""
with client.opener.open(Request(BASE + '/api' + path, headers=with_host()), timeout=30) as response:
return response.read()
def pickup_photo(client, oid, content):
"""The photo of a signed receipt, sent as the counter does, until scanned clean."""
uid = client.call(f'/operator/orders/{oid}/pickup-uploads', {'name': 'recibo.png', 'size': len(content)})['id']
url = client.call(f'/operator/uploads/{uid}/parts/1', {})['url']
with urlopen(Request(url, data=content, 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, 'photo scan did not finish'
time.sleep(0.5)
return uid
def expected_machine(su, product, metres=1.0):
"""What app/machines.py should pick now: the active machine of the product
with the fewest metres open, among those with room, else among all."""
# Listed in the order they were registered: min() keeps the first of equals, as the routing does.
rows = [m for m in su.call('/operator/machines', operator=True)['machines'] if m['active'] and product in m['products']]
room = [m for m in rows if m['limit_metres'] is None or m['open_metres'] + metres <= m['limit_metres']]
return min(room or rows, key=lambda m: m['open_metres'])['id']
def picking():
"""The choice itself: room first, then the fewest metres, then the first registered."""
textil = {'snapshot': {'items': [{'mode': 'file', 'billed_metres': '1'}]}}
uv = {'snapshot': {'items': [{'mode': 'uvfile', 'billed_metres': '1'}]}}
a = {'id': 'a', 'products': ['textil'], 'active': True, 'limit_metres': Decimal('2')}
b = {'id': 'b', 'products': ['textil'], 'active': True, 'limit_metres': None}
off = {'id': 'off', 'products': ['textil'], 'active': False, 'limit_metres': None}
assert routing.pick([a, b], {}, textil)['id'] == 'a'
assert routing.pick([off, a, b], {'a': Decimal('0.5')}, textil)['id'] == 'b'
# Full: the one with room takes it, even with more metres open.
assert routing.pick([a, b], {'a': Decimal('1.5'), 'b': Decimal('9')}, textil)['id'] == 'b'
# All full: the least loaded anyway.
b_full = {**b, 'limit_metres': Decimal('3')}
assert routing.pick([a, b_full], {'a': Decimal('5'), 'b': Decimal('4')}, textil)['id'] == 'b'
assert routing.pick([a, b], {}, uv) is None
def run():
picking()
tag = secrets.token_hex(3)
su = Client()
su.call('/session')
assert su.call('/operator/me', operator=True)['role'] == 'superadmin'
emails = {r: f'{r}-{tag}@example.test' for r in ('admin', 'operador', 'vendedor', 'designer', 'revisor')}
owner = uuid4()
machines, made = [], []
try:
# Machines, then an administrator who creates the rest of the team.
textil = su.call('/operator/machines', {'name': f'Têxtil {tag}', 'products': ['textil']}, operator=True)['id']
uv = su.call('/operator/machines', {'name': f'UV {tag}', 'products': ['uv']}, operator=True)['id']
machines += [textil, uv]
su.call('/operator/machines', {'name': f'uv {tag}', 'products': []}, operator=True, expected=409)
su.call('/operator/users', {'name': 'Marcus', 'email': emails['admin'], 'role': 'admin', 'password': PASSWORD},
operator=True)
# Superadmin is never given through the page.
su.call('/operator/users', {'name': 'X', 'email': f'x-{tag}@example.test', 'role': 'superadmin',
'password': PASSWORD}, operator=True, expected=422)
admin = signed_in(emails['admin'])
# Integrações: an administrator sees what is on and off; only the superadmin acts there.
assert 'integrations' not in admin.call('/operator/me')['can']
assert 'integrations' in su.call('/operator/me', operator=True)['can']
for path in ('/operator/tiny/connect', '/operator/tiny/test', '/operator/mercadopago/check',
'/operator/mail/test', '/operator/backup/run'):
admin.call(path, {}, expected=403)
admin.call('/operator/events', expected=403)
admin.call('/operator/users', {'name': 'Op', 'email': emails['operador'], 'role': 'operador',
'password': PASSWORD, 'machines': [uv]})
admin.call('/operator/users', {'name': 'Vendas', 'email': emails['vendedor'], 'role': 'vendedor',
'password': PASSWORD})
admin.call('/operator/users', {'name': 'Again', 'email': emails['vendedor'], 'role': 'vendedor',
'password': PASSWORD}, expected=409)
users = {u['email']: u for u in admin.call('/operator/users')['users']}
superadmin = next(u for u in users.values() if u['role'] == 'superadmin')
mine = users[emails['admin']]
# An administrator cannot touch the superadmin, nor demote, disable or delete themselves.
admin.call(f"/operator/users/{superadmin['id']}", {'name': 'x', 'email': superadmin['email'],
'role': 'admin'}, expected=403)
admin.call(f"/operator/users/{mine['id']}", {'name': 'Marcus', 'email': emails['admin'], 'role': 'gestao'},
expected=409)
admin.call(f"/operator/users/{mine['id']}/delete", {}, expected=409)
# Orders other suites left open get their machines first; then each paid
# order goes to the machine of its product with the fewest metres open.
su.call('/operator/board', operator=True)
want = {'textil': expected_machine(su, 'textil'), 'uv': expected_machine(su, 'uv')}
with db.connect() as c:
textil_q, textil_o = order_fixture(c, owner, 'file')
uv_q, uv_o = order_fixture(c, owner, 'uvfile')
made += [(textil_q, textil_o), (uv_q, uv_o)]
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert board[str(textil_o)]['machine']['id'] == want['textil'] and not board[str(textil_o)]['machine']['chosen']
assert board[str(uv_o)]['machine']['id'] == want['uv'] and not board[str(uv_o)]['machine']['chosen']
# On the UV machine of this test, whatever the others carry.
su.call(f'/operator/orders/{uv_o}/machine', {'machine_id': uv}, operator=True)
# The operator of the UV machine sees only its orders and prints them:
# Arte conferida to Imprimindo to Revisão, nothing else (Dropstar, 2026-10-23).
op = signed_in(emails['operador'])
seen = {o['id'] for o in op.call('/operator/board')['orders']}
assert str(uv_o) in seen and str(textil_o) not in seen, seen
assert sorted(op.call('/operator/me')['moves']) == [['imp', 'rev'], ['imp', 'tra'], ['rev', 'imp'], ['tra', 'imp']]
op.call(f'/operator/orders/{uv_o}/move', {'state': 'tra', 'version': 0, 'reason': ''}, expected=403)
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET state='imp' WHERE id=%s", (uv_o,))
op.call(f'/operator/orders/{uv_o}/move', {'state': 'cor', 'version': 0, 'reason': 'borrou'}, expected=403)
printed = op.call(f'/operator/orders/{uv_o}/move', {'state': 'rev', 'version': 0, 'reason': ''})
refused = op.call(f'/operator/orders/{uv_o}/move', {'state': 'fin', 'version': printed['version'], 'reason': ''},
expected=403)
assert refused['detail'] == 'Só o Revisor manda o pedido para Finalizado.', refused
op.call(f'/operator/orders/{uv_o}/cancel', {'note': 'não pode'}, expected=403)
op.call('/operator/users', expected=403)
op.call('/operator/payment-events', expected=403)
# Sent to the UV machine by hand, the Têxtil order appears for them.
su.call(f'/operator/orders/{textil_o}/machine', {'machine_id': uv}, operator=True)
assert str(textil_o) in {o['id'] for o in op.call('/operator/board')['orders']}
# The seller reads and changes nothing.
seller = signed_in(emails['vendedor'])
assert {str(uv_o), str(textil_o)} <= {o['id'] for o in seller.call('/operator/board')['orders']}
seller.call('/operator/stats?days=7')
seller.call(f'/operator/orders/{textil_o}/move', {'state': 'tra', 'version': 1, 'reason': ''}, expected=403)
seller.call(f'/operator/quotes/{uv_q}/discard', {}, expected=403)
seller.call(f'/operator/orders/{textil_o}/machine', {'machine_id': None}, expected=403)
seller.call(f'/operator/orders/{textil_o}/contact', {'waiting': True, 'note': 'Ligar'}, expected=403)
# The seller only views the board (D-30): no order registered by hand either.
assert seller.call('/operator/me')['can'] == ['view']
seller.call(f'/operator/quotes/{uv_q}/register', {'origin': 'atendimento', 'method': 'pix'}, expected=403)
# The Revisor releases to Finalizado, and the administrator may too (2026-10-28).
assert ['rev', 'fin'] in admin.call('/operator/me')['moves']
admin.call('/operator/users', {'name': 'Confere', 'email': emails['revisor'], 'role': 'revisor',
'password': PASSWORD})
reviewer = signed_in(emails['revisor'])
me = reviewer.call('/operator/me')
assert me['can'] == ['deliver', 'view'] and sorted(me['moves']) == [['fin', 'rev'], ['rev', 'fin']] and me['reorder'] == ['rev'], me
reviewer.call(f'/operator/orders/{textil_o}/move', {'state': 'tra', 'version': 0, 'reason': ''}, expected=403)
assert reviewer.call(f'/operator/orders/{uv_o}/move', {'state': 'fin', 'version': printed['version'],
'reason': ''})['state'] == 'fin'
# A pickup in Finalizado has its receipt (item 14): 80 mm wide, saved
# in Recibos/ by one computer only, and printed again from the panel.
pdf = raw(su.operator_client, f'/operator/orders/{uv_o}/receipt')
assert pdf.startswith(b'%PDF') and b'/MediaBox [0 0 226.7717 ' in pdf, pdf[:200]
due = lambda: {r['order']: r['name'] for r in su.call('/operator/queue/folder', {'early': True}, operator=True)['receipts']}
number = next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == str(uv_o))['number']
assert due()[str(uv_o)] == f'Recibo-DTF-{number}.pdf'
su.call(f'/operator/orders/{uv_o}/receipt/claim', {}, operator=True)
su.call(f'/operator/orders/{uv_o}/receipt/claim', {}, operator=True, expected=409)
assert str(uv_o) not in due()
# Not saved after all: it goes back for another computer to take.
su.call(f'/operator/orders/{uv_o}/receipt/release', {}, operator=True)
assert str(uv_o) in due()
su.call(f'/operator/orders/{uv_o}/receipt/claim', {}, operator=True)
# "Retirado": anyone but the seller, only in Finalizado, once, with the
# photo of the signed receipt.
seller.call(f'/operator/orders/{uv_o}/picked-up', {}, expected=403)
reviewer.call(f'/operator/orders/{textil_o}/picked-up', {}, expected=409)
png = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR' + (40).to_bytes(4, 'big') + (60).to_bytes(4, 'big') + b'\x08\x06\x00\x00\x00' + b'\x00' * 4
photo = pickup_photo(reviewer, uv_o, png)
reviewer.call(f'/operator/orders/{uv_o}/picked-up', {'photo': photo})
reviewer.call(f'/operator/orders/{uv_o}/picked-up', {}, expected=409)
shown = next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == str(uv_o))
assert (shown['picked_up_by'], shown['picked_up_photo']) == (emails['revisor'], photo) and shown['picked_up_at'], shown
# The designer: every order, whatever its machine; the artwork stages only.
admin.call('/operator/users', {'name': 'Arte', 'email': emails['designer'], 'role': 'designer',
'password': PASSWORD, 'machines': [uv]})
assert next(u for u in admin.call('/operator/users')['users'] if u['email'] == emails['designer'])['machines'] == []
designer = signed_in(emails['designer'])
assert set(designer.call('/operator/me')['can']) == {'view', 'produce', 'deliver'}
designer.call(f'/operator/quotes/{uv_q}/register', {'origin': 'atendimento', 'method': 'pix'}, expected=403)
assert {str(uv_o), str(textil_o)} <= {o['id'] for o in designer.call('/operator/board')['orders']}
version = next(o for o in designer.call('/operator/board')['orders'] if o['id'] == str(textil_o))['version']
# A correction and back; Arte conferida only with the final approved.
moved = designer.call(f'/operator/orders/{textil_o}/move', {'state': 'cor', 'version': version,
'reason': 'fundo branco'})
moved = designer.call(f'/operator/orders/{textil_o}/move', {'state': 'rec', 'version': moved['version'],
'reason': ''})
designer.call(f'/operator/orders/{textil_o}/move', {'state': 'tra', 'version': moved['version'], 'reason': ''},
expected=409)
# In the queue the card is the print room's; the designer only takes it back.
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET state='tra' WHERE id=%s", (textil_o,))
designer.call(f'/operator/orders/{textil_o}/move', {'state': 'imp', 'version': moved['version'], 'reason': ''},
expected=403)
designer.call(f'/operator/orders/{textil_o}/move', {'state': 'rec', 'version': moved['version'],
'reason': 'arte trocada'})
designer.call(f'/operator/orders/{textil_o}/machine', {'machine_id': None}, expected=403)
designer.call(f'/operator/orders/{textil_o}/cancel', {'note': 'não pode'}, expected=403)
designer.call('/operator/queue/finals', expected=403)
designer.call('/operator/users', expected=403)
# The print proof (Dropstar, 2026-10-21): above 10 m, no Finalizado before
# "Prova OK", which the print room marks and the designer cannot.
with db.connect() as c:
long_q, long_o = order_fixture(c, owner, 'file', metres='12')
made.append((long_q, long_o))
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (long_o,))
version = next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == str(long_o))['version']
su.call(f'/operator/orders/{long_o}/move', {'state': 'fin', 'version': version, 'reason': ''},
operator=True, expected=409)
designer.call(f'/operator/orders/{long_o}/proof', {}, expected=403)
seller.call(f'/operator/orders/{long_o}/proof', {}, expected=403)
version = su.call(f'/operator/orders/{long_o}/proof', {}, operator=True)['version']
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert board[str(long_o)]['proof_ok_at'] and board[str(long_o)]['proof_ok_by']
su.call(f'/operator/orders/{long_o}/move', {'state': 'fin', 'version': version, 'reason': ''}, operator=True)
# Up to 10 m, nothing to wait for.
with db.connect() as c:
short_q, short_o = order_fixture(c, owner, 'file', metres='10')
made.append((short_q, short_o))
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (short_o,))
version = next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == str(short_o))['version']
su.call(f'/operator/orders/{short_o}/move', {'state': 'fin', 'version': version, 'reason': ''}, operator=True)
# Asked for at checkout: the paid order arrives waiting for the customer's word.
with db.connect() as c:
asked = uuid4()
content = {'customer': {'mail': 'm@example.test', 'cnpj': '11222333000181', 'zap': '16999999999'},
'items': [{'mode': 'file', 'grade': 100, 'billed_metres': '1', 'unit_cents': 1490, 'uploads': []}],
'freight': {'service': 'pickup'}, 'total_cents': 1490, 'proof': True}
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
VALUES(%s,%s,%s,'users-fixture',%s,%s,now())''', (asked, owner, uuid4(), Jsonb(content), Jsonb(content)))
quote = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s', (asked,)).fetchone()
order, created = payments.create_order(c, quote, {'provider': 'teste', 'id': f'proof-{tag}'}, 'site')
made.append((asked, order['id']))
assert created and order['contact_since'] and order['contact_note'] == proof.CUSTOMER_NOTE, order
# Their own password: the current one is asked for.
seller.call('/operator/me/password', {'current': 'errada', 'new': 'outra-senha-de-teste'}, expected=403)
# Eight characters or more.
seller.call('/operator/me/password', {'current': PASSWORD, 'new': 'sete-77'}, expected=422)
seller.call('/operator/me/password', {'current': PASSWORD, 'new': 'oito-888'})
seller = signed_in(emails['vendedor'], 'oito-888')
seller.call('/operator/me/password', {'current': 'oito-888', 'new': 'outra-senha-de-teste'})
signed_in(emails['vendedor'], 'outra-senha-de-teste').call('/operator/me')
# A second Têxtil machine, its operators ticked on the machine itself: only
# operators are linked, the seller is not.
op_id, seller_id = users[emails['operador']]['id'], users[emails['vendedor']]['id']
textil2 = admin.call('/operator/machines', {'name': f'Têxtil B {tag}', 'products': ['textil'],
'operators': [op_id, seller_id]})['id']
machines.append(textil2)
listed = {m['id']: m for m in admin.call('/operator/machines')['machines']}
assert [o['id'] for o in listed[textil2]['operators']] == [op_id]
assert set(next(u for u in admin.call('/operator/users')['users'] if u['id'] == op_id)['machines']) == {uv, textil2}
# The next order goes to the one with fewer metres open.
target = expected_machine(su, 'textil')
with db.connect() as c:
made.append(order_fixture(c, owner, 'file'))
second = str(made[-1][1])
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert board[second]['machine']['id'] == target
# Chosen by hand, the order stays there; back to automatic, it is routed again.
su.call(f'/operator/orders/{second}/machine', {'machine_id': textil2}, operator=True)
listed = {m['id']: m for m in su.call('/operator/machines', operator=True)['machines']}
assert listed[textil2]['open_orders'] >= 1 and listed[textil2]['states'].get('rec', 0) >= 1
# A limit: once full, the next order goes to a machine with room.
open_now = listed[textil2]['open_metres']
admin.call(f'/operator/machines/{textil2}', {'name': f'Têxtil B {tag}', 'products': ['textil'],
'limit_metres': round(open_now + 0.5, 1)})
listed = {m['id']: m for m in su.call('/operator/machines', operator=True)['machines']}
assert listed[textil2]['limit_metres'] == round(open_now + 0.5, 1)
# Left out, the operators stay as they were.
assert [o['id'] for o in listed[textil2]['operators']] == [op_id]
target = expected_machine(su, 'textil')
assert target != textil2
with db.connect() as c:
made.append(order_fixture(c, owner, 'file'))
third = str(made[-1][1])
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert board[third]['machine']['id'] == target
admin.call(f'/operator/machines/{textil2}', {'name': f'Têxtil B {tag}', 'products': ['textil'],
'limit_metres': 0}, expected=422)
su.call(f'/operator/orders/{second}/machine', {'machine_id': None}, operator=True)
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert not board[second]['machine']['chosen']
# Números per machine: an order printed for half an hour on its machine, then
# finished. It counts the film printed (0,40 m), not the metre billed.
before = {m['id']: m for m in su.call('/operator/stats?days=7', operator=True)['machines']}
with db.connect() as c:
# A real payment: Números leaves test orders out.
c.execute('''UPDATE dtf_local.orders SET payment=%s,
snapshot=jsonb_set(snapshot, '{items,0,metres}', '"0.40"') WHERE id=%s''',
(Jsonb({'provider': 'mercadopago', 'id': f'users-{tag}'}), third))
for frm, to, at in (('rec', 'imp', "now()-interval '30 minutes'"), ('imp', 'fin', 'now()')):
c.execute(f'''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
VALUES(%s,%s,%s,'users-test','',false,{at})''', (third, frm, to))
after = {m['id']: m for m in su.call('/operator/stats?days=7', operator=True)['machines']}
assert after[target]['orders'] == before[target]['orders'] + 1
assert round(after[target]['metres'] - before[target]['metres'], 2) == 0.4, (before[target], after[target])
assert after[target]['last_finished'] and after[target]['metres_per_hour'] is not None
assert after[target]['printing_hours'] >= before[target]['printing_hours'] + 0.49
# Two orders printing at once on one machine: the half hour they share counts
# once, so the machine did 1,50 m in 0,5 h, not in 1 h.
with db.connect() as c:
together = [order_fixture(c, owner, 'file', printed=printed) for printed in ('0.60', '0.90')]
made.extend(together)
for _, oid in together:
c.execute('''UPDATE dtf_local.orders SET payment=%s, state='fin', machine_id=%s, machine_chosen=true
WHERE id=%s''', (Jsonb({'provider': 'mercadopago', 'id': f'users-{tag}-{oid}'}), textil2, oid))
for frm, to, at in (('rec', 'imp', "now()-interval '30 minutes'"), ('imp', 'fin', 'now()')):
c.execute(f'''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
VALUES(%s,%s,%s,'users-test','',false,{at})''', (oid, frm, to))
shared = next(m for m in su.call('/operator/stats?days=7', operator=True)['machines'] if m['id'] == textil2)
assert (shared['orders'], shared['metres'], shared['printing_hours'], shared['metres_per_hour']) == \
(2, 1.5, 0.5, 3.0), shared
# Two at most in Imprimindo per machine (Dropstar, 2026-10-29): the first
# to come in is printing, the second ripping; a third waits for a place.
cap = admin.call('/operator/machines', {'name': f'Cap {tag}', 'products': ['textil']})['id']
machines.append(cap)
with db.connect() as c:
pulled = [order_fixture(c, owner, 'file') for _ in range(4)]
made.extend(pulled)
for _, oid in pulled:
upload = uuid4()
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state) VALUES(%s,%s,'final.pdf',1,%s,'m',true,now()+interval '20 days','clean')''',
(upload, owner, f'test/{upload}'))
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
VALUES(%s,%s,%s,0,'final','ok','t')''', (uuid4(), oid, upload))
c.execute("UPDATE dtf_local.orders SET state='tra', machine_id=%s, machine_chosen=true WHERE id=%s",
(cap, oid))
first, second_in, third, elsewhere = (str(oid) for _, oid in pulled)
pull = lambda oid, version=0: su.call(f'/operator/orders/{oid}/move', {'state': 'imp', 'version': version,
'reason': ''}, operator=True)
running = pull(first)
pull(second_in)
refused = su.call(f'/operator/orders/{third}/move', {'state': 'imp', 'version': 0, 'reason': ''},
operator=True, expected=409)
assert refused['detail'] == f'Cap {tag} já tem 2 em Imprimindo.', refused
loaded = su.call('/operator/board', operator=True)
board = {o['id']: o for o in loaded['orders']}
assert (board[first]['printing'], board[second_in]['printing'], board[third]['printing']) == \
('imprimindo', 'ripando', None)
assert loaded['printing_cap'] == 2
assert next(m for m in loaded['machines'] if m['id'] == cap)['states'] == {'imp': 2, 'tra': 2}
# Nor does an order already printing elsewhere come onto the full machine.
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET state='imp', machine_id=%s WHERE id=%s", (textil, elsewhere))
su.call(f'/operator/orders/{elsewhere}/machine', {'machine_id': cap}, operator=True, expected=409)
assert next(o for o in su.call('/operator/board', operator=True)['orders']
if o['id'] == elsewhere)['machine']['id'] == textil
# The one printing goes to Revisão: the one ripping is now printing, and a place opens.
su.call(f'/operator/orders/{first}/move', {'state': 'rev', 'version': running['version'], 'reason': ''},
operator=True)
pull(third)
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert (board[first]['printing'], board[second_in]['printing'], board[third]['printing']) == \
(None, 'imprimindo', 'ripando')
# Switched off, a machine gives its automatic orders to another one.
with db.connect() as c:
c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=false WHERE id=%s', (textil2, second))
admin.call(f'/operator/machines/{textil2}', {'name': f'Têxtil B {tag}', 'products': ['textil'], 'active': False})
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert board[second]['machine']['id'] not in (None, textil2)
# Disabled, the operator is out at once; deleted, the account is gone.
op_row = users[emails['operador']]
admin.call(f"/operator/users/{op_row['id']}", {'name': 'Op', 'email': emails['operador'], 'role': 'operador',
'active': False, 'machines': [uv]})
op.call('/operator/board', expected=401)
admin.call(f"/operator/users/{op_row['id']}/delete", {})
assert emails['operador'] not in {u['email'] for u in admin.call('/operator/users')['users']}
# A deleted machine sends its orders back to the automatic choice.
su.call(f'/operator/machines/{uv}/delete', {}, operator=True)
machines.remove(uv)
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
back = board[str(textil_o)]['machine']
assert back and back['id'] != uv and not back['chosen']
# Rework (D-02 to D-04): Gestão opens it with its cause, an Administrador
# authorizes it, never their own, and only then it counts in Números.
emails['gestao'] = f'gestao-{tag}@example.test'
admin.call('/operator/users', {'name': 'Mayana', 'email': emails['gestao'], 'role': 'gestao', 'password': PASSWORD})
coord = signed_in(emails['gestao'])
with db.connect() as c:
c.execute('UPDATE dtf_local.orders SET payment=%s WHERE id=%s',
(Jsonb({'provider': 'mercadopago', 'id': f'rework-{tag}'}), uv_o))
figures = lambda: admin.call('/operator/stats?days=7')['rework']
cause = lambda figures, name: next(r for r in figures['causes'] if r['cause'] == name)['metres']
before = figures()
coord.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'outra', 'metres': '1'}, expected=422)
coord.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'impressao', 'metres': '0'}, expected=422)
admin.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'impressao', 'metres': '1'}, expected=403)
signed_in(emails['vendedor'], 'outra-senha-de-teste').call(f'/operator/orders/{uv_o}/reworks',
{'cause': 'impressao', 'metres': '1'}, expected=403)
redo = coord.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'impressao', 'metres': '0.5', 'note': 'Falhou'})
# Who printed it: the operator who sent it to Revisão, for their pay.
assert redo['printed_by'] == emails['operador'] and redo['authorized'] is None, redo
shown = next(o for o in admin.call('/operator/board')['orders'] if o['id'] == str(uv_o))['reworks']
# Names where the account exists; the operator's was deleted above, so their e-mail.
assert [(r['cause'], r['opened_name'], r['printed_name']) for r in shown] == [
('impressao', 'Mayana', emails['operador'])], shown
# Undecided, it does not count; it waits in Números.
waiting = figures()
assert cause(waiting, 'impressao') == cause(before, 'impressao')
assert redo['id'] in [p['id'] for p in waiting['pending']]
coord.call(f"/operator/reworks/{redo['id']}/decision", {'authorized': True}, expected=403)
admin.call(f"/operator/reworks/{redo['id']}/decision", {'authorized': False}, expected=422)
admin.call(f"/operator/reworks/{redo['id']}/decision", {'authorized': True})
admin.call(f"/operator/reworks/{redo['id']}/decision", {'authorized': True}, expected=409)
after = figures()
assert cause(after, 'impressao') == cause(before, 'impressao') + 0.5
assert after['house']['metres'] == before['house']['metres'] + 0.5 and after['house']['goal_percent'] == 1.6
# The customer's approved bad art counts apart, outside the house (D-04).
art = coord.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'arte_cliente', 'metres': '2'})
admin.call(f"/operator/reworks/{art['id']}/decision", {'authorized': True})
last = figures()
assert cause(last, 'arte_cliente') == cause(after, 'arte_cliente') + 2
assert last['house']['metres'] == after['house']['metres']
# Declined, with its reason; and nobody decides a rework they opened.
wrong = coord.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'pedido', 'metres': '1'})
declined = admin.call(f"/operator/reworks/{wrong['id']}/decision", {'authorized': False, 'reason': 'Não houve reimpressão'})
assert declined['authorized'] is False and declined['decline_reason'] == 'Não houve reimpressão'
assert cause(figures(), 'pedido') == cause(last, 'pedido')
own = su.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'pedido', 'metres': '1'}, operator=True)
su.call(f"/operator/reworks/{own['id']}/decision", {'authorized': True}, operator=True, expected=409)
print('PASS: profiles limit actions, admins manage users but not the superadmin or themselves, '
'machines take orders by load and limit, keep a choice, and limit what their operators see')
finally:
with db.connect() as c:
for _, oid in made:
c.execute('DELETE FROM dtf_local.movements WHERE order_id=%s', (oid,))
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.outbox WHERE event_key LIKE %s', (f'{oid}:%',))
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (oid,))
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([q for q, _ in made],))
c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (owner,))
c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',))
c.execute('DELETE FROM dtf_local.machines WHERE id=ANY(%s::uuid[])', (machines,))
if __name__ == '__main__':
run()