feat: Números per machine, month by month (front 1b)
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 5m58s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m4s

A new Números section, "Máquinas, mês a mês", one column per machine
and a month at a time: metres printed, metres per hour and hours
running (time shared by two orders counted once), hours stopped with
their reasons; metres per film roll, ink per 100 m by colour, powder
per 100 m; supplies, parts and total cost per metre; what the printed
orders sold, the month's contribution and since installation; and the
return in % and months to pay back once Gestão types the price.

Refills stand for consumption. Every ratio without data shows "—".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-09 12:50:48 -03:00
parent 29518795a5
commit 4219db8215
8 changed files with 575 additions and 4 deletions

View File

@@ -0,0 +1,92 @@
"""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()

View File

@@ -0,0 +1,78 @@
"""The machine month's pure calculations (Fase 2, front 1b), without a database."""
import unittest
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
from app.machine_stats import month_bounds, ratios
SAO_PAULO = ZoneInfo('America/Sao_Paulo')
class MonthBoundsTest(unittest.TestCase):
def test_a_valid_month(self):
start, end = month_bounds('2026-11')
self.assertEqual((start.year, start.month, start.day), (2026, 11, 1))
self.assertEqual((start.hour, start.minute, start.second), (0, 0, 0))
self.assertEqual(start.utcoffset(), timedelta(hours=-3))
self.assertEqual(start.tzinfo, SAO_PAULO)
self.assertEqual((end.year, end.month, end.day), (2026, 12, 1))
def test_the_year_turns_over(self):
start, end = month_bounds('2026-12')
self.assertEqual((start.year, start.month), (2026, 12))
self.assertEqual((end.year, end.month, end.day), (2027, 1, 1))
def test_a_malformed_month_is_invalid(self):
for month in ('2026-13', '2026-1', 'novembro', '2026-11-05', ''):
with self.subTest(month=month):
with self.assertRaises(ValueError):
month_bounds(month)
def test_none_is_the_current_month(self):
now = datetime.now(SAO_PAULO)
start, end = month_bounds(None)
self.assertEqual((start.year, start.month), (now.year, now.month))
class RatiosTest(unittest.TestCase):
def test_zero_or_unknown_divisors_are_none(self):
value = ratios(0, hours_running=0, supplies_cents=100, parts_cents=50,
rolls=0, inks={'ink_c': 1}, powder=0, price_cents=1000,
contribution_cents=200, months=10)
self.assertIsNone(value['metres_per_hour'])
self.assertIsNone(value['metres_per_roll'])
self.assertIsNone(value['ink_per_100m']['ink_c'])
self.assertIsNone(value['powder_g_per_100m'])
self.assertIsNone(value['supplies_per_metre_cents'])
self.assertIsNone(value['parts_per_metre_cents'])
self.assertIsNone(value['total_per_metre_cents'])
self.assertEqual(value['roi_pct'], 20.0)
def test_no_price_leaves_the_return_blank(self):
value = ratios(0, contribution_cents=500, installed_parts_cents=100, months=5)
self.assertIsNone(value['roi_pct'])
self.assertIsNone(value['payback_months'])
def test_the_known_ratios(self):
value = ratios(100, hours_running=10, supplies_cents=10000, parts_cents=5000,
rolls=2, inks={'ink_c': 1}, powder=1, price_cents=100000,
contribution_cents=30000, installed_parts_cents=20000, months=10)
self.assertEqual(value['metres_per_hour'], 10.0)
self.assertEqual(value['metres_per_roll'], 50.0)
self.assertEqual(value['ink_per_100m']['ink_c'], 1.0)
self.assertEqual(value['powder_g_per_100m'], 1000.0)
self.assertEqual(value['supplies_per_metre_cents'], 100)
self.assertEqual(value['parts_per_metre_cents'], 50)
self.assertEqual(value['total_per_metre_cents'], 150)
self.assertEqual(value['roi_pct'], 25.0)
self.assertEqual(value['payback_months'], 30.0)
def test_a_negative_average_has_no_payback(self):
value = ratios(100, price_cents=100000, contribution_cents=-1000,
installed_parts_cents=0, months=10)
self.assertEqual(value['roi_pct'], -1.0)
self.assertIsNone(value['payback_months'])
if __name__ == '__main__':
unittest.main()