feat: places per machine, drops on Imprimindo go to your machine, a Venda carries its seller to Tiny (DTF-WEB-V)
All checks were successful
Build and deploy / Validate source (push) Successful in 10s
Build and deploy / Integration suite on a real stack (push) Successful in 7m38s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m19s

Marcus, 2026-11-17:
- Each machine has its own places (machines.places, 1 to 6, three to
  start): orders at once in Imprimindo and files at once in its hot
  folder. Admin sets it in the machine dialog; Admin and Gestão in the
  machine sheet's Dados da máquina. A third order shows as "Na vez".
- Whoever is signed in on a machine drops a card anywhere in Imprimindo
  and it goes to that machine; without one, the lane under the pointer.
- Each Kanban user may name their Tiny seller (Usuários, read from
  Tiny's own list); a montador Venda reaches Tiny with the seller of who
  assembled it. Every other order still sends no seller.
- A folder download that never reached storage (a network drop) waits
  for the next pass as a warning and is reported only if it keeps
  failing (Sentry DTF-WEB-V).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-17 14:18:19 -03:00
parent c61ac27ca4
commit aaa6090642
19 changed files with 244 additions and 63 deletions

View File

@@ -67,7 +67,7 @@ def board(user=Depends(operator)):
'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN,
'finished_shown': len(finished), 'finished_total': finished_total,
# Who is on each machine now, for the machine question (item 12).
'machines': machines.rows(c, with_operators=True), 'printing_cap': machines.PRINTING_CAP,
'machines': machines.rows(c, with_operators=True), 'printing_cap': machines.DEFAULT_PLACES,
'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
'names': company_names(c, orders, quotes),
'pending_total': pending_total, 'approved_total': approved_total,

View File

@@ -149,6 +149,25 @@ def tiny_contacts(q: str = Query(min_length=1, max_length=120), user=Depends(can
raise HTTPException(409, 'O Tiny não está conectado.')
@router.get('/api/operator/tiny/sellers')
def tiny_sellers(user=Depends(can('users'))):
"""Tiny's sellers, for the "Vendedor no Tiny" of each Kanban user: a
Venda they assemble reaches Tiny with that seller (Marcus, 2026-11-17)."""
if os.environ.get('TINY_ADAPTER') != 'tiny':
from ...adapters import FakeTiny
return FakeTiny().list_sellers()
if not tiny.configured():
raise HTTPException(409, 'O Tiny não está conectado.')
try:
return tiny.list_sellers(tiny.TinyOrders())
except tiny.TinyNotConnected:
raise HTTPException(409, 'O Tiny não está conectado.')
except tiny.TinyError as exc:
if ': 403 ' in str(exc) or ': 401 ' in str(exc):
raise HTTPException(409, 'O aplicativo do Tiny não tem permissão para ler os vendedores (Contatos, leitura).')
raise
@router.post('/api/operator/tiny/connect')
def tiny_connect(user=Depends(can('integrations'))):
"""Start the one-time authorisation of this system in the client's Tiny."""

View File

@@ -503,9 +503,9 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
WHERE f.order_id=%s AND {FINAL_OK} AND {TREATED}''', (uid,)).fetchall()
if {r['item_index'] for r in treated} != set(range(len(row['snapshot']['items']))):
raise HTTPException(409, 'Ajuste Fino pago: envie e aprove a arte do Ajuste Fino de todos os itens antes de entrar na fila.')
# Two at most per machine in Imprimindo (app/machines.py).
if body.state == 'imp' and (name := machines.full(c, row['machine_id'], uid)):
raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.')
# The machine's places in Imprimindo (app/machines.py).
if body.state == 'imp' and (full := machines.full(c, row['machine_id'], uid)):
raise HTTPException(409, f'{full[0]} já tem {full[1]} em Imprimindo.')
# A proof card ends with its answer, not in Finalizado; its order waits
# for that answer outside the queue (app/proof.py).
if row.get('parent_id') and body.state == 'fin':

View File

@@ -149,6 +149,13 @@ def montador_order(body: MontadorOrder, request: Request, user=Depends(can('asse
# card and in Tiny's internal note.
approved = {**approved, 'kind': body.kind,
**({'with_order': body.with_order} if body.with_order else {})}
# A Venda's seller in Tiny is who assembled it, when their user
# names one (Marcus, 2026-11-17, app/tiny.py order_payload).
if body.kind == 'venda':
seller = c.execute('''SELECT tiny_seller_id AS id, tiny_seller_name AS name
FROM dtf_local.operators WHERE email=%s AND tiny_seller_id IS NOT NULL''', (user,)).fetchone()
if seller:
approved['seller'] = dict(seller)
c.execute('UPDATE dtf_local.quotes SET approved=%s WHERE id=%s',
(Jsonb(approved), quote['id']))
quote = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s', (quote['id'],)).fetchone()

View File

@@ -23,6 +23,11 @@ from ..runtime import BACK, ENVIRONMENT, STATES, TRANSITIONS
router = APIRouter()
class TinySeller(StrictModel):
id: int = Field(gt=0)
name: str = Field(min_length=1, max_length=120)
class UserIn(StrictModel):
# The profiles an administrator may give; superadmin only comes from the console.
name: str = Field(min_length=1, max_length=80)
@@ -33,6 +38,9 @@ class UserIn(StrictModel):
# No longer used: an operator's machine is the one chosen after signing in
# (item 12). Kept so a page loaded before still saves.
machines: list[UUID] = Field(default_factory=list, max_length=50)
# The Tiny seller this user is (app/tiny.py list_sellers): a Venda they
# assemble reaches Tiny with it. None: no seller.
tiny_seller: TinySeller | None = None
@field_validator('email')
@classmethod
@@ -49,11 +57,18 @@ class MachineIn(StrictModel):
active: bool = True
# Metres open before the next order goes to another machine; None is no limit.
limit_metres: Decimal | None = Field(default=None, gt=0, le=99999, decimal_places=1)
# Orders at once in Imprimindo and files in its hot folder (app/machines.py);
# None keeps what it has, or machines.DEFAULT_PLACES for a new one.
places: int | None = Field(default=None, ge=1, le=machines.MAX_PLACES)
# No longer used (item 12): who is on a machine is who chose it after
# signing in. Kept so a page loaded before still saves.
operators: list[UUID] | None = Field(default=None, max_length=200)
class MachinePlaces(StrictModel):
places: int = Field(ge=1, le=machines.MAX_PLACES)
class PasswordChange(StrictModel):
current: str = Field(min_length=1, max_length=128)
new: str = Field(min_length=8, max_length=128)
@@ -134,6 +149,7 @@ def change_password(body: PasswordChange, request: Request):
def user_rows(c):
"""Every account, with the machines its open sessions are on now (item 12)."""
rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.last_login_at,o.created_at,
o.tiny_seller_id,o.tiny_seller_name,
COALESCE(array_agg(DISTINCT s.machine_id) FILTER (WHERE s.machine_id IS NOT NULL), '{}') AS machines,
-- The last use of any open session: "Ativo agora" in Usuários.
(SELECT max(x.seen_at) FROM dtf_local.operator_sessions x
@@ -143,6 +159,8 @@ def user_rows(c):
GROUP BY o.id ORDER BY o.active DESC, o.name, o.email''').fetchall()
for row in rows:
row['machines'] = [str(m) for m in row['machines']]
seller_id, seller_name = row.pop('tiny_seller_id'), row.pop('tiny_seller_name')
row['tiny_seller'] = {'id': seller_id, 'name': seller_name} if seller_id else None
return rows
@@ -170,9 +188,10 @@ def create_user(body: UserIn, request: Request, user=Depends(can('users'))):
with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.operators WHERE email=%s', (body.email,)).fetchone():
raise HTTPException(409, 'Já existe um usuário com este e-mail.')
c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,active)
VALUES(%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
body.role, body.active))
seller = body.tiny_seller
c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,active,tiny_seller_id,tiny_seller_name)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
body.role, body.active, seller and seller.id, seller and seller.name))
audit('operator_created', operator=user, account=body.email, role=body.role)
return {'id': str(uid)}
@@ -189,8 +208,10 @@ def update_user(uid: UUID, body: UserIn, request: Request, user=Depends(can('use
if body.email != row['email'] and c.execute(
'SELECT 1 FROM dtf_local.operators WHERE email=%s AND id<>%s', (body.email, uid)).fetchone():
raise HTTPException(409, 'Já existe um usuário com este e-mail.')
c.execute('UPDATE dtf_local.operators SET name=%s,email=%s,role=%s,active=%s WHERE id=%s',
(body.name.strip(), body.email, role, body.active, uid))
seller = body.tiny_seller
c.execute('''UPDATE dtf_local.operators SET name=%s,email=%s,role=%s,active=%s,tiny_seller_id=%s,
tiny_seller_name=%s WHERE id=%s''', (body.name.strip(), body.email, role, body.active,
seller and seller.id, seller and seller.name, uid))
if body.password:
c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE id=%s', (password_hash(body.password), uid))
if body.email != row['email']:
@@ -234,8 +255,9 @@ def create_machine(body: MachineIn, user=Depends(can('users'))):
with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s)', (body.name.strip(),)).fetchone():
raise HTTPException(409, 'Já existe uma máquina com este nome.')
c.execute('INSERT INTO dtf_local.machines(id,name,products,active,limit_metres) VALUES(%s,%s,%s,%s,%s)',
(mid, body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres))
c.execute('''INSERT INTO dtf_local.machines(id,name,products,active,limit_metres,places)
VALUES(%s,%s,%s,%s,%s,%s)''', (mid, body.name.strip(), sorted(set(body.products)), body.active,
body.limit_metres, body.places or machines.DEFAULT_PLACES))
audit('machine_created', operator=user, machine=body.name)
return {'id': str(mid)}
@@ -246,9 +268,10 @@ def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) AND id<>%s',
(body.name.strip(), mid)).fetchone():
raise HTTPException(409, 'Já existe uma máquina com este nome.')
if not c.execute('''UPDATE dtf_local.machines SET name=%s,products=%s,active=%s,limit_metres=%s
WHERE id=%s RETURNING id''', (body.name.strip(), sorted(set(body.products)), body.active,
body.limit_metres, mid)).fetchone():
if not c.execute('''UPDATE dtf_local.machines SET name=%s,products=%s,active=%s,limit_metres=%s,
places=COALESCE(%s,places) WHERE id=%s RETURNING id''',
(body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres,
body.places, mid)).fetchone():
raise HTTPException(404, 'Máquina não encontrada.')
if not body.active:
release_sessions(c, mid)
@@ -256,6 +279,20 @@ def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
return {'ok': True}
@router.post('/api/operator/machines/{mid}/places')
def machine_places(mid: UUID, body: MachinePlaces, user=Depends(can('manage'))):
"""How many orders the machine takes in Imprimindo, and files in its hot
folder: Admin and Gestão set it from the machine's sheet (Marcus,
2026-11-17). Orders already there stay; the next waits for a place."""
with db.connect() as c:
row = c.execute('UPDATE dtf_local.machines SET places=%s WHERE id=%s RETURNING name',
(body.places, mid)).fetchone()
if not row:
raise HTTPException(404, 'Máquina não encontrada.')
audit('machine_places', operator=user, machine=row['name'], places=body.places)
return {'ok': True}
@router.post('/api/operator/machines/{mid}/delete')
def delete_machine(mid: UUID, user=Depends(can('users'))):
"""Its orders lose that machine; its operators lose the session choice."""