From b8496b858fb7342eb2bf9129fa0a3033dcaddacc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Fri, 27 Nov 2026 10:00:54 -0300 Subject: [PATCH] feat: a reprint sends only the items chosen to the machine (Marcus, 2026-11-26, #105) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An order the machine already printed, back in Arte conferida, sends again only the items whose final changed since the machine took them; the panel's "Vai para a máquina" shows and changes the choice, and the card says "Reimpressão". The order stays one card. The pass to Revisão keeps the items printed, so the machine's metres count only those. Co-Authored-By: Claude Opus 5.5 (1M context) --- .gitea/workflows/deploy.yml | 2 +- app/api/operator/board.py | 8 ++++ app/api/operator/orders.py | 46 ++++++++++++++++++- app/hotfolder.py | 30 ++++++++++-- app/machine_log.py | 7 ++- app/machine_stats.py | 15 +++--- app/migrations/202611271200_reprint-items.sql | 5 ++ tests/print_file_test.py | 2 + tests/test_reprint.py | 35 ++++++++++++++ web/kanban-board.js | 2 + web/kanban-order.js | 27 +++++++++++ 11 files changed, 165 insertions(+), 14 deletions(-) create mode 100644 app/migrations/202611271200_reprint-items.sql create mode 100644 tests/test_reprint.py diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index eb636c9..dff217d 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -101,7 +101,7 @@ jobs: # the generator's geometry. The provider suites use a fake transport: they # prove the documented contract, not the integration. - name: Print-file geometry and provider adapters - run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_sheet_trim tests.test_one_machine tests.test_profiles tests.test_sheet_gap tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain tests.test_db_outage tests.test_health -v + run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_sheet_trim tests.test_one_machine tests.test_profiles tests.test_sheet_gap tests.test_reprint tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain tests.test_db_outage tests.test_health -v - name: Runtime and retention regressions run: | diff --git a/app/api/operator/board.py b/app/api/operator/board.py index 4e40eb0..b005506 100644 --- a/app/api/operator/board.py +++ b/app/api/operator/board.py @@ -209,6 +209,9 @@ def with_print_files(c, orders): FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='cor' ORDER BY order_id,id DESC''', (ids,)).fetchall()} # Where a printing order's files are in its machine's hot folder (item 10). hot = hotfolder.progress(c, [o['id'] for o in orders if o['state'] == 'imp']) + # Orders the machine already printed: a reprint chooses which items go + # again (#105), the ones whose final changed suggested. + taken = hotfolder.printed(c, [o['id'] for o in orders if o['state'] in ('rec', 'tra', 'cor')]) # Each parent's latest proof card, and each card's parent (app/proof.py). children = {r['parent_id']: r for r in c.execute('''SELECT DISTINCT ON (parent_id) parent_id,id,number,state, proof_result,proof_decided_at,proof_decided_by,proof_reason,machine_id FROM dtf_local.orders @@ -239,6 +242,11 @@ def with_print_files(c, orders): order['final_items'] = sorted({row['item_index'] for row in approved}) # The approved finals themselves: "Tratar a arte" keeps those it does not replace. order['finals'] = [{'item_index': row['item_index'], 'upload_id': row['upload_id']} for row in approved] + if order['id'] in taken: + order['printed_before'] = True + order['print_suggested'] = hotfolder.reprint_default( + [(f['item_index'], f['upload_id']) for f in order.get('finals') or []], taken[order['id']], + len(order['snapshot']['items'])) mine = [row for row in treated if row['order_id'] == order['id']] order['treated'] = {'items': [row['item_index'] for row in mine], 'by': mine[0]['created_by']} if mine else None order['corrections'] = [{k: row[k] for k in ('item_index', 'upload_id', 'name', 'expired')} diff --git a/app/api/operator/orders.py b/app/api/operator/orders.py index 745c456..9fdfdc1 100644 --- a/app/api/operator/orders.py +++ b/app/api/operator/orders.py @@ -504,8 +504,24 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)): if body.state == 'imp' and row['machine_id']: machine_name = (c.execute('SELECT name FROM dtf_local.machines WHERE id=%s', (row['machine_id'],)).fetchone() or {}).get('name') - c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,machine) - VALUES(%s,%s,%s,%s,%s,%s,%s)''', (uid,row['state'],body.state,user,body.reason,back,machine_name)) + # A pass from Imprimindo to Revisão keeps the items it printed, when + # only some went again (machine_log counts their metres). + printed_items = row.get('print_items') if row['state'] == 'imp' and body.state == 'rev' and not back else None + c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,machine,items) + VALUES(%s,%s,%s,%s,%s,%s,%s,%s)''', (uid,row['state'],body.state,user,body.reason,back,machine_name,printed_items)) + # Back in the queue after a print: only the items whose final changed + # go to the machine again, unless the team already chose (#105). + if body.state == 'tra' and not back and row.get('print_items') is None: + taken = hotfolder.printed(c, [uid]).get(uid) + if taken: + finals = [(r['item_index'], r['upload_id']) for r in c.execute('''SELECT item_index,upload_id + FROM dtf_local.order_files WHERE order_id=%s AND kind='final' AND active''', (uid,)).fetchall()] + default = hotfolder.reprint_default(finals, taken, len(row['snapshot']['items'])) + if default: + c.execute('UPDATE dtf_local.orders SET print_items=%s WHERE id=%s', (default, uid)) + # Finished: the next time it goes back, the choice starts over. + if body.state == 'fin' and not back: + c.execute('UPDATE dtf_local.orders SET print_items=NULL WHERE id=%s', (uid,)) # Pulled to Imprimindo, its files go to its machine's hot folder; out # of it, what Flexi did not take leaves (item 10). if row['state'] == 'imp': @@ -537,6 +553,32 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)): enqueue(c, key, 'tiny', tiny) return changed +class PrintItems(StrictModel): + items: list[int] = Field(min_length=1, max_length=200) + + +@router.post('/api/operator/orders/{uid}/print-items') +def choose_print_items(uid: UUID, body: PrintItems, user=Depends(can('produce'))): + """Which items go to the machine this time (Marcus, 2026-11-26, #105): + a reprint sends only those. Every item: all go, as on the first print.""" + with db.connect() as c: + row = c.execute('SELECT id,number,state,snapshot,cancelled_at FROM dtf_local.orders WHERE id=%s FOR UPDATE', + (uid,)).fetchone() + if not row: + raise HTTPException(404, 'Pedido não encontrado.') + if row['cancelled_at'] or row['state'] not in ('rec', 'tra', 'cor'): + raise HTTPException(409, 'Os itens que vão para a máquina são escolhidos antes de Imprimindo.') + count = len(row['snapshot']['items']) + items = sorted(set(body.items)) + if any(i < 0 or i >= count for i in items): + raise HTTPException(422, 'Item do pedido inválido.') + chosen = None if len(items) == count else items + c.execute('UPDATE dtf_local.orders SET print_items=%s, version=version+1, updated_at=now() WHERE id=%s', + (chosen, uid)) + audit('order_print_items', order=row['number'], items=','.join(str(i + 1) for i in items), operator=user) + return {'ok': True, 'print_items': chosen} + + @router.post('/api/operator/orders/{uid}/print-files') def regenerate(uid: UUID, user=Depends(can('produce'))): """Queue generation again for items that failed or went to manual preparation, diff --git a/app/hotfolder.py b/app/hotfolder.py index 23a1414..1667410 100644 --- a/app/hotfolder.py +++ b/app/hotfolder.py @@ -52,10 +52,13 @@ def folder_class(order, index): def start(c, order_id): """The order entered Imprimindo: its approved finals queue for its - machine's folder, item by item, part by part.""" + machine's folder, item by item, part by part; on a reprint only the items + chosen to go again (orders.print_items).""" files = c.execute('''SELECT f.item_index, f.upload_id, u.name FROM dtf_local.order_files f - JOIN dtf_local.uploads u ON u.id=f.upload_id - WHERE f.order_id=%s AND f.kind='final' AND f.active ORDER BY f.item_index, u.name''', (order_id,)).fetchall() + JOIN dtf_local.uploads u ON u.id=f.upload_id JOIN dtf_local.orders o ON o.id=f.order_id + WHERE f.order_id=%s AND f.kind='final' AND f.active + AND (o.print_items IS NULL OR f.item_index = ANY(o.print_items)) + ORDER BY f.item_index, u.name''', (order_id,)).fetchall() round_ = c.execute('SELECT COALESCE(max(round), 0) + 1 AS r FROM dtf_local.hot_parts WHERE order_id=%s', (order_id,)).fetchone()['r'] for seq, row in enumerate(files, 1): @@ -63,6 +66,27 @@ def start(c, order_id): VALUES(%s,%s,%s,%s,%s,%s)''', (order_id, round_, seq, row['item_index'], row['upload_id'], row['name'])) +def printed(c, order_ids): + """The files each order's machine has already taken, {order id: {upload + ids}}: an order in it was printed before.""" + rows = c.execute('''SELECT order_id, upload_id FROM dtf_local.hot_parts + WHERE order_id=ANY(%s) AND state IN ('written','consumed')''', (list(order_ids),)).fetchall() + out = {} + for row in rows: + out.setdefault(row['order_id'], set()).add(row['upload_id']) + return out + + +def reprint_default(finals, taken, count): + """The items to print again: those whose current final the machine has + not taken. `finals` is [(item, upload id)]; None when all go (never printed, + or nothing new).""" + if not taken: + return None + changed = sorted({item for item, upload in finals if upload not in taken}) + return changed if changed and len(changed) < count else None + + def stop(c, order_id): """The order left Imprimindo or was cancelled: what is not written stays unwritten, and what Flexi has not taken is withdrawn from the folder.""" diff --git a/app/machine_log.py b/app/machine_log.py index 0606ab4..cf60ba9 100644 --- a/app/machine_log.py +++ b/app/machine_log.py @@ -61,7 +61,7 @@ def one_decimal(value): def printed_since(c, machine_id, since): """Film metres the machine printed after `since` (None: ever), as Decimal.""" from .proof import PROOF_SHEET_CM - rows = c.execute('''SELECT o.snapshot FROM dtf_local.movements m + rows = c.execute('''SELECT o.snapshot, m.items FROM dtf_local.movements m JOIN dtf_local.orders o ON o.id=m.order_id WHERE o.machine_id=%s AND m.from_state='imp' AND m.to_state='rev' AND NOT m.back AND (%s::timestamptz IS NULL OR m.created_at > %s::timestamptz)''', @@ -70,7 +70,10 @@ def printed_since(c, machine_id, since): for row in rows: snapshot = row['snapshot'] or {} proof = bool(snapshot.get('proof_of')) - for item in snapshot.get('items') or []: + for index, item in enumerate(snapshot.get('items') or []): + # A reprint counts only the items that went again (#105). + if row.get('items') is not None and index not in row['items']: + continue if proof: total += PROOF_SHEET_CM else: diff --git a/app/machine_stats.py b/app/machine_stats.py index 10882ed..bb29874 100644 --- a/app/machine_stats.py +++ b/app/machine_stats.py @@ -119,19 +119,22 @@ def ratios(printed, hours_running=None, supplies_cents=0, parts_cents=0, rolls=N def _printed_orders(c, machine_id, start, end): """The orders that left Imprimindo for Revisão on the machine in the period, with what is needed to count film and what they sold.""" - return c.execute('''SELECT o.id, o.snapshot, o.parent_id, o.cancelled_at, o.payment + return c.execute('''SELECT o.id, o.snapshot, o.parent_id, o.cancelled_at, o.payment, m.items FROM dtf_local.movements m JOIN dtf_local.orders o ON o.id=m.order_id WHERE o.machine_id=%s AND m.from_state='imp' AND m.to_state='rev' AND NOT m.back AND m.created_at>=%s AND m.created_at<%s''', (machine_id, start, end)).fetchall() -def _film(snapshot): - """The film printed for one order (machine_log's rule), as Decimal.""" +def _film(snapshot, items=None): + """The film printed for one order (machine_log's rule), as Decimal; on a + reprint only the `items` that went again.""" from .proof import PROOF_SHEET_CM snapshot = snapshot or {} proof = bool(snapshot.get('proof_of')) total = Decimal(0) - for item in snapshot.get('items') or []: + for index, item in enumerate(snapshot.get('items') or []): + if items is not None and index not in items: + continue if proof: total += PROOF_SHEET_CM else: @@ -154,7 +157,7 @@ def _sold(row): def printed_between(c, machine_id, start, end): """Film metres the machine printed in [start, end), as Decimal.""" - return sum((_film(row['snapshot']) for row in _printed_orders(c, machine_id, start, end)), + return sum((_film(row['snapshot'], row.get('items')) for row in _printed_orders(c, machine_id, start, end)), Decimal(0)) @@ -186,7 +189,7 @@ def machine_month(c, machine, start, end): 'contribution_cents'}. `machine` is its row from dtf_local.machines.""" mid = machine['id'] rows = _printed_orders(c, mid, start, end) - printed = sum((_film(row['snapshot']) for row in rows), Decimal(0)) + printed = sum((_film(row['snapshot'], row.get('items')) for row in rows), Decimal(0)) sold = sum((_sold(row) for row in rows), 0) ids = [row['id'] for row in rows] spans = c.execute('''WITH events AS ( diff --git a/app/migrations/202611271200_reprint-items.sql b/app/migrations/202611271200_reprint-items.sql new file mode 100644 index 0000000..a5b61b5 --- /dev/null +++ b/app/migrations/202611271200_reprint-items.sql @@ -0,0 +1,5 @@ +-- Reprinting some items of an order (Marcus, 2026-11-26, #105): the items +-- that go to the machine this time (NULL: all), and on each pass from +-- Imprimindo to Revisão the items that were printed, for the machine's metres. +ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS print_items integer[]; +ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS items integer[]; diff --git a/tests/print_file_test.py b/tests/print_file_test.py index dd3b4a8..f30aaed 100644 --- a/tests/print_file_test.py +++ b/tests/print_file_test.py @@ -265,6 +265,8 @@ def run(): assert not client.call(f'/operator/queue/hot/{part}', {'state': 'consumed'}, operator=True)['ok'] board = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == oid) 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') finally: client.call('/operator/machines/' + machine, {'name': f'Hot {tag}', 'products': ['textil'], 'active': False}, diff --git a/tests/test_reprint.py b/tests/test_reprint.py new file mode 100644 index 0000000..c1ba9cb --- /dev/null +++ b/tests/test_reprint.py @@ -0,0 +1,35 @@ +"""Reprinting some items (Marcus, 2026-11-26, #105): back in the queue after a +print, only the items whose final changed go to the machine again. + +Run from the repository root: python3 -m unittest tests.test_reprint -v. +""" +import unittest +from decimal import Decimal + +from app.hotfolder import reprint_default +from app.machine_stats import _film + + +class ReprintTests(unittest.TestCase): + def test_only_the_item_with_a_new_final_goes_again(self): + finals = [(0, 'a'), (1, 'b-new'), (2, 'c')] + self.assertEqual(reprint_default(finals, {'a', 'b-old', 'c'}, 3), [1]) + + def test_never_printed_or_nothing_new_or_all_new_is_every_item(self): + finals = [(0, 'a'), (1, 'b')] + self.assertIsNone(reprint_default(finals, None, 2)) # never printed + self.assertIsNone(reprint_default(finals, {'a', 'b'}, 2)) # printed again as it was + self.assertIsNone(reprint_default(finals, {'x', 'y'}, 2)) # every file new + + def test_a_film_in_parts_goes_again_when_one_part_is_new(self): + finals = [(0, 'p1'), (0, 'p2-new'), (1, 'q'), (2, 'r')] + self.assertEqual(reprint_default(finals, {'p1', 'p2', 'q', 'r'}, 3), [0]) + + def test_the_machine_counts_only_the_items_printed_again(self): + snapshot = {'items': [{'billed_metres': '2.0'}, {'billed_metres': '3.5'}]} + self.assertEqual(_film(snapshot), Decimal('5.5')) + self.assertEqual(_film(snapshot, [1]), Decimal('3.5')) + + +if __name__ == '__main__': + unittest.main() diff --git a/web/kanban-board.js b/web/kanban-board.js index 6a4b46f..1982d7f 100644 --- a/web/kanban-board.js +++ b/web/kanban-board.js @@ -426,6 +426,8 @@ function cardFlags(order){ if(live&&s.items.some(i=>i.quality_status==='warning'))out.push(['warn','Nota '+(lowestGrade(s.items)??'baixa'),'Nota da arte baixa: o cliente aceitou a ressalva de resolução']); const dots=s.items.reduce((t,i)=>t+(i.residue_accepted||0),0); if(live&&dots)out.push(['warn','Resíduo','O cliente aceitou imprimir com '+residueNote({residue_accepted:dots})]); + // A reprint: only some items go to the machine again (#105). + if(live&&order.print_items?.length)out.push(['warn','Reimpressão','Vão para a máquina só: '+order.print_items.map(i=>'item '+(i+1)).join(', ')]); // A ready sheet with pieces closer than 5 mm (Marcus, 2026-11-26, #81). const close=s.items.reduce((t,i)=>t+(i.close_pieces||0),0); if(live&&close)out.push(['warn','Peças coladas',closeNote(close)]); diff --git a/web/kanban-order.js b/web/kanban-order.js index daec729..4c29e7e 100644 --- a/web/kanban-order.js +++ b/web/kanban-order.js @@ -317,6 +317,9 @@ function nextBox(order){ const b=button('Prova OK',()=>proofOk(order),className);b.dataset.proof='';b.title='A prova foi impressa e conferida';return b;}; const cannot=()=>note(!mayAct(order)?'Pedido da '+(order.machine?.name||'outra máquina')+': só quem está nela move o card.' :st==='rev'?'A folha impressa é conferida e liberada pelo Revisor.':'Daqui em diante, com a produção.'); + // An order the machine already printed: which items go again (#105). + if(['rec','tra','cor'].includes(st)&&order.printed_before&&!order.cancelled_at&&order.snapshot.items.length>1) + body.push(reprintChoice(order)); // The proof was rejected: its reason, and a new proof card when the art is fixed. if(st==='rec'&&proofRejected(order)){ const p=node('p',undefined,'nnote');p.append(node('b','Prova reprovada: '),order.proof_card.proof_reason);body.push(p); @@ -1129,6 +1132,30 @@ function itemCard(order,item,index){ } // A disclosure's summary: the chevron turns when it opens. function discSummary(text){const s=node('summary');s.append(svgIcon(IC.right,'i s'),node('span',text));return s;} +// "Vai para a máquina" (Marcus, 2026-11-26, #105): the order was printed +// before, so only the items ticked go again. Ticked at first: the choice +// saved, or the items whose final changed since the machine took them. +function reprintChoice(order){ + const box=node('div',undefined,'fld');box.append(node('span','Vai para a máquina')); + const chosen=new Set(order.print_items||order.print_suggested||order.snapshot.items.map((_,i)=>i)); + const boxes=order.snapshot.items.map((item,index)=>{ + const input=node('input');input.checked=chosen.has(index);input.disabled=!may('produce'); + box.append(checkbox('Item '+(index+1)+', '+productName(item),input));return input; + }); + box.append(node('small',order.print_items?'Só os itens marcados vão para a máquina.' + :order.print_suggested?'Marcados os itens cujo arquivo mudou desde a última impressão.' + :'O pedido já foi impresso: marque só os itens que precisam sair de novo.')); + if(may('produce')){ + const save=button('Salvar itens',async()=>{ + const items=boxes.map((b,i)=>b.checked?i:null).filter(i=>i!==null); + if(!items.length){say('Marque pelo menos um item para a máquina.');return;} + await api('/orders/'+order.id+'/print-items',{items});await load(); + say(items.length===boxes.length?'Todos os itens vão para a máquina.':'Vão para a máquina: '+items.map(i=>'item '+(i+1)).join(', ')+'.'); + },'btn'); + save.classList.add('self-start');box.append(save); + } + return box; +} // Each item's current final (one file, or a film's parts), to keep as it is. function currentFinals(order,revisions){ return order.snapshot.items.map((_,index)=>{