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

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