From aaa6090642db0ee28aba77148a1416c505de6e3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Tue, 17 Nov 2026 14:18:19 -0300 Subject: [PATCH] feat: places per machine, drops on Imprimindo go to your machine, a Venda carries its seller to Tiny (DTF-WEB-V) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- app/adapters.py | 6 ++ app/api/operator/board.py | 2 +- app/api/operator/integrations.py | 19 +++++++ app/api/operator/orders.py | 6 +- app/api/stamps.py | 7 +++ app/api/users.py | 57 +++++++++++++++---- app/hotfolder.py | 13 ++--- app/machines.py | 33 ++++++----- .../202611171300_machine-places.sql | 5 ++ .../202611171310_operator-tiny-seller.sql | 5 ++ app/tiny.py | 25 +++++++- tests/stamps_test.py | 14 ++++- tests/test_tiny.py | 7 +++ tests/users_test.py | 10 +++- web/kanban-board.js | 17 ++++-- web/kanban-numbers.js | 4 +- web/kanban-order.js | 2 +- web/kanban-users.js | 38 +++++++++++-- web/kanban.js | 37 +++++++++--- 19 files changed, 244 insertions(+), 63 deletions(-) create mode 100644 app/migrations/202611171300_machine-places.sql create mode 100644 app/migrations/202611171310_operator-tiny-seller.sql diff --git a/app/adapters.py b/app/adapters.py index 0d538e5..e4856fc 100644 --- a/app/adapters.py +++ b/app/adapters.py @@ -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] diff --git a/app/api/operator/board.py b/app/api/operator/board.py index 028a8cf..6db1bbc 100644 --- a/app/api/operator/board.py +++ b/app/api/operator/board.py @@ -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, diff --git a/app/api/operator/integrations.py b/app/api/operator/integrations.py index 0b3d217..7596d9a 100644 --- a/app/api/operator/integrations.py +++ b/app/api/operator/integrations.py @@ -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.""" diff --git a/app/api/operator/orders.py b/app/api/operator/orders.py index ab5d884..3982da5 100644 --- a/app/api/operator/orders.py +++ b/app/api/operator/orders.py @@ -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': diff --git a/app/api/stamps.py b/app/api/stamps.py index cb3325a..25a9205 100644 --- a/app/api/stamps.py +++ b/app/api/stamps.py @@ -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() diff --git a/app/api/users.py b/app/api/users.py index 1a9e41b..e2ad5ac 100644 --- a/app/api/users.py +++ b/app/api/users.py @@ -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.""" diff --git a/app/hotfolder.py b/app/hotfolder.py index bed73c3..23a1414 100644 --- a/app/hotfolder.py +++ b/app/hotfolder.py @@ -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}" diff --git a/app/machines.py b/app/machines.py index e65fcbb..393f2d7 100644 --- a/app/machines.py +++ b/app/machines.py @@ -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 diff --git a/app/migrations/202611171300_machine-places.sql b/app/migrations/202611171300_machine-places.sql new file mode 100644 index 0000000..1b10669 --- /dev/null +++ b/app/migrations/202611171300_machine-places.sql @@ -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); diff --git a/app/migrations/202611171310_operator-tiny-seller.sql b/app/migrations/202611171310_operator-tiny-seller.sql new file mode 100644 index 0000000..947bf62 --- /dev/null +++ b/app/migrations/202611171310_operator-tiny-seller.sql @@ -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; diff --git a/app/tiny.py b/app/tiny.py index a63006e..4312597 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -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. diff --git a/tests/stamps_test.py b/tests/stamps_test.py index d560e47..dc6c85d 100644 --- a/tests/stamps_test.py +++ b/tests/stamps_test.py @@ -87,9 +87,17 @@ def run(): # With a dot, as Dropstar's own codes (NX.226). stamp_code = 'T.' + tag try: + # The seller is a Tiny seller too (Marcus, 2026-11-17): the fake Tiny + # lists two, and a Venda this user assembles carries the one chosen. + sellers = su.call('/operator/tiny/sellers', operator=True) + assert sellers == [{'id': 2001, 'name': 'Lais'}, {'id': 2002, 'name': 'Marcus'}], sellers for role, email in emails.items(): - su.call('/operator/users', {'name': role.title(), 'email': email, 'role': role, - 'password': PASSWORD}, operator=True) + su.call('/operator/users', {'name': role.title(), 'email': email, 'role': role, 'password': PASSWORD, + **({'tiny_seller': sellers[0]} if role == 'vendedor' else {})}, + operator=True) + listed = {u['email']: u for u in su.call('/operator/users', operator=True)['users']} + assert listed[emails['vendedor']]['tiny_seller'] == sellers[0], listed[emails['vendedor']] + assert listed[emails['gestao']]['tiny_seller'] is None, listed[emails['gestao']] # The new profile creates through the users API and reads the table. shipping = signed_in(emails['expedicao']) seller = signed_in(emails['vendedor']) @@ -176,6 +184,8 @@ def run(): made_quotes.append(UUID(order_venda['quote_id'])) assert order_venda['state'] == 'rec' and order_venda['origin'] == 'atendimento', order_venda assert order_venda['snapshot']['with_order'] == 4321, order_venda['snapshot'].get('with_order') + assert order_venda['snapshot']['seller'] == {'id': 2001, 'name': 'Lais'}, order_venda['snapshot'].get('seller') + assert 'seller' not in order_interno['snapshot'], order_interno['snapshot'].get('seller') payment = order_venda['payment'] assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'faturado', 'paid'), payment with db.connect() as c: diff --git a/tests/test_tiny.py b/tests/test_tiny.py index a1d5494..79288ba 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -148,6 +148,13 @@ class TinyTests(FakeTinyCase): contact = contact_payload(PAID['order']) self.assertEqual((contact['tipoPessoa'], contact['cpfCnpj'], contact['endereco']['uf']), ('J', '11.222.333/0001-81', 'SP')) + + def test_only_a_montador_venda_names_its_seller(self): + # No seller: Tiny's channel sets it (Dropstar, 2026-10-23). + self.assertNotIn('vendedor', order_payload(PAID, 777, date(2026, 9, 24))) + # A Venda carries who assembled it (Marcus, 2026-11-17). + venda = {**PAID, 'order': {**PAID['order'], 'seller': {'id': 2001, 'name': 'Lais'}}} + self.assertEqual(order_payload(venda, 777, date(2026, 9, 24))['vendedor'], {'id': 2001}) pickup = order_payload({**PAID, 'order': {**PAID['order'], 'destination': None, 'freight': {'service': 'pickup', 'total_cents': 0}}}, 1) self.assertNotIn('enderecoEntrega', pickup) diff --git a/tests/users_test.py b/tests/users_test.py index cab9276..d5f3dcb 100644 --- a/tests/users_test.py +++ b/tests/users_test.py @@ -378,9 +378,13 @@ def run(): assert (shared['orders'], shared['metres'], shared['printing_hours'], shared['metres_per_hour']) == \ (2, 1.5, 0.5, 3.0), shared - # Two at most in Imprimindo per machine (Dropstar, 2026-10-29): the first - # to come in is printing, the second ripping; a third waits for a place. + # A machine's places in Imprimindo (machines.places, Marcus 2026-11-17): + # three for a new one; here two, so the first to come in is printing, + # the second ripping, and a third waits for a place. cap = admin.call('/operator/machines', {'name': f'Cap {tag}', 'products': ['textil']})['id'] + assert next(m for m in admin.call('/operator/machines')['machines'] if m['id'] == cap)['places'] == 3 + su.call(f'/operator/machines/{cap}/places', {'places': 7}, operator=True, expected=422) + su.call(f'/operator/machines/{cap}/places', {'places': 2}, operator=True) machines.append(cap) with db.connect() as c: pulled = [order_fixture(c, owner, 'file') for _ in range(5)] @@ -425,7 +429,7 @@ def run(): board = {o['id']: o for o in loaded['orders']} assert (board[first]['printing'], board[second_in]['printing'], board[third]['printing']) == \ ('imprimindo', 'ripando', None) - assert loaded['printing_cap'] == 2 + assert next(m for m in loaded['machines'] if m['id'] == cap)['places'] == 2 assert next(m for m in loaded['machines'] if m['id'] == cap)['states'] == {'imp': 2, 'tra': 2} # Nor does an order already printing elsewhere come onto the full machine. with db.connect() as c: diff --git a/web/kanban-board.js b/web/kanban-board.js index 166c7eb..85644dd 100644 --- a/web/kanban-board.js +++ b/web/kanban-board.js @@ -55,9 +55,10 @@ const MIRROR_NOTE='O cliente espelhou a arte: confira antes de imprimir'; const residueNote=item=>{const many=item.residue_accepted>1; return item.residue_accepted+(many?' pontos menores':' ponto menor')+' que 2 mm, que '+(many?'podem':'pode')+' se perder no recorte';}; const residueBadge=item=>badge('! Resíduo aceito','warn','O cliente aceitou imprimir com '+residueNote(item)); -// Two places per machine in Imprimindo (app/machines.py): the first to come -// in is printing, the next is being ripped meanwhile. +// A machine's places in Imprimindo (app/machines.py): the first to come in is +// printing, the next is being ripped meanwhile, any after it waits its turn. const PRINTING={imprimindo:['Imprimindo','live','Já ripou, está rodando'], + aguardando:['Na vez','wait','Na hot folder, espera os da frente'], ripando:['Ripando','rip','O Flexi está ripando enquanto o anterior roda']}; // A film in parts on its machine (items 10 and 13, Dropstar 2026-10-30): // "parte 3/7 imprimindo · 4/7 ripando". Flexi rips the part it took last from @@ -259,11 +260,11 @@ function renderBoard(){ column.ondragover=e=>{ if(dragging?.state===state&&state!=='fin'&&mayReorder(state)){e.preventDefault();markDrop(column,e.clientY);return;} if(!column.classList.contains('allowed'))return;e.preventDefault();column.classList.add('target'); - if(state==='imp')markLane(column,laneAt(column,e.clientY));}; + if(state==='imp')markLane(column,dropMachine(column,e.clientY));}; column.ondragleave=e=>{if(!column.contains(e.relatedTarget)){column.classList.remove('target');markLane(column,null);clearDrop();}}; column.ondrop=async e=>{e.preventDefault();column.classList.remove('target'); const order=board.orders.find(o=>o.id===e.dataTransfer.getData('text/plain')); - const machine=state==='imp'?laneAt(column,e.clientY):null;markLane(column,null); + const machine=state==='imp'?dropMachine(column,e.clientY):null;markLane(column,null); if(!order)return; // Above 1 m Finalizado needs the review photo: the drop opens Revisão // instead of a refused move (Sentry DTF-WEB-B). @@ -301,7 +302,7 @@ function renderBoard(){ // machine has its lane, so a card dragged from the queue can be dropped on // the machine it goes to print on. function printingLanes(orders){ - const cap=board.printing_cap||2, mine=myMachine()?.id; + const mine=myMachine()?.id; const filtered=Object.values(boardFilter).some(Boolean); const out=[]; const list=(board.machines||[]).filter(m=>m.active||orders.some(o=>o.machine?.id===m.id)); @@ -310,6 +311,8 @@ function printingLanes(orders){ .sort((a,b)=>(a.printing==='imprimindo'?0:1)-(b.printing==='imprimindo'?0:1)); // Filtered, a lane with nothing to show stays out; unfiltered, the places count every order. if(filtered&&!here.length)continue; + // Each machine's own places (app/machines.py), set in its sheet. + const cap=m.places||board.printing_cap||3; 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':plural(Math.max(0,cap-n),'vaga','vagas'); @@ -336,6 +339,10 @@ function printingLanes(orders){ return out; } // The machine lane under the pointer in Imprimindo: the last lane head above it. +// Where a card dropped on Imprimindo goes: the machine of whoever is signed in +// on one, wherever it lands in the column (Marcus, 2026-11-17); otherwise the +// lane under the pointer. +const dropMachine=(column,y)=>myMachine()?.id||laneAt(column,y); function laneAt(column,y){ let found=null; for(const el of column.querySelectorAll('[data-machine]')){ diff --git a/web/kanban-numbers.js b/web/kanban-numbers.js index 7ec031b..d0b8a51 100644 --- a/web/kanban-numbers.js +++ b/web/kanban-numbers.js @@ -249,12 +249,12 @@ async function loadStats(){ $('stats-kpis').replaceChildren(cards,extra); statsChart($('stats-chart'),data.daily); // Por máquina: what each printed, how fast, and what it has now. - const cap=board.printing_cap||2; + const capOf=id=>(board.machines||[]).find(x=>x.id===id)?.places||board.printing_cap||3; const machineRows=data.machines.map(m=>{ const tr=node('tr');if(!m.active)tr.classList.add('off'); const name=node('td');name.append(node('b',m.name+(m.active?'':', desativada')), node('span',(m.orders?plural(m.orders,'pedido','pedidos'):'nada')+(m.last_finished?', último '+when(m.last_finished):''),'sub')); - const now=!m.id?'—':m.now.imp?(m.now.imp>=cap?'cheia':m.now.imp+' imprimindo')+(m.now.tra?', '+m.now.tra+' na fila':''):m.now.tra?m.now.tra+' na fila':'livre'; + const now=!m.id?'—':m.now.imp?(m.now.imp>=capOf(m.id)?'cheia':m.now.imp+' imprimindo')+(m.now.tra?', '+m.now.tra+' na fila':''):m.now.tra?m.now.tra+' na fila':'livre'; tr.append(name,node('td',m.orders?metres(m.metres):'—','r'), node('td',m.metres_per_hour!=null?String(m.metres_per_hour).replace('.',',')+' m':'—','r'),node('td',now,'muted')); return tr;}); diff --git a/web/kanban-order.js b/web/kanban-order.js index dfc2aeb..a01fdb0 100644 --- a/web/kanban-order.js +++ b/web/kanban-order.js @@ -362,7 +362,7 @@ function nextBox(order){ const p=proofBtn();if(p)more.push(p); fixBtn(); }else if(st==='imp'){ - title=order.printing==='ripando'?'Ripando enquanto o anterior roda':'Terminou de imprimir?'; + title=order.printing==='ripando'?'Ripando enquanto o anterior roda':order.printing==='aguardando'?'Na vez: espera os da frente':'Terminou de imprimir?'; note('A folha segue para o Revisor conferir.'); if(can('rev'))main.push(moveBtn('rev'));else cannot(); const p=proofBtn();if(p)more.push(p); diff --git a/web/kanban-users.js b/web/kanban-users.js index 3f7e510..921de43 100644 --- a/web/kanban-users.js +++ b/web/kanban-users.js @@ -14,9 +14,9 @@ function machineChoice(machine,mine=false){ b.append(head,node('span',machine.products.map(p=>PRODUCT_LABEL[p]).join(' e ')||'Nenhum produto','sub')); const here=board.orders.filter(o=>o.state==='imp'&&!o.cancelled_at&&o.machine?.id===machine.id) .sort((x,y)=>(x.printing==='imprimindo'?0:1)-(y.printing==='imprimindo'?0:1)); - for(let i=0;i{ + const keep=seller.value; + seller.replaceChildren(none,...list.map(x=>{const o=node('option',x.name);o.value=String(x.id);return o;})); + if(keep&&!list.some(x=>String(x.id)===keep)&&u?.tiny_seller){const o=node('option',u.tiny_seller.name+' (não está mais no Tiny)');o.value=keep;seller.append(o);} + seller.value=keep; + }).catch(e=>{sellerNote.textContent='Não foi possível ler os vendedores do Tiny: '+e.message;}); const left=[]; if(editing&&u.email!==ME.email){ const remove=node('button','Excluir usuário','btn quiet');remove.type='button'; @@ -257,18 +269,28 @@ function userForm(u){ } const m=formDialog(editing?u.name||u.email:'Novo usuário',{width:560,left,lead:editing?avatar(u,'bigava'):null, text:editing?PRESENCE[presence(u)].split(':')[0]+', último acesso '+(u.last_login_at?when(u.last_login_at):'nunca'):'A pessoa entra com o e-mail e esta senha, e troca a senha em Minha conta.', - fields:[row,roleField,field(editing?'Nova senha':'Senha inicial',pass),checkbox('Ativo: pode entrar no sistema',active)], + fields:[row,roleField,field(editing?'Nova senha':'Senha inicial',pass),field('Vendedor no Tiny',seller,sellerNote),checkbox('Ativo: pode entrar no sistema',active)], label:editing?'Salvar':'Criar usuário',onsave:async()=>{ - const body={name:name.value,email:email.value,role:role.value()==='superadmin'?'admin':role.value(),active:active.checked,password:pass.value||null}; + const picked=seller.value?{id:Number(seller.value),name:seller.selectedOptions[0].textContent.replace(/ \(não está mais no Tiny\)$/,'')}:null; + const body={name:name.value,email:email.value,role:role.value()==='superadmin'?'admin':role.value(),active:active.checked,password:pass.value||null,tiny_seller:picked}; await api(editing?'/users/'+u.id:'/users',body); say(editing?'Usuário salvo.':'Usuário criado. Passe o e-mail e a senha inicial para a pessoa.');await loadUsers(); }}); } +// A machine's places in Imprimindo, which are also the files at once in its +// hot folder (app/machines.py): Admin and Gestão set them (Marcus, 2026-11-17). +const PLACES_NOTE='Quantos pedidos a máquina aceita em Imprimindo, e quantos arquivos ficam juntos na hot folder dela.'; +function placesSelect(value){ + const select=node('select'); + for(let n=1;n<=6;n++){const o=node('option',String(n));o.value=String(n);select.append(o);} + select.value=String(value||3);return select; +} function machineForm(m){ const name=node('input');name.required=true;name.maxLength=60;name.value=m?.name||'';name.placeholder='Ex.: Têxtil 2'; const products=pills([['textil','Têxtil'],['uv','UV']],m?.products||[]); const limit=node('input');limit.type='number';limit.min='1';limit.max='99999';limit.step='0.1';limit.inputMode='decimal'; limit.placeholder='Sem limite';limit.value=m?.limit_metres??''; + const places=placesSelect(m?.places); const active=node('input');active.checked=m?m.active:true; const left=[]; if(m){ @@ -281,11 +303,12 @@ function machineForm(m){ const d=formDialog(m?'Editar máquina':'Nova máquina',{width:520,left, fields:[field('Nome',name),group('Imprime',products), field('Limite de metros em aberto',unit(limit,'metros'),'Pedidos novos vão para a máquina do produto com menos metros em aberto, dentro do limite.'), + field('Vagas em Imprimindo',places,PLACES_NOTE), checkbox('Ativa: recebe pedidos',active)], onsave:async()=>{ if(!products.values().length)throw new Error('Marque o que a máquina imprime.'); await api(m?'/machines/'+m.id:'/machines',{name:name.value,active:active.checked,products:products.values(), - limit_metres:limit.value?Number(limit.value):null}); + limit_metres:limit.value?Number(limit.value):null,places:Number(places.value)}); say(m?'Máquina salva.':'Máquina criada.');await loadUsers();await load(); }}); } @@ -396,9 +419,10 @@ async function openMachineSheet(machineId, tab='situacao'){ const price=node('input');price.type='number';price.min='0';price.step='0.01';price.inputMode='decimal'; price.value=machine.price_cents!==null&&machine.price_cents!==undefined?(machine.price_cents/100).toFixed(2):''; const installed=node('input');installed.type='date';installed.value=machine.installed_on||''; + const places=placesSelect(machineState?.places); const minimums={}; const box=node('div',undefined,'mblock'); - box.append(field('Preço de compra (R$)',price),field('Data de instalação',installed)); + box.append(field('Vagas em Imprimindo',places,PLACES_NOTE),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'; const typed=data.minimums[item], fallback=data.default_minimums?.[item]; @@ -412,6 +436,8 @@ async function openMachineSheet(machineId, tab='situacao'){ save.onclick=async()=>{ save.disabled=true;error.hidden=true; try{ + if(machineState&&Number(places.value)!==machineState.places) + await api('/machines/'+machine.id+'/places',{places:Number(places.value)}); await api('/machines/'+machine.id+'/sheet',{ price_cents:price.value.trim()===''?null:Math.round(Number(price.value)*100), installed_on:installed.value||null, diff --git a/web/kanban.js b/web/kanban.js index a6cc952..b2f6f11 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -286,8 +286,9 @@ const REVIEWS_FOLDER='Revisões'; const FOLDER={mode:'showDirectoryPicker' in window?'folder':/Firefox\//.test(navigator.userAgent)?'downloads':'none', brave:!!navigator.brave,handle:null,granted:false,downloads:false,since:null, saved:new Map(),busy:false,status:'',error:'',last:null,lastSig:null, - // Passes in a row each file was held open by another program (DTF-WEB-M). - locked:new Map(), + // Passes in a row each file was held open by another program (DTF-WEB-M), + // or could not be downloaded for the network (DTF-WEB-V). + locked:new Map(),unreachable:new Map(), // Since when the main folder does not answer (DTF-WEB-P), and whether that was reported. awaySince:0,awayReported:false, // Whether this page load cleared the old version's leftovers (order #30). @@ -501,10 +502,11 @@ async function sweepLeftovers(dir,depth){ // tries again. // A file that arrived incomplete waits for the next pass too, reported. const LOCKED=new Set(['NoModificationAllowedError','InvalidModificationError','NotReadableError','InvalidStateError']); -function fileStep(locked,incomplete){ +function fileStep(locked,incomplete,unreachable){ return async(name,fn)=>{try{await fn();return true;} catch(e){ if(e.name==='IncompleteFile'){incomplete.push(e.message);return false;} + if(e.unreachable){unreachable.push(name);return false;} if(!LOCKED.has(e.name))throw e;locked.push(name);return false;}}; } const stageDir=name=>FOLDER.handle.getDirectoryHandle(name,{create:true}); @@ -532,8 +534,14 @@ async function moveSaved(rec,to){ return true; } // One file from storage, whole, into a folder. +// A download that never reached storage or the server (the network dropped +// for a moment, Sentry DTF-WEB-V) is marked unreachable: the file waits for +// the next pass, like one held open, and is reported only if it keeps failing. +async function fetchFile(url,options){ + try{return await fetch(url,options);}catch(e){e.unreachable=true;throw e;} +} async function fetchInto(dir,file,watched=false){ - const r=await fetch(file.url,{referrerPolicy:'no-referrer'}); + const r=await fetchFile(file.url,{referrerPolicy:'no-referrer'}); if(!r.ok||!r.body)throw new Error('não foi possível baixar '+file.name+' (erro '+r.status+').'); await writeWhole(dir,file.name,r,watched); } @@ -598,7 +606,7 @@ async function syncFolder(force=false){ const wanted=new Map(files.map(f=>[f.upload_id,f])); const where=stages?'“'+FOLDER.handle.name+'”':'a pasta de downloads'; let removed=0, moved=0, saved=0; - const locked=[], incomplete=[], step=fileStep(locked,incomplete); + const locked=[], incomplete=[], unreachable=[], step=fileStep(locked,incomplete,unreachable); if(stages){ await clearWork(); if(!FOLDER.swept){for(const name of FLOW_FOLDERS)await sweepLeftovers(await stageDir(name),2);FOLDER.swept=true;} @@ -652,7 +660,7 @@ async function syncFolder(force=false){ for(const r of receipts){ try{await api('/orders/'+r.order+'/receipt/claim',{});}catch(e){if(e.status===409)continue;throw e;} await step(r.name,async()=>{try{ - const res=await fetch('/api/operator/orders/'+r.order+'/receipt'); + const res=await fetchFile('/api/operator/orders/'+r.order+'/receipt'); if(!res.ok||!res.body)throw new Error('não foi possível gerar '+r.name+' (erro '+res.status+').'); await writeWhole(await stageDir(RECEIPTS_FOLDER),r.name,res,true);printed++; }catch(e){await api('/orders/'+r.order+'/receipt/release',{}).catch(()=>{});throw e;}}); @@ -666,7 +674,7 @@ async function syncFolder(force=false){ FOLDER.status='Salvando revisão: '+review.name;paintFolder(); if(!await step(review.name,async()=>{ const view=await api('/orders/'+review.order+'/reviews/'+review.id+'/view'); - const res=await fetch(view.url,{referrerPolicy:'no-referrer'}); + const res=await fetchFile(view.url,{referrerPolicy:'no-referrer'}); if(!res.ok||!res.body)throw new Error('não foi possível baixar '+review.name+' (erro '+res.status+').'); await writeWhole(await stageDir(REVIEWS_FOLDER),review.name,res); }))continue; @@ -685,6 +693,19 @@ async function syncFolder(force=false){ // Expected while the FlexiPRINT reads a file: a warning the first time, and // an error (which reaches Sentry) only when the same file is still held // after LOCKED_REPORT_PASSES passes (Sentry DTF-WEB-M). + // Not downloaded for the network: a warning, and an error (so in Sentry) + // only when the same file still fails after LOCKED_REPORT_PASSES passes. + for(const name of [...FOLDER.unreachable.keys()])if(!unreachable.includes(name))FOLDER.unreachable.delete(name); + for(const name of unreachable)FOLDER.unreachable.set(name,(FOLDER.unreachable.get(name)||0)+1); + if(unreachable.length){ + FOLDER.lastSig=null; + const stuck=unreachable.filter(name=>FOLDER.unreachable.get(name)===LOCKED_REPORT_PASSES); + FOLDER.error='Não foi possível baixar '+unreachable[0]+(unreachable.length>1?' e mais '+(unreachable.length-1):'')+ + ' agora (a rede oscilou). Os outros foram gravados; o Kanban tenta de novo em 30 s.'; + if(stuck.length)say('Pastas automáticas: '+stuck.join(', ')+' não baixa há '+Math.round(LOCKED_REPORT_PASSES*30/60)+ + ' minutos. Confira a internet deste computador.',true); + else if(unreachable.some(name=>FOLDER.unreachable.get(name)===1))say('Pastas automáticas: '+FOLDER.error); + } for(const name of [...FOLDER.locked.keys()])if(!locked.includes(name))FOLDER.locked.delete(name); for(const name of locked)FOLDER.locked.set(name,(FOLDER.locked.get(name)||0)+1); if(locked.length){ @@ -971,7 +992,7 @@ function stageLimitsDialog(){ }).catch(error=>say(error.message,true)); } function field(label,input,hint){ - const l=node('label',undefined,'fld');l.append(label,input);if(hint)l.append(node('small',hint));return l; + const l=node('label',undefined,'fld');l.append(label,input);if(hint)l.append(hint instanceof Node?hint:node('small',hint));return l; } // A checkbox drawn as the design's box. function checkbox(label,input){