Compare commits

..

2 Commits

Author SHA1 Message Date
Cauê Faleiros
1216998914 feat: the Kanban saves the print queue's files into a folder the operator chose
All checks were successful
Build and deploy / Validate source (push) Successful in 1m26s
Build and deploy / Integration suite on a real stack (push) Successful in 3m31s
Build and deploy / Secret scan and release gate (push) Successful in 11s
Build and deploy / Publish images (push) Successful in 1m27s
The meeting asked that files moved to Fila de impressão land in the print
room's folder by themselves, instead of each one being downloaded from the
cloud. Beside "Baixar" in that column, a folder button lets the operator
pick a folder (FlexiPRINT's, or the internal server's share). While the
Kanban is open in Chrome or Edge, every final file that enters the queue is
saved there, named after its order, written under a temporary name and
renamed only when whole so FlexiPRINT never reads half a file. A file
already saved is not fetched again, even after FlexiPRINT moves it away.
The folder is remembered; after the browser restarts the button turns
orange and one click releases it. A machine's operator gets only that
machine's queue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 10:42:02 -03:00
Cauê Faleiros
2a2a783ff7 feat: deleting an order frees its files from storage
A deleted order's files stayed in R2 until they expired on their own, up
to 30 days. Deleting now expires its finals, the customer's corrections
and the generated PDFs at once, and its originals too unless it was a
test order, whose quote can still be paid. A file another order or an
open quote still uses is kept. The worker removes them within a minute.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 10:25:18 -03:00
4 changed files with 191 additions and 11 deletions

View File

@@ -439,6 +439,14 @@ def delete_order(uid: UUID, user=Depends(can('manage'))):
test = payments.is_test(row)
if not test and not row.get('cancelled_at'):
raise HTTPException(409, 'Cancele o pedido antes de excluir. Só pedidos cancelados ou de teste podem ser excluídos.')
# Its files leave storage too: the finals, corrections and generated PDFs,
# and the customer's originals unless the quote can still be paid (a test
# order's). The worker deletes them within a minute.
originals = {str(u) for item in row['snapshot'].get('items') or [] for u in item.get('uploads') or []}
produced = {str(r['upload_id']) for r in c.execute('''SELECT upload_id FROM dtf_local.order_files WHERE order_id=%s
UNION SELECT upload_id FROM dtf_local.print_files WHERE order_id=%s AND upload_id IS NOT NULL''',
(uid, uid)).fetchall()}
candidates = produced - originals if test else produced | originals
for table in ('movements', 'order_files', 'print_files'):
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=%s', (uid,))
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{uid}:%',))
@@ -446,11 +454,33 @@ def delete_order(uid: UUID, user=Depends(can('manage'))):
if not test:
c.execute('UPDATE dtf_local.quotes SET discarded_at=COALESCE(discarded_at,now()), discarded_by=COALESCE(discarded_by,%s) WHERE id=%s',
(user, row['quote_id']))
freed = release_files(c, candidates)
audit('order_deleted', order=row['number'], test=test, operator=user,
reason=row.get('cancel_reason') or '')
reason=row.get('cancel_reason') or '', files_released=freed)
return {'ok': True}
def release_files(c, uploads):
"""Expire these uploads now, except any another order or an open quote
still uses: a customer can buy the same file again. Returns how many."""
free = []
for upload in uploads:
used = c.execute('''SELECT 1 FROM dtf_local.order_files WHERE upload_id=%s
UNION ALL SELECT 1 FROM dtf_local.print_files WHERE upload_id=%s
UNION ALL SELECT 1 FROM dtf_local.orders o, jsonb_array_elements(o.snapshot->'items') i
WHERE i->'uploads' ? %s
UNION ALL SELECT 1 FROM dtf_local.quotes q, jsonb_array_elements(q.draft->'items') i
WHERE q.discarded_at IS NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.orders x WHERE x.quote_id=q.id)
AND i->'uploads' ? %s
LIMIT 1''', (upload, upload, upload, upload)).fetchone()
if not used:
free.append(upload)
if free:
c.execute('''UPDATE dtf_local.uploads SET expires_at=now() WHERE id=ANY(%s::uuid[])
AND purged_at IS NULL''', (free,))
return len(free)
@router.post('/api/operator/orders/{uid}/cancel')
def cancel_order(uid: UUID, body: Resolution, user=Depends(can('manage'))):
"""A paid order leaves the board but keeps its payment and history. Nothing
@@ -741,13 +771,13 @@ def production_stats(days: int = Query(default=30, ge=7, le=365), user=Depends(o
@router.get('/api/operator/queue/finals')
def queue_finals(request: Request, user=Depends(can('produce'))):
def queue_finals(request: Request, auto: bool = False, user=Depends(can('produce'))):
"""The approved final files of every order in the print queue, in queue
order, each named after its order so a folder of them stays readable. The
browser downloads them straight from storage: a zip of multi-GB sheets
would go through the server."""
with db.connect() as c:
rows = c.execute(f'''SELECT o.number,f.item_index,u.object_key,u.name FROM dtf_local.orders o
rows = c.execute(f'''SELECT o.number,f.item_index,f.upload_id,u.object_key,u.name FROM dtf_local.orders o
JOIN dtf_local.order_files f ON f.order_id=o.id JOIN dtf_local.uploads u ON u.id=f.upload_id
WHERE o.state='fil' AND o.cancelled_at IS NULL AND {FINAL_OK}
ORDER BY COALESCE(o.queue_key, extract(epoch FROM o.created_at)),o.id,f.item_index,f.created_at''').fetchall()
@@ -766,8 +796,10 @@ def queue_finals(request: Request, user=Depends(can('produce'))):
copy += 1
names.add(name)
files.append({'number': row['number'], 'item': row['item_index'] + 1, 'name': name,
'url': storage.download(row['object_key'], name)})
audit('queue_finals_downloaded', operator=user, files=len(files))
'upload_id': str(row['upload_id']), 'url': storage.download(row['object_key'], name)})
# The automatic folder asks whenever the queue changes; only a person's download is logged.
if not auto:
audit('queue_finals_downloaded', operator=user, files=len(files))
return {'files': files}

View File

@@ -84,7 +84,50 @@ def run():
assert not c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (paid_order,)).fetchone()
assert c.execute('SELECT discarded_at FROM dtf_local.quotes WHERE id=%s', (paid_quote,)).fetchone()['discarded_at']
assert str(paid_quote) not in listed()
print('PASS: discard hides and blocks a quote; test orders delete; paid orders cancel, then delete')
# Deleting frees the order's files from storage, but not a file another order uses,
# nor a test order's originals, whose quote can still be paid.
files = {name: uuid4() for name in ('original', 'shared', 'final', 'pdf', 'test_original', 'test_final')}
other_order, other_quote, gone_quote, gone_order, test2_quote, test2_order = (uuid4() for _ in range(6))
with db.connect() as c:
for name, fid in files.items():
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state) VALUES(%s,%s,%s,1,%s,'m',true,now()+interval '20 days','clean')''',
(fid, owner, name + '.png', f'test/{fid}'))
def place(quote, order, uploads, provider, cancelled):
content = {'customer': {'mail': mail}, 'items': [{'mode': 'file', 'uploads': [str(u) for u in uploads]}],
'total_cents': 1490}
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
VALUES(%s,%s,%s,'actions-fixture',%s,%s,now())''', (quote, owner, uuid4(), Jsonb(content), Jsonb(content)))
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,cancelled_at,cancelled_by,cancel_reason)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s)''', (order, quote, owner, Jsonb(content), Jsonb({'provider': provider, 'id': '1'}),
'now()' if cancelled else None, 'x' if cancelled else None,
'teste' if cancelled else None))
place(gone_quote, gone_order, [files['original'], files['shared']], 'mercadopago', True)
place(other_quote, other_order, [files['shared']], 'mercadopago', False)
place(test2_quote, test2_order, [files['test_original']], 'teste', False)
for order, fid in ((gone_order, files['final']), (test2_order, files['test_final'])):
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
VALUES(%s,%s,%s,0,'final','ok','t')''', (uuid4(), order, fid))
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index,status,upload_id)
VALUES(%s,%s,0,'ready',%s)''', (uuid4(), gone_order, files['pdf']))
try:
client.call(f'/operator/orders/{gone_order}/delete', {}, operator=True)
client.call(f'/operator/orders/{test2_order}/delete', {}, operator=True)
with db.connect() as c:
expired = {name for name, fid in files.items() if c.execute(
'SELECT expires_at<=now() AS e FROM dtf_local.uploads WHERE id=%s', (fid,)).fetchone()['e']}
assert expired == {'original', 'final', 'pdf', 'test_final'}, expired
finally:
with db.connect() as c:
for order in (gone_order, other_order, test2_order):
c.execute('DELETE FROM dtf_local.order_files WHERE order_id=%s', (order,))
c.execute('DELETE FROM dtf_local.print_files WHERE order_id=%s', (order,))
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order,))
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([gone_quote, other_quote, test2_quote],))
c.execute('DELETE FROM dtf_local.uploads WHERE id=ANY(%s)', (list(files.values()),))
print('PASS: discard hides and blocks a quote; test orders delete; paid orders cancel, then delete '
'and free their files')
finally:
with db.connect() as c:
for oid in filter(None, (test_order, paid_order, newer_order)):

View File

@@ -444,4 +444,11 @@ a.zap{display:inline-flex;align-items:center;gap:4px;vertical-align:bottom}
.danger-text{color:var(--bad)}
.machine-select{height:36px;padding:0 10px;border-radius:8px;border:1px solid var(--line3);background:var(--bg);color:var(--tx);font:inherit;font-size:14px}
.card .machine{color:var(--accent-tx)}
/* Fila de impressão's tools: Baixar, and the automatic folder (grey off, green saving, orange to release). */
.coltools{display:flex;gap:6px;flex-shrink:0}
.autofolder{color:var(--faint);padding:0 8px}
.autofolder.on{color:var(--ok);border-color:rgba(111,209,156,.4)}
.autofolder.warn{color:var(--warn);border-color:rgba(242,179,61,.5)}
.autofolder.busy svg{animation:pulse 1s ease-in-out infinite alternate}
@keyframes pulse{to{opacity:.35}}

View File

@@ -189,6 +189,99 @@ function download(uid){return async()=>{
const result=await api('/uploads/'+uid+'/download');
const link=node('a');link.href=result.url;link.referrerPolicy='no-referrer';link.download=result.name;link.click();
};}
// ---- Automatic folder ------------------------------------------------------
// The print queue's files, saved by this browser into a folder the operator
// chose (the FlexiPRINT folder, or the internal server's share), as orders
// enter Fila de impressão. Chrome and Edge only, while the Kanban is open.
// The folder is remembered; after the browser restarts it needs one click.
const kv=(()=>{let opened;const open=()=>opened||(opened=new Promise((ok,fail)=>{const r=indexedDB.open('dtf-kanban',1);
r.onupgradeneeded=()=>r.result.createObjectStore('kv');r.onsuccess=()=>ok(r.result);r.onerror=()=>fail(r.error);}));
const run=async(mode,fn)=>{const db=await open();return new Promise((ok,fail)=>{const t=db.transaction('kv',mode);const req=fn(t.objectStore('kv'));
t.oncomplete=()=>ok(req?.result);t.onerror=()=>fail(t.error);});};
return {get:k=>run('readonly',s=>s.get(k)),set:(k,v)=>run('readwrite',s=>s.put(v,k)),del:k=>run('readwrite',s=>s.delete(k))};})();
const FOLDER={supported:'showDirectoryPicker' in window,handle:null,granted:false,saved:new Set(),busy:false,status:'',lastSig:null};
async function restoreFolder(){
if(!FOLDER.supported)return;
try{FOLDER.handle=await kv.get('folder')||null;
if(FOLDER.handle){FOLDER.granted=(await FOLDER.handle.queryPermission({mode:'readwrite'}))==='granted';
FOLDER.saved=new Set(await kv.get('saved:'+FOLDER.handle.name)||[]);
if(!FOLDER.granted)setTimeout(()=>say('Clique na pasta laranja em Fila de impressão para voltar a salvar os arquivos sozinho.',false,10000),2500);}}
catch{FOLDER.handle=null;}
}
function folderLine(){
const b=node('button',undefined,'btn ghost small autofolder');b.type='button';b.id='autofolder';
b.append(icon(['M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z']));
paintFolder(b);b.onclick=folderClick;return b;
}
function folderText(){
const h=FOLDER.handle;
return !h?'Pasta automática desligada: clique para escolher a pasta onde os arquivos da fila são salvos sozinhos'
:!FOLDER.granted?'Clique para liberar a pasta “'+h.name+'” e voltar a salvar os arquivos da fila'
:FOLDER.status||'Salvando os arquivos da fila em “'+h.name+'”';
}
function paintFolder(b=$('autofolder')){
if(!b)return;
const h=FOLDER.handle;b.classList.toggle('on',!!h&&FOLDER.granted);b.classList.toggle('warn',!!h&&!FOLDER.granted);
b.classList.toggle('busy',FOLDER.busy);b.title=folderText();b.setAttribute('aria-label',folderText());
}
async function chooseFolder(){
const handle=await window.showDirectoryPicker({id:'dtf-fila',mode:'readwrite'});
FOLDER.handle=handle;FOLDER.granted=true;FOLDER.lastSig=null;
FOLDER.saved=new Set(await kv.get('saved:'+handle.name).catch(()=>null)||[]);
await kv.set('folder',handle).catch(()=>{});
paintFolder();say('Os arquivos da fila vão ser salvos em “'+handle.name+'”.');syncFolder();
}
async function folderClick(){
try{
if(FOLDER.handle&&!FOLDER.granted){
FOLDER.granted=(await FOLDER.handle.requestPermission({mode:'readwrite'}))==='granted';
FOLDER.lastSig=null;paintFolder();if(FOLDER.granted)syncFolder();return;
}
const back=node('div',undefined,'modal');const box=node('div',undefined,'modal-box');
box.append(node('h2','Pasta automática'),node('p','Os arquivos finais dos pedidos que entram na Fila de impressão são salvos sozinhos '+
'nesta pasta, com o número do pedido no nome. Escolha a pasta que o FlexiPRINT lê, ou a pasta da rede do servidor. '+
'Funciona no Chrome e no Edge, enquanto o Kanban estiver aberto neste computador.','muted'));
if(FOLDER.handle)box.append(node('p','Pasta atual: “'+FOLDER.handle.name+'” · '+FOLDER.saved.size+' arquivo(s) já salvos','faint'));
const row=node('div',undefined,'modal-actions');
const close=node('button','Fechar','btn ghost');close.type='button';close.onclick=()=>back.remove();
const pick=button(FOLDER.handle?'Trocar pasta':'Escolher pasta',async()=>{back.remove();await chooseFolder();},'btn primary');
if(FOLDER.handle)row.append(button('Desligar',async()=>{back.remove();FOLDER.handle=null;FOLDER.granted=false;
await kv.del('folder').catch(()=>{});paintFolder();say('Pasta automática desligada.');},'btn ghost'));
row.append(close,pick);box.append(row);back.append(box);back.onclick=e=>{if(e.target===back)back.remove();};document.body.append(back);
}catch(e){if(e.name!=='AbortError')say(e.message,true);}
}
// Save what the queue has and this folder has not received yet. A file the
// FlexiPRINT moved away after importing is not downloaded again.
async function syncFolder(){
if(!FOLDER.handle||!FOLDER.granted||FOLDER.busy||!board||!may('produce'))return;
const sig=board.orders.filter(o=>o.state==='fil'&&!o.cancelled_at).map(o=>o.id+':'+o.version).join(',');
if(sig===FOLDER.lastSig)return;
FOLDER.busy=true;
try{
const {files}=await api('/queue/finals?auto=1');
const pending=files.filter(f=>!FOLDER.saved.has(f.upload_id));
for(const [i,file] of pending.entries()){
FOLDER.status='Salvando '+(i+1)+' de '+pending.length+': '+file.name;paintFolder();
say(FOLDER.status,false,60000);
const temp=await FOLDER.handle.getFileHandle(file.name+'.baixando',{create:true});
const out=await temp.createWritable();
const r=await fetch(file.url,{referrerPolicy:'no-referrer'});
if(!r.ok||!r.body){await out.abort();throw new Error('Não foi possível baixar '+file.name+'.');}
await r.body.pipeTo(out);
// The FlexiPRINT sees the file only once it is whole.
await FOLDER.handle.removeEntry(file.name).catch(()=>{});
if('move' in temp)await temp.move(file.name);
FOLDER.saved.add(file.upload_id);
await kv.set('saved:'+FOLDER.handle.name,[...FOLDER.saved].slice(-3000)).catch(()=>{});
}
FOLDER.lastSig=sig;FOLDER.status=pending.length?'Salvos '+pending.length+' arquivo(s) em “'+FOLDER.handle.name+'”':'';
if(pending.length)say(FOLDER.status+'.');
}catch(e){
if(e.name==='NotAllowedError'){FOLDER.granted=false;}
FOLDER.status='';say('Pasta automática: '+e.message,true);
}finally{FOLDER.busy=false;paintFolder();}
}
async function downloadQueue(){
const {files}=await api('/queue/finals');
if(!files.length){say('Nenhum arquivo final aprovado na fila.');return;}
@@ -262,6 +355,7 @@ async function load(quiet=false){
$('login').hidden=true;$('app').hidden=false;
if(!quiet)say('Atualizado às '+new Date().toLocaleTimeString('pt-BR')+tinyNotice,false,tinyNotice?6000:2500);
render();
syncFolder();
}catch(e){
if(e.status===401||e.status===503){$('app').hidden=true;$('login').hidden=false;$('drawer').hidden=true;}
// Not being signed in yet is the normal start, not an error.
@@ -346,11 +440,15 @@ function renderBoard(){
// Finished orders are a recent window, not the whole history: say so.
const count=state==='fin'&&board.finished_total>orders.length?orders.length+' de '+board.finished_total:String(orders.length);
line.append(swatch,node('h2',title),node('span',count,'n'));
const sub=node('div',undefined,'col-sub');sub.append(node('small',orders.length?metres(total)+' no total':'vazio'));
// The print queue's tools need the room: there it says only the metres.
const tools=state==='fil'&&may('produce');
const sub=node('div',undefined,'col-sub');sub.append(node('small',orders.length?metres(total)+(tools?'':' no total'):'vazio'));
// The print queue's files, all at once, to import into FlexiPRINT.
if(state==='fil'&&orders.length&&may('produce')){
const all=downloadButton('Baixar',downloadQueue,'btn ghost small');all.title='Baixar os arquivos finais de todos os pedidos da fila';
sub.append(all);
if(tools){
const tools=node('div',undefined,'coltools');
if(orders.length){const all=downloadButton('Baixar',downloadQueue,'btn ghost small');all.title='Baixar os arquivos finais de todos os pedidos da fila';tools.append(all);}
if(FOLDER.supported)tools.append(folderLine());
sub.append(tools);
}
head.append(line,sub);
column.append(head);
@@ -1502,4 +1600,4 @@ function scheduleAuto(){
};
scheduleAuto();
})();
load();
restoreFolder().finally(()=>load());