diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index af7ec52..36392df 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -73,7 +73,7 @@ jobs: # one a developer exercises on localhost. - name: API and workflow regressions 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; 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; do echo "--- $suite" $COMPOSE exec -T \ -e SITE_BASE_URL=http://site \ @@ -86,7 +86,7 @@ jobs: # the generator's geometry. The provider suites use a fake transport: they # prove the documented contract, not the integration. - 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 -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 -v - name: Runtime and retention regressions run: | diff --git a/app/api/machine_log.py b/app/api/machine_log.py new file mode 100644 index 0000000..5acb4db --- /dev/null +++ b/app/api/machine_log.py @@ -0,0 +1,119 @@ +"""Routes of the machine sheet (Fase 2, front 1a, app/machine_log.py).""" +from uuid import UUID + +from fastapi import APIRouter, Depends, HTTPException, Request + +from .. import machine_log +from ..core import db +from ..core.auth import audit, can +from ..core.models import MachineEntry, MachineSheet + +router = APIRouter() + + +def machine_row(c, mid): + row = c.execute('SELECT id,name,price_cents,installed_on FROM dtf_local.machines WHERE id=%s', + (mid,)).fetchone() + if not row: + raise HTTPException(404, 'Máquina não encontrada.') + return row + + +def own_machine(request, mid): + """An operator enters only on the machine of their session; management, anywhere.""" + account = request.state.operator + if account['role'] != 'operador': + return + session_machine = account['machine'] + if not session_machine or str(session_machine['id']) != str(mid): + raise HTTPException(403, 'Você só lança na máquina em que está.') + + +def entry_label(row): + if row['kind'] == 'supply': + return machine_log.SUPPLIES.get(row['item'], (row['item'],))[0] + if row['kind'] == 'part': + return machine_log.PARTS.get(row['item'], row['item']) + return machine_log.EVENTS.get(row['item'], row['item']) + + +@router.get('/api/operator/machines/{mid}/sheet') +def sheet(mid: UUID, user=Depends(can('view'))): + with db.connect() as c: + machine = machine_row(c, mid) + entries = c.execute('''SELECT * FROM dtf_local.machine_entries + WHERE machine_id=%s ORDER BY created_at DESC, id DESC LIMIT 50''', (mid,)).fetchall() + minimums = {row['item']: row['minimum'] for row in c.execute( + 'SELECT item,minimum FROM dtf_local.machine_minimums WHERE machine_id=%s', (mid,)).fetchall()} + return {'machine': {'id': str(machine['id']), 'name': machine['name'], + 'price_cents': machine['price_cents'], 'installed_on': machine['installed_on']}, + 'counters': machine_log.counters(c, mid), + 'supplies': machine_log.supply_estimates(c, mid), + 'minimums': minimums, + 'alerts': machine_log.alerts(c, mid), + 'entries': [{**row, 'label': entry_label(row)} for row in entries], + 'catalog': {'supplies': machine_log.SUPPLIES, 'parts': machine_log.PARTS, + 'events': machine_log.EVENTS}} + + +@router.post('/api/operator/machines/{mid}/entries') +def add_entry(mid: UUID, body: MachineEntry, request: Request, user=Depends(can('print'))): + own_machine(request, mid) + catalog = {'supply': machine_log.SUPPLIES, 'part': machine_log.PARTS, + 'event': machine_log.EVENTS}[body.kind] + if body.item not in catalog: + raise HTTPException(422, 'Escolha um item da lista.') + if body.kind == 'supply': + if body.quantity is None: + raise HTTPException(422, 'Informe a quantidade que entrou.') + elif body.kind == 'part': + if body.cost_cents is None: + raise HTTPException(422, 'Informe o custo da peça.') + if body.item == 'other' and not (body.note or '').strip(): + raise HTTPException(422, 'Descreva a outra peça.') + elif body.item == 'stop': + if not (body.note or '').strip() or body.stop_minutes is None: + raise HTTPException(422, 'Informe o motivo e os minutos da parada.') + elif body.quantity is not None or body.cost_cents is not None: + raise HTTPException(422, 'Limpeza e alinhamento não levam quantidade nem custo.') + with db.connect() as c: + machine_row(c, mid) + row = machine_log.add_entry(c, mid, body, user, from_alert=body.from_alert) + audit('machine_entry', operator=user, machine=str(mid), kind=body.kind, item=body.item, + from_alert=body.from_alert) + return row + + +@router.post('/api/operator/machines/{mid}/sheet') +def save_sheet(mid: UUID, body: MachineSheet, user=Depends(can('manage'))): + unknown = set(body.minimums) - set(machine_log.SUPPLIES) + if unknown: + raise HTTPException(422, 'Só os insumos têm mínimo.') + for value in body.minimums.values(): + if value is not None and value < 0: + raise HTTPException(422, 'O mínimo não pode ser negativo.') + with db.connect() as c: + machine_row(c, mid) + c.execute('UPDATE dtf_local.machines SET price_cents=%s, installed_on=%s WHERE id=%s', + (body.price_cents, body.installed_on, mid)) + for item, value in body.minimums.items(): + if value is None: + c.execute('DELETE FROM dtf_local.machine_minimums WHERE machine_id=%s AND item=%s', + (mid, item)) + else: + c.execute('''INSERT INTO dtf_local.machine_minimums(machine_id,item,minimum) + VALUES(%s,%s,%s) ON CONFLICT (machine_id,item) DO UPDATE SET minimum=EXCLUDED.minimum''', + (mid, item, value)) + audit('machine_sheet', operator=user, machine=str(mid), price_cents=body.price_cents, + installed_on=str(body.installed_on) if body.installed_on else None) + return {'ok': True} + + +@router.post('/api/operator/machines/{mid}/alerts/{key}/snooze') +def snooze_alert(mid: UUID, key: str, request: Request, user=Depends(can('print'))): + own_machine(request, mid) + with db.connect() as c: + machine_row(c, mid) + machine_log.snooze(c, mid, key, user) + audit('machine_alert_snoozed', operator=user, machine=str(mid), alert=key) + return {'ok': True} diff --git a/app/api/operator.py b/app/api/operator.py index 6eae8b3..c0206b1 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -18,7 +18,7 @@ from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, MOVERS, audit, can, login_failed, may_move, may_reorder, password_matches, throttle) from ..core.models import Contraction, Move, OperatorLogin, Resolution, Review, StrictModel, UploadStart from ..printjobs import CLAIM_TIMEOUT, file_prefix, queue as queue_print_files -from .. import cnpj, hotfolder, machines, mail, payments, proof, prumo, quote_review, receipt, reviews, unpaid +from .. import cnpj, hotfolder, machine_log, machines, mail, payments, proof, prumo, quote_review, receipt, reviews, unpaid from .. import tiny from ..payments import release_files from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES, @@ -1147,6 +1147,11 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)): raise HTTPException(409, 'Essa máquina não existe mais ou está desativada.') if machines.product_family(row) not in target['products']: raise HTTPException(409, f"A {target['name']} não imprime este produto.") + # The machine's sheet speaks between one file and the next, never in + # the middle: a blocking alert stops this card here (app/machine_log.py). + blocking = [alert for alert in machine_log.alerts(c, chosen) if alert['blocking']] + if blocking: + raise HTTPException(409, 'Antes do próximo arquivo: ' + blocking[0]['text']) linked = c.execute('''SELECT machine_id FROM dtf_local.orders WHERE parent_id=%s AND proof_result='ok' AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (uid,)).fetchone() if linked and linked['machine_id'] and chosen != linked['machine_id']: diff --git a/app/app.py b/app/app.py index fd7b2af..cbdd6cb 100644 --- a/app/app.py +++ b/app/app.py @@ -13,7 +13,7 @@ from starlette.middleware.trustedhost import TrustedHostMiddleware from .core import db from .core.auth import audit, client_ip from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage -from .api import artwork, customer, health, operator, orders, payments, quotes, reviews, site_videos, uploads, users +from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, site_videos, uploads, users @asynccontextmanager @@ -45,5 +45,5 @@ async def safe_headers(request, call_next): # Order is not significant: no two routers declare the same path. -for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, reviews): +for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, reviews, machine_log): app.include_router(module.router) diff --git a/app/core/models.py b/app/core/models.py index 24e9e81..b213c39 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -1,4 +1,5 @@ import re +from datetime import date from decimal import Decimal from typing import Literal from uuid import UUID @@ -332,6 +333,25 @@ class Move(StrictModel): # Pulled into Imprimindo onto a machine's lane: the machine it prints on. machine_id: UUID | None = None +class MachineEntry(StrictModel): + """One thing entered into a machine (Fase 2, front 1a, app/machine_log.py).""" + kind: Literal['supply', 'part', 'event'] + item: str = Field(min_length=1, max_length=40) + quantity: Decimal | None = Field(default=None, gt=0, le=999999, decimal_places=3) + cost_cents: int | None = Field(default=None, ge=0, le=10**12, strict=True) + serial: str | None = Field(default=None, max_length=200) + note: str | None = Field(default=None, max_length=1000) + stop_minutes: int | None = Field(default=None, gt=0, le=100000, strict=True) + from_alert: bool = False + + +class MachineSheet(StrictModel): + """The machine's own data, typed by Gestão: cost, start and supply minimums.""" + price_cents: int | None = Field(default=None, ge=0, le=10**12, strict=True) + installed_on: date | None = None + minimums: dict[str, Decimal | None] = Field(default_factory=dict) + + class Contraction(StrictModel): item_index: int = Field(ge=0, le=100) # None returns the item to the class the browser measured. diff --git a/app/machine_log.py b/app/machine_log.py new file mode 100644 index 0000000..8d8634d --- /dev/null +++ b/app/machine_log.py @@ -0,0 +1,250 @@ +"""Each machine's sheet: supplies, parts, events, counters and alerts +(Fase 2, front 1, part a; the Números block per machine is part b). + +The room enters what goes into a machine with one click on its card: a +supply (film roll, ink by colour, powder) with its quantity and lot cost, +a part (cap, damper, head, wiper, other) with its cost and serial, or an +event (cleaned, aligned the head, a stop with its reason and minutes). The +Kanban already knows what each machine printed; with what goes in, it knows +what it uses. + +Alerts appear on the machine's computer between one file and the next, +never in the middle: when someone on that machine pulls the next card into +Imprimindo. They are marked done (which records the event) or postponed +once, which lets exactly one more card through. + + clean CLEAN_EVERY_METRES printed since the last "clean" event. + align ALIGN_AFTER_FILM_METRES printed since the last film change (a + supply entry of "film") with no "align" event after it. + supply a supply whose estimated stock is at or below the minimum Gestão set + for that machine (no minimum, no alert). + +The supply estimate assumes each entry refills what was used since the one +before: the use per metre is the quantity entered over the metres printed in +that interval, averaged over the last SUPPLY_INTERVALS intervals; the stock is +the average refill minus that use times the metres printed since the last +entry. Fewer than two entries, no estimate. + +"Printed" is what left Imprimindo for Revisão on the machine (orders.machine_id, +the movement imp -> rev not back): the film metres of the items +(COALESCE(metres, billed_metres)), and PROOF_SHEET_CM per item for a proof card. +""" +from datetime import datetime, timezone +from decimal import Decimal + +CLEAN_EVERY_METRES = Decimal('10') +ALIGN_AFTER_FILM_METRES = Decimal('20') +SUPPLY_INTERVALS = 3 +# item -> (Portuguese label, unit shown). Supplies are counted in rolls, +# litres and kilograms; Números shows ink per 100 m and powder in grams. +SUPPLIES = {'film': ('Filme', 'rolo'), 'ink_c': ('Tinta ciano', 'L'), 'ink_m': ('Tinta magenta', 'L'), + 'ink_y': ('Tinta amarela', 'L'), 'ink_k': ('Tinta preta', 'L'), 'ink_w': ('Tinta branca', 'L'), + 'powder': ('Poliamida', 'kg')} +PARTS = {'cap': 'Cap', 'damper': 'Damper', 'head': 'Cabeça de impressão', 'wiper': 'Wiper', 'other': 'Outra peça'} +EVENTS = {'clean': 'Limpeza', 'align': 'Alinhamento da cabeça', 'stop': 'Parada'} + +# A cycle with no resetting event still needs a value the snooze row can key on. +_EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc) + + +def one_decimal(value): + """One decimal place with the Brazilian comma, as the alert lines show it.""" + return f'{Decimal(str(value)):.1f}'.replace('.', ',') + + +def printed_since(c, machine_id, since): + """Film metres the machine printed after `since` (None: ever), as Decimal.""" + from .proof import PROOF_SHEET_CM + rows = c.execute('''SELECT o.snapshot 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 (%s::timestamptz IS NULL OR m.created_at > %s::timestamptz)''', + (machine_id, since, since)).fetchall() + total = Decimal(0) + for row in rows: + snapshot = row['snapshot'] or {} + proof = bool(snapshot.get('proof_of')) + 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 _last_entry(c, machine_id, kind, item): + return c.execute('''SELECT * FROM dtf_local.machine_entries + WHERE machine_id=%s AND kind=%s AND item=%s + ORDER BY created_at DESC, id DESC LIMIT 1''', (machine_id, kind, item)).fetchone() + + +def counters(c, machine_id): + """{'clean': {'metres': Decimal, 'since': datetime|None}, + 'film': {'metres': Decimal, 'since': datetime|None, 'aligned': bool}}""" + clean = _last_entry(c, machine_id, 'event', 'clean') + film = _last_entry(c, machine_id, 'supply', 'film') + clean_since = clean['created_at'] if clean else None + # No cleaning on record yet: count from when the sheet started, or every + # machine would ask for one on the day this went live. + start = c.execute('SELECT log_since FROM dtf_local.machines WHERE id=%s', (machine_id,)).fetchone() + film_since = film['created_at'] if film else None + aligned = False + if film: + aligned = c.execute('''SELECT 1 FROM dtf_local.machine_entries + WHERE machine_id=%s AND kind='event' AND item='align' AND created_at>=%s LIMIT 1''', + (machine_id, film_since)).fetchone() is not None + return {'clean': {'metres': printed_since(c, machine_id, clean_since or (start or {}).get('log_since')), + 'since': clean_since}, + 'film': {'metres': printed_since(c, machine_id, film_since or (start or {}).get('log_since')), + 'since': film_since, + 'aligned': aligned}} + + +def estimate(entries, metres_between, metres_since_last, minimum=None): + """The supply estimate from simple lists, so it is tested without a database. + + `entries` are the quantities entered, oldest first; `metres_between[i]` is + the film printed between entry i and entry i+1; `metres_since_last` is the + film printed since the last entry. None with fewer than two entries or when + no interval had film printed (nothing to divide by). + """ + quantities = [Decimal(str(value)) for value in entries] + if len(quantities) < 2: + return None + uses, refills = [], [] + for quantity, metres in list(zip(quantities[1:], metres_between))[-SUPPLY_INTERVALS:]: + metres = Decimal(str(metres)) + if metres <= 0: + continue + uses.append(quantity / metres) + refills.append(quantity) + if not uses: + return None + per_metre = sum(uses, Decimal(0)) / len(uses) + refill = sum(refills, Decimal(0)) / len(refills) + stock = refill - per_metre * Decimal(str(metres_since_last)) + return {'per_metre': per_metre, 'stock': stock, 'metres_left': stock / per_metre, + 'minimum': minimum} + + +def supply_low(value): + """Whether an estimate is at or below the machine's minimum (no minimum, no alert).""" + return bool(value) and value['minimum'] is not None and value['stock'] <= value['minimum'] + + +def supply_estimates(c, machine_id): + """{item: {'per_metre': Decimal, 'stock': Decimal, 'metres_left': Decimal, + 'minimum': Decimal|None}} for the supplies with an estimate (see module doc).""" + minimums = {row['item']: row['minimum'] for row in c.execute( + 'SELECT item,minimum FROM dtf_local.machine_minimums WHERE machine_id=%s', (machine_id,)).fetchall()} + result = {} + for item in SUPPLIES: + # Only the entries the estimate uses: the board asks for it on every refresh. + rows = c.execute('''SELECT quantity, created_at FROM (SELECT quantity, created_at, id + FROM dtf_local.machine_entries WHERE machine_id=%s AND kind='supply' AND item=%s + ORDER BY created_at DESC, id DESC LIMIT %s) last ORDER BY created_at, id''', + (machine_id, item, SUPPLY_INTERVALS + 1)).fetchall() + if len(rows) < 2: + continue + printed = [printed_since(c, machine_id, row['created_at']) for row in rows] + between = [printed[index - 1] - printed[index] for index in range(1, len(printed))] + value = estimate([row['quantity'] for row in rows], between, printed[-1], minimums.get(item)) + if value is not None: + result[item] = value + return result + + +def alerts(c, machine_id): + """The alerts due on this machine now, each {'key': 'clean' | 'align' | + 'supply:', 'text': Portuguese line, 'cycle_from': datetime|None, + 'snoozable': bool, 'blocking': bool}. blocking is False when it was + postponed this cycle and no card was pulled on the machine since. + Texts, with metres in one decimal and a comma: + clean ": 10,4 m desde a última limpeza — limpe antes do próximo arquivo" + align ": 19,8 m desde a troca de filme — alinhe a cabeça antes do próximo" + supply "