"""The machine month numbers against the local stack (Fase 2, front 1b). Run inside the API container: python -m tests.machine_stats_test """ from datetime import datetime, timedelta, timezone from uuid import uuid4 from psycopg.types.json import Jsonb from app.core import db from tests.smoke_test import Client from tests.users_test import PASSWORD, order_fixture def paid_order(c, owner, machine, metres, total_cents): """A real (not test) paid order already in Imprimindo on the machine, with its item's total_cents set for what it sold.""" _, oid = order_fixture(c, owner, 'file', metres=metres) snapshot = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()['snapshot'] snapshot['items'][0]['total_cents'] = total_cents c.execute('''UPDATE dtf_local.orders SET snapshot=%s, payment=%s, state='imp', machine_id=%s WHERE id=%s''', (Jsonb(snapshot), Jsonb({'provider': 'fake', 'id': str(oid)}), machine, oid)) return str(oid) def current_month(): return datetime.now(timezone(timedelta(hours=-3))).strftime('%Y-%m') def run(): su = Client() su.call('/session') tag = uuid4().hex[:6] machine = su.call('/operator/machines', {'name': f'Números {tag}', 'products': ['textil']}, operator=True)['id'] email = f'numeros-{tag}@example.test' su.call('/operator/users', {'name': 'Números', 'email': email, 'role': 'operador', 'password': PASSWORD}, operator=True) op = Client() op.call('/session') op.call('/operator/login', {'email': email, 'password': PASSWORD}) op.call('/operator/me/machine', {'machine_id': machine}) owner = uuid4() # What went in this month: one film roll, one litre of white ink and a part. op.call(f'/operator/machines/{machine}/entries', {'kind': 'supply', 'item': 'film', 'quantity': 1, 'cost_cents': 30000}) op.call(f'/operator/machines/{machine}/entries', {'kind': 'supply', 'item': 'ink_w', 'quantity': 1, 'cost_cents': 18000}) op.call(f'/operator/machines/{machine}/entries', {'kind': 'part', 'item': 'cap', 'cost_cents': 5000, 'serial': f'cap-{tag}'}) with db.connect() as c: order = paid_order(c, owner, machine, '6', 9000) op.call(f'/operator/orders/{order}/move', {'state': 'rev', 'version': 0}) month = current_month() data = su.call('/operator/stats/machines?month=' + month, operator=True) row = next((m for m in data['machines'] if m['id'] == machine), None) assert row, data month_row = row['month'] assert abs(float(month_row['printed_metres']) - 6) < 0.01, month_row assert abs(float(month_row['metres_per_roll']) - 6) < 0.01, month_row assert month_row['supplies_cents'] == 48000, month_row assert month_row['parts_cents'] == 5000, month_row assert month_row['sold_cents'] > 0, month_row assert month_row['contribution_cents'] == month_row['sold_cents'] - 53000, month_row assert row['total']['roi_pct'] is None, row['total'] # Without a purchase price the return is blank; with it, it is a number. su.call(f'/operator/machines/{machine}/sheet', {'price_cents': 1234500, 'installed_on': '2020-01-01', 'minimums': {}}, operator=True) data = su.call('/operator/stats/machines?month=' + month, operator=True) row = next((m for m in data['machines'] if m['id'] == machine), None) assert row['total']['roi_pct'] is not None, row['total'] # Números is not the operator's: only management, the seller and finance read it. designer_email = f'desenho-{tag}@example.test' su.call('/operator/users', {'name': 'Desenho', 'email': designer_email, 'role': 'designer', 'password': PASSWORD}, operator=True) designer = Client() designer.call('/session') designer.call('/operator/login', {'email': designer_email, 'password': PASSWORD}) designer.call('/operator/stats/machines?month=' + month, expected=403) # A malformed month is refused before any query. su.call('/operator/stats/machines?month=2026-13', operator=True, expected=422) print('PASS: machine month printed, consumption, costs, sold, contribution, ROI, ' 'operator refused and a malformed month rejected') if __name__ == '__main__': run()