fix: a cancelled order takes its open proof card, a renamed machine keeps its hot folder, a film is approved with all its parts
All checks were successful
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Successful in 8m8s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m11s
All checks were successful
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Successful in 8m8s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m11s
- Cancelling an order left its proof card not yet answered on the board, where it could still be pulled and printed. It is cancelled with it. - The hot folder path was the machine's current name, so renaming a machine sent its next files to a folder FlexiPRINT does not watch. Each machine now keeps the folder it was created with (migration fills it with today's names); no other machine may take that name, and the machine form shows the folder. - A final set with only some parts of a film was accepted, the #130 failure through the manual path. The server now refuses it and names the parts missing. - The proof card note says up to 30 cm. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -73,6 +73,14 @@ def cancel_order(uid: UUID, body: Resolution, user=Depends(can('cancel'))):
|
|||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(404, 'Pedido não encontrado ou já cancelado.')
|
raise HTTPException(404, 'Pedido não encontrado ou já cancelado.')
|
||||||
hotfolder.stop(c, uid)
|
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):
|
if payments.in_tiny(row):
|
||||||
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
|
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
|
||||||
(f'{uid}:paid:tiny',)).fetchone()
|
(f'{uid}:paid:tiny',)).fetchone()
|
||||||
|
|||||||
@@ -269,11 +269,14 @@ def list_machines(user=Depends(can('view'))):
|
|||||||
def create_machine(body: MachineIn, user=Depends(can('users'))):
|
def create_machine(body: MachineIn, user=Depends(can('users'))):
|
||||||
mid = uuid4()
|
mid = uuid4()
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s)', (body.name.strip(),)).fetchone():
|
# A machine's hot folder is its first name, for good: no other machine
|
||||||
raise HTTPException(409, 'Já existe uma máquina com este nome.')
|
# may be called that, or two would share one folder.
|
||||||
c.execute('''INSERT INTO dtf_local.machines(id,name,products,active,limit_metres,places)
|
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) OR lower(folder)=lower(%s)',
|
||||||
VALUES(%s,%s,%s,%s,%s,%s)''', (mid, body.name.strip(), sorted(set(body.products)), body.active,
|
(body.name.strip(), body.name.strip())).fetchone():
|
||||||
body.limit_metres, body.places or machines.DEFAULT_PLACES))
|
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)
|
audit('machine_created', operator=user, machine=body.name)
|
||||||
return {'id': str(mid)}
|
return {'id': str(mid)}
|
||||||
|
|
||||||
@@ -281,9 +284,9 @@ def create_machine(body: MachineIn, user=Depends(can('users'))):
|
|||||||
@router.post('/api/operator/machines/{mid}')
|
@router.post('/api/operator/machines/{mid}')
|
||||||
def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
|
def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) AND id<>%s',
|
if c.execute('''SELECT 1 FROM dtf_local.machines WHERE (lower(name)=lower(%s) OR lower(folder)=lower(%s))
|
||||||
(body.name.strip(), mid)).fetchone():
|
AND id<>%s''', (body.name.strip(), body.name.strip(), mid)).fetchone():
|
||||||
raise HTTPException(409, 'Já existe uma máquina com este nome.')
|
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,
|
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''',
|
places=COALESCE(%s,places) WHERE id=%s RETURNING id''',
|
||||||
(body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres,
|
(body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres,
|
||||||
|
|||||||
@@ -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(
|
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",
|
"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()
|
(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}
|
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):
|
if kept and len(kept) == len(body.files):
|
||||||
raise HTTPException(409, 'Estes já são os arquivos finais. Envie o arquivo novo.')
|
raise HTTPException(409, 'Estes já são os arquivos finais. Envie o arquivo novo.')
|
||||||
|
|||||||
@@ -119,12 +119,12 @@ def claim(c, user):
|
|||||||
they entered it, until the machine has its places' worth in its folder."""
|
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
|
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,))
|
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
|
(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
|
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
|
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
|
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()
|
due, busy, blocked = [], {}, set()
|
||||||
for row in rows:
|
for row in rows:
|
||||||
machine = row['machine_id']
|
machine = row['machine_id']
|
||||||
@@ -139,7 +139,9 @@ def claim(c, user):
|
|||||||
if busy.get(machine, 0) >= row['places'] or not cls:
|
if busy.get(machine, 0) >= row['places'] or not cls:
|
||||||
blocked.add(order)
|
blocked.add(order)
|
||||||
continue
|
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
|
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']))
|
WHERE id=%s''', (user, folder, row['id']))
|
||||||
busy[machine] = busy.get(machine, 0) + 1
|
busy[machine] = busy.get(machine, 0) + 1
|
||||||
|
|||||||
@@ -39,7 +39,8 @@ def loads(c):
|
|||||||
|
|
||||||
def rows(c, with_operators=False):
|
def rows(c, with_operators=False):
|
||||||
"""Every machine with its load, for the Kanban."""
|
"""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()
|
ORDER BY created_at, name''').fetchall()
|
||||||
load = loads(c)
|
load = loads(c)
|
||||||
operators = {}
|
operators = {}
|
||||||
@@ -55,7 +56,7 @@ def rows(c, with_operators=False):
|
|||||||
for m in machines:
|
for m in machines:
|
||||||
key = str(m['id'])
|
key = str(m['id'])
|
||||||
used = load.get(key, {'metres': Decimal(0), 'orders': 0, 'states': {}})
|
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,
|
'limit_metres': float(m['limit_metres']) if m['limit_metres'] is not None else None,
|
||||||
'places': m['places'],
|
'places': m['places'],
|
||||||
'open_metres': float(used['metres']), 'open_orders': used['orders'], 'states': used['states'],
|
'open_metres': float(used['metres']), 'open_orders': used['orders'], 'states': used['states'],
|
||||||
|
|||||||
5
app/migrations/202611272000_machine-folder.sql
Normal file
5
app/migrations/202611272000_machine-folder.sql
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
-- Each machine's hot folder (3. Imprimindo/<folder>/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;
|
||||||
@@ -251,6 +251,13 @@ def run():
|
|||||||
# No class measured or chosen: the part waits for one.
|
# 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]
|
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)
|
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)
|
hot = client.call('/operator/queue/hot', {}, operator=True)
|
||||||
due = [p for p in hot['write'] if p['order'] == oid]
|
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] == \
|
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']
|
assert board['hot'] == {'parts': 1, 'taken': 1, 'waiting': 0}, board['hot']
|
||||||
# Which items go again is chosen before Imprimindo, not while printing (#105).
|
# 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)
|
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:
|
finally:
|
||||||
client.call('/operator/machines/' + machine, {'name': f'Hot {tag}', 'products': ['textil'], 'active': False},
|
client.call('/operator/machines/' + machine, {'name': f'Hot {tag}', 'products': ['textil'], 'active': False},
|
||||||
operator=True)
|
operator=True)
|
||||||
@@ -444,6 +452,36 @@ def run():
|
|||||||
(f"{parent['id']}:production_started:tiny",)).fetchone()
|
(f"{parent['id']}:production_started:tiny",)).fetchone()
|
||||||
print('PASS: a file finished after Prova OK becomes the final, queues the order and tells Tiny')
|
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
|
# 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
|
# 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
|
# only that item; the pass to Revisão keeps it for the machine's metres and
|
||||||
|
|||||||
@@ -330,7 +330,7 @@ function nextBox(order){
|
|||||||
const manual=(order.print_files||[]).some(r=>r.status==='manual');
|
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
|
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 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(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(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'))
|
if((order.print_files||[]).some(r=>r.status==='failed'||r.status==='manual'||r.timed_out)&&may('produce'))
|
||||||
|
|||||||
@@ -323,7 +323,10 @@ function machineForm(m){
|
|||||||
left.push(remove);
|
left.push(remove);
|
||||||
}
|
}
|
||||||
const d=formDialog(m?'Editar máquina':'Nova máquina',{width:520,left,
|
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('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),
|
field('Vagas em Imprimindo',places,PLACES_NOTE),
|
||||||
checkbox('Ativa: recebe pedidos',active)],
|
checkbox('Ativa: recebe pedidos',active)],
|
||||||
|
|||||||
Reference in New Issue
Block a user