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

@@ -216,6 +216,12 @@ class FakeTiny:
def search_contacts(self, query: str) -> list:
return [dict(contact) for contact in self.CONTACTS]
# Tiny's sellers, for the Kanban users' "Vendedor no Tiny".
SELLERS = [{'id': 2001, 'name': 'Lais'}, {'id': 2002, 'name': 'Marcus'}]
def list_sellers(self) -> list:
return [dict(seller) for seller in self.SELLERS]
def product_id(self, code: str) -> int:
"""The fake Tiny product id for a SKU code, as the real catalogue does."""
return self.SKUS[code]

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

View File

@@ -5,8 +5,9 @@ file out of it when it rips. When the operator pulls a card to Imprimindo, its
files go, as a copy, into its machine's folder for the item's contraction
class; a premium item always goes to PREMIUM, whichever class it carries;
the order's own file stays in its stage folder. A film over 15 m is several
parts (item 13): all on the same machine, in order, never more than two in
the folder at once. The third is written when Flexi takes the first.
parts (item 13): all on the same machine, in order. A machine's folder holds
as many files at once as it has places in Imprimindo (machines.places, three
since 2026-11-17); the next is written when Flexi takes one.
Only the server knows what each folder should get, and the Kanban's
computers write it: a part is claimed by one computer, so two never write
@@ -23,8 +24,6 @@ from datetime import timedelta
# The machines' folders, inside the Kanban's main folder (Dropstar, 2026-10-30).
PRINTING_FOLDER = '3. Imprimindo'
# Two parts at most in a machine's folder (Dropstar, 2026-10-30).
IN_FOLDER = 2
# A computer that claimed a part and never said it was written.
CLAIM_TIMEOUT = timedelta(minutes=10)
CLASSES = ('C1', 'C2', 'C3')
@@ -75,10 +74,10 @@ def stop(c, order_id):
def claim(c, user):
"""The parts due in the folders now, claimed for this computer to write:
for each machine, the next parts of its orders in Imprimindo, in the order
they entered it, until the machine has two in its folder."""
they entered it, until the machine has its places' worth in its folder."""
c.execute('''UPDATE dtf_local.hot_parts SET state='queued', claimed_at=NULL, claimed_by=NULL
WHERE state='claimed' AND claimed_at < now() - %s''', (CLAIM_TIMEOUT,))
rows = c.execute('''SELECT h.*, o.machine_id, o.contraction, o.snapshot, m.name AS machine_name,
rows = c.execute('''SELECT h.*, o.machine_id, o.contraction, o.snapshot, m.name AS machine_name, m.places,
(SELECT max(v.id) FROM dtf_local.movements v WHERE v.order_id=o.id AND v.to_state='imp') AS entered
FROM dtf_local.hot_parts h JOIN dtf_local.orders o ON o.id=h.order_id
JOIN dtf_local.machines m ON m.id=o.machine_id
@@ -95,7 +94,7 @@ def claim(c, user):
continue
cls = folder_class(row, row['item_index'])
# A part without its class waits, and the parts after it with it.
if busy.get(machine, 0) >= IN_FOLDER or not cls:
if busy.get(machine, 0) >= row['places'] or not cls:
blocked.add(order)
continue
folder = f"{row['machine_name']}/{cls}"

View File

@@ -1,14 +1,17 @@
"""The print machines, their load and the two printing places on each one."""
"""The print machines, their load and the 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
# printing, the next being ripped by FlexiPRINT meanwhile. A third would
# make the RIP choke; two mean the next sheet is ready when one ends.
PRINTING_CAP = 2
# Orders at most in Imprimindo per machine, and files in its hot folder at
# once: dtf_local.machines.places, set per machine by Admin and Gestão
# (Marcus, 2026-11-17). It was two for all (Dropstar, 2026-10-29): one
# printing, the next ripped by FlexiPRINT meanwhile; three keeps one more
# waiting in the folder. A new machine starts with DEFAULT_PLACES.
DEFAULT_PLACES = 3
MAX_PLACES = 6
def product_family(order):
@@ -36,7 +39,7 @@ def loads(c):
def rows(c, with_operators=False):
"""Every machine with its load, for the Kanban."""
machines = c.execute('''SELECT id, name, products, active, limit_metres FROM dtf_local.machines
machines = c.execute('''SELECT id, name, products, active, limit_metres, places FROM dtf_local.machines
ORDER BY created_at, name''').fetchall()
load = loads(c)
operators = {}
@@ -54,6 +57,7 @@ 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,
'places': m['places'],
'open_metres': float(used['metres']), 'open_orders': used['orders'], 'states': used['states'],
'alerts': machine_log.alerts(c, m['id'])}
if with_operators:
@@ -63,22 +67,23 @@ def rows(c, with_operators=False):
def full(c, machine_id, order_id):
"""The machine's name when it already has PRINTING_CAP other orders in
Imprimindo, so this one cannot join them; None when it has room. The
machine's row is locked, so two pulls at once cannot both take the last
place."""
"""(name, places) when the machine already has its places' worth of
other orders in Imprimindo, so this one cannot join them; None when it
has room. The machine's row is locked, so two pulls at once cannot both
take the last place."""
if machine_id is None:
return None
machine = c.execute('SELECT name FROM dtf_local.machines WHERE id=%s FOR UPDATE', (machine_id,)).fetchone()
machine = c.execute('SELECT name, places FROM dtf_local.machines WHERE id=%s FOR UPDATE', (machine_id,)).fetchone()
printing = c.execute('''SELECT count(*) AS n FROM dtf_local.orders WHERE machine_id=%s AND state='imp'
AND cancelled_at IS NULL AND id<>%s''', (machine_id, order_id)).fetchone()['n']
return machine['name'] if machine and printing >= PRINTING_CAP else None
return (machine['name'], machine['places']) if machine and printing >= machine['places'] else None
def printing_slots(c):
"""Per order in Imprimindo: 'imprimindo' for the first to enter it on its
machine (ripped, running), 'ripando' for the one after it."""
return {row['id']: 'imprimindo' if row['place'] == 1 else 'ripando' for row in c.execute('''
machine (ripped, running), 'ripando' for the one after it, 'aguardando'
for those after that, waiting in the hot folder."""
return {row['id']: {1: 'imprimindo', 2: 'ripando'}.get(row['place'], 'aguardando') for row in c.execute('''
SELECT o.id, row_number() OVER (PARTITION BY o.machine_id ORDER BY m.at, o.number) AS place
FROM dtf_local.orders o, LATERAL (SELECT max(created_at) AS at FROM dtf_local.movements
WHERE order_id=o.id AND to_state='imp') m

View File

@@ -0,0 +1,5 @@
-- How many orders each machine takes in Imprimindo, and files in its hot
-- folder at once: three, set per machine by Admin and Gestão (Marcus,
-- 2026-11-17; it was two for every machine, app/machines.py).
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS places smallint NOT NULL DEFAULT 3
CHECK (places BETWEEN 1 AND 6);

View File

@@ -0,0 +1,5 @@
-- The Tiny seller (vendedor) each Kanban user is, so a Venda the user
-- assembles reaches Tiny with them as its seller (Marcus, 2026-11-17).
-- Tiny takes the seller by its id; the name is kept to show it.
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS tiny_seller_id bigint;
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS tiny_seller_name text;

View File

@@ -149,7 +149,7 @@ PICKUP_CARRIER = 761565838
# Dropstar's answers: the financial category "DTF SITE" (RECEITAS, id sent on
# 2026-10-26; it goes in pagamento.categoria, and replaced the store's
# "DUPLICADO DROP", 965775137), no seller (Tiny sets it from the contact,
# 2026-10-23), and the marcador SITE DTF, added after the order is created:
# 2026-10-23; a montador Venda carries who assembled it, 2026-11-17), and the marcador SITE DTF, added after the order is created:
# POST /pedidos does not take marcadores. Capitals, no accent, no extra
# space: the string Kondado reads for Power BI.
CATEGORY = 986932924
@@ -460,6 +460,24 @@ def search_forms(document):
return list(dict.fromkeys((punctuated(d), d)))
def list_sellers(orders, pages=10):
"""Tiny's sellers (vendedores) as [{id, name}], for the Kanban user a
Venda's seller comes from (Marcus, 2026-11-17). v3 names the seller on
the entry or on its contact; both are read."""
sellers = []
for page in range(pages):
found = orders.request('GET', '/vendedores', params={'limit': 100, 'offset': page * 100})
items = found if isinstance(found, list) else (found.get('itens') or [])
for entry in items:
contact = entry.get('contato') or {}
name = entry.get('nome') or contact.get('nome') or contact.get('fantasia') or ''
if entry.get('id'):
sellers.append({'id': entry['id'], 'name': name or f"Vendedor {entry['id']}"})
if len(items) < 100:
break
return sorted(sellers, key=lambda s: s['name'].lower())
def search_contacts(orders, query, limit=10):
"""Up to `limit` contacts matching what was typed (the montador's typeahead,
front 7a.3): by CPF/CNPJ when it is only digits and punctuation, else by
@@ -591,6 +609,11 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
'valorFrete': money(freight['total_cents']),
'observacoes': f"Pedido DTF #{payload['number']}" + (' · retirada em Franca' if pickup else ''),
'observacoesInternas': internal_note(payload)}
# No seller, so Tiny's channel sets it (Dropstar, 2026-10-23), except a
# montador Venda, whose seller is who assembled it (Marcus, 2026-11-17).
seller = (order.get('seller') or {}).get('id')
if seller:
pedido['vendedor'] = {'id': int(seller)}
coupon = order.get('coupon') or {}
if coupon:
# Tiny's v3 order has the order-level discount next to valorFrete.