feat: Gestão moves a printing order to another machine with a reason; the new one resumes from the part being ripped (Rodada 5, D4)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-30 15:03:02 -03:00
parent 030b66c697
commit c2aa1d4937
7 changed files with 185 additions and 0 deletions

View File

@@ -219,6 +219,9 @@ def with_print_files(c, orders):
# clock leaves out the time a preview waited for the customer (D2).
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
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'])
# Orders the machine already printed: a reprint chooses which items go
@@ -267,6 +270,9 @@ def with_print_files(c, orders):
order['previews'] = [{k: row[k] for k in ('number', 'sent_at', 'sent_by', 'decided_at', 'result',
'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')}
for row in transfers if row['order_id'] == order['id']]
return assign_machines(c, orders)

View File

@@ -133,6 +133,47 @@ def choose_machine(uid: UUID, body: MachineChoice, request: Request, user=Depend
return {'ok': True}
class MachineTransfer(StrictModel):
machine_id: UUID
reason: str = Field(max_length=500)
@router.post('/api/operator/orders/{uid}/transfer')
def transfer_machine(uid: UUID, body: MachineTransfer, user=Depends(can('manage'))):
"""A card already in Imprimindo changes machine (Rodada 5, D4), by Gestão
or an administrator and with its reason: the old machine keeps what Flexi
already took, and the new one starts from the part it was ripping."""
reason = ' '.join(body.reason.split())
with db.connect() as c:
current = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not current:
raise HTTPException(404, 'Pedido não encontrado.')
if current['cancelled_at'] or current['state'] != 'imp':
raise HTTPException(409, 'Só um pedido em Imprimindo muda de máquina por aqui.')
if len(reason) < 3:
raise HTTPException(422, 'Escreva o motivo da transferência.')
target = c.execute('SELECT name,products,active FROM dtf_local.machines WHERE id=%s',
(body.machine_id,)).fetchone()
if not target or not target['active']:
raise HTTPException(404, 'Máquina não encontrada ou desativada.')
if body.machine_id == current['machine_id']:
raise HTTPException(409, 'O pedido já está nessa máquina.')
if machines.product_family(current) not in target['products']:
raise HTTPException(409, f"A {target['name']} não imprime este produto.")
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)
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))
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}
@router.post('/api/operator/orders/{uid}/contraction')
def choose_contraction(uid: UUID, body: Contraction, user=Depends(can('produce'))):
"""The contraction class of an item (Dropstar, 2026-10-30): the browser's

View File

@@ -113,6 +113,24 @@ 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."""
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']
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
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

View File

@@ -0,0 +1,16 @@
-- Rodada 5, D4: a card already in Imprimindo changes machine, by Gestão or an
-- administrator with a reason; the part the new machine resumed from is kept
-- for the Revisor to check the tone seam.
CREATE TABLE IF NOT EXISTS dtf_local.machine_transfers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
from_machine uuid,
to_machine uuid NOT NULL,
from_name text,
to_name text NOT NULL,
reason text NOT NULL,
resumed_from int,
created_by text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS machine_transfers_order ON dtf_local.machine_transfers(order_id);

View File

@@ -0,0 +1,85 @@
"""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)."""
from uuid import uuid4
from app.core import db
from tests.smoke_test import Client
from tests.users_test import PASSWORD, order_fixture, signed_in
def run():
client = Client()
client.call('/session')
tag = uuid4().hex[:6]
machine = client.call('/operator/machines', {'name': f'Transfere A {tag}', 'products': ['textil']},
operator=True)['id']
other = client.call('/operator/machines', {'name': f'Transfere B {tag}', 'products': ['textil']},
operator=True)['id']
email = f'transfere-{tag}@example.test'
operator_id = client.call('/operator/users', {'name': 'Operador', 'email': email, 'role': 'operador',
'password': PASSWORD}, operator=True)['id']
owner = uuid4()
quote = order = None
try:
with db.connect() as c:
quote, order = order_fixture(c, owner, 'file')
upload = uuid4()
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state) VALUES(%s,%s,'transfer-test.png',1,%s,'',true,now()+interval '1 day','clean')''',
(upload, owner, f'originals/transfer-test-{upload}'))
c.execute('''UPDATE dtf_local.orders SET state='imp', machine_id=%s, machine_chosen=true
WHERE id=%s''', (machine, order))
for seq, state in enumerate(('consumed', 'consumed', 'written', 'queued'), 1):
c.execute('''INSERT INTO dtf_local.hot_parts(order_id,round,seq,item_index,upload_id,name,state)
VALUES(%s,1,%s,0,%s,%s,%s)''', (order, seq, upload, f'parte {seq}.png', state))
path = f'/operator/orders/{order}/transfer'
# The reason is required, even if only spaces.
answer = client.call(path, {'machine_id': other, 'reason': ' '}, operator=True, expected=422)
assert answer['detail'] == 'Escreva o motivo da transferência.', answer
# 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}
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()
old = {row['seq']: row['state'] for row in parts if row['round'] == 1}
assert old == {1: 'consumed', 2: 'consumed', 3: 'withdraw', 4: 'gone'}, old
new = [row for row in parts if row['round'] == 2]
assert [row['seq'] for row in new] == [1, 2, 3], parts
assert [row['name'] for row in new] == ['parte 2.png', 'parte 3.png', 'parte 4.png'], new
assert all(row['state'] == 'queued' for row in new), new
moved = c.execute('SELECT machine_id,machine_chosen FROM dtf_local.orders WHERE id=%s',
(order,)).fetchone()
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['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')
# 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)
# Outside Imprimindo there is no transfer.
with db.connect() as c:
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')
finally:
if order is not None:
with db.connect() as c:
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order,))
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,))
if operator_id:
client.call(f'/operator/users/{operator_id}/delete', {}, operator=True)
for machine_id in (machine, other):
client.call(f'/operator/machines/{machine_id}/delete', {}, operator=True)
if __name__ == '__main__':
run()

View File

@@ -430,6 +430,10 @@ function cardFlags(order){
if(redo.length)out.push(['bad','Retrabalho',redo.map(r=>'Retrabalho · '+REWORK_CAUSES[r.cause]+' · '+metres(r.metres)+(r.authorized?'':' · aguardando autorização')).join(' · ')]);
if(live&&s.items.some(mirroredItem))out.push(['warn','Espelhada',MIRROR_NOTE]);
if(waitingContact(order))out.push(['warn','Contato','Aguardando contato: '+order.contact_note+' · '+contactWho(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.']);}
if(order.snapshot.treatment){
const n=Number(order.snapshot.treatment.arts)||1;
out.push(['warn','Ajuste Fino · '+n+(n===1?' arte':' artes'),

View File

@@ -423,6 +423,21 @@ function nextBox(order){
if(can('rev'))main.push(moveBtn('rev'));else cannot();
const p=proofBtn();if(p)more.push(p);
fixBtn();
if(may('manage'))more.push(button('Transferir máquina',()=>{
const family=order.snapshot.items.some(i=>i.mode==='uvfile'||i.mode==='uv')?'uv':'textil';
const choices=(board.machines||[]).filter(m=>m.active&&m.id!==order.machine?.id&&
(!m.products?.length||m.products.includes(family)));
if(!choices.length){say('Nenhuma outra máquina ativa imprime este produto.',true);return;}
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');
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();}});
},'btn quiet lg'));
}else if(st==='rev'){
if(proofPending(order)){
// Finalizado waits for the proof: printing it and checking it is the next step.