fix: a transfer asks which part the new machine resumes from and names the old machine's .prt to delete (Marcus, 2026-12-01)

The hot folder takes a PNG in about 10 s and the Hoson queues it, so the
last part taken is not the one being ripped. The dialog lists the parts
(already taken or still in the folder) and asks where to resume once any
was taken; the new round starts there, and the parts from there on that
the old machine took are named as Hoson .prt files to delete, in the
toast, the card and the history. The film card no longer claims which part
prints: '2/3 partes com a máquina'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-12-01 09:39:58 -03:00
parent ea05ba6a31
commit 41e905555b
7 changed files with 111 additions and 38 deletions

View File

@@ -220,10 +220,12 @@ def with_print_files(c, orders):
previews = c.execute('''SELECT order_id,number,sent_at,sent_by,decided_at,result,reason,decided_by
FROM dtf_local.redesign_previews WHERE order_id=ANY(%s) ORDER BY order_id,number''', (ids,)).fetchall()
# Each order's machine transfers, oldest first (Rodada 5, D4).
transfers = c.execute('''SELECT order_id,from_name,to_name,reason,resumed_from,created_by,created_at
transfers = c.execute('''SELECT order_id,from_name,to_name,reason,resumed_from,delete_prt,created_by,created_at
FROM dtf_local.machine_transfers WHERE order_id=ANY(%s) ORDER BY id''', (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'])
# Each printing order's parts, for the transfer dialog's "Recomeçar da parte" (D4).
hot_parts = hotfolder.last_round(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')])
@@ -241,6 +243,7 @@ def with_print_files(c, orders):
proof_reviews = reviews.by_order(c, [r['id'] for r in children.values()])
for order in orders:
order['hot'] = hot.get(order['id'])
order['hot_parts'] = hot_parts.get(order['id'], [])
order['reviews'] = review_rows.get(str(order['id']), [])
child = children.get(order['id'])
# Its machine: an order prints where its approved proof did (Dropstar, 2026-11-05).
@@ -278,7 +281,7 @@ def with_print_files(c, orders):
'reason', 'decided_by')}
for row in previews if row['order_id'] == order['id']]
order['transfers'] = [{k: row[k] for k in ('from_name', 'to_name', 'reason', 'resumed_from',
'created_by', 'created_at')}
'delete_prt', 'created_by', 'created_at')}
for row in transfers if row['order_id'] == order['id']]
return assign_machines(c, orders)

View File

@@ -136,6 +136,9 @@ def choose_machine(uid: UUID, body: MachineChoice, request: Request, user=Depend
class MachineTransfer(StrictModel):
machine_id: UUID
reason: str = Field(max_length=500)
# The part of the last round the new machine resumes from (Marcus,
# 2026-12-01): required once the old machine has taken any part.
resume_from: int | None = Field(default=None, ge=1, le=10000, strict=True)
@router.post('/api/operator/orders/{uid}/transfer')
@@ -163,15 +166,21 @@ def transfer_machine(uid: UUID, body: MachineTransfer, user=Depends(can('manage'
from_name = (c.execute('SELECT name FROM dtf_local.machines WHERE id=%s',
(current['machine_id'],)).fetchone() if current['machine_id'] else None)
from_name = from_name and from_name['name']
resumed = hotfolder.transfer(c, uid)
parts = hotfolder.last_round(c, [uid]).get(uid, [])
if any(part['state'] == 'consumed' for part in parts) and not body.resume_from:
raise HTTPException(422, 'Escolha de qual parte a nova máquina recomeça.')
if body.resume_from and body.resume_from not in {part['seq'] for part in parts}:
raise HTTPException(422, 'Essa parte não existe neste pedido.')
resumed, delete_prt = hotfolder.transfer(c, uid, body.resume_from)
c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=true WHERE id=%s',
(body.machine_id, uid))
c.execute('''INSERT INTO dtf_local.machine_transfers(order_id,from_machine,to_machine,from_name,to_name,
reason,resumed_from,created_by) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)''',
(uid, current['machine_id'], body.machine_id, from_name, target['name'], reason, resumed, user))
reason,resumed_from,delete_prt,created_by) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)''',
(uid, current['machine_id'], body.machine_id, from_name, target['name'], reason, resumed,
delete_prt, user))
audit('order_machine_transferred', order=current['number'], from_machine=str(current['machine_id'] or ''),
to_machine=str(body.machine_id), operator=user)
return {'ok': True}
return {'ok': True, 'delete_prt': delete_prt}
@router.post('/api/operator/orders/{uid}/contraction')

View File

@@ -113,22 +113,45 @@ def stop(c, order_id):
WHERE order_id=%s AND state IN ('queued','claimed','written')''', (order_id,))
def transfer(c, order_id):
"""The order changed machine in Imprimindo (Rodada 5, D4): the old machine
keeps what Flexi already took, and what it had not leaves its folder; the
new one starts from the part the old was ripping, in a new round."""
def last_round(c, order_ids):
"""Each order's parts in its last round, in order: {order id: [{seq, name,
state}]}, for the transfer dialog to ask where the new machine resumes."""
rows = c.execute('''SELECT h.order_id, h.seq, h.name, h.state FROM dtf_local.hot_parts h
WHERE h.order_id=ANY(%s) AND h.round=(SELECT max(round) FROM dtf_local.hot_parts x
WHERE x.order_id=h.order_id) ORDER BY h.order_id, h.seq''', (list(order_ids),)).fetchall()
out = {}
for row in rows:
out.setdefault(row['order_id'], []).append({'seq': row['seq'], 'name': row['name'], 'state': row['state']})
return out
def prt_name(name):
"""The Hoson file the RIP makes from a part: its name with .prt."""
return name.rsplit('.', 1)[0] + '.prt'
def transfer(c, order_id, resume_from=None):
"""The order changed machine in Imprimindo (Rodada 5, D4). The hot folder
takes a PNG in about 10 s (Marcus, 2026-12-01), so a part the old machine
took may still be waiting in its Hoson queue: Gestão says which part the
new machine resumes from. The old machine's folder loses what it had not
taken; the new round holds that part onward. Returns (resume_from, the
.prt files to delete from the old machine's Hoson folder: the parts from
there on that it had already taken)."""
last = c.execute('SELECT max(round) AS r FROM dtf_local.hot_parts WHERE order_id=%s',
(order_id,)).fetchone()['r']
if last is None:
return 1
taken = c.execute('''SELECT max(seq) AS s FROM dtf_local.hot_parts
WHERE order_id=%s AND round=%s AND state='consumed' ''', (order_id, last)).fetchone()['s']
return 1, []
parts = c.execute('''SELECT seq, name, state FROM dtf_local.hot_parts WHERE order_id=%s AND round=%s
ORDER BY seq''', (order_id, last)).fetchall()
start = resume_from or 1
delete = [prt_name(part['name']) for part in parts if part['seq'] >= start and part['state'] == 'consumed']
stop(c, order_id)
c.execute('''INSERT INTO dtf_local.hot_parts(order_id,round,seq,item_index,upload_id,name)
SELECT order_id, %s, row_number() OVER (ORDER BY seq), item_index, upload_id, name
FROM dtf_local.hot_parts WHERE order_id=%s AND round=%s AND seq >= %s''',
(last + 1, order_id, last, taken or 1))
return taken or 1
(last + 1, order_id, last, start))
return start, delete
def claim(c, user):
@@ -194,9 +217,10 @@ def report(c, part_id, what, user):
def progress(c, order_ids):
"""For each order in parts, where its film is (Dropstar, 2026-10-30):
"parte 3/7 imprimindo · 4/7 ripando". Flexi rips the part it took last
while the one before it prints."""
"""For each order in parts, how many of its parts the machine took
(Dropstar, 2026-10-30). The hot folder takes a PNG in about 10 s and the
Hoson queues it (Marcus, 2026-12-01): a part taken may still wait to be
ripped, so nothing here says which part prints."""
rows = c.execute('''SELECT h.order_id, count(*) AS parts,
max(h.seq) FILTER (WHERE h.state='consumed') AS taken,
count(*) FILTER (WHERE h.state IN ('claimed','written')) AS waiting

View File

@@ -0,0 +1,4 @@
-- Marcus, 2026-12-01 (D4): the hot folder takes a PNG in about 10 s, so a
-- transfer leaves the old machine's .prt files in the Hoson folder; the
-- transfer keeps which ones to delete, for the card and the history.
ALTER TABLE dtf_local.machine_transfers ADD COLUMN IF NOT EXISTS delete_prt text[] NOT NULL DEFAULT '{}';

View File

@@ -1,5 +1,7 @@
"""An order in Imprimindo changes machine: the new one resumes from the part
the old was ripping, with the reason kept for the Revisor (Rodada 5, D4)."""
"""An order in Imprimindo changes machine: Gestão says which part the new one
resumes from, the reason stays for the Revisor, and the old machine's .prt
files from that part on are named for the operator to delete (Rodada 5, D4;
Marcus, 2026-12-01)."""
from uuid import uuid4
from app.core import db
@@ -39,10 +41,18 @@ def run():
# It only goes to another machine.
answer = client.call(path, {'machine_id': machine, 'reason': 'quebrou'}, operator=True, expected=409)
assert answer['detail'] == 'O pedido já está nessa máquina.', answer
# With the reason, the old machine unloads what was not taken and the
# new round resumes from part 2, renumbered.
assert client.call(path, {'machine_id': other, 'reason': ' quebrou a cabeça '},
operator=True) == {'ok': True}
# The old machine took parts 1 and 2: the part to resume from is asked,
# and it must be one of the order's.
answer = client.call(path, {'machine_id': other, 'reason': 'quebrou'}, operator=True, expected=422)
assert answer['detail'] == 'Escolha de qual parte a nova máquina recomeça.', answer
answer = client.call(path, {'machine_id': other, 'reason': 'quebrou', 'resume_from': 9},
operator=True, expected=422)
assert answer['detail'] == 'Essa parte não existe neste pedido.', answer
# Part 1 was printed, part 2 was waiting in the Hoson queue: the new
# round resumes from part 2, renumbered, and the old machine's part 2
# .prt is to be deleted; parts 3 and 4 leave its folder.
assert client.call(path, {'machine_id': other, 'reason': ' quebrou a cabeça ', 'resume_from': 2},
operator=True) == {'ok': True, 'delete_prt': ['parte 2.prt']}
with db.connect() as c:
parts = c.execute('''SELECT round,seq,state,name FROM dtf_local.hot_parts
WHERE order_id=%s ORDER BY round,seq''', (order,)).fetchall()
@@ -57,9 +67,13 @@ def run():
assert str(moved['machine_id']) == other and moved['machine_chosen'], moved
row = c.execute('SELECT * FROM dtf_local.machine_transfers WHERE order_id=%s', (order,)).fetchone()
assert row['resumed_from'] == 2 and row['reason'] == 'quebrou a cabeça', row
assert row['delete_prt'] == ['parte 2.prt'], row
assert (row['from_name'], row['to_name']) == (f'Transfere A {tag}', f'Transfere B {tag}'), row
mine = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == str(order))
assert mine['transfers'][0]['resumed_from'] == 2, mine.get('transfers')
assert mine['transfers'][0]['delete_prt'] == ['parte 2.prt'], mine.get('transfers')
# The board lists the new round's parts for the next transfer's dialog.
assert [p['seq'] for p in mine['hot_parts']] == [1, 2, 3], mine.get('hot_parts')
# Only Gestão and the administrators move a card between machines.
op = signed_in(email)
op.call(path, {'machine_id': machine, 'reason': 'outra tentativa'}, expected=403)
@@ -68,8 +82,8 @@ def run():
c.execute("UPDATE dtf_local.orders SET state='tra' WHERE id=%s", (order,))
answer = client.call(path, {'machine_id': machine, 'reason': 'fora de hora'}, operator=True, expected=409)
assert answer['detail'] == 'Só um pedido em Imprimindo muda de máquina por aqui.', answer
print('PASS: an order in Imprimindo transfers machine with its reason, '
'the old machine unloads what was not taken and the new resumes from part 2')
print('PASS: an order in Imprimindo transfers machine with its reason and the part to resume from, '
'the old machine unloads what was not taken and its .prt to delete is named')
finally:
if order is not None:
with db.connect() as c:

View File

@@ -86,15 +86,16 @@ const residueBadge=item=>badge('! Resíduo aceito','warn','O cliente aceitou imp
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
// the hot folder while the one before it prints.
// A film in parts on its machine (items 10 and 13, Dropstar 2026-10-30): how
// many parts the machine has taken. The hot folder takes a PNG in about 10 s
// and the Hoson queues it (Marcus, 2026-12-01), so a part taken is not known
// to be ripping or printing: the card says only what the folder shows.
function partsStep(order){
const hot=order.hot;if(!hot||hot.parts<2)return null;
const n=hot.parts, t=hot.taken;
if(!t)return ['Parte 1/'+n+' na hot folder','wait'];
if(t===1)return ['Parte 1/'+n+' ripando','rip'];
return ['Parte '+(t-1)+'/'+n+' imprimindo · '+t+'/'+n+' ripando','live'];
if(t<n)return [t+'/'+n+' partes com a máquina','live'];
return ['As '+n+' partes com a máquina','live'];
}
async function proofOk(order){
await api('/orders/'+order.id+'/proof',{});say('Prova do pedido #'+order.number+' conferida.');await load();
@@ -436,7 +437,8 @@ function cardFlags(order){
const transfers=order.transfers||[];
if(live&&transfers.length){const t=transfers[transfers.length-1];
out.push(['warn','Transferido · '+t.from_name+' → '+t.to_name,
'Motivo: '+t.reason+' · '+t.created_by+' em '+when(t.created_at)+(t.resumed_from>1?' · recomeçou da parte '+t.resumed_from:'')+'. Confira a emenda de tom.']);}
'Motivo: '+t.reason+' · '+t.created_by+' em '+when(t.created_at)+(t.resumed_from>1?' · recomeçou da parte '+t.resumed_from:'')+
(t.delete_prt?.length?' · apague da pasta do Hoson da '+t.from_name+': '+t.delete_prt.join(', '):'')+'. Confira a emenda de tom.']);}
if(order.snapshot.treatment){
const n=Number(order.snapshot.treatment.arts)||1;
out.push(['warn','Ajuste Fino · '+n+(n===1?' arte':' artes'),

View File

@@ -431,12 +431,27 @@ function nextBox(order){
const select=node('select');select.required=true;select.setAttribute('aria-label','Máquina que recebe o pedido');
for(const m of choices){const o=node('option',m.name);o.value=m.id;select.append(o);}
const reason=node('input');reason.maxLength=500;reason.required=true;reason.setAttribute('aria-label','Motivo da transferência');
// The hot folder takes a PNG in about 10 s (Marcus, 2026-12-01): a part
// the machine took may still wait in its Hoson queue, so whoever moves
// the card says where the new machine resumes, after looking at the Hoson.
const parts=order.hot_parts||[], taken=parts.some(p=>p.state==='consumed');
const resume=node('select');resume.setAttribute('aria-label','Parte de onde a nova máquina recomeça');
if(taken){const pick=node('option','Escolha a parte');pick.value='';resume.append(pick);resume.required=true;}
for(const p of parts){const o=node('option','Parte '+p.seq+' · '+(p.state==='consumed'?'já pega pela máquina':'ainda na pasta'));
o.value=String(p.seq);resume.append(o);}
const fields=[field('Máquina',select)];
if(parts.length>1||taken)fields.push(field('Recomeçar da parte',resume,'Confira no Hoson qual parte a máquina atual já imprimiu.'));
fields.push(field('Motivo',reason,'Fica no card para o Revisor conferir a emenda de tom.'));
formDialog('Transferir o pedido #'+order.number,{host:$('drawer'),className:'reason',width:540,
text:'O que a máquina atual ainda não pegou sai da pasta dela. A nova recomeça da parte que estava ripando.',
fields:[field('Máquina',select),field('Motivo',reason,'Fica no card para o Revisor conferir a emenda de tom.')],
label:'Transferir',tone:'red',
onsave:async()=>{await api('/orders/'+order.id+'/transfer',{machine_id:select.value,reason:reason.value.trim()});
say('Pedido #'+order.number+' transferido.');await load();}});
text:'O que a máquina atual ainda não pegou sai da pasta dela.',
fields,label:'Transferir',tone:'red',
onsave:async()=>{
const body={machine_id:select.value,reason:reason.value.trim()};
if(parts.length&&resume.value)body.resume_from=Number(resume.value);
const done=await api('/orders/'+order.id+'/transfer',body);
const prt=done.delete_prt||[];
say('Pedido #'+order.number+' transferido.'+(prt.length?' Apague da pasta do Hoson da máquina antiga: '+prt.join(', ')+'.':''),false,prt.length?20000:undefined);
await load();}});
},'btn quiet lg'));
}else if(st==='rev'){
if(proofPending(order)){
@@ -1321,7 +1336,9 @@ function historyView(order,rows,view){
r.operator+(r.machine?', na '+r.machine:''),r.created_at,r.reason));
// Machine transfers in Imprimindo (D4), newest first.
for(const t of [...(order.transfers||[])].reverse())
list.append(entry('Transferido · '+t.from_name+' → '+t.to_name,t.created_by,t.created_at,t.reason));
list.append(entry('Transferido · '+t.from_name+' → '+t.to_name,t.created_by,t.created_at,
t.reason+(t.resumed_from>1?' · recomeçou da parte '+t.resumed_from:'')+
(t.delete_prt?.length?' · apagar do Hoson da '+t.from_name+': '+t.delete_prt.join(', '):'')));
// The Redesenho previews (D2), newest first, like the moves above.
for(const p of [...previewsOf(order)].reverse()){
if(p.decided_at)list.append(entry('Prévia '+p.number+(p.result==='approved'?' aprovada':' reprovada'),p.decided_by,p.decided_at,p.reason));