From 6a921415ea67e9feaf7e35a6a53991cb306d0f24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Tue, 27 Oct 2026 10:15:16 -0300 Subject: [PATCH] feat: the folders catch up on what passed while the Kanban computer was off Dropstar's internal rules (2026-10-26): the folder must reproduce what passed, not only what sits in the columns when the computer comes back, or a room running 24 hours leaves a gap a week in the Finalizado archive. - the Kanban remembers when the folders were chosen and asks for every order paid since then, whatever its stage; each file goes to its stage's folder, so an order finished while the computer was off lands in 3. Finalizado - orders paid before the folders were chosen still stay out, so setting them up never pulls old orders back into the queue - the server's file list for the folders and Baixar now loads only the orders that have a file, not every order in the stages Co-Authored-By: Claude Opus 5.5 --- app/api/operator.py | 33 +++++++++++++++++++++++---------- docs/CONTEXT.md | 10 ++++++---- tests/print_file_test.py | 9 +++++++++ web/kanban.js | 26 +++++++++++++++++++------- 4 files changed, 57 insertions(+), 21 deletions(-) diff --git a/app/api/operator.py b/app/api/operator.py index e0ac8cc..a9d5dae 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -970,32 +970,35 @@ def named_files(rows): return files -def print_ready(c, request, states, only=None): +def print_ready(c, request, states, only=None, paid_after=None): """The file to print for each item of the orders in these stages, in queue order: the approved final, or before approval the generated print file (unless the customer has sent a correction since). `only` narrows it to - these orders. An operator who works on some machines gets only those - machines' orders.""" + these orders, `paid_after` to the orders paid since then. An operator who + works on some machines gets only those machines' orders.""" ids = None if only is None else list(only) rows = c.execute(f'''SELECT o.id AS order_id,o.state,o.number,f.item_index,f.upload_id,u.object_key,u.name, COALESCE(o.queue_key, extract(epoch FROM o.created_at)) AS position 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=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s)) AND o.cancelled_at IS NULL AND {FINAL_OK} + WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s)) + AND (%s::timestamptz IS NULL OR o.created_at>=%s) AND o.cancelled_at IS NULL AND {FINAL_OK} UNION ALL SELECT o.id,o.state,o.number,p.item_index,p.upload_id,u.object_key,u.name, COALESCE(o.queue_key, extract(epoch FROM o.created_at)) FROM dtf_local.orders o JOIN dtf_local.print_files p ON p.order_id=o.id JOIN dtf_local.uploads u ON u.id=p.upload_id - WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s)) AND o.state IN ('rec','tra') AND o.cancelled_at IS NULL AND p.status='ready' + WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s)) + AND (%s::timestamptz IS NULL OR o.created_at>=%s) AND o.state IN ('rec','tra') AND o.cancelled_at IS NULL AND p.status='ready' AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean' AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='final' AND f.active AND f.item_index=p.item_index) AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='correction') - ORDER BY position,order_id,item_index''', (list(states), ids, ids, list(states), ids, ids)).fetchall() - staged = assign_machines(c, c.execute('''SELECT * FROM dtf_local.orders - WHERE state=ANY(%s) AND (%s::uuid[] IS NULL OR id=ANY(%s)) AND cancelled_at IS NULL''', - (list(states), ids, ids)).fetchall()) + ORDER BY position,order_id,item_index''', + (list(states), ids, ids, paid_after, paid_after, list(states), ids, ids, paid_after, paid_after)).fetchall() + # Only the orders that have a file, for their machines: not every order in the stages. + staged = assign_machines(c, c.execute('SELECT * FROM dtf_local.orders WHERE id=ANY(%s)', + (list({row['order_id'] for row in rows}),)).fetchall()) mine = {o['id'] for o in visible(request, staged)} return [row for row in rows if row['order_id'] in mine] @@ -1016,6 +1019,9 @@ def queue_finals(request: Request, auto: bool = False, user=Depends(can('print') class FolderSync(StrictModel): early: bool = False held: list[UUID] = Field(default_factory=list, max_length=1000) + # When the folders were chosen: the orders paid since are fetched whatever + # their stage, so what passed while the computer was off is not lost. + since: datetime | None = None @router.post('/api/operator/queue/folder') @@ -1024,7 +1030,10 @@ def queue_folder(body: FolderSync, request: Request, user=Depends(can('print'))) three folders (2026-10-26): the files of orders in Arte recebida and Arte conferida, and, for the orders the folders already hold, their files while they print, are checked in Revisão and sit in Finalizado, so one taken out - of a folder can be fetched again when the order moves on. Without it, only + of a folder can be fetched again when the order moves on. With `since`, + also every order paid after the folders were chosen, whatever its stage: + a computer that was off catches up on what passed meanwhile (Dropstar's + rules, 2026-10-26). Without it, only the queue's (Firefox's downloads). `states` answers for the orders the folders hold files of: a stage, 'cancelled', or nothing when the order was deleted, so their files can be removed.""" @@ -1032,6 +1041,10 @@ def queue_folder(body: FolderSync, request: Request, user=Depends(can('print'))) rows = print_ready(c, request, ('rec', 'tra') if body.early else ('tra',)) if body.early and body.held: rows += print_ready(c, request, ('imp', 'rev', 'fin'), only=body.held) + if body.early and body.since: + seen = {(r['order_id'], r['item_index'], r['upload_id']) for r in rows} + rows += [r for r in print_ready(c, request, ('imp', 'rev', 'fin'), paid_after=body.since) + if (r['order_id'], r['item_index'], r['upload_id']) not in seen] files = named_files(rows) held = c.execute('SELECT id,state,cancelled_at FROM dtf_local.orders WHERE id=ANY(%s)', (body.held,)).fetchall() if body.held else [] diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index 75cc261..4672921 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -347,7 +347,10 @@ prints and is checked in Revisão) and "3. Finalizado" (when the order is released, kept 30 days there). They are created as soon as the main folder is chosen. Correção, a cancellation or a deletion takes the file out; a replaced final is swapped. Orders already -printing when the folder is chosen are not downloaded. A file someone took +printing when the folder is chosen are not downloaded; every order paid after +it is, whatever its stage, so a computer that was off catches up when it +comes back (Dropstar's rules, 2026-10-26: the folder must reproduce what +passed, not only what sits in the columns). A file someone took out is fetched again only when its order moves on (`POST /api/operator/queue/folder`, which also returns the files of orders the folders hold once they print). Who opens each folder is set in the server's @@ -448,9 +451,8 @@ Still to do (2026-10-26): - Still open from the internal rules (docs received 2026-10-26): file type by its first bytes (D-13), every order's origin and a manual order entry in the Kanban (D-21, D-35; also how orders paid with credit come in), the - rework register (D-02 to D-04), Aguardando contato time out of the time - figures (D-38), and the folders fetching what passed while the Kanban - computer was off. + rework register (D-02 to D-04), and Aguardando contato time out of the time + figures (D-38). - Settled on 2026-10-26: the DTF SITE category (986932924, CATEGORY in app/tiny.py), the white spot also under the print PDF's footer (nothing to change here), and the montador's order format (customer, files, product, the batch with diff --git a/tests/print_file_test.py b/tests/print_file_test.py index fd80676..39c9bef 100644 --- a/tests/print_file_test.py +++ b/tests/print_file_test.py @@ -125,6 +125,15 @@ def run(): assert held['states'] == {oid: 'imp'} others = client.call('/operator/queue/folder', {'early': True, 'held': []}, operator=True) assert not [f for f in others['files'] if f['order'] == oid], others['files'] + # A folder chosen before this order was paid catches up on it, printing or + # not, as a computer that was off does when it comes back; one chosen + # after it does not. + earlier = client.call('/operator/queue/folder', {'early': True, 'held': [], 'since': '2000-01-01T00:00:00Z'}, + operator=True) + assert [(f['state'], f['upload_id']) for f in earlier['files'] if f['order'] == oid] == [('imp', str(row['upload_id']))] + later = client.call('/operator/queue/folder', {'early': True, 'held': [], 'since': '2999-01-01T00:00:00Z'}, + operator=True) + assert not [f for f in later['files'] if f['order'] == oid], later['files'] # Once queued for printing, the final set can no longer change. client.call('/operator/orders/' + oid + '/final-files', {'version': version, 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}], diff --git a/web/kanban.js b/web/kanban.js index f646f26..dd15a08 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -230,8 +230,16 @@ const BRAVE_FLAG='brave://flags/#file-system-access-api'; const STAGE_FOLDERS={rec:'1. Arte recebida',tra:'2. Arte conferida',imp:'2. Arte conferida',rev:'2. Arte conferida',fin:'3. Finalizado'}; const KEEP_FINISHED_DAYS=30; const FOLDER={mode:'showDirectoryPicker' in window?'folder':/Firefox\//.test(navigator.userAgent)?'downloads':'none', - brave:!!navigator.brave,handle:null,granted:false,downloads:false, + brave:!!navigator.brave,handle:null,granted:false,downloads:false,since:null, saved:new Map(),busy:false,status:'',error:'',last:null,lastSig:null}; +// When the folders were chosen: every order paid since then ends up in them, +// even one that went through while this computer was off (Dropstar's rules, +// 2026-10-26). Folders chosen before this existed count from their first round. +async function folderSince(reset=false){ + let since=reset?null:await kv.get('folder-since').catch(()=>null); + if(!since){since=new Date().toISOString();await kv.set('folder-since',since).catch(()=>{});} + return FOLDER.since=since; +} // Switched on: a chosen folder released, or automatic downloads. const folderActive=()=>FOLDER.mode==='folder'?!!FOLDER.handle&&FOLDER.granted:FOLDER.downloads; // The three folders started their own record: files saved by the single @@ -251,7 +259,7 @@ async function restoreFolder(){ if(FOLDER.mode!=='folder')return; try{FOLDER.handle=await kv.get('folder')||null; if(FOLDER.handle){FOLDER.granted=(await FOLDER.handle.queryPermission({mode:'readwrite'}))==='granted'; - FOLDER.saved=await loadSaved(); + FOLDER.saved=await loadSaved();await folderSince(); if(!FOLDER.granted)setTimeout(()=>say('Para voltar a salvar os arquivos nas pastas, abra Integrações e clique em “Liberar pasta”.',false,10000),2500);}} catch{FOLDER.handle=null;} } @@ -298,7 +306,8 @@ function folderCard(){ node('p','Dentro de “'+h.name+'”: o arquivo do pedido chega em Arte recebida, passa para Arte conferida quando o card vai para lá '+ '(e fica lá enquanto imprime e na Revisão) e vai para Finalizado quando o pedido é finalizado, onde fica '+KEEP_FINISHED_DAYS+' dias.'), node('p','Pedido cancelado, excluído ou devolvido para correção: o arquivo sai das pastas. Arquivo trocado: a versão antiga sai. '+ - 'Pedidos que já estavam imprimindo quando a pasta foi escolhida não são baixados. Deixe o Kanban aberto neste computador.')], + 'Pedidos que já estavam imprimindo quando a pasta foi escolhida não são baixados. Se este computador ficar desligado, '+ + 'ao voltar ele busca também o que passou nesse tempo, cada arquivo na pasta da etapa em que o pedido está. Deixe o Kanban aberto neste computador.')], extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]}); } row.id='folder-card';return row; @@ -321,6 +330,7 @@ async function chooseFolder(){ FOLDER.handle=handle;FOLDER.granted=true;FOLDER.lastSig=null;FOLDER.error='';FOLDER.last=null; FOLDER.saved=await loadSaved(); await kv.set('folder',handle).catch(()=>{}); + await folderSince(true); await makeStageFolders(); paintFolder();say('Pastas '+[...new Set(Object.values(STAGE_FOLDERS))].join(', ')+' criadas dentro de “'+handle.name+'”.');syncFolder(true); } @@ -395,7 +405,7 @@ async function syncFolder(force=false){ try{ if(stages)await makeStageFolders(); const held=stages?[...new Set([...FOLDER.saved.values()].map(r=>r.order).filter(Boolean))].slice(-1000):[]; - const {files,states}=await api('/queue/folder',{early:stages,held}); + const {files,states}=await api('/queue/folder',{early:stages,held,since:stages?FOLDER.since||await folderSince():null}); const wanted=new Map(files.map(f=>[f.order+':'+f.item,f])); const where=stages?'“'+FOLDER.handle.name+'”':'a pasta de downloads'; let removed=0, moved=0, saved=0; @@ -416,9 +426,11 @@ async function syncFolder(force=false){ if(now&&now.upload_id===uid){await fetchInto(await stageDir(target),now);await record(uid,now,target);moved++;} else{FOLDER.saved.delete(uid);await keepSaved();} } - // New files: only orders in Arte recebida or Arte conferida. One already - // printing when the folder was chosen is the room's already. - const pending=files.filter(f=>!FOLDER.saved.has(f.upload_id)&&(stages?f.state==='rec'||f.state==='tra':f.state==='tra')); + // New files, each into its stage's folder: the server sends those in Arte + // recebida and Arte conferida, and the orders paid since the folders were + // chosen in any stage, so what passed while this computer was off comes in + // too. An order already printing when the folders were chosen is the room's. + const pending=files.filter(f=>!FOLDER.saved.has(f.upload_id)&&(stages?!!STAGE_FOLDERS[f.state]:f.state==='tra')); for(const [i,file] of pending.entries()){ FOLDER.status=(stages?'Salvando ':'Baixando ')+(i+1)+' de '+pending.length+': '+file.name;paintFolder(); say(FOLDER.status,false,60000);