feat: each machine's sheet, counters and alerts (front 1a)
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 6m20s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m11s

The machine's name in Imprimindo (and "Ficha" in Usuários › Máquinas)
opens its sheet: metres since the last cleaning and since the last film
change, each supply's estimate, pending alerts and the entries. The room
enters supplies (film, ink by colour, powder; a supply without cost
takes the last one), parts (cap, damper, head, wiper, other) and events
(cleaning, head alignment, a stop with reason and minutes). Gestão types
the price, installation date and supply minimums.

Alerts appear when someone pulls the next card onto the machine, never
mid-print: 10 m since the last cleaning, 20 m after a film change
without aligning the head, and a supply at its minimum. Marked done it
records the event; postponed once it lets one more card through. The
server refuses the pull otherwise. Counters start when the sheet went
live (machines.log_since), not from everything printed before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-09 12:19:31 -03:00
parent b280e0cfa6
commit 29518795a5
12 changed files with 915 additions and 11 deletions

View File

@@ -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: |

119
app/api/machine_log.py Normal file
View File

@@ -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}

View File

@@ -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']:

View File

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

View File

@@ -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.

250
app/machine_log.py Normal file
View File

@@ -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:<item>', '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 "<máquina>: 10,4 m desde a última limpeza — limpe antes do próximo arquivo"
align "<máquina>: 19,8 m desde a troca de filme — alinhe a cabeça antes do próximo"
supply "<label minúsculo> da <máquina> deve acabar em ~3 m" (e.g. "tinta branca da máquina2 deve acabar em ~3,0 m")
"""
machine = c.execute('SELECT name FROM dtf_local.machines WHERE id=%s', (machine_id,)).fetchone()
if not machine:
return []
name = machine['name']
counts = counters(c, machine_id)
supplies = supply_estimates(c, machine_id)
result = []
def postponed(key, cycle):
return c.execute('''SELECT snoozed_at FROM dtf_local.machine_snoozes
WHERE machine_id=%s AND alert=%s AND cycle_from=%s''',
(machine_id, key, cycle or _EPOCH)).fetchone()
def pulled_since(moment):
return c.execute('''SELECT 1 FROM dtf_local.movements m
JOIN dtf_local.orders o ON o.id=m.order_id
WHERE o.machine_id=%s AND m.to_state='imp' AND NOT m.back AND m.created_at>%s LIMIT 1''',
(machine_id, moment)).fetchone() is not None
def due(key, text, cycle):
snooze = postponed(key, cycle)
blocking = not (snooze and not pulled_since(snooze['snoozed_at']))
result.append({'key': key, 'text': text, 'cycle_from': cycle,
'snoozable': snooze is None, 'blocking': blocking})
if counts['clean']['metres'] >= CLEAN_EVERY_METRES:
due('clean', f"{name}: {one_decimal(counts['clean']['metres'])} m desde a última limpeza "
'— limpe antes do próximo arquivo', counts['clean']['since'])
if (counts['film']['since'] is not None and not counts['film']['aligned']
and counts['film']['metres'] >= ALIGN_AFTER_FILM_METRES):
due('align', f"{name}: {one_decimal(counts['film']['metres'])} m desde a troca de filme "
'— alinhe a cabeça antes do próximo', counts['film']['since'])
for item, value in supplies.items():
if not supply_low(value):
continue
last = _last_entry(c, machine_id, 'supply', item)
due('supply:' + item, f"{SUPPLIES[item][0].lower()} da {name} deve acabar em "
f"~{one_decimal(value['metres_left'])} m", last['created_at'] if last else None)
return result
def _field(body, name, default=None):
return body.get(name, default) if isinstance(body, dict) else getattr(body, name, default)
def add_entry(c, machine_id, body, user, from_alert=False):
"""Record one entry. A supply without cost takes the cost of that item's
last entry on the machine. Returns the row."""
kind = _field(body, 'kind')
item = _field(body, 'item')
cost = _field(body, 'cost_cents')
if kind == 'supply' and cost is None:
last = c.execute('''SELECT cost_cents FROM dtf_local.machine_entries
WHERE machine_id=%s AND kind='supply' AND item=%s AND cost_cents IS NOT NULL
ORDER BY created_at DESC, id DESC LIMIT 1''', (machine_id, item)).fetchone()
if last:
cost = last['cost_cents']
quantity = _field(body, 'quantity') if kind == 'supply' else None
stop_minutes = _field(body, 'stop_minutes') if kind == 'event' and item == 'stop' else None
return c.execute('''INSERT INTO dtf_local.machine_entries
(machine_id,kind,item,quantity,cost_cents,serial,note,stop_minutes,from_alert,created_by)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING *''',
(machine_id, kind, item, quantity, cost if kind in ('supply', 'part') else None,
_field(body, 'serial') if kind == 'part' else None, _field(body, 'note'),
stop_minutes, from_alert, user)).fetchone()
def snooze(c, machine_id, key, user):
"""Postpone an alert once per cycle; a second time in the same cycle is 409."""
from fastapi import HTTPException
current = next((alert for alert in alerts(c, machine_id) if alert['key'] == key), None)
if current is None:
raise HTTPException(409, 'Este aviso não está pendente.')
if not current['snoozable']:
raise HTTPException(409, 'Este aviso já foi adiado neste ciclo.')
row = c.execute('''INSERT INTO dtf_local.machine_snoozes(machine_id,alert,cycle_from,snoozed_by)
VALUES(%s,%s,%s,%s) ON CONFLICT (machine_id,alert,cycle_from) DO NOTHING RETURNING *''',
(machine_id, key, current['cycle_from'] or _EPOCH, user)).fetchone()
if not row:
raise HTTPException(409, 'Este aviso já foi adiado neste ciclo.')
return row

View File

@@ -1,6 +1,8 @@
"""The print machines, their load and the two printing places on each one."""
from decimal import Decimal
from . import machine_log
# Not finished: the work still ahead of a machine.
OPEN = ('rec', 'tra', 'imp', 'cor')
# Two orders at most in Imprimindo per machine (Dropstar, 2026-10-29): one
@@ -52,7 +54,8 @@ def rows(c, with_operators=False):
used = load.get(key, {'metres': Decimal(0), 'orders': 0, 'states': {}})
row = {'id': key, 'name': m['name'], 'products': m['products'], 'active': m['active'],
'limit_metres': float(m['limit_metres']) if m['limit_metres'] is not None else None,
'open_metres': float(used['metres']), 'open_orders': used['orders'], 'states': used['states']}
'open_metres': float(used['metres']), 'open_orders': used['orders'], 'states': used['states'],
'alerts': machine_log.alerts(c, m['id'])}
if with_operators:
row['operators'] = operators.get(key, [])
result.append(row)

View File

@@ -546,3 +546,38 @@ CREATE TABLE IF NOT EXISTS dtf_local.order_reviews (
UNIQUE(order_id, seq)
);
CREATE INDEX IF NOT EXISTS order_reviews_order ON dtf_local.order_reviews(order_id);
-- Each machine's sheet (Fase 2, front 1, app/machine_log.py): what it cost and
-- when it started, typed once by Gestão; what goes into it, entered by the
-- room; and the minimum of each supply that raises the alert.
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS price_cents bigint CHECK (price_cents >= 0);
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS installed_on date;
-- When the counters start: a machine with no cleaning on record counts from
-- here, not from everything it printed before the sheet existed.
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS log_since timestamptz NOT NULL DEFAULT now();
CREATE TABLE IF NOT EXISTS dtf_local.machine_entries (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
machine_id uuid NOT NULL REFERENCES dtf_local.machines(id) ON DELETE CASCADE,
kind text NOT NULL CHECK(kind IN ('supply','part','event')),
item text NOT NULL,
quantity numeric(12,3) CHECK (quantity > 0),
cost_cents bigint CHECK (cost_cents >= 0),
serial text, note text,
stop_minutes integer CHECK (stop_minutes > 0),
from_alert boolean NOT NULL DEFAULT false,
created_by text NOT NULL, created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS machine_entries_machine ON dtf_local.machine_entries(machine_id, created_at);
CREATE TABLE IF NOT EXISTS dtf_local.machine_minimums (
machine_id uuid NOT NULL REFERENCES dtf_local.machines(id) ON DELETE CASCADE,
item text NOT NULL, minimum numeric(12,3) NOT NULL CHECK (minimum >= 0),
PRIMARY KEY(machine_id, item)
);
-- "Adiar uma vez": an alert postponed lets one more card be pulled, once per
-- cycle (the cycle starts at the event that resets its counter).
CREATE TABLE IF NOT EXISTS dtf_local.machine_snoozes (
machine_id uuid NOT NULL REFERENCES dtf_local.machines(id) ON DELETE CASCADE,
alert text NOT NULL, cycle_from timestamptz NOT NULL,
snoozed_by text NOT NULL, snoozed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY(machine_id, alert, cycle_from)
);

122
tests/machine_log_test.py Normal file
View File

@@ -0,0 +1,122 @@
"""The machine sheet against the local stack (Fase 2, front 1a).
Run inside the API container: python -m tests.machine_log_test
"""
from uuid import uuid4
from app.core import db
from tests.smoke_test import Client
from tests.users_test import PASSWORD, order_fixture
def final_stub(c, oid, owner):
uid = uuid4()
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state) VALUES(%s,%s,'machine-log-test.png',1,%s,'',true,now()+interval '1 day','clean')''',
(uid, owner, f'machine-log-test/{uid}'))
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
VALUES(%s,%s,%s,0,'final','machine log test','test')''', (uuid4(), oid, uid))
def run():
su = Client()
su.call('/session')
tag = uuid4().hex[:6]
machine = su.call('/operator/machines', {'name': f'Ficha {tag}', 'products': ['textil']},
operator=True)['id']
other = su.call('/operator/machines', {'name': f'Outra {tag}', 'products': ['textil']},
operator=True)['id']
email = f'ficha-{tag}@example.test'
su.call('/operator/users', {'name': 'Ficha', '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()
# A clean starts the cycle, then two sheets leave Imprimindo for Revisão:
# 12 m since the last clean, above the 10 m limit.
op.call(f'/operator/machines/{machine}/entries', {'kind': 'event', 'item': 'clean'})
printed = []
with db.connect() as c:
for _ in range(2):
_, oid = order_fixture(c, owner, 'file', metres='6')
c.execute("UPDATE dtf_local.orders SET state='imp', machine_id=%s WHERE id=%s", (machine, oid))
printed.append(str(oid))
for oid in printed:
op.call(f'/operator/orders/{oid}/move', {'state': 'rev', 'version': 0})
board = op.call('/operator/board')
row = next(m for m in board['machines'] if m['id'] == machine)
clean = [a for a in row['alerts'] if a['key'] == 'clean']
assert clean and clean[0]['blocking'], row['alerts']
assert clean[0]['text'].endswith('limpe antes do próximo arquivo'), clean[0]
# The next card into Imprimindo is refused before the server moves it.
with db.connect() as c:
_, first = order_fixture(c, owner, 'file')
final_stub(c, first, owner)
c.execute("UPDATE dtf_local.orders SET state='tra' WHERE id=%s", (first,))
refused = op.call(f'/operator/orders/{first}/move', {'state': 'imp', 'version': 0}, expected=409)
assert refused['detail'].startswith('Antes do próximo arquivo: '), refused
# "Adiar uma vez" lets exactly one card through; the next is refused again,
# and the same alert cannot be postponed twice in one cycle.
op.call(f'/operator/machines/{machine}/alerts/clean/snooze', {})
op.call(f'/operator/orders/{first}/move', {'state': 'imp', 'version': 0})
with db.connect() as c:
_, second = order_fixture(c, owner, 'file')
final_stub(c, second, owner)
c.execute("UPDATE dtf_local.orders SET state='tra' WHERE id=%s", (second,))
refused = op.call(f'/operator/orders/{second}/move', {'state': 'imp', 'version': 0}, expected=409)
assert 'Antes do próximo arquivo' in refused['detail'], refused
op.call(f'/operator/machines/{machine}/alerts/clean/snooze', {}, expected=409)
# Recording the clean resets the counter and releases the queue.
op.call(f'/operator/machines/{machine}/entries', {'kind': 'event', 'item': 'clean', 'from_alert': True})
sheet = op.call(f'/operator/machines/{machine}/sheet')
assert float(sheet['counters']['clean']['metres']) == 0, sheet['counters']
assert not [a for a in sheet['alerts'] if a['key'] == 'clean'], sheet['alerts']
op.call(f'/operator/orders/{second}/move', {'state': 'imp', 'version': 0})
# A supply without cost inherits the last cost of that same item.
first_supply = op.call(f'/operator/machines/{machine}/entries',
{'kind': 'supply', 'item': 'ink_w', 'quantity': 1, 'cost_cents': 18000})
assert first_supply['cost_cents'] == 18000, first_supply
second_supply = op.call(f'/operator/machines/{machine}/entries',
{'kind': 'supply', 'item': 'ink_w', 'quantity': 0.5})
assert second_supply['cost_cents'] == 18000, second_supply
# An operator enters only on the machine of their session; Gestão anywhere.
op.call(f'/operator/machines/{other}/entries', {'kind': 'event', 'item': 'clean'}, expected=403)
gestao_email = f'gestao-{tag}@example.test'
su.call('/operator/users', {'name': 'Gestão', 'email': gestao_email, 'role': 'gestao',
'password': PASSWORD}, operator=True)
gestao = Client()
gestao.call('/session')
gestao.call('/operator/login', {'email': gestao_email, 'password': PASSWORD})
ges = gestao.call(f'/operator/machines/{other}/entries',
{'kind': 'supply', 'item': 'film', 'quantity': 1, 'cost_cents': 0})
assert ges['cost_cents'] == 0, ges
# Preço, data e mínimos are saved and the sheet returns them.
su.call(f'/operator/machines/{machine}/sheet',
{'price_cents': 1234500, 'installed_on': '2026-01-15', 'minimums': {'ink_w': 5}},
operator=True)
sheet = op.call(f'/operator/machines/{machine}/sheet')
assert sheet['machine']['price_cents'] == 1234500, sheet['machine']
assert sheet['machine']['installed_on'] == '2026-01-15', sheet['machine']
assert float(sheet['minimums']['ink_w']) == 5, sheet['minimums']
assert sheet['catalog']['supplies']['ink_w'] == ['Tinta branca', 'L'], sheet['catalog']
su.call(f'/operator/machines/{machine}/sheet',
{'price_cents': 1234500, 'installed_on': '2026-01-15', 'minimums': {'ink_w': None}},
operator=True)
assert 'ink_w' not in op.call(f'/operator/machines/{machine}/sheet')['minimums']
print('PASS: clean alert blocks and releases the pull, one snooze per cycle, '
'supply cost inheritance, operator scope and the machine data')
if __name__ == '__main__':
run()

50
tests/test_machine_log.py Normal file
View File

@@ -0,0 +1,50 @@
"""The machine sheet's pure calculations (Fase 2, front 1a), without a database."""
import unittest
from decimal import Decimal
from app.machine_log import (ALIGN_AFTER_FILM_METRES, CLEAN_EVERY_METRES, estimate,
one_decimal, supply_low)
class EstimateTest(unittest.TestCase):
def test_two_entries_give_an_estimate(self):
value = estimate([Decimal('1'), Decimal('2')], [Decimal('10')], Decimal('5'), Decimal('0.5'))
self.assertEqual(value['per_metre'], Decimal('0.2'))
self.assertEqual(value['stock'], Decimal('1.0'))
self.assertEqual(value['metres_left'], Decimal('5'))
self.assertEqual(value['minimum'], Decimal('0.5'))
self.assertFalse(supply_low(value))
def test_one_entry_has_no_estimate(self):
self.assertIsNone(estimate([Decimal('1')], [], Decimal('10'), None))
def test_an_interval_without_film_has_no_estimate(self):
self.assertIsNone(estimate([Decimal('1'), Decimal('1')], [Decimal('0')], Decimal('0'), None))
def test_the_minimum_reached_is_an_alert(self):
# 0.1 per metre, one litre refilled on average, nine metres later:
# 0.1 L left, below the machine's 1.5 L minimum.
value = estimate([Decimal('1'), Decimal('1')], [Decimal('10')], Decimal('9'), Decimal('1.5'))
self.assertEqual(value['stock'], Decimal('0.1'))
self.assertTrue(supply_low(value))
def test_only_the_last_intervals_are_averaged(self):
# Four intervals; SUPPLY_INTERVALS is three, so the 100 m one is ignored.
value = estimate([Decimal('1'), Decimal('1'), Decimal('3'), Decimal('3'), Decimal('3')],
[Decimal('100'), Decimal('10'), Decimal('10'), Decimal('10')], Decimal('0'), None)
self.assertEqual(value['per_metre'], Decimal('0.3'))
def test_the_thresholds_are_the_documented_ones(self):
self.assertEqual(CLEAN_EVERY_METRES, Decimal('10'))
self.assertEqual(ALIGN_AFTER_FILM_METRES, Decimal('20'))
class AlertTextTest(unittest.TestCase):
def test_one_decimal_uses_a_comma(self):
self.assertEqual(one_decimal(Decimal('10.44')), '10,4')
self.assertEqual(one_decimal(Decimal('3')), '3,0')
self.assertEqual(one_decimal(Decimal('19.86')), '19,9')
if __name__ == '__main__':
unittest.main()

View File

@@ -255,6 +255,9 @@ main{padding:0}
.lanehead b{font-weight:650;color:var(--tx);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.lanehead span{margin-left:auto;color:var(--tx3);white-space:nowrap}
.lanehead.mine,.lanehead.mine b,.lanehead.mine span{color:var(--mine)}
/* The machine's head opens its sheet; a due alert shows a warning dot. */
.lanehead[role="button"]{cursor:pointer}
.lanealert{width:8px;height:8px;flex:none;border-radius:999px;background:var(--warn)}
.lanehead+.card{margin-top:-2px}
.card+.lanehead,.freeslot+.lanehead{margin-top:8px}
.freeslot{display:flex;align-items:center;justify-content:center;gap:9px;min-height:46px;padding:8px 14px;border:1.5px dashed var(--ln2);border-radius:11px;font-size:12.5px;color:var(--tx3);text-align:center}
@@ -503,6 +506,7 @@ main{padding:0}
.dlghead p{margin:6px 0 0;color:var(--tx2);font-size:14px}
.dlghead .btn.sq{margin-top:-4px;margin-right:-8px}
.fld{display:flex;flex-direction:column;gap:7px;font-size:13px;font-weight:600;color:var(--tx2)}
.fld[hidden]{display:none}
.fld input,.fld select,.fld textarea,.fact select,.decide input,.inp{height:42px;padding:0 12px;border-radius:9px;border:1px solid var(--ln2);background:var(--bg);font-size:14px;font-weight:500;color:var(--tx);outline:none;font-family:inherit;width:100%}
.fld textarea{height:96px;padding:10px 12px;resize:vertical}
.fld input:focus,.fld select:focus,.fld textarea:focus,.fact select:focus,.decide input:focus,.inp:focus{border-color:var(--acc);box-shadow:0 0 0 3px color-mix(in srgb,var(--acc) 18%,transparent)}
@@ -853,6 +857,13 @@ select.inp{appearance:none;-webkit-appearance:none;padding-right:32px;background
.modal .mli{display:flex;align-items:center;gap:12px;padding:10px 14px;border-bottom:1px solid var(--ln)}
.modal .mli:last-child{border-bottom:0}
.modal .mli .grow{flex:1;min-width:0}
/* The machine sheet: entries scroll inside a fixed height, alerts are rows. */
.sheetentries{height:240px;overflow:auto}
.sheetalert{display:flex;align-items:flex-start;gap:10px;padding:10px 0;border-bottom:1px solid var(--ln);font-size:13.5px}
.sheetalert:last-child{border-bottom:0}
.sheetalert .grow{flex:1;min-width:0}
.sheetalert .grow b{display:block;font-weight:600;color:var(--tx)}
.sheetalert .grow .sub{font-size:12.5px;color:var(--tx3)}
#payments .table td .who{gap:10px}
/* Lists never change the page's size: a panel keeps its height and its

View File

@@ -167,6 +167,8 @@ function gradePill(grade){
const lowestGrade=items=>{const g=items.map(i=>Number(i.grade)).filter(Number.isFinite);return g.length?Math.min(...g):null;};
function badge(text,tone='',title=''){const b=node('span',text,'pill '+tone);if(title)b.title=title;return b;}
const cm=v=>Number(v).toLocaleString('pt-BR',{maximumFractionDigits:1});
// The machine sheet shows metres with one decimal even when it is a round number.
const m1=v=>Number(v).toLocaleString('pt-BR',{minimumFractionDigits:1,maximumFractionDigits:1});
const plural=(n,one,many)=>n+' '+(n===1?one:many);
// The customer's CPF or CNPJ, formatted, and which of the two it is.
function cnpj(value){const d=String(value||'').replace(/\D/g,'');return d.length===14?d.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/,'$1.$2.$3/$4-$5'):d.length===11?d.replace(/^(\d{3})(\d{3})(\d{3})(\d{2})$/,'$1.$2.$3-$4'):String(value||'');}
@@ -939,7 +941,7 @@ function renderBoard(){
const machine=state==='imp'?laneAt(column,e.clientY):null;markLane(column,null);
if(!order)return;
try{
if(order.state!==state)await move(order,state,'',machine);
if(order.state!==state)await (state==='imp'?pullTo(order,machine):move(order,state,'',machine));
else if(state!=='fin')await reorder(order,column,e.clientY);
}catch(error){say(error.message,true);}
finally{clearDrop();}};
@@ -972,8 +974,17 @@ function printingLanes(orders){
const n=filtered?here.length:Math.max(m.states?.imp||0,here.length);
const lane=node('div',undefined,'lanehead'+(m.id===mine?' mine':''));lane.dataset.machine=m.id;
const load=n>cap?'acima do limite':n>=cap?'cheia':plural(cap-n,'vaga','vagas');
lane.append(svgIcon(IC.printer,'i s'),node('b',m.name),node('span',(m.id===mine?'sua máquina · ':'')+load));
lane.append(svgIcon(IC.printer,'i s'),node('b',m.name));
// The machine's sheet opens here; an alert due shows a warning dot with its text.
const alerts=m.alerts||[];
if(alerts.length){const mark=node('i',undefined,'lanealert');mark.title=alerts.map(a=>a.text).join(' · ');
mark.setAttribute('aria-hidden','true');lane.append(mark);}
lane.append(node('span',(m.id===mine?'sua máquina · ':'')+load));
lane.title=m.name+' · '+n+' de '+cap+(n>=cap?' · cheia: abre vaga quando um pedido sair de Imprimindo':'');
lane.tabIndex=0;lane.setAttribute('role','button');lane.setAttribute('aria-label','Ficha da '+m.name);
const openSheet=()=>openMachineSheet(m.id);
lane.onclick=openSheet;
lane.onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();openSheet();}};
out.push(lane,...here.map(o=>{const c=card(o);c.dataset.machine=m.id;return c;}));
if(!filtered&&n<cap){
const slot=node('div',undefined,'freeslot');slot.dataset.machine=m.id;
@@ -1601,7 +1612,10 @@ function nextBox(order){
let title='';const body=[],main=[],more=[];
const note=text=>body.push(node('p',text,'nnote'));
const can=to=>mayMove(st,to)&&mayAct(order);
const moveBtn=(to,label,className='btn pri lg')=>{const b=button(label||'Mover para '+board.states[to],()=>move(order,to),className);b.dataset.move=to;return b;};
const moveBtn=(to,label,className='btn pri lg')=>{
// Pulling to a machine goes through the sheet's alerts first (front 1a).
const fn=to==='imp'?()=>pullTo(order,order.machine?.id||myMachine()?.id||null):()=>move(order,to);
const b=button(label||'Mover para '+board.states[to],fn,className);b.dataset.move=to;return b;};
if(waitingProof(order)){
title='Aguardando prova do #'+order.proof_card.number;
const manual=(board.orders.find(o=>o.id===order.proof_card.id)?.print_files||[]).some(r=>r.status==='manual');
@@ -2555,7 +2569,7 @@ function avatar(u,className='ava'){
// "O que cada perfil faz": Y does it, V only looks; the server's rules (app/core/auth.py).
const ROLE_COLUMNS=['admin','gestao','designer','operador','revisor','vendedor','financeiro'];
const ROLE_MATRIX=[['Aprovar o arquivo final','YYYNNNN'],['Pedir correção','YYYNNNN'],['Puxar da fila e imprimir','YNNYNNN'],
['Liberar para Finalizado','YNNNYNN'],['Foto da revisão','YYNNYNN'],['Voltar uma etapa, com motivo','YYYYYNN'],['Marcar retirado','YYYYYNN'],
['Lançar na ficha da máquina','YYNYNNN'],['Liberar para Finalizado','YNNNYNN'],['Foto da revisão','YYNNYNN'],['Voltar uma etapa, com motivo','YYYYYNN'],['Marcar retirado','YYYYYNN'],
['Cotações e Números','YYNNNVV'],['Pagamentos','YYNNNNV'],['Pedido pago fora do site','YYNNNNN'],['Prova OK ou reprovada','YYNNNYN'],['Cancelar pedido','YYNNNNY'],
['Abrir retrabalho','NYNNNNN'],['Autorizar retrabalho','YNNNNNN'],['Usuários e máquinas','YNNNNNN']];
let usersData=null;
@@ -2608,7 +2622,7 @@ function machineTile(m){
const head=node('div',undefined,'row');
head.append(node('h3',m.name),node('span',m.products.map(p=>PRODUCT_LABEL[p]).join(' e ')||'Nenhum produto','lbl'));
if(!m.active)head.append(badge('Desativada',''));
head.append(button('Editar',()=>machineForm(m),'btn ghost right'));
head.append(button('Ficha',()=>openMachineSheet(m.id),'btn ghost right'),button('Editar',()=>machineForm(m),'btn ghost'));
const over=!!m.limit_metres&&m.open_metres>m.limit_metres;
const load=node('div',undefined,'row base');
load.append(node('b',metres(m.open_metres),over?'bad':''),node('span','em aberto, '+(m.limit_metres?'limite de '+metres(m.limit_metres)+(over?', acima do limite':''):'sem limite'),'lbl'));
@@ -2680,6 +2694,281 @@ function machineForm(m){
say(m?'Máquina salva.':'Máquina criada.');await loadUsers();await load();
}});
}
// ---- Machine sheet (Fase 2, front 1a) --------------------------------------
//
// What goes into a machine, what the room has printed since the last clean and
// the last film roll, and the alerts that wait between one file and the next.
// The numbers per machine (cost, ROI) are part b and stay in Números.
function machineEntryLine(entry, catalog){
const label=entry.label||entry.item;
let detail='';
if(entry.kind==='supply'){
const unit=catalog.supplies[entry.item]?.[1]||'';
detail=Number(entry.quantity).toLocaleString('pt-BR',{maximumFractionDigits:3})+' '+unit;
if(entry.cost_cents!==null&&entry.cost_cents!==undefined)detail+=' · '+money(entry.cost_cents);
}else if(entry.kind==='part'){
detail=(entry.note?entry.note+' · ':'')+(entry.serial?'série '+entry.serial+' · ':'')+money(entry.cost_cents);
}else if(entry.item==='stop'){
detail=entry.stop_minutes+' min'+(entry.note?' · '+entry.note:'');
}
return [when(entry.created_at),label,detail,entry.created_by].filter(Boolean).join(' · ');
}
async function openMachineSheet(machineId){
let data;
try{data=await api('/machines/'+machineId+'/sheet');}
catch(e){say(e.message,true);return;}
const machine=data.machine;
const launch=may('print')&&(ME?.role!=='operador'||myMachine()?.id===machine.id);
const body=[];
let sheetModal=null;
const refresh=async()=>{sheetModal?.close();await load();openMachineSheet(machine.id);};
const minimum=value=>Number(value).toLocaleString('pt-BR',{maximumFractionDigits:3});
const counts=node('div',undefined,'mblock');
const fact=(label,value)=>{const row=node('div',undefined,'mfact');row.append(node('span',label),node('b',value));counts.append(row);};
const clean=data.counters.clean, film=data.counters.film;
fact('Desde a última limpeza',m1(clean.metres)+' m'+(clean.since?'':' (nenhuma limpeza lançada ainda)'));
fact('Desde a troca de filme',film.since?m1(film.metres)+' m '+(film.aligned?'(cabeça alinhada)':'(falta alinhar)'):'sem registro');
body.push(node('h4','Contadores','sh'),counts);
const supplies=node('div',undefined,'mblock');
for(const [item,[label,unit]] of Object.entries(data.catalog.supplies)){
const value=data.supplies[item];
const row=node('div',undefined,'mfact');
let text;
if(value){
text='acaba em ~'+m1(value.metres_left)+' m';
if(value.minimum!==null&&value.minimum!==undefined)text+=' · mínimo '+minimum(value.minimum)+' '+unit;
}else text='lance duas reposições para estimar';
row.append(node('span',label),node('b',text));
supplies.append(row);
}
body.push(node('h4','Insumos','sh'),supplies);
if(data.alerts.length){
const box=node('div',undefined,'mblock');
const done=async alert=>{
if(alert.key.startsWith('supply:')){
const saved=await machineEntryForm(machine.id,{kind:'supply',item:alert.key.slice(7),from_alert:true},data);
if(!saved)return;
}else{
await api('/machines/'+machine.id+'/entries',{kind:'event',item:alert.key,from_alert:true});
}
say('Aviso resolvido.');
await refresh();
};
for(const alert of data.alerts){
const row=node('div',undefined,'sheetalert');
const words=node('span',undefined,'grow');
words.append(node('b',alert.text),node('span',alert.blocking?'pendente':'adiado neste ciclo','sub'));
row.append(words);
if(launch){
const actions=node('span',undefined,'prow');
actions.append(button('Marcar como feito',()=>done(alert),'btn'));
if(alert.snoozable)actions.append(button('Adiar uma vez',async()=>{
await api('/machines/'+machine.id+'/alerts/'+encodeURIComponent(alert.key)+'/snooze',{});
say('Aviso adiado: passa um arquivo e ele volta.');
await refresh();
},'btn ghost'));
row.append(actions);
}
box.append(row);
}
body.push(node('h4','Avisos pendentes','sh'),box);
}
const entries=node('div',undefined,'mlist sheetentries');
if(data.entries.length)for(const entry of data.entries)entries.append(node('div',machineEntryLine(entry,data.catalog),'mli'));
else entries.append(node('div','Nenhum lançamento ainda','mli muted'));
body.push(node('h4','Lançamentos','sh'),entries);
if(launch){
const prow=node('div',undefined,'prow');
prow.append(button('Lançar',async()=>{
const saved=await machineEntryForm(machine.id,{},data);
if(!saved)return;
say('Lançamento registrado.');
await refresh();
},'btn pri'));
body.push(prow);
}
if(may('manage')){
const price=node('input');price.type='number';price.min='0';price.step='0.01';price.inputMode='decimal';
price.value=data.machine.price_cents!==null&&data.machine.price_cents!==undefined?(data.machine.price_cents/100).toFixed(2):'';
const installed=node('input');installed.type='date';installed.value=data.machine.installed_on||'';
const minimums={};
const box=node('div',undefined,'mblock');
box.append(field('Preço de compra (R$)',price),field('Data de instalação',installed));
for(const [item,[label,unit]] of Object.entries(data.catalog.supplies)){
const input=node('input');input.type='number';input.min='0';input.step='0.001';input.inputMode='decimal';
input.value=data.minimums[item]!==null&&data.minimums[item]!==undefined?Number(data.minimums[item]).toString():'';
minimums[item]=input;
box.append(field('Mínimo de '+label.toLowerCase()+' ('+unit+')',input));
}
const error=node('span',undefined,'warn');error.hidden=true;
const save=node('button','Salvar','btn pri');save.type='button';
save.onclick=async()=>{
save.disabled=true;error.hidden=true;
try{
await api('/machines/'+machine.id+'/sheet',{
price_cents:price.value.trim()===''?null:Math.round(Number(price.value)*100),
installed_on:installed.value||null,
minimums:Object.fromEntries(Object.entries(minimums).map(([item,input])=>
[item,input.value.trim()===''?null:Number(input.value)]))});
say('Dados da máquina salvos.');
await refresh();
}catch(e){error.textContent=e.message;error.hidden=false;}
finally{save.disabled=false;}
};
const foot=node('div',undefined,'prow');foot.append(error,save);
box.append(foot,node('small','Preço e data servem para o retorno da máquina em Números.','sub'));
body.push(node('h4','Dados da máquina','sh'),box);
}
sheetModal=modal('Ficha da '+machine.name,{host:dialogHost(),width:640,body});
}
// The launch form: type, item, and only the fields that type uses. Resolves
// true when the entry was saved, false when the dialog was closed.
async function machineEntryForm(machineId, preset={}, data=null){
if(!data){
try{data=await api('/machines/'+machineId+'/sheet');}
catch(e){say(e.message,true);return false;}
}
const catalog=data.catalog;
const kind=node('select');
for(const [value,label] of [['supply','Insumo'],['part','Peça'],['event','Evento']]){
const option=node('option',label);option.value=value;kind.append(option);}
kind.value=preset.kind||'supply';
const item=node('select');
const fillItems=()=>{
const map=kind.value==='supply'?catalog.supplies:kind.value==='part'?catalog.parts:catalog.events;
item.replaceChildren(...Object.entries(map).map(([value,meta])=>{
const option=node('option',Array.isArray(meta)?meta[0]:meta);option.value=value;return option;}));
if(preset.item&&kind.value===(preset.kind||'supply'))item.value=preset.item;
};
fillItems();
const quantity=node('input');quantity.type='number';quantity.min='0.001';quantity.step='0.001';quantity.inputMode='decimal';
const cost=node('input');cost.type='number';cost.min='0';cost.step='0.01';cost.inputMode='decimal';
const serial=node('input');serial.maxLength=200;
const note=node('input');note.maxLength=1000;
const minutes=node('input');minutes.type='number';minutes.min='1';minutes.step='1';
const quantityField=field('Quantidade',quantity,'Unidade: ');
const costField=field('Custo (R$)',cost,'Vazio usa o último custo');
const serialField=field('Número de série',serial);
const noteCaption=node('span','Descrição');
const noteField=node('label',undefined,'fld');noteField.append(noteCaption,note);
const minutesField=field('Minutos parados',minutes);
const quantityHint=quantityField.querySelector('small'),costHint=costField.querySelector('small');
const sync=()=>{
const supply=kind.value==='supply',part=kind.value==='part',event=kind.value==='event';
const stop=event&&item.value==='stop';
quantityField.hidden=!supply;
costField.hidden=!(supply||part);
serialField.hidden=!part;
noteField.hidden=!((part&&item.value==='other')||stop);
minutesField.hidden=!stop;
noteCaption.textContent=stop?'Motivo da parada':'Descrição';
quantityHint.textContent=supply?'Unidade: '+(catalog.supplies[item.value]?.[1]||''):'';
costHint.textContent=supply?'Vazio usa o último custo':'';
};
kind.onchange=()=>{preset.item=null;fillItems();sync();};
item.onchange=sync;
sync();
return new Promise(resolve=>{
let settled=false;
const finish=value=>{if(settled)return;settled=true;resolve(value);};
const error=node('span',undefined,'warn');error.hidden=true;
const dialog=formDialog('Lançar na ficha',{host:dialogHost(),width:560,left:[error],
fields:[field('Tipo',kind),field('Item',item),quantityField,costField,serialField,noteField,minutesField],
label:'Lançar',onsave:async()=>{
try{
const payload={kind:kind.value,item:item.value,from_alert:!!preset.from_alert};
if(kind.value==='supply'){
if(quantity.value.trim()==='')throw new Error('Informe a quantidade que entrou.');
payload.quantity=Number(quantity.value);
payload.cost_cents=cost.value.trim()===''?null:Math.round(Number(cost.value)*100);
}else if(kind.value==='part'){
if(cost.value.trim()==='')throw new Error('Informe o custo da peça.');
payload.cost_cents=Math.round(Number(cost.value)*100);
payload.serial=serial.value.trim()||null;
payload.note=note.value.trim()||null;
}else if(item.value==='stop'){
if(!note.value.trim()||minutes.value.trim()==='')throw new Error('Informe o motivo e os minutos da parada.');
payload.note=note.value.trim();
payload.stop_minutes=Number(minutes.value);
}
await api('/machines/'+machineId+'/entries',payload);
}catch(e){error.textContent=e.message;error.hidden=false;return false;}
finish(true);
}});
const close=dialog.close.bind(dialog);
dialog.close=()=>{close();finish(false);};
});
}
// The alert shown when a card is pulled between one file and the next. Resolves
// true when the alert was resolved or postponed, false when the user backs out.
function machineAlertDialog(order,machineId,alert){
return new Promise(resolve=>{
let decided=false;
const made=node('button','Marcar como feito','btn pri');made.type='button';
const later=node('button','Adiar uma vez','btn');later.type='button';
const back=node('button','Voltar','btn ghost right');back.type='button';
const modalEntry=modal('Antes do próximo arquivo',{text:alert.text,host:dialogHost(),width:520,
role:'alertdialog',foot:[...(alert.snoozable?[later]:[]),back,made],
onclose:()=>{if(!decided)resolve(false);}});
back.onclick=()=>modalEntry.close();
const run=async action=>{
made.disabled=true;later.disabled=true;message.hidden=true;
try{
const proceed=await action();
if(proceed===false)return;
decided=true;modalEntry.close();
await load();
resolve(true);
}catch(e){message.textContent=e.message;message.hidden=false;}
finally{made.disabled=false;later.disabled=false;}
};
const message=node('span',undefined,'warn');message.hidden=true;
modalEntry.box.querySelector('.dfoot')?.prepend(message);
made.onclick=()=>run(async()=>{
if(alert.key.startsWith('supply:')){
return await machineEntryForm(machineId,{kind:'supply',item:alert.key.slice(7),from_alert:true});
}
await api('/machines/'+machineId+'/entries',{kind:'event',item:alert.key,from_alert:true});
return true;
});
later.onclick=()=>run(async()=>{
await api('/machines/'+machineId+'/alerts/'+encodeURIComponent(alert.key)+'/snooze',{});
return true;
});
});
}
// Pulling a card to a machine always passes the sheet's blocking alert first,
// then the server re-checks it under the machine's lock.
async function pullTo(order, machineId){
const target=machineId||order.machine?.id||myMachine()?.id||null;
if(target){
const machine=(board.machines||[]).find(row=>row.id===target);
const alert=(machine?.alerts||[]).find(row=>row.blocking);
if(alert&&!await machineAlertDialog(order,target,alert))return;
}
try{
await move(order,'imp','',target);
}catch(e){
if(e.status===409&&String(e.message).startsWith('Antes do próximo arquivo')){say(e.message,true);return;}
throw e;
}
}
// Minha conta: who is signed in, and the password, which only the person changes.
function accountForm(){
const current=node('input');current.type='password';current.required=true;current.autocomplete='current-password';