diff --git a/app/api/operator.py b/app/api/operator.py index 6f6f1d3..456a01d 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -217,7 +217,7 @@ def with_print_files(c, orders): generated = c.execute('''SELECT p.order_id,p.item_index,p.status,p.upload_id,p.detail,u.name FROM dtf_local.print_files p LEFT JOIN dtf_local.uploads u ON u.id=p.upload_id WHERE p.order_id=ANY(%s) ORDER BY p.item_index''', (ids,)).fetchall() - finals = c.execute(f'''SELECT DISTINCT f.order_id,f.item_index FROM dtf_local.order_files f + finals = c.execute(f'''SELECT f.order_id,f.item_index,f.upload_id FROM dtf_local.order_files f JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=ANY(%s) AND {FINAL_OK}''', (ids,)).fetchall() # Expired ones too: once corrected, a generated file is no longer the artwork. fixes = c.execute('''SELECT f.order_id,f.item_index,f.upload_id,u.name, @@ -239,7 +239,10 @@ def with_print_files(c, orders): for order in orders: order['correction_reason'] = reasons.get(order['id']) if order['state'] == 'cor' else None order['print_files'] = [row for row in generated if row['order_id'] == order['id']] - order['final_items'] = sorted(row['item_index'] for row in finals if row['order_id'] == order['id']) + approved = [row for row in finals if row['order_id'] == order['id']] + order['final_items'] = sorted({row['item_index'] for row in approved}) + # The approved finals themselves: "Tratar a arte" keeps those it does not replace. + order['finals'] = [{'item_index': row['item_index'], 'upload_id': row['upload_id']} for row in approved] mine = [row for row in treated if row['order_id'] == order['id']] order['treated'] = {'items': [row['item_index'] for row in mine], 'by': mine[0]['created_by']} if mine else None order['corrections'] = [{k: row[k] for k in ('item_index', 'upload_id', 'name', 'expired')} @@ -1184,6 +1187,18 @@ def print_ready(c, request, states, only=None, paid_after=None): return [row for row in rows if row['order_id'] in mine] +@router.get('/api/operator/orders/{uid}/folder-files') +def folder_files(uid: UUID, request: Request, user=Depends(can('produce'))): + """What each item's file is called in the order's stage folder, as the + automatic folders save it: "Tratar a arte" shows where to open it.""" + with db.connect() as c: + row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone() + if not row: + raise HTTPException(404, 'Pedido não encontrado.') + files = named_files(print_ready(c, request, (row['state'],), only=[uid])) + return {'state': row['state'], 'files': [{'item': f['item'], 'name': f['name']} for f in files]} + + @router.get('/api/operator/queue/finals') def queue_finals(request: Request, auto: bool = False, user=Depends(can('print'))): """The approved final files of every order in the print queue (Arte diff --git a/app/artwork.py b/app/artwork.py index 9542bbb..bbfd3c6 100644 --- a/app/artwork.py +++ b/app/artwork.py @@ -67,7 +67,18 @@ def submit_files(c, order, body, identity, kind, actor): expiry = first + timedelta(days=30) if expiry <= datetime.now(timezone.utc): raise HTTPException(410, 'Os arquivos deste pedido expiraram (30 dias).') + # A final already approved for its item may stay as it is beside a new + # one for another item: "Tratar a arte" replaces only the item treated + # (Dropstar, 2026-10-29). Something has to change, though. + 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", + (order['id'],)).fetchall()} if kind == 'final' else set() + 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): + raise HTTPException(409, 'Estes já são os arquivos finais. Envie o arquivo novo.') for ref in body.files: + if ref.upload_id in kept: + continue corrected = correction_owner(c, order, ref, kind) upload = upload_row(c, ref.upload_id, corrected or generated_owner(c, order, ref, kind) or identity, lock=True) if not upload['complete']: @@ -84,6 +95,10 @@ def submit_files(c, order, body, identity, kind, actor): else: c.execute('UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind=%s', (order['id'],kind)) for ref in body.files: + if ref.upload_id in kept: + c.execute("UPDATE dtf_local.order_files SET active=true WHERE order_id=%s AND upload_id=%s AND kind='final'", + (order['id'], ref.upload_id)) + continue c.execute('INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by) VALUES(%s,%s,%s,%s,%s,%s,%s)', (uuid4(),order['id'],ref.upload_id,ref.item_index,kind,body.note,actor)) # The order's window, whatever the upload's own hold was. diff --git a/tests/workflow_test.py b/tests/workflow_test.py index 4cec67c..5062f59 100644 --- a/tests/workflow_test.py +++ b/tests/workflow_test.py @@ -115,5 +115,37 @@ def run(): cookie.value=old_cookie;revoked.jar.set_cookie(cookie);revoked.call('/customer/orders',expected=401) other.call('/session');assert other.call('/customer/orders')['items']==[] print('PASS: logout revokes server session and signed-out visitors cannot see account orders') + treating() + +def treating(): + """"Tratar a arte" (Dropstar, 2026-10-29): the item's name in the folder, + and a treated file that replaces only its own item's final.""" + customer=Client();customer.call('/session') + originals=[upload_bytes(customer,b'LOCAL TREAT ORIGINAL %d' % n) for n in (1,2)] + items=[item_spec('file','1.01',0,uid) for uid in originals] + profile={'cnpj':'11222333000181','zap':'11999999999','mail':'treat-'+uuid4().hex[:8]+'@example.test'} + q=customer.call('/quotes',{'request_key':str(uuid4()),'customer':profile,'items':items,'freight':{'service':'pickup'}}) + approved_quote(customer,q,items) + order=customer.call('/orders/dev-paid',{'quote_id':q['id']});oid=order['id'];number=order['number'] + files=lambda:[f for f in customer.call('/operator/orders/'+oid+'/files',operator=True) if f['kind']=='final' and f['active']] + first=[upload_bytes(customer,b'LOCAL FIRST FINAL %d' % n,order_id=oid) for n in (1,2)] + version=customer.call('/operator/orders/'+oid+'/final-files',{'version':0,'note':'Aprovado', + 'files':[{'item_index':i,'upload_id':u} for i,u in enumerate(first)]},operator=True)['version'] + # Where each item is in the stage folder, named as the folders save it. + folder=customer.call('/operator/orders/'+oid+'/folder-files',operator=True) + assert folder['state']=='rec' and [f['item'] for f in folder['files']]==[1,2], folder + assert all(f['name'].startswith('DTF-%d-item-%d' % (number,f['item'])) for f in folder['files']), folder + customer.call('/operator/orders/'+oid+'/folder-files',expected=401) + # Saved over with the same name and sent back: item 1 changes, item 2 keeps its final. + png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+(2000).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4 + treated=upload_bytes(customer,png,name='DTF-%d-item-1.png' % number,order_id=oid) + both=[{'item_index':0,'upload_id':treated},{'item_index':1,'upload_id':first[1]}] + version=customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':both,'note':'Arte tratada'},operator=True)['version'] + assert sorted((f['item_index'],f['upload_id']) for f in files())==[(0,treated),(1,first[1])], files() + assert customer.call('/operator/orders/'+oid+'/folder-files',operator=True)['files'][0]['name']=='DTF-%d-item-1.png' % number + # Nothing new: refused. + customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':both,'note':'De novo'},operator=True,expected=409) + customer.call('/operator/orders/'+oid+'/cancel',{'note':'Teste de arte tratada'},operator=True) + print('PASS: treating the art: the file in the folder, and one item replaced while the other keeps its final') if __name__=='__main__':run() diff --git a/web/kanban.css b/web/kanban.css index 3e1fb5e..1739b07 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -190,6 +190,8 @@ main{padding:0 24px 24px} .finalform input[type=file]{color:var(--muted);font:inherit;font-size:13.5px;font-weight:500} .finalform input[type=file]::file-selector-button{height:34px;padding:0 12px;margin-right:10px;border-radius:8px;border:1px solid var(--line2);background:var(--card2);color:var(--tx);font:inherit;font-size:13.5px;font-weight:600;cursor:pointer} .finalform .slot{display:flex;flex-direction:column;gap:6px;font-size:14px;font-weight:600} +.treatline{display:flex;align-items:center;gap:8px} +.treatpath{flex:1;min-width:0;padding:7px 10px;border-radius:8px;background:var(--card2);font-family:var(--mono);font-size:13px;font-weight:500;color:var(--tx);word-break:break-all} .timeline{margin:0;padding:0;list-style:none;display:flex;flex-direction:column;gap:10px} .timeline li::before{content:"";width:8px;height:8px;margin-top:6px;border-radius:999px;background:var(--c,var(--muted));flex-shrink:0} diff --git a/web/kanban.js b/web/kanban.js index 51995cd..3748d92 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -972,11 +972,17 @@ function moves(order){ const actions=node('div',undefined,'stepactions'); const b=button(all?'Aprovar arquivo final':'Enviar arquivo final',all?()=>approveReady(order,ready):async()=>toggle(upload),'btn primary'); b.dataset.approve='';actions.append(b); + // In Arte recebida the art may need work first (Dropstar, 2026-10-29). + const treat=order.state==='rec'&&may('produce')?treatForm(order):null; + if(treat){forms.unshift(treat); + const t=node('button','Tratar a arte','btn ghost');t.type='button';t.dataset.treat=''; + t.onclick=async()=>{toggle(treat);if(!treat.hidden)await treat.load();};actions.append(t); + const close=node('button','Cancelar','linkbtn');close.type='button';close.onclick=()=>toggle(treat);treat.append(close);} if(all){const other=node('button','Enviar outro arquivo','btn ghost');other.type='button';other.onclick=()=>toggle(upload);actions.append(other);} - // The upload form opens inside the step, in place of its buttons. + // The upload forms open inside the step, in place of its buttons. const cancel=node('button','Cancelar','linkbtn');cancel.type='button';cancel.onclick=()=>toggle(upload); - upload.append(cancel);sync=()=>{actions.hidden=!upload.hidden;}; - text.append(actions,upload); + upload.append(cancel);sync=()=>{actions.hidden=!upload.hidden||!!treat&&!treat.hidden;}; + text.append(actions,upload,...(treat?[treat]:[])); step=node('div',undefined,'nextstep lead');step.append(node('span','!','nextmark'),text); }else if(next==='fin'&&proofPending(order)){ // Finalizado waits for the proof: printing it and checking it is the next step. @@ -1005,6 +1011,12 @@ function moves(order){ backForm.append(why,go); backForm.onsubmit=async e=>{e.preventDefault();go.disabled=true;try{await move(order,previous,why.value.trim());}catch(error){say(error.message,true);go.disabled=false;}}; } + // Approved already, the art can still be treated while in Arte recebida. + if(order.state==='rec'&&finalDone(order)&&may('produce')&&!order.cancelled_at){ + const treat=treatForm(order);forms.push(treat); + const b=node('button','Tratar a arte','linkbtn');b.type='button';b.dataset.treat=''; + b.onclick=async()=>{toggle(treat);if(!treat.hidden)await treat.load();};sub.append(b); + } // The proof is checked by the room, in the queue (Arte conferida) or while printing. if(['tra','imp'].includes(order.state)&&proofPending(order)&&may('print')){ const b=button('✓ Prova OK',()=>proofOk(order),'linkbtn');b.title='A prova foi impressa e conferida';sub.append(b); @@ -1148,6 +1160,78 @@ function finalForm(order,ready){ }catch(error){say(error.message,true);submit.disabled=false;}}; return form; } +// "Tratar a arte" (Dropstar, 2026-10-29): where each item's file is in the +// orders folder, to open it, treat it and save it over with the same name; +// then the treated file sent here becomes the item's final, "Arte tratada". +// The browser only knows the folder's name, so each computer is told once +// where the folder is, to copy the whole path. +const TREAT_NOTE='Arte tratada'; +const FOLDER_PATH_KEY='folder-path'; +function treatForm(order){ + const form=node('form',undefined,'finalform');form.hidden=true; + form.append(node('b','Tratar a arte'),node('span','Copie o caminho e abra o arquivo. Trate e salve por cima, com o mesmo nome. Depois suba aqui o arquivo tratado.','faint')); + const base=node('input');base.placeholder='Ex.: D:\\'+(FOLDER.handle?.name||'Pedidos'); + const baseField=node('label',undefined,'slot');baseField.append('Pasta dos pedidos neste computador',base); + const names={}; + const rows=order.snapshot.items.map((item,index)=>{ + const slot=node('div',undefined,'slot'); + const path=node('code','Procurando o arquivo…','treatpath'); + const copy=node('button','Copiar','btn ghost small');copy.type='button';copy.disabled=true; + const line=node('div',undefined,'treatline');line.append(path,copy); + const input=node('input');input.type='file';input.dataset.treatItem=index; + input.setAttribute('aria-label','Arte tratada do item '+(index+1)); + slot.append(node('span',order.snapshot.items.length>1?'Item '+(index+1)+' · '+PRODUCT[item.mode]:PRODUCT[item.mode]),line,input); + return {path,copy,input}; + }); + // Windows paths unless the folder was written the other way. + const where=name=>{const b=base.value.trim().replace(/[\\/]+$/,''),sep=b.includes('/')&&!b.includes('\\')?'/':'\\'; + return (b?b+sep:'')+STAGE_FOLDERS[order.state]+sep+name;}; + const paint=()=>rows.forEach((row,index)=>{ + const name=names[index+1]; + row.path.textContent=name?(base.value.trim()?'':'…\\')+where(name):'Este item ainda não tem arquivo na pasta.'; + row.copy.disabled=!name; + row.copy.onclick=async()=>{try{await navigator.clipboard.writeText(where(name)); + say(base.value.trim()?'Caminho copiado.':'Caminho copiado a partir da pasta dos pedidos: informe onde ela fica neste computador para copiar o caminho inteiro.');} + catch(_){say('Não foi possível copiar.',true);}}; + }); + base.onchange=()=>{kv.set(FOLDER_PATH_KEY,base.value.trim()).catch(()=>{});paint();}; + const submit=node('button','Subir arte tratada','btn primary'); + form.append(...rows.map(r=>r.input.parentNode),baseField,submit); + // Filled when it opens: the names the automatic folders give the files. + form.load=async()=>{ + base.value=await kv.get(FOLDER_PATH_KEY).catch(()=>'')||''; + try{for(const f of (await api('/orders/'+order.id+'/folder-files')).files)names[f.item]=names[f.item]||f.name;} + catch(error){say(error.message,true);} + paint(); + }; + form.onsubmit=async event=>{event.preventDefault(); + // Each item keeps its approved final, or else the file ready to approve, + // unless a treated one is sent for it. + const ready=readyFinals(order); + const plan=rows.map((row,index)=>{ + const file=row.input.files[0]; + if(file)return {file}; + const kept=(order.finals||[]).filter(f=>f.item_index===index).map(f=>f.upload_id); + return {ids:kept.length?kept:ready[index]?[ready[index].upload_id]:[]}; + }); + if(!plan.some(p=>p.file)){say('Escolha o arquivo tratado.',true);return;} + const empty=plan.findIndex(p=>!p.file&&!p.ids.length); + if(empty>=0){say('O item '+(empty+1)+' ainda não tem arquivo: suba a arte tratada dele também.',true);return;} + submit.disabled=true; + try{ + const refs=[]; + for(const [index,p] of plan.entries()){ + if(!p.file){refs.push(...p.ids.map(upload_id=>({item_index:index,upload_id})));continue;} + const uid=await dtfUpload(p.file,{api,startPath:'/orders/'+order.id+'/uploads',scope:'operator:'+order.id+':'+order.version,progress:text=>say(text)}); + refs.push({item_index:index,upload_id:uid}); + } + await api('/orders/'+order.id+'/final-files',{version:order.version,files:refs,note:TREAT_NOTE}); + await load(); + say(mayMove(order.state,'tra')?'Arte tratada aprovada como arquivo final. Agora é só mover para Arte conferida.':'Arte tratada aprovada como arquivo final.'); + }catch(error){say(error.message,true);submit.disabled=false;} + }; + return form; +} const PRINT_TEXT={pending:'Na fila para gerar',rendering:'Gerando arquivo…',ready:'PDF gerado',manual:'Preparar à mão',failed:'Falhou ao gerar'}; function itemCard(order,item,index){ const row=(order.print_files||[]).find(r=>r.item_index===index);