feat: a reprint sends only the items chosen to the machine (Marcus, 2026-11-26, #105)
All checks were successful
Build and deploy / Validate source (push) Successful in 11s
Build and deploy / Integration suite on a real stack (push) Successful in 7m55s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m34s
All checks were successful
Build and deploy / Validate source (push) Successful in 11s
Build and deploy / Integration suite on a real stack (push) Successful in 7m55s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m34s
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) <noreply@anthropic.com>
This commit is contained in:
@@ -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')}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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."""
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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 (
|
||||
|
||||
5
app/migrations/202611271200_reprint-items.sql
Normal file
5
app/migrations/202611271200_reprint-items.sql
Normal file
@@ -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[];
|
||||
Reference in New Issue
Block a user