diff --git a/app/api/operator/orders.py b/app/api/operator/orders.py index 11919eb..65bbf4b 100644 --- a/app/api/operator/orders.py +++ b/app/api/operator/orders.py @@ -73,6 +73,14 @@ def cancel_order(uid: UUID, body: Resolution, user=Depends(can('cancel'))): if not row: raise HTTPException(404, 'Pedido não encontrado ou já cancelado.') hotfolder.stop(c, uid) + # Its proof card not yet answered goes with it: left on the board, it + # could still be pulled and printed for an order no one will take. + cards = c.execute('''UPDATE dtf_local.orders SET cancelled_at=now(), cancelled_by=%s, cancel_reason=%s, + version=version+1, updated_at=now() + WHERE parent_id=%s AND cancelled_at IS NULL AND proof_result IS NULL RETURNING id''', + (user, f"Pedido #{row['number']} cancelado: {body.note}", uid)).fetchall() + for card in cards: + hotfolder.stop(c, card['id']) if payments.in_tiny(row): sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL", (f'{uid}:paid:tiny',)).fetchone() diff --git a/app/api/users.py b/app/api/users.py index f15ff5b..483f05a 100644 --- a/app/api/users.py +++ b/app/api/users.py @@ -269,11 +269,14 @@ def list_machines(user=Depends(can('view'))): def create_machine(body: MachineIn, user=Depends(can('users'))): mid = uuid4() 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,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)) + # A machine's hot folder is its first name, for good: no other machine + # may be called that, or two would share one folder. + if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) OR lower(folder)=lower(%s)', + (body.name.strip(), body.name.strip())).fetchone(): + raise HTTPException(409, 'Já existe uma máquina, ou a pasta de uma máquina, com este nome.') + c.execute('''INSERT INTO dtf_local.machines(id,name,folder,products,active,limit_metres,places) + VALUES(%s,%s,%s,%s,%s,%s,%s)''', (mid, body.name.strip(), 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)} @@ -281,9 +284,9 @@ def create_machine(body: MachineIn, user=Depends(can('users'))): @router.post('/api/operator/machines/{mid}') def update_machine(mid: UUID, 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) AND id<>%s', - (body.name.strip(), mid)).fetchone(): - raise HTTPException(409, 'Já existe uma máquina com este nome.') + if c.execute('''SELECT 1 FROM dtf_local.machines WHERE (lower(name)=lower(%s) OR lower(folder)=lower(%s)) + AND id<>%s''', (body.name.strip(), body.name.strip(), mid)).fetchone(): + raise HTTPException(409, 'Já existe uma máquina, ou a pasta de uma máquina, com este nome.') 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, diff --git a/app/artwork.py b/app/artwork.py index b07079c..5800b2b 100644 --- a/app/artwork.py +++ b/app/artwork.py @@ -74,6 +74,20 @@ def submit_files(c, order, body, identity, kind, actor): current = {(row['upload_id'], row['item_index']) for row in c.execute( "SELECT upload_id,item_index FROM dtf_local.order_files WHERE order_id=%s AND kind='final' AND active", (order['id'],)).fetchall()} if kind == 'final' else set() + # A film in parts is approved whole: with only some of its parts, the + # others never reach the folders or the machine (#114, #128, #130). + if kind == 'final': + sent = {} + for ref in body.files: + sent.setdefault(ref.item_index, set()).add(str(ref.upload_id)) + for row in c.execute('''SELECT item_index, array_agg(upload_id::text ORDER BY part) AS uploads, + array_agg(part ORDER BY part) AS numbers FROM dtf_local.print_parts WHERE order_id=%s + GROUP BY item_index HAVING count(*) > 1''', (order['id'],)).fetchall(): + mine = sent.get(row['item_index'], set()) + missing = [n for n, u in zip(row['numbers'], row['uploads']) if u not in mine] + if mine & set(row['uploads']) and missing: + raise HTTPException(422, f"O filme do item {row['item_index'] + 1} tem {len(row['uploads'])} partes: " + f"envie todas (faltam {', '.join('p' + str(n) for n in missing)}).") kept = {ref.upload_id for ref in body.files if (ref.upload_id, ref.item_index) in current} if kept and len(kept) == len(body.files): raise HTTPException(409, 'Estes já são os arquivos finais. Envie o arquivo novo.') diff --git a/app/hotfolder.py b/app/hotfolder.py index 02fa535..0976c4f 100644 --- a/app/hotfolder.py +++ b/app/hotfolder.py @@ -119,12 +119,12 @@ def claim(c, user): 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, m.places, + rows = c.execute('''SELECT h.*, o.machine_id, o.contraction, o.snapshot, COALESCE(m.folder, m.name) AS machine_folder, 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 WHERE h.state IN ('queued','claimed','written') AND o.state='imp' AND o.cancelled_at IS NULL - ORDER BY m.name, entered, h.order_id, h.seq FOR UPDATE OF h''').fetchall() + ORDER BY m.created_at, m.id, entered, h.order_id, h.seq FOR UPDATE OF h''').fetchall() due, busy, blocked = [], {}, set() for row in rows: machine = row['machine_id'] @@ -139,7 +139,9 @@ def claim(c, user): if busy.get(machine, 0) >= row['places'] or not cls: blocked.add(order) continue - folder = f"{row['machine_name']}/{cls}" + # The machine's folder, fixed at its creation: a renamed machine keeps + # the path FlexiPRINT watches. + folder = f"{row['machine_folder']}/{cls}" c.execute('''UPDATE dtf_local.hot_parts SET state='claimed', claimed_at=now(), claimed_by=%s, folder=%s WHERE id=%s''', (user, folder, row['id'])) busy[machine] = busy.get(machine, 0) + 1 diff --git a/app/machines.py b/app/machines.py index 393f2d7..ae32cc4 100644 --- a/app/machines.py +++ b/app/machines.py @@ -39,7 +39,8 @@ 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, places FROM dtf_local.machines + machines = c.execute('''SELECT id, name, COALESCE(folder, name) AS folder, products, active, limit_metres, places + FROM dtf_local.machines ORDER BY created_at, name''').fetchall() load = loads(c) operators = {} @@ -55,7 +56,7 @@ def rows(c, with_operators=False): for m in machines: key = str(m['id']) used = load.get(key, {'metres': Decimal(0), 'orders': 0, 'states': {}}) - row = {'id': key, 'name': m['name'], 'products': m['products'], 'active': m['active'], + row = {'id': key, 'name': m['name'], 'folder': m['folder'], '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'], diff --git a/app/migrations/202611272000_machine-folder.sql b/app/migrations/202611272000_machine-folder.sql new file mode 100644 index 0000000..d514b15 --- /dev/null +++ b/app/migrations/202611272000_machine-folder.sql @@ -0,0 +1,5 @@ +-- Each machine's hot folder (3. Imprimindo//C1..) is fixed when the +-- machine is created: FlexiPRINT watches that path, so renaming the machine +-- must not send its files to a folder nobody watches (2026-11-27). +ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS folder text; +UPDATE dtf_local.machines SET folder=name WHERE folder IS NULL; diff --git a/tests/print_file_test.py b/tests/print_file_test.py index d4d3081..a88022f 100644 --- a/tests/print_file_test.py +++ b/tests/print_file_test.py @@ -251,6 +251,13 @@ def run(): # No class measured or chosen: the part waits for one. assert not [p for p in client.call('/operator/queue/hot', {}, operator=True)['write'] if p['order'] == oid] client.call('/operator/orders/' + oid + '/contraction', {'item_index': 0, 'value': 'C2'}, operator=True) + # Renamed, the machine keeps its folder, the path FlexiPRINT watches; + # no other machine may then take that folder's name. + client.call('/operator/machines/' + machine, {'name': f'Hot {tag} renomeada', 'products': ['textil']}, + operator=True) + listed = next(m for m in client.call('/operator/machines', operator=True)['machines'] if m['id'] == machine) + assert listed['name'] == f'Hot {tag} renomeada' and listed['folder'] == f'Hot {tag}', listed + client.call('/operator/machines', {'name': f'Hot {tag}', 'products': ['textil']}, operator=True, expected=409) hot = client.call('/operator/queue/hot', {}, operator=True) due = [p for p in hot['write'] if p['order'] == oid] assert hot['folder'] == '3. Imprimindo' and [(p['folder'], p['name']) for p in due] == \ @@ -269,7 +276,8 @@ def run(): assert board['hot'] == {'parts': 1, 'taken': 1, 'waiting': 0}, board['hot'] # Which items go again is chosen before Imprimindo, not while printing (#105). client.call('/operator/orders/' + oid + '/print-items', {'items': [0]}, operator=True, expected=409) - print('PASS: the printing file goes once into its machine\'s hot folder for its class') + print('PASS: the printing file goes once into its machine\'s hot folder for its class, ' + 'and a renamed machine keeps its folder') finally: client.call('/operator/machines/' + machine, {'name': f'Hot {tag}', 'products': ['textil'], 'active': False}, operator=True) @@ -444,6 +452,36 @@ def run(): (f"{parent['id']}:production_started:tiny",)).fetchone() print('PASS: a file finished after Prova OK becomes the final, queues the order and tells Tiny') + # Cancelled, an order takes its proof card not yet answered with it: left + # on the board, the card could still be pulled and printed. + readable = upload_bytes(client, artwork(), name='LOCAL-PROOF-CANCEL.png') + parent = paid_order(client, loose_item(readable, copies=1)) + with db.connect() as c: + c.execute("UPDATE dtf_local.orders SET snapshot=jsonb_set(snapshot,'{proof}','true') WHERE id=%s", + (parent['id'],)) + card = client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True) + client.call('/operator/orders/' + parent['id'] + '/cancel', {'note': 'cliente desistiu'}, operator=True) + with db.connect() as c: + gone = c.execute('SELECT cancelled_at, cancel_reason FROM dtf_local.orders WHERE id=%s', (card['id'],)).fetchone() + assert gone['cancelled_at'] and 'cliente desistiu' in gone['cancel_reason'], gone + print('PASS: cancelling an order cancels its open proof card') + + # A film in parts is approved whole: only some of its parts are refused, + # or the others never reach the machine (#114, #128, #130). + whole = upload_bytes(client, artwork(), name='LOCAL-PARTS.png') + film = paid_order(client, loose_item(whole, copies=1)) + _, film_row = wait_print(client, film['id'], 'ready') + second = upload_bytes(client, artwork(), name='LOCAL-PARTS-P2.png') + with db.connect() as c: + c.execute('INSERT INTO dtf_local.print_parts(order_id,item_index,part,upload_id) VALUES(%s,0,2,%s)', + (film['id'], second)) + refused = client.call('/operator/orders/' + film['id'] + '/final-files', + {'version': version_of(film['id']), 'note': 'só a primeira', + 'files': [{'item_index': 0, 'upload_id': str(film_row['upload_id'])}]}, + operator=True, expected=422) + assert 'faltam p2' in refused['detail'], refused + print('PASS: a film in parts is approved with all its parts or not at all') + # Reprinting some items (Marcus, 2026-11-26, #105): an order the machine # already printed, back in the queue after one item's final changed, sends # only that item; the pass to Revisão keeps it for the machine's metres and diff --git a/web/kanban-order.js b/web/kanban-order.js index 9bd0153..b0af8d2 100644 --- a/web/kanban-order.js +++ b/web/kanban-order.js @@ -330,7 +330,7 @@ function nextBox(order){ const manual=(order.print_files||[]).some(r=>r.status==='manual'); note(finalDone(order)?'Abra o PNG gerado pelo Prumo e confirme a contração.':manual ?'O original exige preparo manual. Abra o pedido pai, envie o PNG completo e depois gere a prova de novo.' - :'O Prumo prepara até 15 cm por classe e aprova o PNG final automaticamente.'); + :'O Prumo prepara até 30 cm por classe e aprova o PNG final automaticamente.'); if(manual&&may('produce'))more.push(button('Abrir pedido pai',()=>openPanel(order.proof_parent.id),'btn lg')); if(finalDone(order)&&may('produce'))main.push(checkButton(order,'btn pri lg')); if((order.print_files||[]).some(r=>r.status==='failed'||r.status==='manual'||r.timed_out)&&may('produce')) diff --git a/web/kanban-users.js b/web/kanban-users.js index 71c2ad5..353f32a 100644 --- a/web/kanban-users.js +++ b/web/kanban-users.js @@ -323,7 +323,10 @@ function machineForm(m){ left.push(remove); } const d=formDialog(m?'Editar máquina':'Nova máquina',{width:520,left, - fields:[field('Nome',name),group('Imprime',products), + // The hot folder is the machine's first name, for good (FlexiPRINT watches + // that path): renaming the machine does not move it. + fields:[field('Nome',name,m?'Pasta no FlexiPRINT: 3. Imprimindo/'+(m.folder||m.name)+'. Trocar o nome não muda a pasta.':undefined), + 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)],