feat: approving the final file is the Kanban's next step, at the top of the order
All checks were successful
Build and deploy / Validate source (push) Successful in 1m11s
Build and deploy / Integration suite on a real stack (push) Successful in 3m7s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m24s
All checks were successful
Build and deploy / Validate source (push) Successful in 1m11s
Build and deploy / Integration suite on a real stack (push) Successful in 3m7s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m24s
An order in Arte tratada without an approved final showed "Mover para Fila de impressão" as its main button, which the server refused, while the approval sat folded at the bottom of the panel. Now the top of the panel says what comes next: approve the final, with the file that would be printed and a link to download it. A customer's correction or the generated PDF is approved with one click; otherwise the upload form opens in place. Once approved, the main button becomes the move to the queue. A customer's correction can be approved as the final itself, without downloading and sending it back. The board carries each order's approved items and corrections, so cards say "Falta aprovar o final", "Correção recebida" or "Final aprovado", and the item card shows the correction instead of the stale reason the generated file could not be made. Going back a stage is a small link, and cancelling or deleting a test order moved into a "⋯" menu. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -149,12 +149,30 @@ def thumbnails(c, *groups):
|
||||
return [str(r['upload_id']) for r in rows]
|
||||
|
||||
|
||||
# An item's final counts while its file is still there and scanned clean: the
|
||||
# same rule that lets an order into the print queue.
|
||||
FINAL_OK = """f.kind='final' AND f.active AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean'"""
|
||||
|
||||
|
||||
def with_print_files(c, orders):
|
||||
"""Each order with its generated print files, the items whose final file is
|
||||
approved, and the customer's corrections waiting to be approved as finals."""
|
||||
ids = [o['id'] for o in 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''', ([o['id'] for o in orders],)).fetchall()
|
||||
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
|
||||
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,
|
||||
(u.expires_at<=now() OR u.purged_at IS NOT NULL) AS expired FROM dtf_local.order_files f
|
||||
JOIN dtf_local.uploads u ON u.id=f.upload_id
|
||||
WHERE f.order_id=ANY(%s) AND f.kind='correction' AND f.active ORDER BY f.item_index''', (ids,)).fetchall()
|
||||
for order in orders:
|
||||
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'])
|
||||
order['corrections'] = [{k: row[k] for k in ('item_index', 'upload_id', 'name', 'expired')}
|
||||
for row in fixes if row['order_id'] == order['id']]
|
||||
return orders
|
||||
|
||||
|
||||
@@ -462,7 +480,8 @@ def move(uid: UUID, body: Move, user=Depends(operator)):
|
||||
if back and not body.reason.strip():
|
||||
raise HTTPException(422, 'Informe por que o pedido está voltando de etapa.')
|
||||
if body.state in ('fil','imp'):
|
||||
coverage = c.execute('SELECT DISTINCT f.item_index FROM dtf_local.order_files f JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=%s AND f.kind=\'final\' AND f.active AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state=\'clean\'', (uid,)).fetchall()
|
||||
coverage = c.execute(f'''SELECT DISTINCT f.item_index FROM dtf_local.order_files f
|
||||
JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=%s AND {FINAL_OK}''', (uid,)).fetchall()
|
||||
if {r['item_index'] for r in coverage} != set(range(len(row['snapshot']['items']))):
|
||||
raise HTTPException(409, 'Aprove os arquivos finais de todos os itens antes de colocar na fila.')
|
||||
if body.state == 'cor':
|
||||
|
||||
@@ -32,6 +32,21 @@ def generated_owner(c, order, ref, kind):
|
||||
# A large sheet's print file is its original, owned by the customer.
|
||||
return c.execute('SELECT owner FROM dtf_local.uploads WHERE id=%s', (ref.upload_id,)).fetchone()['owner']
|
||||
|
||||
|
||||
def correction_owner(c, order, ref, kind):
|
||||
"""The owner of a customer correction approved as it is, or None if it is not one.
|
||||
|
||||
A corrected file is often ready to print: the operator approves it as the
|
||||
final of the item it corrects, without downloading and sending it back.
|
||||
"""
|
||||
if kind != 'final':
|
||||
return None
|
||||
row = c.execute('''SELECT u.owner FROM dtf_local.order_files f JOIN dtf_local.uploads u ON u.id=f.upload_id
|
||||
WHERE f.order_id=%s AND f.upload_id=%s AND f.kind='correction' AND f.active AND f.item_index=%s''',
|
||||
(order['id'], ref.upload_id, ref.item_index)).fetchone()
|
||||
return row and row['owner']
|
||||
|
||||
|
||||
def submit_files(c, order, body, identity, kind, actor):
|
||||
if order['version'] != body.version:
|
||||
raise HTTPException(409, 'Order changed. Refresh before submitting files.')
|
||||
@@ -52,11 +67,14 @@ def submit_files(c, order, body, identity, kind, actor):
|
||||
if expiry <= datetime.now(timezone.utc):
|
||||
raise HTTPException(410, 'Order artwork retention has expired')
|
||||
for ref in body.files:
|
||||
upload = upload_row(c, ref.upload_id, generated_owner(c, order, ref, kind) or identity, lock=True)
|
||||
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']:
|
||||
raise HTTPException(409, 'Complete all uploads first')
|
||||
require_clean(upload)
|
||||
if c.execute('SELECT id FROM dtf_local.order_files WHERE upload_id=%s', (ref.upload_id,)).fetchone():
|
||||
# Attached once, except a correction approved as its own final.
|
||||
if c.execute('SELECT id FROM dtf_local.order_files WHERE upload_id=%s'+(" AND kind<>'correction'" if corrected else ''),
|
||||
(ref.upload_id,)).fetchone():
|
||||
raise HTTPException(409, 'File is already attached. Upload a new revision.')
|
||||
# A new customer correction supersedes every final prepared from earlier
|
||||
# artwork, including finals uploaded while this order was in correction.
|
||||
|
||||
@@ -166,7 +166,13 @@ try{
|
||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move]')`),'order panel');
|
||||
for(const [title,state] of [['Arte tratada','tra'],['Fila de impressão','fil'],['Imprimindo','imp'],['Finalizado','fin']]){
|
||||
if(state==='fil'){
|
||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-final-item]')`),'final upload controls');
|
||||
// Without an approved final, the next step at the top is approving it,
|
||||
// not a move the server would refuse. The CDR has no ready file, so
|
||||
// the button opens the upload form there.
|
||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-approve]')`),'approve final button');
|
||||
assert.equal(await kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="fil"]')`),false);
|
||||
await kanban.click(`[data-order="${oid}"] [data-approve]`);
|
||||
await waitFor(()=>kanban.eval(`(()=>{const input=document.querySelector('[data-order="${oid}"] [data-final-item]');return !!input&&!input.closest('form').hidden;})()`),'final upload controls');
|
||||
const doc=await kanban.call('DOM.getDocument');
|
||||
const input=await kanban.call('DOM.querySelector',{nodeId:doc.root.nodeId,selector:`[data-order="${oid}"] [data-final-item]`});
|
||||
await kanban.call('DOM.setFileInputFiles',{nodeId:input.nodeId,files:[resolve('tests/fixtures/local-test.cdr')]});
|
||||
|
||||
@@ -77,6 +77,11 @@ def run():
|
||||
assert not any(f['kind']=='final' and f['active'] for f in files), 'new correction kept a stale final active'
|
||||
version=move('tra',version)
|
||||
customer.call('/operator/orders/'+oid+'/move',{'state':'fil','version':version},operator=True,expected=409)
|
||||
# The correction itself can be approved as the final of the item it corrects.
|
||||
version=customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':correction_id}],'note':'Correction is print-ready'},operator=True)['version']
|
||||
files=customer.call('/operator/orders/'+oid+'/files',operator=True)
|
||||
assert any(f['kind']=='final' and f['active'] and f['upload_id']==correction_id for f in files)
|
||||
customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':correction_id}],'note':'Twice'},operator=True,expected=409)
|
||||
new_final=upload_bytes(customer,b'LOCAL FINAL VERSION TWO',order_id=oid)
|
||||
version=customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':new_final}],'note':'Checked corrected final'},operator=True)['version']
|
||||
for state in ('fil','imp','fin'):version=move(state,version)
|
||||
|
||||
@@ -109,7 +109,10 @@ main{padding:0 24px 24px}
|
||||
.drawer{position:fixed;inset:0;z-index:10;display:flex;justify-content:flex-end}
|
||||
.scrim{position:absolute;inset:0;background:rgba(8,9,11,.6)}
|
||||
.panel{position:relative;width:min(600px,100vw);height:100%;background:var(--panel);border-left:1px solid var(--line2);display:flex;flex-direction:column}
|
||||
.panel-head{padding:20px 24px;border-bottom:1px solid var(--line);display:flex;flex-direction:column;gap:14px}
|
||||
.panel-head{padding:20px 24px;border-bottom:1px solid var(--line);display:flex;flex-direction:column;gap:14px;flex-shrink:0}
|
||||
/* The actions never shrink to make room: the body below scrolls instead. */
|
||||
.panel-head>*,.panel-actions>*{flex-shrink:0}
|
||||
.panel-actions{display:flex;flex-direction:column;gap:10px}
|
||||
.panel-head .row{display:flex;align-items:center;gap:12px;flex-wrap:wrap}
|
||||
.panel-head .num{font-size:22px;font-weight:800}
|
||||
.stage{font-size:13.5px;font-weight:700;padding:4px 10px;border-radius:999px;background:color-mix(in srgb,var(--c) 18%,transparent);color:var(--c)}
|
||||
@@ -121,6 +124,18 @@ main{padding:0 24px 24px}
|
||||
.steps li.now{color:var(--tx);font-weight:700}.steps li.now::before{background:var(--c)}
|
||||
.moves{display:flex;gap:10px;flex-wrap:wrap}
|
||||
.moves .primary{flex:1}
|
||||
.moves{align-items:center}
|
||||
/* Going back is rare: a link, not a button the size of going forward. */
|
||||
.linkbtn{background:none;border:0;padding:6px 2px;color:var(--muted);font:inherit;font-size:13.5px;cursor:pointer;text-decoration:underline;text-underline-offset:3px}
|
||||
.linkbtn:hover{color:var(--tx)}
|
||||
.morewrap{position:relative;margin-left:auto}
|
||||
.more{min-width:44px;font-weight:800;letter-spacing:1px}
|
||||
.menu{position:absolute;right:0;top:calc(100% + 6px);z-index:5;min-width:200px;display:flex;flex-direction:column;padding:6px;
|
||||
background:var(--card2);border:1px solid var(--line3);border-radius:10px;box-shadow:0 10px 30px rgba(0,0,0,.4)}
|
||||
.menu[hidden]{display:none}
|
||||
.menuitem{background:none;border:0;text-align:left;padding:9px 10px;border-radius:7px;font:inherit;font-size:14px;color:inherit;cursor:pointer}
|
||||
.menuitem:hover{background:rgba(255,255,255,.06)}
|
||||
.menuitem.bad{color:var(--bad)}
|
||||
.reason{display:flex;flex-direction:column;gap:8px}
|
||||
.panel-body{flex:1;overflow:auto;padding:20px 24px 32px;display:flex;flex-direction:column;gap:24px}
|
||||
.facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}
|
||||
@@ -139,8 +154,13 @@ main{padding:0 24px 24px}
|
||||
.buttons{display:flex;gap:8px;flex-wrap:wrap}
|
||||
.finals{display:flex;flex-direction:column;gap:12px}
|
||||
.finals .rev{font-size:14px;display:flex;flex-direction:column;gap:4px;padding:10px 12px;border:1px solid var(--line2);border-radius:10px}
|
||||
.finals form{display:flex;flex-direction:column;gap:12px;padding:14px;border:1px solid var(--line2);border-radius:12px}
|
||||
.finals .slot{display:flex;flex-direction:column;gap:6px;font-size:14px;font-weight:600}
|
||||
.finalform{display:flex;flex-direction:column;gap:12px;padding:14px;border:1px solid var(--line2);border-radius:12px}
|
||||
.finalform[hidden]{display:none}
|
||||
.nextstep .finalform{margin-top:12px;background:var(--panel)}
|
||||
.finalform .linkbtn{align-self:center}
|
||||
.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}
|
||||
.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}
|
||||
|
||||
@@ -331,7 +351,15 @@ a.zap{display:inline-flex;align-items:center;gap:4px;vertical-align:bottom}
|
||||
.nextstep>div{flex:1;display:flex;flex-direction:column;gap:2px}
|
||||
.nextstep b{font-size:14.5px}
|
||||
.nextstep span{font-size:13.5px;color:var(--muted)}
|
||||
.nextmark{width:32px;height:32px;flex-shrink:0;border-radius:9px;background:rgba(255,139,43,.14);color:var(--accent-tx);display:flex;align-items:center;justify-content:center;font-weight:800}
|
||||
.nextstep .nextmark,.nextmark{width:32px;height:32px;flex-shrink:0;border-radius:9px;background:rgba(255,139,43,.14);color:var(--accent-tx);display:flex;align-items:center;justify-content:center;font-weight:800}
|
||||
.nextstep.lead{align-items:flex-start;border-style:solid;border-color:rgba(255,139,43,.45);background:rgba(255,139,43,.06)}
|
||||
.readyfiles{display:flex;flex-direction:column;gap:6px;margin-top:8px}
|
||||
.readyfile{display:flex;align-items:center;gap:10px;padding:6px 6px 6px 12px;background:var(--card2);border-radius:8px}
|
||||
.readyfile .faint{flex-shrink:0;font-size:13px;color:var(--faint)}
|
||||
.readyfile b{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13.5px}
|
||||
.stepactions{display:flex;gap:10px;margin-top:12px;flex-wrap:wrap}
|
||||
.btn.small{height:30px;padding:0 10px;font-size:13px}
|
||||
.subactions{display:flex;margin-top:-4px}
|
||||
.timeline li{display:flex;align-items:baseline;gap:10px;font-size:14px}
|
||||
.timeline li div{flex:1;min-width:0}
|
||||
.timeline small{flex-shrink:0;color:var(--faint);font-size:13px}
|
||||
|
||||
211
web/kanban.js
211
web/kanban.js
@@ -265,10 +265,12 @@ function printState(order){
|
||||
if(order.state==='fil'||order.state==='imp')return {text:'Final aprovado',tone:'ok'};
|
||||
if(order.state==='fin')return {text:'Concluído',tone:'ok'};
|
||||
if(order.state==='cor')return {text:'Aguardando o cliente',tone:''};
|
||||
if(finalDone(order))return {text:'Final aprovado',tone:'ok'};
|
||||
if((order.corrections||[]).length)return {text:'Correção recebida',tone:'warn'};
|
||||
const rows=order.print_files||[], items=order.snapshot.items.length;
|
||||
const ready=rows.filter(r=>r.status==='ready').length;
|
||||
if(rows.some(r=>r.status==='pending'||r.status==='rendering'))return {text:'Gerando arquivo…',tone:''};
|
||||
if(ready===items)return {text:'PDF pronto',tone:'ok'};
|
||||
if(ready===items)return {text:'Falta aprovar o final',tone:'warn'};
|
||||
if(rows.some(r=>r.status==='manual'||r.status==='failed'))
|
||||
return {text:items>1&&ready?ready+' de '+items+' pronto':'Preparar à mão',tone:'warn'};
|
||||
return {text:'Sem arquivo gerado',tone:'warn'};
|
||||
@@ -284,7 +286,8 @@ function matchesFilter(order,key){
|
||||
if(key==='entrega')return !!order.snapshot.destination;
|
||||
if(key==='retirada')return !order.snapshot.destination;
|
||||
if(key==='parados')return stalled(order);
|
||||
if(key==='manual')return (order.print_files||[]).some(r=>r.status==='manual'||r.status==='failed');
|
||||
if(key==='manual')return ['rec','tra'].includes(order.state)&&!finalDone(order)&&(order.print_files||[]).some(r=>
|
||||
(r.status==='manual'||r.status==='failed')&&!(order.corrections||[]).some(f=>f.item_index===r.item_index));
|
||||
return true;
|
||||
}
|
||||
const matches=order=>matchesFilter(order,filter);
|
||||
@@ -477,7 +480,7 @@ function renderPanel(order){
|
||||
api('/orders/'+order.id+'/history').then(rows=>{if(token===openToken)historySection(order,rows,history);}).catch(e=>say(e.message,true));
|
||||
}
|
||||
function moves(order){
|
||||
const box=node('div');box.style.display='flex';box.style.flexDirection='column';box.style.gap='10px';
|
||||
const box=node('div',undefined,'panel-actions');
|
||||
if(order.cancelled_at){
|
||||
const note=node('div',undefined,'callout bad');
|
||||
note.append(node('b','Pedido cancelado'),node('span',when(order.cancelled_at)+' · '+order.cancelled_by+' · '+order.cancel_reason));
|
||||
@@ -488,39 +491,71 @@ function moves(order){
|
||||
box.append(note,remove);return box;
|
||||
}
|
||||
const row=node('div',undefined,'moves');
|
||||
const reason=node('form',undefined,'reason');reason.hidden=true;
|
||||
// One form open at a time under the buttons.
|
||||
const forms=[];
|
||||
let sync=()=>{};
|
||||
const toggle=form=>{const show=form.hidden;for(const f of forms)f.hidden=true;form.hidden=!show;sync();
|
||||
if(show)form.querySelector('textarea,input:not([type=checkbox]):not([hidden])')?.focus();};
|
||||
const reason=node('form',undefined,'reason');reason.hidden=true;forms.push(reason);
|
||||
let step=null;
|
||||
for(const next of board.transitions[order.state]){
|
||||
if(next==='cor'){
|
||||
const b=node('button','Pedir correção','btn danger');b.type='button';b.dataset.move='cor';
|
||||
b.onclick=()=>{reason.hidden=!reason.hidden;backForm.hidden=true;if(!reason.hidden)reason.querySelector('textarea').focus();};row.append(b);
|
||||
b.onclick=()=>toggle(reason);row.append(b);
|
||||
}else if(next==='fil'&&!finalDone(order)){
|
||||
// The queue needs an approved final: approving it is the next step,
|
||||
// shown first, with the file that would be printed.
|
||||
const ready=readyFinals(order), all=ready.every(Boolean), many=ready.length>1;
|
||||
const upload=finalForm(order,all?ready.map(()=>null):ready);forms.unshift(upload);
|
||||
const text=node('div');text.append(node('b','Próximo passo: aprovar o arquivo final'));
|
||||
if(all){
|
||||
text.append(node('span','Baixe e confira. É este arquivo que vai para a impressão.'));
|
||||
const files=node('div',undefined,'readyfiles');
|
||||
ready.forEach((r,i)=>{const line=node('div',undefined,'readyfile');
|
||||
line.append(node('span',(many?'Item '+(i+1)+' · ':'')+FINAL_TITLE[r.source],'faint'),node('b',r.name),
|
||||
downloadButton('Baixar',download(r.upload_id),'btn ghost small'));files.append(line);});
|
||||
text.append(files);
|
||||
}else text.append(node('span',ready.some(Boolean)?'Alguns itens já têm arquivo pronto; envie o arquivo preparado dos outros.'
|
||||
:'Nenhum arquivo pronto para aprovar como está: envie o arquivo preparado para a impressão.'));
|
||||
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);
|
||||
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.
|
||||
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);
|
||||
step=node('div',undefined,'nextstep lead');step.append(node('span','!','nextmark'),text);
|
||||
}else{
|
||||
const b=button('Mover para '+board.states[next],()=>move(order,next),'btn primary');b.dataset.move=next;row.append(b);
|
||||
}
|
||||
}
|
||||
if(!row.children.length)row.append(node('span','Pedido concluído.','muted'));
|
||||
// Undo a mistaken move: one stage back, internal reason, no customer message.
|
||||
const previous=board.back?.[order.state];
|
||||
const backForm=node('form',undefined,'reason');backForm.hidden=true;
|
||||
const sub=node('div',undefined,'subactions');
|
||||
const backForm=node('form',undefined,'reason');backForm.hidden=true;forms.push(backForm);
|
||||
if(previous){
|
||||
const b=node('button','Voltar para '+board.states[previous],'btn ghost');b.type='button';b.dataset.back=previous;
|
||||
b.onclick=()=>{backForm.hidden=!backForm.hidden;reason.hidden=true;if(!backForm.hidden)backForm.querySelector('input').focus();};
|
||||
row.append(b);
|
||||
const b=node('button','← Voltar para '+board.states[previous],'linkbtn');b.type='button';b.dataset.back=previous;
|
||||
b.onclick=()=>toggle(backForm);sub.append(b);
|
||||
const why=node('input');why.placeholder='Motivo';why.setAttribute('aria-label','Motivo do retorno');why.required=true;why.maxLength=1000;
|
||||
const go=node('button','Voltar para '+board.states[previous],'btn');
|
||||
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;}};
|
||||
}
|
||||
if(!row.children.length)row.append(node('span','Pedido concluído.','muted'));
|
||||
// A test order is deleted; a paid one is cancelled, with a reason, and kept.
|
||||
const cancelForm=node('form',undefined,'reason');cancelForm.hidden=true;
|
||||
// Rare and destructive: behind a menu. A test order is deleted; a paid one
|
||||
// is cancelled, with a reason, and kept.
|
||||
const cancelForm=node('form',undefined,'reason');cancelForm.hidden=true;forms.push(cancelForm);
|
||||
const menu=node('div',undefined,'menu');menu.hidden=true;menu.setAttribute('role','menu');
|
||||
if(isTest(order)){
|
||||
row.append(button('Excluir pedido de teste',async()=>{
|
||||
menu.append(button('Excluir pedido de teste',async()=>{
|
||||
menu.hidden=true;
|
||||
if(!window.confirm('Excluir o pedido de teste #'+order.number+'? Ele some do Kanban, com o histórico.'))return;
|
||||
await api('/orders/'+order.id+'/delete',{});closePanel();say('Pedido de teste #'+order.number+' excluído.');await load();
|
||||
},'btn ghost'));
|
||||
},'menuitem bad'));
|
||||
}else{
|
||||
const b=node('button','Cancelar pedido','btn ghost');b.type='button';
|
||||
b.onclick=()=>{cancelForm.hidden=!cancelForm.hidden;reason.hidden=true;backForm.hidden=true;if(!cancelForm.hidden)cancelForm.querySelector('input').focus();};
|
||||
row.append(b);
|
||||
const b=node('button','Cancelar pedido','menuitem bad');b.type='button';
|
||||
b.onclick=()=>{menu.hidden=true;toggle(cancelForm);};menu.append(b);
|
||||
const why=node('input');why.placeholder='Motivo do cancelamento';why.setAttribute('aria-label','Motivo do cancelamento');why.required=true;why.minLength=3;why.maxLength=1000;
|
||||
const go=node('button','Cancelar pedido #'+order.number,'btn danger');
|
||||
cancelForm.append(node('span','O pedido sai do quadro e fica em "Cancelados", com o pagamento e o histórico. O estorno, se houver, é feito no Mercado Pago, e o pedido no Tiny se cancela lá.','muted'),why,go);
|
||||
@@ -528,17 +563,84 @@ function moves(order){
|
||||
try{await api('/orders/'+order.id+'/cancel',{note:why.value.trim()});say('Pedido #'+order.number+' cancelado.');await load();}
|
||||
catch(error){say(error.message,true);go.disabled=false;}};
|
||||
}
|
||||
const more=node('button','⋯','btn ghost more');more.type='button';more.title='Mais ações';more.setAttribute('aria-label','Mais ações');
|
||||
more.setAttribute('aria-haspopup','menu');
|
||||
more.onclick=e=>{e.stopPropagation();menu.hidden=!menu.hidden;
|
||||
if(!menu.hidden)document.addEventListener('click',()=>{menu.hidden=true;},{once:true});};
|
||||
const wrap=node('div',undefined,'morewrap');wrap.append(more,menu);row.append(wrap);
|
||||
const text=node('textarea');text.placeholder='Motivo da correção';text.setAttribute('aria-label','Motivo da correção');text.maxLength=1000;text.required=true;
|
||||
const sendFix=node('button','Enviar para correção','btn danger');
|
||||
reason.append(text,sendFix);
|
||||
reason.onsubmit=async e=>{e.preventDefault();sendFix.disabled=true;try{await move(order,'cor',text.value.trim());}catch(error){say(error.message,true);sendFix.disabled=false;}};
|
||||
box.append(row,reason,backForm,cancelForm);return box;
|
||||
box.append(...(step?[step]:[]),row,...(sub.children.length?[sub]:[]),...forms.filter(f=>!f.parentNode));return box;
|
||||
}
|
||||
// ---- Final files: the file each item is printed from, approved by an operator.
|
||||
const finalDone=order=>order.snapshot.items.every((_,index)=>(order.final_items||[]).includes(index));
|
||||
const FINAL_SOURCE={correction:'correção do cliente',generated:'PDF gerado',original:'original'};
|
||||
const FINAL_TITLE={correction:'Correção do cliente',generated:'PDF gerado',original:'Original do cliente'};
|
||||
// Per item, a file that can be approved as it is, or null: the customer's
|
||||
// correction, or else the generated PDF (or the original that already is one).
|
||||
// After a correction, a generated file reproduces artwork nobody wants printed.
|
||||
function readyFinals(order){
|
||||
const fixes=order.corrections||[];
|
||||
return order.snapshot.items.map((item,index)=>{
|
||||
const fix=fixes.find(f=>f.item_index===index);
|
||||
if(fix)return fix.expired?null:{upload_id:fix.upload_id,name:fix.name,source:'correction',label:'Correção do cliente ('+fix.name+')'};
|
||||
const made=fixes.length?null:(order.print_files||[]).find(r=>r.item_index===index&&r.status==='ready');
|
||||
if(!made)return null;
|
||||
const original=made.detail?.source==='original';
|
||||
return {upload_id:made.upload_id,name:made.name,source:original?'original':'generated',label:(original?'O original (':'PDF gerado (')+made.name+')'};
|
||||
});
|
||||
}
|
||||
async function approveReady(order,ready){
|
||||
const many=ready.length>1;
|
||||
if(!window.confirm('Conferiu o arquivo? Ele vai ser o arquivo de impressão.\n\n'+
|
||||
ready.map((r,i)=>(many?'Item '+(i+1)+': ':'')+r.label).join('\n')))return;
|
||||
const note='Aprovado como está: '+[...new Set(ready.map(r=>FINAL_SOURCE[r.source]))].join(', ');
|
||||
await api('/orders/'+order.id+'/final-files',{version:order.version,files:ready.map((r,i)=>({item_index:i,upload_id:r.upload_id})),note});
|
||||
await load();say('Arquivo final aprovado. Agora é só mover para a fila.');
|
||||
}
|
||||
// The form for a file the operator prepared, or to pick per item; ready
|
||||
// files come ticked.
|
||||
function finalForm(order,ready){
|
||||
const form=node('form',undefined,'finalform');form.hidden=true;
|
||||
const inputs=order.snapshot.items.map((item,index)=>{
|
||||
const slot=node('label',undefined,'slot');slot.append('Item '+(index+1)+' · '+PRODUCT[item.mode]);
|
||||
const input=node('input');input.type='file';input.multiple=true;input.required=true;input.dataset.finalItem=index;
|
||||
const file=ready[index];
|
||||
if(file){
|
||||
const use=node('input');use.type='checkbox';use.checked=true;use.dataset.useGenerated=index;input.required=false;input.hidden=true;
|
||||
use.onchange=()=>{input.hidden=use.checked;input.required=!use.checked;};
|
||||
const choice=node('label',undefined,'check');choice.append(use,'Usar: '+file.label);
|
||||
slot.append(choice);input.generated=()=>use.checked?file.upload_id:null;
|
||||
}
|
||||
slot.append(input);form.append(slot);return input;
|
||||
});
|
||||
const note=node('input');note.placeholder='Nota da revisão';note.required=true;note.maxLength=1000;
|
||||
const check=node('input');check.type='checkbox';check.required=true;check.dataset.confirm='';
|
||||
const checked=node('label',undefined,'check');checked.append(check,'Arquivos conferidos');
|
||||
const submit=node('button','Aprovar arquivo final','btn primary');
|
||||
form.append(note,checked,submit);
|
||||
form.onsubmit=async event=>{event.preventDefault();submit.disabled=true;try{
|
||||
const refs=[];
|
||||
for(const [index,input] of inputs.entries()){
|
||||
const generated=input.generated?.();
|
||||
if(generated){refs.push({item_index:index,upload_id:generated});continue;}
|
||||
for(const file of input.files){
|
||||
const uid=await dtfUpload(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:note.value});
|
||||
await load();say('Arquivo final aprovado.');
|
||||
}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);
|
||||
const box=node('div',undefined,'item');
|
||||
if(row&&(row.status==='manual'||row.status==='failed'))box.classList.add('attention');
|
||||
if(row&&(row.status==='manual'||row.status==='failed')&&!(order.corrections||[]).some(f=>f.item_index===index))box.classList.add('attention');
|
||||
const preview=itemPreview(item);
|
||||
const body=node('div',undefined,'body');
|
||||
const spec=item.production;
|
||||
@@ -546,8 +648,15 @@ function itemCard(order,item,index){
|
||||
body.append(title,facts([['Folha',sheetSize(spec)],['Peças',spec?String(spec.placements.length):null],
|
||||
['Metro',item.unit_cents?money(item.unit_cents):null],['Arquivos',spec&&spec.sources.length>1?String(spec.sources.length):null]]));
|
||||
if(item.quality_status==='warning')body.append(badge('! Ressalva de resolução aceita','warn'));
|
||||
// After a customer correction, that file is the artwork: the generated
|
||||
// print file, or the reason it could not be made, no longer applies.
|
||||
const fix=(order.corrections||[]).find(f=>f.item_index===index);
|
||||
if(fix){
|
||||
const file=node('div',undefined,'file');
|
||||
file.append(icon(ICON_OK),node('span','Correção do cliente recebida · '+fix.name,'ok'));body.append(file);
|
||||
}
|
||||
// The print file: a line when it is fine, a callout when someone must act.
|
||||
if(!row)body.append(node('div','Arquivo de impressão ainda não gerado','line'));
|
||||
else if(!row)body.append(node('div','Arquivo de impressão ainda não gerado','line'));
|
||||
else if(row.status==='manual'||row.status==='failed'){
|
||||
const call=node('div',undefined,'callout');
|
||||
call.append(node('b',row.status==='failed'?'! Falhou ao gerar':'! Preparar à mão'),
|
||||
@@ -565,11 +674,17 @@ function itemCard(order,item,index){
|
||||
if(extra)body.append(node('div',extra,'line'));
|
||||
}
|
||||
}
|
||||
if(['rec','tra','cor'].includes(order.state)){
|
||||
const done=(order.final_items||[]).includes(index), status=node('div',undefined,'file');
|
||||
status.append(icon(done?ICON_OK:ICON_WARN),node('span',done?'Arquivo final aprovado':'Falta aprovar o arquivo final',done?'ok':'warn'));
|
||||
body.append(status);
|
||||
}
|
||||
const buttons=node('div',undefined,'buttons');
|
||||
if(row?.status==='ready'&&row.detail?.source!=='original')buttons.append(downloadButton('PDF',download(row.upload_id)));
|
||||
if(fix&&!fix.expired)buttons.append(downloadButton('Correção',download(fix.upload_id)));
|
||||
else if(row?.status==='ready'&&row.detail?.source!=='original')buttons.append(downloadButton('PDF',download(row.upload_id)));
|
||||
item.uploads.forEach((uid,i)=>buttons.append(downloadButton(item.uploads.length>1?'Original '+(i+1):'Original',download(uid),'btn ghost')));
|
||||
if(spec?.placements)buttons.append(button('Manifesto',()=>manifest(spec),'btn ghost'));
|
||||
if(['rec','tra'].includes(order.state)&&(!row||row.status==='manual'||row.status==='failed'))
|
||||
if(!fix&&['rec','tra'].includes(order.state)&&(!row||row.status==='manual'||row.status==='failed'))
|
||||
buttons.append(button('Gerar de novo',async()=>{await api('/orders/'+order.id+'/print-files',{});await load();},'btn ghost'));
|
||||
body.append(buttons);
|
||||
box.append(preview,body);return box;
|
||||
@@ -583,49 +698,15 @@ function finalsSection(order,revisions,section){
|
||||
if(!file.expired){const b=downloadButton('Baixar',download(file.upload_id),'btn ghost');b.style.alignSelf='flex-start';rev.append(b);}
|
||||
section.append(rev);
|
||||
}
|
||||
if(!['rec','tra','cor'].includes(order.state)){if(!revisions.length)section.append(node('p','Nenhum arquivo final registrado.','faint'));return;}
|
||||
// A generated print file reproduces the approved layout: offer it first. Not
|
||||
// after a customer correction, which replaced the artwork it was made from.
|
||||
const corrected=revisions.some(file=>file.kind==='correction');
|
||||
// The form stays folded behind the next step until someone opens it.
|
||||
const next=node('div',undefined,'nextstep');
|
||||
const nextText=node('div');nextText.append(node('b',revisions.some(f=>f.kind==='final'&&f.active)?'Arquivo final enviado':'Próximo passo: arquivo final'),
|
||||
node('span','Aprove o arquivo pronto para imprimir antes de ir para a fila.'));
|
||||
const open=node('button',revisions.some(f=>f.kind==='final')?'Enviar nova versão':'Enviar arquivo','btn');open.type='button';
|
||||
next.append(node('span','!','nextmark'),nextText,open);
|
||||
const form=node('form');form.hidden=true;
|
||||
open.onclick=()=>{form.hidden=false;next.hidden=true;form.querySelector('input')?.focus();};
|
||||
const inputs=order.snapshot.items.map((item,index)=>{
|
||||
const slot=node('label',undefined,'slot');slot.append('Item '+(index+1)+' · '+PRODUCT[item.mode]);
|
||||
const input=node('input');input.type='file';input.multiple=true;input.required=true;input.dataset.finalItem=index;
|
||||
const generated=corrected?null:(order.print_files||[]).find(r=>r.item_index===index&&r.status==='ready');
|
||||
if(generated){
|
||||
const use=node('input');use.type='checkbox';use.checked=true;use.dataset.useGenerated=index;input.required=false;input.hidden=true;
|
||||
use.onchange=()=>{input.hidden=use.checked;input.required=!use.checked;};
|
||||
const choice=node('label',undefined,'check');choice.append(use,(generated.detail?.source==='original'?'Usar o original como arquivo final (':'Usar o PDF gerado (')+generated.name+')');
|
||||
slot.append(choice);input.generated=()=>use.checked?generated.upload_id:null;
|
||||
}
|
||||
slot.append(input);form.append(slot);return input;
|
||||
});
|
||||
const note=node('input');note.placeholder='Nota da revisão';note.required=true;note.maxLength=1000;
|
||||
const check=node('input');check.type='checkbox';check.required=true;check.dataset.confirm='';
|
||||
const checked=node('label',undefined,'check');checked.append(check,'Arquivos conferidos');
|
||||
const submit=node('button','Aprovar arquivos finais','btn primary');
|
||||
form.append(note,checked,submit);
|
||||
form.onsubmit=async event=>{event.preventDefault();submit.disabled=true;try{
|
||||
const refs=[];
|
||||
for(const [index,input] of inputs.entries()){
|
||||
const generated=input.generated?.();
|
||||
if(generated){refs.push({item_index:index,upload_id:generated});continue;}
|
||||
for(const file of input.files){
|
||||
const uid=await dtfUpload(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:note.value});
|
||||
await load();
|
||||
}catch(error){say(error.message,true);submit.disabled=false;}};
|
||||
section.append(next,form);
|
||||
if(!revisions.length)section.append(node('p','Nenhum arquivo final ainda.','faint'));
|
||||
// Approving is the button at the top; this is for replacing an approved
|
||||
// final, or sending one before the art is marked as handled.
|
||||
// Before approval in Arte tratada, the step at the top is the way in.
|
||||
if(!['rec','tra','cor'].includes(order.state)||(order.state==='tra'&&!finalDone(order)))return;
|
||||
const form=finalForm(order,readyFinals(order).map(()=>null));
|
||||
const open=node('button',finalDone(order)?'Enviar nova versão':'Enviar arquivo final','btn ghost');open.type='button';
|
||||
open.style.alignSelf='flex-start';open.onclick=()=>{form.hidden=!form.hidden;if(!form.hidden)form.querySelector('input:not([hidden])')?.focus();};
|
||||
section.append(open,form);
|
||||
}
|
||||
function historySection(order,rows,section){
|
||||
const list=node('ol',undefined,'timeline');
|
||||
|
||||
Reference in New Issue
Block a user