Files
dtf-system/tests/users_test.py
Cauê Faleiros 0319039328
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 3m21s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m1s
feat: every order is born with its origin, shown, filtered and counted (Dropstar's rules D-21 and D-35)
Orders carry site, dropflow or atendimento, required and with no default,
limited to the three. The Site's orders are marked site where they are
created; older orders became site. The Kanban shows the origin on each card
and in the order panel, filters by it, and Numeros has a Por origem table:
orders, metres, money and time from payment to Finalizado per way in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 11:39:08 -03:00

348 lines
24 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
from decimal import Decimal
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 Client
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 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)
assert seller.call('/operator/me')['can'] == ['view']
# Only the Revisor releases to Finalizado: not even the administrator.
admin.call(f'/operator/orders/{uv_o}/move', {'state': 'fin', 'version': printed['version'], 'reason': ''},
expected=403)
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'] == ['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'
# 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'}
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}'})
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
# 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']
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.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.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()