All checks were successful
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Successful in 3m23s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m7s
- a machine's metres are the film printed, not the metres billed, which round up to one metre and made small orders look like fast printing - orders in Imprimindo together on one machine count that time once - a stage's median time is per order, the sum of its passages, so rework reads as one slow order instead of quick passages Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
282 lines
18 KiB
Python
282 lines
18 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.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) VALUES(%s,%s,%s,%s,%s)',
|
|
(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')}
|
|
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, moves them, and nothing more.
|
|
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
|
|
op.call(f'/operator/orders/{uv_o}/move', {'state': 'tra', 'version': 0, 'reason': ''})
|
|
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']
|
|
# 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']
|
|
moved = designer.call(f'/operator/orders/{textil_o}/move', {'state': 'tra', 'version': version, 'reason': ''})
|
|
designer.call(f'/operator/orders/{textil_o}/move', {'state': 'fil', '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)
|
|
|
|
# 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()
|