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

@@ -73,7 +73,7 @@ jobs:
# one a developer exercises on localhost. # one a developer exercises on localhost.
- name: API and workflow regressions - name: API and workflow regressions
run: | run: |
for suite in smoke_test workflow_test security_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test; do for suite in smoke_test workflow_test security_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test; do
echo "--- $suite" echo "--- $suite"
$COMPOSE exec -T \ $COMPOSE exec -T \
-e SITE_BASE_URL=http://site \ -e SITE_BASE_URL=http://site \
@@ -86,7 +86,7 @@ jobs:
# the generator's geometry. The provider suites use a fake transport: they # the generator's geometry. The provider suites use a fake transport: they
# prove the documented contract, not the integration. # prove the documented contract, not the integration.
- name: Print-file geometry and provider adapters - name: Print-file geometry and provider adapters
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log -v run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats -v
- name: Runtime and retention regressions - name: Runtime and retention regressions
run: | run: |

View File

@@ -3,13 +3,16 @@ from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Request from fastapi import APIRouter, Depends, HTTPException, Request
from .. import machine_log from .. import machine_log, machine_stats
from ..core import db from ..core import db
from ..core.auth import audit, can from ..core.auth import audit, can, operator
from ..core.models import MachineEntry, MachineSheet from ..core.models import MachineEntry, MachineSheet
router = APIRouter() router = APIRouter()
# Números is read by management and by the seller and finance, who consult it.
STATS_ROLES = ('superadmin', 'admin', 'gestao', 'vendedor', 'financeiro')
def machine_row(c, mid): def machine_row(c, mid):
row = c.execute('SELECT id,name,price_cents,installed_on FROM dtf_local.machines WHERE id=%s', row = c.execute('SELECT id,name,price_cents,installed_on FROM dtf_local.machines WHERE id=%s',
@@ -117,3 +120,18 @@ def snooze_alert(mid: UUID, key: str, request: Request, user=Depends(can('print'
machine_log.snooze(c, mid, key, user) machine_log.snooze(c, mid, key, user)
audit('machine_alert_snoozed', operator=user, machine=str(mid), alert=key) audit('machine_alert_snoozed', operator=user, machine=str(mid), alert=key)
return {'ok': True} return {'ok': True}
@router.get('/api/operator/stats/machines')
def machine_stats_month(request: Request, month: str | None = None, user=Depends(operator)):
"""Números per machine, month by month (Fase 2, front 1b)."""
if request.state.operator['role'] not in STATS_ROLES:
raise HTTPException(403, 'Seu perfil não permite esta ação.')
try:
start, _ = machine_stats.month_bounds(month)
except ValueError:
raise HTTPException(422, 'Informe o mês como AAAA-MM.')
if start > machine_stats.month_bounds(None)[0]:
raise HTTPException(422, 'Esse mês ainda não começou.')
with db.connect() as c:
return machine_stats.report(c, month=month)

281
app/machine_stats.py Normal file
View File

@@ -0,0 +1,281 @@
"""Números per machine, month by month (Fase 2, front 1, part b).
From what the room enters on each machine's sheet (app/machine_log.py) and
what the board already knows it printed, per machine and calendar month
(America/Sao_Paulo):
Produção printed metres (machine_log rule: imp -> rev, film metres,
PROOF_SHEET_CM per proof item); hours running = the union of the
time its orders spent in Imprimindo, clipped to the month (two
orders printing together count once); metres per hour = printed
/ hours running; hours stopped = the "stop" events' minutes, in
total and by reason (the note, as typed).
Consumo metres per film roll = printed / rolls entered in the month;
ink litres per 100 m, per colour = litres entered / printed * 100;
powder grams per 100 m = kg entered * 1000 / printed * 100.
Refills stand for what was used: an entry replaces what ran out.
Custo supplies per metre and parts per metre = their cost entered in
the month / printed; total per metre = the sum.
Resultado contribution = what the orders it printed in the month sold
(their items' total_cents, not freight or treatment; no proof
or test order) minus its supplies and parts of the month. Also
accumulated since installation (installed_on, else log_since).
ROI accumulated contribution / (price + parts since installation),
in %, and months to pay back = (price + parts since
installation - accumulated contribution) / the average monthly
contribution since installation (None when that average is not
positive or the price is unknown).
Every ratio is None when its divisor is zero or unknown: no number is
better than a made-up one.
"""
from datetime import datetime, time
from decimal import Decimal, ROUND_HALF_UP
from zoneinfo import ZoneInfo
from .machine_log import SUPPLIES
SAO_PAULO = ZoneInfo('America/Sao_Paulo')
# The five inks Números lists, in the order the sheet knows them.
INK_ITEMS = tuple(item for item in SUPPLIES if item.startswith('ink_'))
# Average month, for the monthly contribution since installation.
_MONTH_SECONDS = Decimal('30.4375') * 86400
def month_bounds(month):
"""'2026-11' (None: the current month, local) -> (first day, first day of
the next month) as timezone-aware datetimes at 00:00 America/Sao_Paulo.
A malformed month is ValueError."""
now = datetime.now(SAO_PAULO)
if month is None:
year, number = now.year, now.month
else:
try:
parsed = datetime.strptime(month, '%Y-%m')
except (TypeError, ValueError):
raise ValueError('month must be YYYY-MM') from None
# strptime accepts a single digit; the board always sends two.
if month != f'{parsed.year:04d}-{parsed.month:02d}':
raise ValueError('month must be YYYY-MM')
year, number = parsed.year, parsed.month
start = datetime(year, number, 1, tzinfo=SAO_PAULO)
if number == 12:
end = datetime(year + 1, 1, 1, tzinfo=SAO_PAULO)
else:
end = datetime(year, number + 1, 1, tzinfo=SAO_PAULO)
return start, end
def ratios(printed, hours_running=None, supplies_cents=0, parts_cents=0, rolls=None,
inks=None, powder=None, price_cents=None, contribution_cents=0,
installed_parts_cents=0, months=None):
"""Every Números ratio from raw totals, so they are tested without a
database. A zero or unknown divisor gives None; cents are whole."""
printed = Decimal(str(printed or 0))
def per_metre(cents):
if printed == 0:
return None
return int((Decimal(cents) / printed).quantize(Decimal('1'), rounding=ROUND_HALF_UP))
result = {
'metres_per_hour': (round(float(printed) / float(hours_running), 1)
if hours_running else None),
'metres_per_roll': round(float(printed / Decimal(str(rolls))), 1) if rolls else None,
'ink_per_100m': {
item: (None if quantity is None or not printed
else round(float(Decimal(str(quantity)) / printed * 100), 1))
for item, quantity in (inks or {}).items()},
'powder_g_per_100m': (round(float(Decimal(str(powder)) * 1000 / printed * 100), 1)
if powder is not None and printed else None),
'supplies_per_metre_cents': per_metre(supplies_cents),
'parts_per_metre_cents': per_metre(parts_cents),
'total_per_metre_cents': per_metre(Decimal(supplies_cents) + Decimal(parts_cents)),
'roi_pct': None,
'payback_months': None,
}
# Without a price there is no investment to measure the return against.
invested = None if price_cents is None else Decimal(price_cents) + Decimal(installed_parts_cents)
if invested:
result['roi_pct'] = round(float(Decimal(contribution_cents) * 100 / invested), 1)
if price_cents is not None and months and months > 0:
average = Decimal(contribution_cents) / Decimal(str(months))
if average > 0:
result['payback_months'] = round(
float((invested - Decimal(contribution_cents)) / average), 1)
return result
def _printed_orders(c, machine_id, start, end):
"""The orders that left Imprimindo for Revisão on the machine in the
period, with what is needed to count film and what they sold."""
return c.execute('''SELECT o.id, o.snapshot, o.parent_id, o.cancelled_at, o.payment
FROM dtf_local.movements m JOIN dtf_local.orders o ON o.id=m.order_id
WHERE o.machine_id=%s AND m.from_state='imp' AND m.to_state='rev' AND NOT m.back
AND m.created_at>=%s AND m.created_at<%s''', (machine_id, start, end)).fetchall()
def _film(snapshot):
"""The film printed for one order (machine_log's rule), as Decimal."""
from .proof import PROOF_SHEET_CM
snapshot = snapshot or {}
proof = bool(snapshot.get('proof_of'))
total = Decimal(0)
for item in snapshot.get('items') or []:
if proof:
total += PROOF_SHEET_CM
else:
value = item.get('metres')
if value is None:
value = item.get('billed_metres')
total += Decimal(str(value or 0))
return total
def _sold(row):
"""What the order's items sold; proof cards, tests and cancelled orders
are not sales (as REAL_ORDER in the board)."""
if (row['parent_id'] is not None or row['cancelled_at'] is not None
or (row['payment'] or {}).get('provider') == 'teste'):
return 0
return sum(int(item.get('total_cents') or 0)
for item in (row['snapshot'] or {}).get('items') or [])
def printed_between(c, machine_id, start, end):
"""Film metres the machine printed in [start, end), as Decimal."""
return sum((_film(row['snapshot']) for row in _printed_orders(c, machine_id, start, end)),
Decimal(0))
def _union_hours(spans, start, end):
"""The hours the spans (start, end) cover inside [start, end); time shared
by several orders is counted once."""
clipped = []
for at, until in spans:
first, last = max(at, start), min(until, end)
if last > first:
clipped.append((first, last))
seconds, reached = 0.0, None
for at, until in sorted(clipped):
if reached is None or at >= reached:
seconds += (until - at).total_seconds()
reached = until
elif until > reached:
seconds += (until - reached).total_seconds()
reached = until
return round(seconds / 3600, 1)
def machine_month(c, machine, start, end):
"""One machine's figures for [start, end): {'printed_metres', 'hours_running',
'metres_per_hour', 'stopped_hours', 'stops': [{'reason', 'hours'}],
'metres_per_roll', 'ink_per_100m': {item: litres}, 'powder_g_per_100m',
'supplies_cents', 'parts_cents', 'supplies_per_metre_cents',
'parts_per_metre_cents', 'total_per_metre_cents', 'sold_cents',
'contribution_cents'}. `machine` is its row from dtf_local.machines."""
mid = machine['id']
rows = _printed_orders(c, mid, start, end)
printed = sum((_film(row['snapshot']) for row in rows), Decimal(0))
sold = sum((_sold(row) for row in rows), 0)
ids = [row['id'] for row in rows]
spans = c.execute('''WITH events AS (
SELECT m.order_id AS id, m.to_state AS state, m.created_at AS at FROM dtf_local.movements m
WHERE m.order_id=ANY(%s)),
spans AS (SELECT id, state, at, LEAD(at) OVER (PARTITION BY id ORDER BY at) AS until FROM events)
SELECT at, until FROM spans WHERE state='imp' AND until IS NOT NULL''',
(ids,)).fetchall() if ids else []
hours = _union_hours([(row['at'], row['until']) for row in spans], start, end)
supplies = c.execute('''SELECT item, COALESCE(sum(quantity),0) AS quantity,
COALESCE(sum(cost_cents),0) AS cents FROM dtf_local.machine_entries
WHERE machine_id=%s AND kind='supply' AND created_at>=%s AND created_at<%s
GROUP BY item''', (mid, start, end)).fetchall()
quantities = {row['item']: row['quantity'] for row in supplies}
supplies_cents = int(sum((row['cents'] for row in supplies), 0))
parts_cents = int(c.execute('''SELECT COALESCE(sum(cost_cents),0) AS cents
FROM dtf_local.machine_entries WHERE machine_id=%s AND kind='part'
AND created_at>=%s AND created_at<%s''', (mid, start, end)).fetchone()['cents'])
stops = c.execute('''SELECT note, COALESCE(sum(stop_minutes),0) AS minutes
FROM dtf_local.machine_entries WHERE machine_id=%s AND kind='event' AND item='stop'
AND created_at>=%s AND created_at<%s GROUP BY note ORDER BY minutes DESC, note''',
(mid, start, end)).fetchall()
stop_list = [{'reason': row['note'] or '', 'hours': round(float(row['minutes']) / 60, 1)}
for row in stops if row['minutes']]
stopped = round(sum(float(row['minutes']) for row in stops) / 60, 1)
values = ratios(printed, hours_running=hours, supplies_cents=supplies_cents,
parts_cents=parts_cents, rolls=quantities.get('film'),
inks={item: quantities.get(item) for item in INK_ITEMS},
powder=quantities.get('powder'))
return {
'printed_metres': round(float(printed), 2),
'hours_running': hours,
'metres_per_hour': values['metres_per_hour'],
'stopped_hours': stopped,
'stops': stop_list,
'metres_per_roll': values['metres_per_roll'],
'ink_per_100m': values['ink_per_100m'],
'powder_g_per_100m': values['powder_g_per_100m'],
'supplies_cents': supplies_cents,
'parts_cents': parts_cents,
'supplies_per_metre_cents': values['supplies_per_metre_cents'],
'parts_per_metre_cents': values['parts_per_metre_cents'],
'total_per_metre_cents': values['total_per_metre_cents'],
'sold_cents': sold,
'contribution_cents': sold - supplies_cents - parts_cents,
}
def since_installation(c, machine, until):
"""{'from': date, 'contribution_cents', 'parts_cents', 'months': float,
'roi_pct': float|None, 'payback_months': float|None} from installed_on
(else log_since) to `until`."""
mid = machine['id']
if machine['installed_on'] is not None:
from_date = machine['installed_on']
start = datetime.combine(from_date, time.min, tzinfo=SAO_PAULO)
else:
start = machine['log_since'] or datetime.now(SAO_PAULO)
from_date = start.astimezone(SAO_PAULO).date()
sold = sum((_sold(row) for row in _printed_orders(c, mid, start, until)), 0)
cents = lambda kind: int(c.execute('''SELECT COALESCE(sum(cost_cents),0) AS cents
FROM dtf_local.machine_entries WHERE machine_id=%s AND kind=%s
AND created_at>=%s AND created_at<%s''', (mid, kind, start, until)).fetchone()['cents'])
supplies_cents, parts_cents = cents('supply'), cents('part')
contribution = sold - supplies_cents - parts_cents
seconds = (until - start).total_seconds()
months = round(float(Decimal(str(seconds)) / _MONTH_SECONDS), 1) if seconds > 0 else 0.0
values = ratios(0, price_cents=machine['price_cents'], contribution_cents=contribution,
installed_parts_cents=parts_cents, months=months)
return {'from': from_date, 'contribution_cents': contribution, 'parts_cents': parts_cents,
'months': months, 'roi_pct': values['roi_pct'],
'payback_months': values['payback_months']}
def report(c, month=None):
"""{'month': '2026-11', 'machines': [{'id', 'name', 'price_cents',
'installed_on', 'month': machine_month(...), 'total': since_installation(...)}]}
for every machine (active or not) that has entries or printed in the month,
plus every active one."""
start, end = month_bounds(month)
until = min(datetime.now(SAO_PAULO), end)
machines = c.execute('''SELECT id, name, price_cents, installed_on, log_since, active
FROM dtf_local.machines ORDER BY created_at, name''').fetchall()
entered = {str(row['machine_id']) for row in c.execute(
'''SELECT DISTINCT machine_id FROM dtf_local.machine_entries
WHERE created_at>=%s AND created_at<%s''', (start, end)).fetchall()}
printed = {str(row['machine_id']) for row in c.execute(
'''SELECT DISTINCT o.machine_id FROM dtf_local.movements m
JOIN dtf_local.orders o ON o.id=m.order_id
WHERE m.from_state='imp' AND m.to_state='rev' AND NOT m.back
AND m.created_at>=%s AND m.created_at<%s''', (start, end)).fetchall()}
result = []
for machine in machines:
key = str(machine['id'])
if not (machine['active'] or key in entered or key in printed):
continue
result.append({'id': key, 'name': machine['name'], 'price_cents': machine['price_cents'],
'installed_on': machine['installed_on'],
'month': machine_month(c, machine, start, end),
'total': since_installation(c, machine, until)})
return {'month': start.strftime('%Y-%m'), 'machines': result}

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()

View File

@@ -881,6 +881,16 @@ select.inp{appearance:none;-webkit-appearance:none;padding-right:32px;background
.fillbox>.mtiles,.fillbox>.scrollin{position:absolute;inset:0;overflow:auto;margin:0} .fillbox>.mtiles,.fillbox>.scrollin{position:absolute;inset:0;overflow:auto;margin:0}
.fillbox>.mtiles{border-top:1px solid var(--ln);align-content:start} .fillbox>.mtiles{border-top:1px solid var(--ln);align-content:start}
.panel:has(> .fillbox){display:flex;flex-direction:column} .panel:has(> .fillbox){display:flex;flex-direction:column}
/* Máquinas, mês a mês: a fixed panel whose table scrolls both ways, the month
between its arrows and the first column pinned while it scrolls sideways. */
.mnav{display:flex;align-items:center;gap:6px;margin-left:auto}
.mnav b{font-size:13px;font-weight:600;min-width:132px;text-align:center}
.machinebox{height:420px;min-height:0;flex:none}
.machine-month{width:max-content;min-width:100%}
.machine-month tr.group td{font-weight:650;background:var(--sf2)}
.machine-month thead th:first-child,.machine-month tbody tr:not(.group) td:first-child{position:sticky;left:0;z-index:2;background:var(--sf)}
.machine-month thead th:first-child{z-index:3}
#stats-machine-panel .phint{margin-top:-1px}
.cols2.lean{align-items:stretch} .cols2.lean{align-items:stretch}
/* The board fills the window; each column scrolls on its own, its head stays. */ /* The board fills the window; each column scrolls on its own, its head stays. */
#tab-board:not([hidden]){display:flex;flex-direction:column;height:calc(100vh - 72px)} #tab-board:not([hidden]){display:flex;flex-direction:column;height:calc(100vh - 72px)}

View File

@@ -145,6 +145,9 @@
</div> </div>
<section class="panel clip"><div class="phead"><h2>Pedidos sem pagamento</h2><span class="hint" tabindex="0" data-tip="Cotações aprovadas no período, pela data de aprovação. Pagas viraram pedido; expiradas passaram de 24 horas sem pagamento; aguardando ainda podem ser pagas. A taxa de abandono é expiradas sobre pagas mais expiradas."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div> <section class="panel clip"><div class="phead"><h2>Pedidos sem pagamento</h2><span class="hint" tabindex="0" data-tip="Cotações aprovadas no período, pela data de aprovação. Pagas viraram pedido; expiradas passaram de 24 horas sem pagamento; aguardando ainda podem ser pagas. A taxa de abandono é expiradas sobre pagas mais expiradas."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div>
<table class="table"><thead><tr><th scope="col">Indicador</th><th scope="col" class="r">Valor</th></tr></thead><tbody id="stats-unpaid"></tbody></table></section> <table class="table"><thead><tr><th scope="col">Indicador</th><th scope="col" class="r">Valor</th></tr></thead><tbody id="stats-unpaid"></tbody></table></section>
<section class="panel clip" id="stats-machine-panel"><div class="phead"><h2>Máquinas, mês a mês</h2><div class="mnav" id="stats-machine-nav"></div></div>
<div class="fillbox machinebox"><div class="scrollin"><table class="table machine-month"><thead id="stats-machine-head"></thead><tbody id="stats-machine-body"></tbody></table></div></div>
<p class="phint" id="stats-machine-note"></p></section>
<section class="panel clip"><div class="phead"><h2>Velocidade do site e do Prumo</h2><span class="hint tip-l" tabindex="0" data-tip="Média e p95 do que o cliente sente, por pedido pago no período: abrir a página, subir o arquivo (segundos por MB), a conferência do Prumo, a montagem das avulsas, a geração do arquivo final por 10 m e o tempo do evento de pagamento até o card. Referências: página < 3 s; conferência < 30 s; geração < 2 min por 10 m; card em até 1 min."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div> <section class="panel clip"><div class="phead"><h2>Velocidade do site e do Prumo</h2><span class="hint tip-l" tabindex="0" data-tip="Média e p95 do que o cliente sente, por pedido pago no período: abrir a página, subir o arquivo (segundos por MB), a conferência do Prumo, a montagem das avulsas, a geração do arquivo final por 10 m e o tempo do evento de pagamento até o card. Referências: página < 3 s; conferência < 30 s; geração < 2 min por 10 m; card em até 1 min."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div>
<table class="table"><thead><tr><th scope="col">Etapa</th><th scope="col" class="r">Média</th><th scope="col" class="r">p95</th><th scope="col" class="r">Amostras</th></tr></thead><tbody id="stats-speed"></tbody></table></section> <table class="table"><thead><tr><th scope="col">Etapa</th><th scope="col" class="r">Média</th><th scope="col" class="r">p95</th><th scope="col" class="r">Amostras</th></tr></thead><tbody id="stats-speed"></tbody></table></section>
</section> </section>

View File

@@ -3012,6 +3012,8 @@ $('new-machine').onclick=()=>machineForm(null);
// The period: the last 7, 30 or 90 days, or two dates picked on the calendar. // The period: the last 7, 30 or 90 days, or two dates picked on the calendar.
let statsDays=30, statsRange=null, statsData=null; let statsDays=30, statsRange=null, statsData=null;
// The machine block has a month of its own, apart from the period above.
let machineMonth=null, machineStats=null, machineStatsMonth=null;
function duration(hours){ function duration(hours){
if(hours===null||hours===undefined)return '—'; if(hours===null||hours===undefined)return '—';
if(hours<1)return Math.max(1,Math.round(hours*60))+' min'; if(hours<1)return Math.max(1,Math.round(hours*60))+' min';
@@ -3086,7 +3088,94 @@ function calendar(){
document.addEventListener('click',()=>pop.remove(),{once:true}); document.addEventListener('click',()=>pop.remove(),{once:true});
return pop; return pop;
} }
// ---- Máquinas, mês a mês -------------------------------------------------
// This block has its own month: it does not follow the period at the top, so
// it is fetched apart and kept until the month changes.
const MACHINE_MONTHS=['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho',
'Agosto','Setembro','Outubro','Novembro','Dezembro'];
function machineMonthShift(key,delta){
const [year,month]=key.split('-').map(Number),d=new Date(Date.UTC(year,month-1+delta,1));
return d.getUTCFullYear()+'-'+String(d.getUTCMonth()+1).padStart(2,'0');
}
function machineMonthName(key){
const [year,month]=key.split('-').map(Number);
return MACHINE_MONTHS[month-1].toLowerCase()+' de '+year;
}
function machineMonthNav(){
const data=machineStats;if(!data)return;
const current=todayIso().slice(0,7);
const prev=iconButton(IC.left,'Mês anterior',()=>changeMachineMonth(-1));
const next=iconButton(IC.right,'Próximo mês',()=>changeMachineMonth(1));
next.disabled=data.month>=current;
$('stats-machine-nav').replaceChildren(prev,node('b',machineMonthName(data.month)),next);
}
function changeMachineMonth(delta){
const current=todayIso().slice(0,7);
machineMonth=machineMonthShift(machineMonth||current,delta);
if(machineMonth>current)machineMonth=current;
loadMachineStats().catch(e=>say(e.message,true));
}
async function loadMachineStats(){
const month=machineMonth||todayIso().slice(0,7);
if(machineStats&&machineStatsMonth===month){renderMachineStats();return;}
const data=await api('/stats/machines?month='+month);
machineStats=data;machineStatsMonth=month;renderMachineStats();
}
function renderMachineStats(){
const data=machineStats;if(!data)return;
machineMonthNav();
const machines=data.machines,one=v=>v==null?'—':Number(v).toLocaleString('pt-BR',
{minimumFractionDigits:1,maximumFractionDigits:1}),unit=(v,u)=>v==null?'—':one(v)+u,
cash=v=>v==null?'—':money(v);
const head=node('tr');head.append(node('th','Indicador'));
for(const m of machines){const th=node('th',m.name,'r');th.scope='col';head.append(th);}
$('stats-machine-head').replaceChildren(head);
const stopsTitle=m=>(m.month.stops||[]).map(s=>(s.reason||'Parada')+' '+one(s.hours)+' h').join('; ');
const groups=[
['Produção',[
['Metros impressos',m=>m.month.printed_metres==null?'—':metres(m.month.printed_metres)],
['Metros por hora',m=>unit(m.month.metres_per_hour,' m/h')],
['Horas rodando',m=>unit(m.month.hours_running,' h')],
['Horas paradas',m=>unit(m.month.stopped_hours,' h'),stopsTitle]]],
['Consumo',[
['Metros por rolo de filme',m=>unit(m.month.metres_per_roll,' m')],
...['ink_c','ink_m','ink_y','ink_k','ink_w'].map(item=>
['Tinta '+{ink_c:'ciano',ink_m:'magenta',ink_y:'amarela',ink_k:'preta',ink_w:'branca'}[item]+' por 100 m',
m=>unit(m.month.ink_per_100m[item],' L')]),
['Poliamida por 100 m',m=>unit(m.month.powder_g_per_100m,' g')]]],
['Custo',[
['Insumos por metro',m=>cash(m.month.supplies_per_metre_cents)],
['Peças por metro',m=>cash(m.month.parts_per_metre_cents)],
['Total por metro',m=>cash(m.month.total_per_metre_cents)]]],
['Resultado',[
['Vendido',m=>cash(m.month.sold_cents)],
['Contribuição do mês',m=>cash(m.month.contribution_cents)],
['Contribuição desde a instalação',m=>cash(m.total.contribution_cents)]]],
['Retorno',[
['Retorno (%)',m=>m.total.roi_pct==null?'—':one(m.total.roi_pct)+'%'],
['Meses para se pagar',m=>one(m.total.payback_months)]]]];
const body=$('stats-machine-body');
if(!machines.length){body.replaceChildren(emptyRow('Nenhuma máquina com números neste mês.',1));}
else{
const rows=[];
for(const [label,items] of groups){
const group=node('tr',undefined,'group'),cell=node('td',label);cell.colSpan=machines.length+1;
group.append(cell);rows.push(group);
for(const [name,value,title] of items){
const tr=node('tr');tr.append(node('td',name));
for(const m of machines){const td=node('td',value(m),'r'),tip=title&&title(m);if(tip)td.title=tip;tr.append(td);}
rows.push(tr);
}
}
body.replaceChildren(...rows);
}
const missing=machines.some(m=>m.price_cents==null);
$('stats-machine-note').textContent='Os custos vêm dos lançamentos na ficha de cada máquina; '
+'preço e data de instalação vêm de Dados da máquina.'
+(missing?' Sem o preço de compra, o retorno fica em branco.':'');
}
async function loadStats(){ async function loadStats(){
loadMachineStats().catch(e=>say(e.message,true));
const data=await api('/stats?'+(statsRange?'start='+statsRange.start+'&end='+statsRange.end:'days='+statsDays)); const data=await api('/stats?'+(statsRange?'start='+statsRange.start+'&end='+statsRange.end:'days='+statsDays));
const editLimits=$('edit-stage-limits'); const editLimits=$('edit-stage-limits');
if(editLimits){editLimits.hidden=!may('manage');editLimits.onclick=()=>stageLimitsDialog();} if(editLimits){editLimits.hidden=!may('manage');editLimits.onclick=()=>stageLimitsDialog();}