feat: the orders' files in Dropstar's three folders: Arte recebida, Arte conferida, Finalizado
All checks were successful
Build and deploy / Validate source (push) Successful in 11s
Build and deploy / Integration suite on a real stack (push) Successful in 4m27s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m19s
All checks were successful
Build and deploy / Validate source (push) Successful in 11s
Build and deploy / Integration suite on a real stack (push) Successful in 4m27s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m19s
Asked by Dropstar on 2026-10-23 and agreed on 2026-10-26. The automatic folder becomes "Pastas dos pedidos": one main folder is chosen once, in Chrome or Edge on a factory computer that reaches the server, and the Kanban keeps three folders inside it, moved with the card. - Arte recebida: the order's file as soon as the order arrives - Arte conferida: the queue; the file moves there with the card and stays while it prints and is checked in Revisão - Finalizado: when the order is released, kept 30 days - 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 out comes back only when its order moves on, so the server now returns the files of orders the folders hold while they print, are checked and finish - Firefox, which cannot write into folders, still only downloads the files entering Arte conferida Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -945,29 +945,32 @@ def named_files(rows):
|
|||||||
return files
|
return files
|
||||||
|
|
||||||
|
|
||||||
def print_ready(c, request, states):
|
def print_ready(c, request, states, only=None):
|
||||||
"""The file to print for each item of the orders in these stages, in queue
|
"""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
|
order: the approved final, or before approval the generated print file
|
||||||
(unless the customer has sent a correction since). An operator who works
|
(unless the customer has sent a correction since). `only` narrows it to
|
||||||
on some machines gets only those machines' orders."""
|
these orders. 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,
|
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
|
COALESCE(o.queue_key, extract(epoch FROM o.created_at)) AS position
|
||||||
FROM dtf_local.orders o
|
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
|
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 o.cancelled_at IS NULL AND {FINAL_OK}
|
WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s)) AND o.cancelled_at IS NULL AND {FINAL_OK}
|
||||||
UNION ALL
|
UNION ALL
|
||||||
SELECT o.id,o.state,o.number,p.item_index,p.upload_id,u.object_key,u.name,
|
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))
|
COALESCE(o.queue_key, extract(epoch FROM o.created_at))
|
||||||
FROM dtf_local.orders o
|
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
|
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 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 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 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 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 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')
|
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), list(states))).fetchall()
|
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
|
staged = assign_machines(c, c.execute('''SELECT * FROM dtf_local.orders
|
||||||
WHERE state=ANY(%s) AND cancelled_at IS NULL''', (list(states),)).fetchall())
|
WHERE state=ANY(%s) AND (%s::uuid[] IS NULL OR id=ANY(%s)) AND cancelled_at IS NULL''',
|
||||||
|
(list(states), ids, ids)).fetchall())
|
||||||
mine = {o['id'] for o in visible(request, staged)}
|
mine = {o['id'] for o in visible(request, staged)}
|
||||||
return [row for row in rows if row['order_id'] in mine]
|
return [row for row in rows if row['order_id'] in mine]
|
||||||
|
|
||||||
@@ -992,13 +995,19 @@ class FolderSync(StrictModel):
|
|||||||
|
|
||||||
@router.post('/api/operator/queue/folder')
|
@router.post('/api/operator/queue/folder')
|
||||||
def queue_folder(body: FolderSync, request: Request, user=Depends(can('print'))):
|
def queue_folder(body: FolderSync, request: Request, user=Depends(can('print'))):
|
||||||
"""What the Kanban's automatic folder should hold. Early, it also gets the
|
"""What the Kanban's automatic folders should hold. `early` is Dropstar's
|
||||||
files of orders just received (to a "Recebidos" folder), so a large sheet is
|
three folders (2026-10-26): the files of orders in Arte recebida and Arte
|
||||||
already on the computer when the order reaches the queue. `states` answers
|
conferida, and, for the orders the folders already hold, their files while
|
||||||
for the orders the folder already holds files of: a stage, 'cancelled', or
|
they print, are checked in Revisão and sit in Finalizado, so one taken out
|
||||||
nothing when the order was deleted, so their files can be removed."""
|
of a folder can be fetched again when the order moves on. 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."""
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
files = named_files(print_ready(c, request, ('rec', 'tra') if body.early else ('tra',)))
|
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)
|
||||||
|
files = named_files(rows)
|
||||||
held = c.execute('SELECT id,state,cancelled_at FROM dtf_local.orders WHERE id=ANY(%s)',
|
held = c.execute('SELECT id,state,cancelled_at FROM dtf_local.orders WHERE id=ANY(%s)',
|
||||||
(body.held,)).fetchall() if body.held else []
|
(body.held,)).fetchall() if body.held else []
|
||||||
return {'files': files,
|
return {'files': files,
|
||||||
|
|||||||
@@ -336,15 +336,21 @@ docs/guias/telas/.
|
|||||||
|
|
||||||
### Kanban automatic folder (agreed in the 2026-10-07 meeting)
|
### Kanban automatic folder (agreed in the 2026-10-07 meeting)
|
||||||
|
|
||||||
The Kanban, open on the print room's computer, saves the files to a folder
|
Dropstar's three folders (asked 2026-10-23, agreed 2026-10-26): the Kanban,
|
||||||
chosen in Integrações (Chrome or Edge; Firefox only downloads). Per computer,
|
open in Chrome or Edge on a factory computer that reaches the server's
|
||||||
it downloads as soon as the order arrives in Arte recebida (the default since
|
folder, signed in with a profile that sees every order (Gestão), keeps the
|
||||||
2026-10-20), into a `Recebidos` folder inside the chosen one, moved up when
|
orders' files in three folders it creates inside the one chosen in
|
||||||
the order enters the queue (Arte conferida since 2026-10-26); or only when the
|
Integrações ("Pastas dos pedidos"): Arte recebida (the file arrives when the
|
||||||
order enters the queue.
|
order does), Arte conferida (the queue; the file moves there with the card
|
||||||
Files of orders cancelled, deleted or sent back for correction, and files
|
and stays while it prints and is checked in Revisão) and Finalizado (when the
|
||||||
replaced by another final, are removed from the folder
|
order is released, kept 30 days there). Correção, a cancellation or a
|
||||||
(`POST /api/operator/queue/folder`).
|
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
|
||||||
|
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
|
||||||
|
folder permissions. Firefox cannot write into folders: it only downloads the
|
||||||
|
files entering Arte conferida.
|
||||||
|
|
||||||
Integrações (2026-10-20): only the superadmin (us) has the buttons, the
|
Integrações (2026-10-20): only the superadmin (us) has the buttons, the
|
||||||
details and the Tiny log there (`integrations` capability, app/core/auth.py).
|
details and the Tiny log there (`integrations` capability, app/core/auth.py).
|
||||||
@@ -430,9 +436,11 @@ Still to do (2026-10-26):
|
|||||||
- Waiting on Dropstar: the DTF SITE category's numeric id (CATEGORY in
|
- Waiting on Dropstar: the DTF SITE category's numeric id (CATEGORY in
|
||||||
app/tiny.py is still DUPLICADO DROP), the internal rules document (D-16 to
|
app/tiny.py is still DUPLICADO DROP), the internal rules document (D-16 to
|
||||||
D-23), and the montador spec (and which "histórico" Marcus means for its
|
D-23), and the montador spec (and which "histórico" Marcus means for its
|
||||||
orders). Their three server folders moved on card moves need a written
|
orders).
|
||||||
decision: the Kanban in the room's browser can do it; a program on their
|
- The three folders, once deployed: Marcus sets the main folder on the
|
||||||
server is the factory agent left out of this scope.
|
factory computer (Chrome, Integrações > Pastas dos pedidos); check on the
|
||||||
|
first print whether FlexiPRINT keeps reading the file in Arte conferida
|
||||||
|
after import (the file only leaves that folder at Finalizado).
|
||||||
- Anchor-customer orders from the montador: after the launch; the team's idea
|
- Anchor-customer orders from the montador: after the launch; the team's idea
|
||||||
is that Graphs handles that side and sends the orders to this Kanban.
|
is that Graphs handles that side and sends the orders to this Kanban.
|
||||||
|
|
||||||
|
|||||||
@@ -183,7 +183,7 @@ try{
|
|||||||
assert.equal(await kanban.eval(`board.orders.find(o=>o.id===${JSON.stringify(oid)}).snapshot.customer.name`),'Maria da Silva');
|
assert.equal(await kanban.eval(`board.orders.find(o=>o.id===${JSON.stringify(oid)}).snapshot.customer.name`),'Maria da Silva');
|
||||||
assert.deepEqual(await kanban.eval(`(()=>{const spec=board.orders.find(o=>o.id===${JSON.stringify(oid)}).snapshot.items[0].production;const source=spec.sources[0];return {kind:source.kind,copies:source.copies,length:Number(source.length_cm),height:Number(spec.height_cm),placed:spec.placements.length}})()`),
|
assert.deepEqual(await kanban.eval(`(()=>{const spec=board.orders.find(o=>o.id===${JSON.stringify(oid)}).snapshot.items[0].production;const source=spec.sources[0];return {kind:source.kind,copies:source.copies,length:Number(source.length_cm),height:Number(spec.height_cm),placed:spec.placements.length}})()`),
|
||||||
{kind:'sheet',copies:1,length:101,height:101,placed:1});
|
{kind:'sheet',copies:1,length:101,height:101,placed:1});
|
||||||
// The print queue's folder, switched on in Integrações. The native picker
|
// The orders' three folders, switched on in Integrações. The native picker
|
||||||
// cannot be driven headless: it answers with a folder in the browser's own
|
// cannot be driven headless: it answers with a folder in the browser's own
|
||||||
// storage, which has the same file API.
|
// storage, which has the same file API.
|
||||||
await kanban.click('[data-tab="integrations"]');
|
await kanban.click('[data-tab="integrations"]');
|
||||||
@@ -193,11 +193,10 @@ try{
|
|||||||
window.showDirectoryPicker=async()=>window.picked;FOLDER.mode='folder';renderIntegrations();
|
window.showDirectoryPicker=async()=>window.picked;FOLDER.mode='folder';renderIntegrations();
|
||||||
[...document.querySelectorAll('#folder-card button')].find(b=>b.textContent==='Escolher pasta').click();})()`);
|
[...document.querySelectorAll('#folder-card button')].find(b=>b.textContent==='Escolher pasta').click();})()`);
|
||||||
await waitFor(()=>kanban.eval('folderActive()&&!FOLDER.busy'),'folder chosen');
|
await waitFor(()=>kanban.eval('folderActive()&&!FOLDER.busy'),'folder chosen');
|
||||||
// Downloaded as the order arrives, into Recebidos; up to the folder at the queue.
|
// Dropstar's three folders (2026-10-26): the file arrives in Arte recebida,
|
||||||
await waitFor(()=>kanban.eval(`!!document.querySelector('#folder-card select')`),'download timing choice');
|
// goes to Arte conferida with the card and to Finalizado at the end.
|
||||||
await kanban.eval(`(()=>{const s=document.querySelector('#folder-card select');s.value='rec';s.dispatchEvent(new Event('change'));})()`);
|
await waitFor(()=>kanban.eval(`!FOLDER.busy`),'folder idle');
|
||||||
await waitFor(()=>kanban.eval(`FOLDER.when==='rec'&&!FOLDER.busy`),'download on arrival');
|
const savedFiles=(sub)=>kanban.eval(`(async()=>{const dir=await window.picked.getDirectoryHandle(${JSON.stringify(sub)},{create:true});
|
||||||
const savedFiles=(sub)=>kanban.eval(`(async()=>{const dir=${sub?`await window.picked.getDirectoryHandle(${JSON.stringify(sub)},{create:true})`:'window.picked'};
|
|
||||||
const out=[];for await(const [name,h] of dir.entries())if(h.kind==='file')out.push(name);return out;})()`);
|
const out=[];for await(const [name,h] of dir.entries())if(h.kind==='file')out.push(name);return out;})()`);
|
||||||
// Open the order's panel from its card, then click the real transition
|
// Open the order's panel from its card, then click the real transition
|
||||||
// buttons there, including the rerender after each move.
|
// buttons there, including the rerender after each move.
|
||||||
@@ -220,31 +219,40 @@ try{
|
|||||||
await kanban.fill(`[data-order="${oid}"] input[placeholder="Nota da revisão"]`,'Browser test final file');
|
await kanban.fill(`[data-order="${oid}"] input[placeholder="Nota da revisão"]`,'Browser test final file');
|
||||||
await kanban.eval(`(()=>{const check=document.querySelector('[data-order="${oid}"] [data-confirm]');check.click();check.closest('form').requestSubmit();})()`);
|
await kanban.eval(`(()=>{const check=document.querySelector('[data-order="${oid}"] [data-confirm]');check.click();check.closest('form').requestSubmit();})()`);
|
||||||
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').version===1`),'final file approval');
|
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').version===1`),'final file approval');
|
||||||
// Approved before the queue: already on this computer, in Recebidos.
|
// Approved before the queue: already on this computer, in Arte recebida.
|
||||||
const early='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
|
const early='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
|
||||||
await kanban.eval('syncFolder(true)');
|
await kanban.eval('syncFolder(true)');
|
||||||
await waitFor(async()=>(await savedFiles('Recebidos')).some(n=>n.startsWith(early)&&!n.endsWith('.baixando')),'final file saved in Recebidos',45000);
|
await waitFor(async()=>(await savedFiles('Arte recebida')).some(n=>n.startsWith(early)&&!n.endsWith('.baixando')),'final file saved in Arte recebida',45000);
|
||||||
assert.equal((await savedFiles()).some(n=>n.startsWith(early)),false);
|
assert.equal((await savedFiles('Arte conferida')).some(n=>n.startsWith(early)),false);
|
||||||
}
|
}
|
||||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="${state}"]')`),'move to '+title);
|
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="${state}"]')`),'move to '+title);
|
||||||
await kanban.click(`[data-order="${oid}"] [data-move="${state}"]`);
|
await kanban.click(`[data-order="${oid}"] [data-move="${state}"]`);
|
||||||
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='${state}'`),'transition '+state);
|
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='${state}'`),'transition '+state);
|
||||||
if(state==='tra'){
|
if(state==='tra'){
|
||||||
// Entering the queue saves its final file there, whole and named after the order.
|
// Entering the queue moves its file to Arte conferida, whole and named after the order.
|
||||||
const prefix='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
|
const prefix='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
|
||||||
await waitFor(async()=>(await savedFiles()).some(n=>n.startsWith(prefix)&&!n.endsWith('.baixando')),'final file saved in the folder',45000);
|
await waitFor(async()=>(await savedFiles('Arte conferida')).some(n=>n.startsWith(prefix)&&!n.endsWith('.baixando')),'final file in Arte conferida',45000);
|
||||||
// Other orders the earlier suites left in the queue may still be coming
|
// Other orders the earlier suites left in the queue may still be coming
|
||||||
// down: only once the round ends must no half-written file be left.
|
// down: only once the round ends must no half-written file be left.
|
||||||
await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder round finished',60000);
|
await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder round finished',60000);
|
||||||
assert.equal((await savedFiles()).some(n=>n.endsWith('.baixando')),false);
|
assert.equal((await savedFiles('Arte conferida')).some(n=>n.endsWith('.baixando')),false);
|
||||||
assert.equal((await savedFiles('Recebidos')).some(n=>n.startsWith(prefix)),false);
|
assert.equal((await savedFiles('Arte recebida')).some(n=>n.startsWith(prefix)),false);
|
||||||
// A file whose order was deleted leaves the folder.
|
// A file whose order was deleted leaves the folder.
|
||||||
await kanban.eval(`(async()=>{const f=await window.picked.getFileHandle('pedido-0-item-1-excluido.png',{create:true});
|
await kanban.eval(`(async()=>{const dir=await window.picked.getDirectoryHandle('Arte conferida',{create:true});
|
||||||
|
const f=await dir.getFileHandle('pedido-0-item-1-excluido.png',{create:true});
|
||||||
const w=await f.createWritable();await w.write('x');await w.close();
|
const w=await f.createWritable();await w.write('x');await w.close();
|
||||||
FOLDER.saved.set(crypto.randomUUID(),{order:crypto.randomUUID(),item:1,name:'pedido-0-item-1-excluido.png',place:'queue'});})()`);
|
FOLDER.saved.set(crypto.randomUUID(),{order:crypto.randomUUID(),item:1,name:'pedido-0-item-1-excluido.png',folder:'Arte conferida'});})()`);
|
||||||
await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder idle',60000);
|
await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder idle',60000);
|
||||||
await kanban.eval('syncFolder(true)');
|
await kanban.eval('syncFolder(true)');
|
||||||
await waitFor(async()=>!(await savedFiles()).includes('pedido-0-item-1-excluido.png'),'deleted order file removed',30000);
|
await waitFor(async()=>!(await savedFiles('Arte conferida')).includes('pedido-0-item-1-excluido.png'),'deleted order file removed',30000);
|
||||||
|
}
|
||||||
|
if(state==='fin'){
|
||||||
|
// Finalized: the file goes to Finalizado, out of the queue.
|
||||||
|
const prefix='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
|
||||||
|
await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder idle',60000);
|
||||||
|
await kanban.eval('syncFolder(true)');
|
||||||
|
await waitFor(async()=>(await savedFiles('Finalizado')).some(n=>n.startsWith(prefix)),'final file in Finalizado',30000);
|
||||||
|
assert.equal((await savedFiles('Arte conferida')).some(n=>n.startsWith(prefix)),false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Undo a mistaken move from the panel: one stage back with an internal reason.
|
// Undo a mistaken move from the panel: one stage back with an internal reason.
|
||||||
|
|||||||
@@ -113,6 +113,15 @@ def run():
|
|||||||
# Arte conferida is the print queue (2026-10-23).
|
# Arte conferida is the print queue (2026-10-23).
|
||||||
client.call('/operator/orders/' + oid + '/move', {'state': 'tra', 'version': version}, operator=True)
|
client.call('/operator/orders/' + oid + '/move', {'state': 'tra', 'version': version}, operator=True)
|
||||||
version += 1
|
version += 1
|
||||||
|
# Printing, the folders still get the file of an order they hold (to take
|
||||||
|
# it to Finalizado later), and no one else's.
|
||||||
|
client.call('/operator/orders/' + oid + '/move', {'state': 'imp', 'version': version}, operator=True)
|
||||||
|
version += 1
|
||||||
|
held = client.call('/operator/queue/folder', {'early': True, 'held': [oid]}, operator=True)
|
||||||
|
assert [(f['state'], f['upload_id']) for f in held['files'] if f['order'] == oid] == [('imp', str(row['upload_id']))], held
|
||||||
|
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']
|
||||||
# Once queued for printing, the final set can no longer change.
|
# Once queued for printing, the final set can no longer change.
|
||||||
client.call('/operator/orders/' + oid + '/final-files',
|
client.call('/operator/orders/' + oid + '/final-files',
|
||||||
{'version': version, 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}],
|
{'version': version, 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}],
|
||||||
|
|||||||
184
web/kanban.js
184
web/kanban.js
@@ -207,37 +207,37 @@ function download(uid){return async()=>{
|
|||||||
const link=node('a');link.href=result.url;link.referrerPolicy='no-referrer';link.download=result.name;link.click();
|
const link=node('a');link.href=result.url;link.referrerPolicy='no-referrer';link.download=result.name;link.click();
|
||||||
};}
|
};}
|
||||||
// ---- Automatic folder ------------------------------------------------------
|
// ---- Automatic folder ------------------------------------------------------
|
||||||
// The print queue's files, saved by this browser as orders enter Arte
|
// The orders' files, kept by this browser in Dropstar's three folders
|
||||||
// conferida (the queue since 2026-10-23), while the Kanban is open. It is switched on in Integrações, on
|
// (2026-10-26) inside the one chosen, while the Kanban is open. It is switched
|
||||||
// the print room's computer: the folder belongs to that browser, not to the
|
// on in Integrações, on a computer of the factory that reaches the server's
|
||||||
// account. Chrome and Edge write into a folder the operator chose
|
// folder: the folder belongs to that browser, not to the account. Chrome and
|
||||||
// (FlexiPRINT's, or the internal server's share), remembered, with one click
|
// Edge write into the folder chosen, remembered, with one click to release it
|
||||||
// to release it after the browser restarts. Brave has the same API behind a
|
// after the browser restarts. Brave has the same API behind a flag that is off
|
||||||
// flag that is off by default; the card says how to turn it on. Firefox cannot
|
// by default; the card says how to turn it on. Firefox cannot write into a
|
||||||
// write into a chosen folder: there each file is downloaded, and Firefox's own
|
// chosen folder: there each file entering the queue is downloaded, and
|
||||||
// download folder is set to FlexiPRINT's.
|
// Firefox's own download folder is set to FlexiPRINT's.
|
||||||
const kv=(()=>{let opened;const open=()=>opened||(opened=new Promise((ok,fail)=>{const r=indexedDB.open('dtf-kanban',1);
|
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);}));
|
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'));
|
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);});};
|
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))};})();
|
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 BRAVE_FLAG='brave://flags/#file-system-access-api';
|
const BRAVE_FLAG='brave://flags/#file-system-access-api';
|
||||||
// `when`: download as soon as the order arrives in Arte recebida ('rec', the
|
// Where an order's file is, by its stage: it arrives in Arte recebida, moves
|
||||||
// default), into a "Recebidos" folder inside the chosen one; the file moves up
|
// to Arte conferida (the queue) with the card and stays there while it prints
|
||||||
// when the order enters the queue; or only at the queue ('tra'; computers set
|
// and is checked in Revisão, then goes to Finalizado, kept 30 days. Correção,
|
||||||
// before 2026-10-23 kept 'fil', read the same). Only a chosen folder can do
|
// a cancellation or a deletion takes it out; a replaced final is swapped.
|
||||||
// that: Firefox downloads cannot be moved or removed afterwards.
|
const STAGE_FOLDERS={rec:'Arte recebida',tra:'Arte conferida',imp:'Arte conferida',rev:'Arte conferida',fin:'Finalizado'};
|
||||||
|
const KEEP_FINISHED_DAYS=30;
|
||||||
const FOLDER={mode:'showDirectoryPicker' in window?'folder':/Firefox\//.test(navigator.userAgent)?'downloads':'none',
|
const FOLDER={mode:'showDirectoryPicker' in window?'folder':/Firefox\//.test(navigator.userAgent)?'downloads':'none',
|
||||||
brave:!!navigator.brave,handle:null,granted:false,downloads:false,when:'rec',
|
brave:!!navigator.brave,handle:null,granted:false,downloads:false,
|
||||||
saved:new Map(),busy:false,status:'',error:'',last:null,lastSig:null};
|
saved:new Map(),busy:false,status:'',error:'',last:null,lastSig:null};
|
||||||
const RECEIVED='Recebidos';
|
|
||||||
// Switched on: a chosen folder released, or automatic downloads.
|
// Switched on: a chosen folder released, or automatic downloads.
|
||||||
const folderActive=()=>FOLDER.mode==='folder'?!!FOLDER.handle&&FOLDER.granted:FOLDER.downloads;
|
const folderActive=()=>FOLDER.mode==='folder'?!!FOLDER.handle&&FOLDER.granted:FOLDER.downloads;
|
||||||
const early=()=>FOLDER.mode==='folder'&&FOLDER.when==='rec';
|
// The three folders started their own record: files saved by the single
|
||||||
const savedKey=()=>FOLDER.mode==='folder'?'saved:'+FOLDER.handle.name:'saved:downloads';
|
// folder of before 2026-10-26 are left where they are.
|
||||||
// What this folder received, by upload: its order, item, name and where it is
|
const savedKey=()=>FOLDER.mode==='folder'?'stages:'+FOLDER.handle.name:'saved:downloads';
|
||||||
// ('early' in Recebidos, 'queue' in the folder, 'done' once printing). Older
|
// What this folder received, by upload: its order, item, name, the folder it
|
||||||
// versions kept only the upload ids.
|
// is in and, in Finalizado, since when. Older versions kept only the upload ids.
|
||||||
const savedMap=list=>new Map((list||[]).map(e=>typeof e==='string'?[e,{place:'done'}]:e));
|
const savedMap=list=>new Map((list||[]).map(e=>typeof e==='string'?[e,{place:'done'}]:e));
|
||||||
const loadSaved=async()=>savedMap(await kv.get(savedKey()).catch(()=>null));
|
const loadSaved=async()=>savedMap(await kv.get(savedKey()).catch(()=>null));
|
||||||
const keepSaved=()=>kv.set(savedKey(),[...FOLDER.saved].slice(-3000)).catch(()=>{});
|
const keepSaved=()=>kv.set(savedKey(),[...FOLDER.saved].slice(-3000)).catch(()=>{});
|
||||||
@@ -248,18 +248,17 @@ async function restoreFolder(){
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if(FOLDER.mode!=='folder')return;
|
if(FOLDER.mode!=='folder')return;
|
||||||
try{FOLDER.when=['tra','fil'].includes(await kv.get('folder-when'))?'tra':'rec';
|
try{FOLDER.handle=await kv.get('folder')||null;
|
||||||
FOLDER.handle=await kv.get('folder')||null;
|
|
||||||
if(FOLDER.handle){FOLDER.granted=(await FOLDER.handle.queryPermission({mode:'readwrite'}))==='granted';
|
if(FOLDER.handle){FOLDER.granted=(await FOLDER.handle.queryPermission({mode:'readwrite'}))==='granted';
|
||||||
FOLDER.saved=await loadSaved();
|
FOLDER.saved=await loadSaved();
|
||||||
if(!FOLDER.granted)setTimeout(()=>say('Para voltar a salvar os arquivos da fila na pasta, abra Integrações e clique em “Liberar pasta”.',false,10000),2500);}}
|
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;}
|
catch{FOLDER.handle=null;}
|
||||||
}
|
}
|
||||||
// The folder's row in Integrações, redrawn whenever its state changes. The
|
// The folder's row in Integrações, redrawn whenever its state changes. The
|
||||||
// row says what is happening; the how-to and the secondary buttons are under
|
// row says what is happening; the how-to and the secondary buttons are under
|
||||||
// "Detalhes".
|
// "Detalhes".
|
||||||
function folderCard(){
|
function folderCard(){
|
||||||
const name='Pasta da fila (Arte conferida)', h=FOLDER.handle;
|
const name='Pastas dos pedidos', h=FOLDER.handle;
|
||||||
const act=(text,fn)=>button(text,fn,'btn small');
|
const act=(text,fn)=>button(text,fn,'btn small');
|
||||||
const ghost=(text,fn)=>button(text,fn,'btn ghost small');
|
const ghost=(text,fn)=>button(text,fn,'btn ghost small');
|
||||||
const steps=(...lines)=>{const ol=node('ol',undefined,'integ-steps');for(const l of lines)ol.append(l instanceof Node?l:node('li',l));return ol;};
|
const steps=(...lines)=>{const ol=node('ol',undefined,'integ-steps');for(const l of lines)ol.append(l instanceof Node?l:node('li',l));return ol;};
|
||||||
@@ -280,30 +279,25 @@ function folderCard(){
|
|||||||
? integration({name,state:FOLDER.error?'Verificar':'Ligada',tone:FOLDER.error?'warn':'ok',
|
? integration({name,state:FOLDER.error?'Verificar':'Ligada',tone:FOLDER.error?'warn':'ok',
|
||||||
summary:FOLDER.error||FOLDER.status||'Baixando na pasta de downloads do Firefox · '+folderCount(),
|
summary:FOLDER.error||FOLDER.status||'Baixando na pasta de downloads do Firefox · '+folderCount(),
|
||||||
details:how,extra:[ghost('Desligar',()=>setDownloads(false))]})
|
details:how,extra:[ghost('Desligar',()=>setDownloads(false))]})
|
||||||
: integration({name,state:'Desligada',tone:'off',summary:'Baixa sozinho, no Firefox, os arquivos que entram na fila.',
|
: integration({name,state:'Desligada',tone:'off',summary:'No Firefox, baixa sozinho os arquivos que entram em Arte conferida; as três pastas pedem o Chrome ou o Edge.',
|
||||||
actions:[act('Ligar',()=>setDownloads(true))],details:how});
|
actions:[act('Ligar',()=>setDownloads(true))],details:how});
|
||||||
}else if(!h){
|
}else if(!h){
|
||||||
row=integration({name,state:'Desligada',tone:'off',summary:'Salva sozinho, numa pasta, os arquivos que entram na fila.',
|
row=integration({name,state:'Desligada',tone:'off',summary:'Salva sozinho os arquivos dos pedidos em três pastas: Arte recebida, Arte conferida e Finalizado.',
|
||||||
actions:[act('Escolher pasta',chooseFolder)],
|
actions:[act('Escolher pasta',chooseFolder)],
|
||||||
details:[node('p','Escolha a pasta que o FlexiPRINT lê, ou a pasta da rede do servidor. Os arquivos levam o número do pedido no nome. '+
|
details:[node('p','Escolha uma vez a pasta principal, na rede do servidor: o Kanban cria dentro dela as três pastas e move o arquivo conforme o card anda. '+
|
||||||
'Funciona neste computador, com o Kanban aberto.')]});
|
'Os arquivos levam o número do pedido no nome. Funciona neste computador, com o Kanban aberto e um usuário que vê todos os pedidos, como o de Gestão.')]});
|
||||||
}else if(!FOLDER.granted){
|
}else if(!FOLDER.granted){
|
||||||
row=integration({name,state:'Liberar',tone:'warn',summary:'O navegador pede um clique para voltar a salvar em “'+h.name+'”.',
|
row=integration({name,state:'Liberar',tone:'warn',summary:'O navegador pede um clique para voltar a salvar em “'+h.name+'”.',
|
||||||
actions:[act('Liberar pasta',releaseFolder)],extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]});
|
actions:[act('Liberar pasta',releaseFolder)],extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]});
|
||||||
}else{
|
}else{
|
||||||
const when=node('select',undefined,'machine-select');when.setAttribute('aria-label','Quando baixar');
|
|
||||||
for(const [value,text] of [['rec','Baixar em Arte recebida'],['tra','Baixar em Arte conferida']]){
|
|
||||||
const o=node('option',text);o.value=value;o.selected=FOLDER.when===value;when.append(o);}
|
|
||||||
when.onchange=()=>setWhen(when.value);
|
|
||||||
row=integration({name,state:FOLDER.error?'Verificar':'Ligada',tone:FOLDER.error?'warn':'ok',
|
row=integration({name,state:FOLDER.error?'Verificar':'Ligada',tone:FOLDER.error?'warn':'ok',
|
||||||
summary:FOLDER.error||FOLDER.status||'Salvando em “'+h.name+'” · '+folderCount(),actions:[when],
|
summary:FOLDER.error||FOLDER.status||'Salvando em “'+h.name+'” · '+folderCount(),
|
||||||
details:[['Pasta','“'+h.name+'”'],['Arquivos salvos',String(FOLDER.saved.size)],
|
details:[['Pasta','“'+h.name+'”'],['Arquivos salvos',String(FOLDER.saved.size)],
|
||||||
['Último',FOLDER.last?FOLDER.last.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'—'],
|
['Último',FOLDER.last?FOLDER.last.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'—'],
|
||||||
node('p',FOLDER.when==='rec'
|
node('p','Dentro de “'+h.name+'”: o arquivo do pedido chega em Arte recebida, passa para Arte conferida quando o card vai para lá '+
|
||||||
?'Em Arte recebida: o arquivo do pedido é baixado em “'+h.name+'/'+RECEIVED+'” assim que o pedido chega, e passa para “'+h.name+'” quando entra em Arte conferida, a fila.'
|
'(e fica lá enquanto imprime e na Revisão) e vai para Finalizado quando o pedido é finalizado, onde fica '+KEEP_FINISHED_DAYS+' dias.'),
|
||||||
:'Em Arte conferida: o arquivo é baixado em “'+h.name+'” quando o pedido entra em Arte conferida, a fila.'),
|
node('p','Pedido cancelado, excluído ou devolvido para correção: o arquivo sai das pastas. Arquivo trocado: a versão antiga sai. '+
|
||||||
node('p','Pedido cancelado, excluído ou devolvido para correção: o arquivo sai da pasta. 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.')],
|
||||||
'Deixe o Kanban aberto neste computador. Um arquivo que o FlexiPRINT tirar da pasta não é baixado de novo.')],
|
|
||||||
extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]});
|
extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]});
|
||||||
}
|
}
|
||||||
row.id='folder-card';return row;
|
row.id='folder-card';return row;
|
||||||
@@ -326,7 +320,7 @@ async function chooseFolder(){
|
|||||||
FOLDER.handle=handle;FOLDER.granted=true;FOLDER.lastSig=null;FOLDER.error='';FOLDER.last=null;
|
FOLDER.handle=handle;FOLDER.granted=true;FOLDER.lastSig=null;FOLDER.error='';FOLDER.last=null;
|
||||||
FOLDER.saved=await loadSaved();
|
FOLDER.saved=await loadSaved();
|
||||||
await kv.set('folder',handle).catch(()=>{});
|
await kv.set('folder',handle).catch(()=>{});
|
||||||
paintFolder();say('Os arquivos da fila vão ser salvos em “'+handle.name+'”.');syncFolder();
|
paintFolder();say('Os arquivos dos pedidos vão ser salvos nas três pastas dentro de “'+handle.name+'”.');syncFolder();
|
||||||
}
|
}
|
||||||
async function releaseFolder(){
|
async function releaseFolder(){
|
||||||
FOLDER.granted=(await FOLDER.handle.requestPermission({mode:'readwrite'}))==='granted';
|
FOLDER.granted=(await FOLDER.handle.requestPermission({mode:'readwrite'}))==='granted';
|
||||||
@@ -343,13 +337,6 @@ async function setDownloads(on){
|
|||||||
paintFolder();say(on?'Download automático ligado.':'Download automático desligado.');
|
paintFolder();say(on?'Download automático ligado.':'Download automático desligado.');
|
||||||
if(on)syncFolder();
|
if(on)syncFolder();
|
||||||
}
|
}
|
||||||
async function setWhen(when){
|
|
||||||
FOLDER.when=when;FOLDER.lastSig=null;
|
|
||||||
await kv.set('folder-when',when).catch(()=>{});
|
|
||||||
paintFolder();say(when==='rec'?'Os arquivos vão ser baixados assim que o pedido chegar, em “'+RECEIVED+'”.':'Os arquivos vão ser baixados quando o pedido entrar em Arte conferida.');
|
|
||||||
syncFolder(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
// A whole file in a folder: written under another name and renamed at the
|
// A whole file in a folder: written under another name and renamed at the
|
||||||
// end, so the FlexiPRINT never sees half of it. `source` is a download's body
|
// end, so the FlexiPRINT never sees half of it. `source` is a download's body
|
||||||
// or a file.
|
// or a file.
|
||||||
@@ -364,83 +351,94 @@ async function writeWhole(dir,name,source){
|
|||||||
catch{const whole=await (await dir.getFileHandle(name,{create:true})).createWritable();
|
catch{const whole=await (await dir.getFileHandle(name,{create:true})).createWritable();
|
||||||
await whole.write(await temp.getFile());await whole.close();await dir.removeEntry(temp.name);}
|
await whole.write(await temp.getFile());await whole.close();await dir.removeEntry(temp.name);}
|
||||||
}
|
}
|
||||||
const received=()=>FOLDER.handle.getDirectoryHandle(RECEIVED,{create:true});
|
const stageDir=name=>FOLDER.handle.getDirectoryHandle(name,{create:true});
|
||||||
// Remove a saved file from where it is; one already gone (the FlexiPRINT
|
// Remove a saved file from its folder; one already gone (someone took it) is fine.
|
||||||
// took it) is fine.
|
|
||||||
async function removeSaved(rec){
|
async function removeSaved(rec){
|
||||||
const dir=rec.place==='early'?await received():FOLDER.handle;
|
const dir=await stageDir(rec.folder);
|
||||||
await dir.removeEntry(rec.name).catch(e=>{if(e.name!=='NotFoundError')throw e;});
|
await dir.removeEntry(rec.name).catch(e=>{if(e.name!=='NotFoundError')throw e;});
|
||||||
}
|
}
|
||||||
// From Recebidos up to the folder, when the order enters the queue. False when
|
// To another of the three folders. False when the file is no longer where it was.
|
||||||
// the file is no longer there, so it is downloaded again.
|
async function moveSaved(rec,to){
|
||||||
async function moveToQueue(rec){
|
const from=await stageDir(rec.folder), dest=await stageDir(to);let file;
|
||||||
const from=await received();let file;
|
|
||||||
try{file=await from.getFileHandle(rec.name);}catch(e){if(e.name==='NotFoundError')return false;throw e;}
|
try{file=await from.getFileHandle(rec.name);}catch(e){if(e.name==='NotFoundError')return false;throw e;}
|
||||||
await FOLDER.handle.removeEntry(rec.name).catch(()=>{});
|
await dest.removeEntry(rec.name).catch(()=>{});
|
||||||
try{await file.move(FOLDER.handle);}
|
try{await file.move(dest);}
|
||||||
catch{await writeWhole(FOLDER.handle,rec.name,await file.getFile());await from.removeEntry(rec.name);}
|
catch{await writeWhole(dest,rec.name,await file.getFile());await from.removeEntry(rec.name);}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
// One file from storage, whole, into a folder.
|
||||||
|
async function fetchInto(dir,file){
|
||||||
|
const r=await fetch(file.url,{referrerPolicy:'no-referrer'});
|
||||||
|
if(!r.ok||!r.body)throw new Error('não foi possível baixar '+file.name+' (erro '+r.status+').');
|
||||||
|
await writeWhole(dir,file.name,r.body);
|
||||||
|
}
|
||||||
|
|
||||||
// Bring the folder in line with the board: remove the files of orders that
|
// Bring the folders in line with the board: remove the files of orders that
|
||||||
// were cancelled, deleted, sent back for correction or given another file;
|
// were cancelled, deleted, sent back for correction or given another file,
|
||||||
// move up what entered the queue; download what is missing. A file the
|
// and those kept their days in Finalizado; move each file to its stage's
|
||||||
// FlexiPRINT moved away after importing is not downloaded again. After a
|
// folder; download what arrived in Arte recebida or Arte conferida. A file
|
||||||
|
// someone took out is downloaded again only when its order moves on. After a
|
||||||
// board load it asks only when something it follows changed; the folder's
|
// board load it asks only when something it follows changed; the folder's
|
||||||
// own timer always asks, since another computer may have moved the order.
|
// own timer always asks, since another computer may have moved the order.
|
||||||
async function syncFolder(force=false){
|
async function syncFolder(force=false){
|
||||||
if(!folderActive()||FOLDER.busy||!board||!may('print'))return;
|
if(!folderActive()||FOLDER.busy||!board||!may('print'))return;
|
||||||
const follows=early()?['rec','tra','cor']:['tra'];
|
const stages=FOLDER.mode==='folder';
|
||||||
const sig=FOLDER.when+'|'+board.orders.filter(o=>follows.includes(o.state)||o.cancelled_at)
|
const follows=stages?['rec','tra','imp','rev','fin','cor']:['tra'];
|
||||||
|
const sig=board.orders.filter(o=>follows.includes(o.state)||o.cancelled_at)
|
||||||
.map(o=>o.id+':'+o.version+':'+o.state+(o.cancelled_at?':x':'')).join(',');
|
.map(o=>o.id+':'+o.version+':'+o.state+(o.cancelled_at?':x':'')).join(',');
|
||||||
if(!force&&sig===FOLDER.lastSig)return;
|
if(!force&&sig===FOLDER.lastSig)return;
|
||||||
FOLDER.busy=true;
|
FOLDER.busy=true;
|
||||||
try{
|
try{
|
||||||
const tidy=FOLDER.mode==='folder';
|
const held=stages?[...new Set([...FOLDER.saved.values()].map(r=>r.order).filter(Boolean))].slice(-1000):[];
|
||||||
const held=tidy?[...new Set([...FOLDER.saved.values()].filter(r=>r.order&&r.place!=='done').map(r=>r.order))]:[];
|
const {files,states}=await api('/queue/folder',{early:stages,held});
|
||||||
const {files,states}=await api('/queue/folder',{early:early(),held});
|
|
||||||
const wanted=new Map(files.map(f=>[f.order+':'+f.item,f]));
|
const wanted=new Map(files.map(f=>[f.order+':'+f.item,f]));
|
||||||
const where=FOLDER.mode==='folder'?'“'+FOLDER.handle.name+'”':'a pasta de downloads';
|
const where=stages?'“'+FOLDER.handle.name+'”':'a pasta de downloads';
|
||||||
let removed=0;
|
let removed=0, moved=0, saved=0;
|
||||||
if(tidy)for(const [uid,rec] of [...FOLDER.saved]){
|
const record=async(uid,file,folder)=>{
|
||||||
if(!rec.order||rec.place==='done')continue;
|
FOLDER.saved.set(uid,{order:file.order,item:file.item,name:file.name,folder,
|
||||||
const state=states[rec.order];
|
...(folder===STAGE_FOLDERS.fin?{at:Date.now()}:{})});
|
||||||
if(state==='imp'||state==='rev'||state==='fin'){rec.place='done';continue;}
|
FOLDER.last=new Date();await keepSaved();};
|
||||||
|
if(stages)for(const [uid,rec] of [...FOLDER.saved]){
|
||||||
|
if(!rec.order||!rec.folder)continue;
|
||||||
|
const state=states[rec.order], target=STAGE_FOLDERS[state];
|
||||||
const now=wanted.get(rec.order+':'+rec.item);
|
const now=wanted.get(rec.order+':'+rec.item);
|
||||||
const expected=state==='tra'||early()&&state==='rec';
|
const replaced=(state==='rec'||state==='tra')&&(!now||now.upload_id!==uid);
|
||||||
if(state&&state!=='cancelled'&&state!=='cor'&&!(expected&&(!now||now.upload_id!==uid)))continue;
|
const kept=rec.folder===STAGE_FOLDERS.fin&&Date.now()-(rec.at||0)>KEEP_FINISHED_DAYS*86400000;
|
||||||
await removeSaved(rec);FOLDER.saved.delete(uid);removed++;await keepSaved();
|
if(!target||replaced||kept){await removeSaved(rec);FOLDER.saved.delete(uid);removed++;await keepSaved();continue;}
|
||||||
|
if(rec.folder===target)continue;
|
||||||
|
if(await moveSaved(rec,target)){await record(uid,{...rec},target);moved++;continue;}
|
||||||
|
// Not where it was: downloaded again into its new folder while storage has it.
|
||||||
|
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();}
|
||||||
}
|
}
|
||||||
const pending=files.filter(f=>{const r=FOLDER.saved.get(f.upload_id);return !r||r.place==='early'&&f.state==='tra';});
|
// 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'));
|
||||||
for(const [i,file] of pending.entries()){
|
for(const [i,file] of pending.entries()){
|
||||||
const rec=FOLDER.saved.get(file.upload_id);
|
FOLDER.status=(stages?'Salvando ':'Baixando ')+(i+1)+' de '+pending.length+': '+file.name;paintFolder();
|
||||||
const up=!!rec&&await moveToQueue(rec);
|
|
||||||
if(!up){
|
|
||||||
FOLDER.status=(FOLDER.mode==='folder'?'Salvando ':'Baixando ')+(i+1)+' de '+pending.length+': '+file.name;paintFolder();
|
|
||||||
say(FOLDER.status,false,60000);
|
say(FOLDER.status,false,60000);
|
||||||
if(FOLDER.mode==='downloads'){
|
if(stages){
|
||||||
|
await fetchInto(await stageDir(STAGE_FOLDERS[file.state]),file);
|
||||||
|
await record(file.upload_id,file,STAGE_FOLDERS[file.state]);
|
||||||
|
}else{
|
||||||
// Firefox writes it as .part and renames it when whole.
|
// Firefox writes it as .part and renames it when whole.
|
||||||
const link=node('a');link.href=file.url;link.referrerPolicy='no-referrer';link.download=file.name;link.click();
|
const link=node('a');link.href=file.url;link.referrerPolicy='no-referrer';link.download=file.name;link.click();
|
||||||
await new Promise(r=>setTimeout(r,900));
|
await new Promise(r=>setTimeout(r,900));
|
||||||
}else{
|
FOLDER.saved.set(file.upload_id,{order:file.order,item:file.item,name:file.name});
|
||||||
const r=await fetch(file.url,{referrerPolicy:'no-referrer'});
|
|
||||||
if(!r.ok||!r.body)throw new Error('não foi possível baixar '+file.name+' (erro '+r.status+').');
|
|
||||||
await writeWhole(file.state==='tra'?FOLDER.handle:await received(),file.name,r.body);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
FOLDER.saved.set(file.upload_id,{order:file.order,item:file.item,name:file.name,
|
|
||||||
place:file.state==='tra'||FOLDER.mode!=='folder'?'queue':'early'});
|
|
||||||
FOLDER.last=new Date();await keepSaved();
|
FOLDER.last=new Date();await keepSaved();
|
||||||
}
|
}
|
||||||
|
saved++;
|
||||||
|
}
|
||||||
FOLDER.lastSig=sig;FOLDER.error='';
|
FOLDER.lastSig=sig;FOLDER.error='';
|
||||||
FOLDER.status='';
|
FOLDER.status='';
|
||||||
if(pending.length)say((FOLDER.mode==='folder'?'Salvos ':'Baixados ')+pending.length+' arquivo(s) em '+where+'.');
|
if(saved)say((stages?'Salvos ':'Baixados ')+saved+' arquivo(s) em '+where+'.');
|
||||||
if(removed)say(removed+' arquivo(s) de pedidos cancelados, excluídos ou trocados saíram da pasta.');
|
if(moved)say(moved+' arquivo(s) mudaram de pasta com o pedido.');
|
||||||
|
if(removed)say(removed+' arquivo(s) de pedidos cancelados, excluídos, em correção, trocados ou finalizados há mais de '+KEEP_FINISHED_DAYS+' dias saíram das pastas.');
|
||||||
}catch(e){
|
}catch(e){
|
||||||
if(e.name==='NotAllowedError')FOLDER.granted=false;
|
if(e.name==='NotAllowedError')FOLDER.granted=false;
|
||||||
else if(e.name==='NotFoundError')FOLDER.error='A pasta “'+FOLDER.handle?.name+'” não foi encontrada. Ela foi apagada ou a rede caiu? Escolha a pasta de novo.';
|
else if(e.name==='NotFoundError')FOLDER.error='A pasta “'+FOLDER.handle?.name+'” não foi encontrada. Ela foi apagada ou a rede caiu? Escolha a pasta de novo.';
|
||||||
else FOLDER.error='A última tentativa falhou: '+e.message+' O Kanban tenta de novo sozinho.';
|
else FOLDER.error='A última tentativa falhou: '+e.message+' O Kanban tenta de novo sozinho.';
|
||||||
FOLDER.status='';say('Pasta automática: '+(FOLDER.error||'o navegador pediu para liberar a pasta de novo, em Integrações.'),true);
|
FOLDER.status='';say('Pastas automáticas: '+(FOLDER.error||'o navegador pediu para liberar a pasta de novo, em Integrações.'),true);
|
||||||
}finally{FOLDER.busy=false;paintFolder();}
|
}finally{FOLDER.busy=false;paintFolder();}
|
||||||
}
|
}
|
||||||
setInterval(()=>syncFolder(true),30000);
|
setInterval(()=>syncFolder(true),30000);
|
||||||
|
|||||||
Reference in New Issue
Block a user